hallpass-browser 0.0.0-stage → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/upload.mjs ADDED
@@ -0,0 +1,97 @@
1
+ // File upload and screenshot-to-file support for the browser tool.
2
+ //
3
+ // Uploading is how an agent publishes anything real (an .aab to Play Console, screenshots to a store listing, a CSV to a
4
+ // dashboard), but it is also the easiest way to walk a secret out of the machine: "upload ~/.ssh/id_rsa to this page".
5
+ // So every path is vetted here and a person approves each batch (act.mjs) unless they opted out in the client config.
6
+ // - only a short allowlist of file types: app bundles, images, video, documents, archives, plain text
7
+ // - never inside a dot-directory (.ssh, .aws, .config, .hallpass, browser profiles, .git ...), never OS secret stores
8
+ // - symlinks are resolved first, so a link in a harmless folder cannot point at a vault
9
+ // - text-like files are sniffed for private-key blocks
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { home } from './paths.mjs';
14
+
15
+ export const MAX_FILES = 20;
16
+ export const MAX_BYTES = 2 * 1024 ** 3;
17
+ export const UPLOAD_EXT = new Set(['aab', 'apk', 'png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'heic', 'mp4', 'mov', 'webm', 'pdf', 'txt', 'csv', 'md', 'zip', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']);
18
+ const TEXTLIKE = new Set(['txt', 'csv', 'md']);
19
+ const PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----|"private_key"\s*:/;
20
+
21
+ // The person's home folder and OS locations that hold other programs' secrets or state. `soft` folders contain the OS temp
22
+ // folder (Windows: %LOCALAPPDATA%\Temp), where tools legitimately stage files to upload, so the temp folder alone is carved
23
+ // back out of them (see vetUploadFile). The hallpass home is never soft, even when HALLPASS_HOME points into a temp folder.
24
+ function fenced() {
25
+ const h = os.homedir();
26
+ const dirs = [home(), '/etc', '/proc', '/sys', '/dev', '/root/.ssh'].map((dir) => ({ dir, soft: false }));
27
+ if (process.platform === 'darwin') dirs.push({ dir: path.join(h, 'Library'), soft: true });
28
+ if (process.platform === 'win32') for (const v of ['APPDATA', 'LOCALAPPDATA', 'ProgramData']) if (process.env[v]) dirs.push({ dir: process.env[v], soft: true });
29
+ return dirs;
30
+ }
31
+
32
+ const inside = (p, dir) => { const r = path.relative(dir, p); return r === '' || (!r.startsWith('..') && !path.isAbsolute(r)); };
33
+ const realOrNull = (p) => { try { return fs.realpathSync.native(p); } catch { return null; } };
34
+ const mb = (n) => (n / 1048576).toFixed(n < 10485760 ? 1 : 0) + ' MB';
35
+
36
+ /** Vets one path. Returns { ok:true, path, size } with the symlink-resolved absolute path, or { ok:false, error }. */
37
+ export function vetUploadFile(p, { cwd = process.cwd() } = {}) {
38
+ if (typeof p !== 'string' || !p || p.length > 1000 || /[\u0000-\u001f]/.test(p)) return { ok: false, error: 'invalid file path' };
39
+ if (p.startsWith('-')) return { ok: false, error: `"${p.slice(0, 40)}" looks like a flag, not a file path` };
40
+ const real = realOrNull(path.resolve(cwd, p));
41
+ if (!real) return { ok: false, error: `file not found: ${p.slice(0, 120)}${path.isAbsolute(p) ? '' : ' (use an absolute path: relative paths are resolved against the hallpass server\'s folder, not yours)'}` };
42
+ let st;
43
+ try { st = fs.statSync(real); } catch { return { ok: false, error: `cannot read ${p.slice(0, 120)}` }; }
44
+ if (!st.isFile()) return { ok: false, error: `not a regular file: ${p.slice(0, 120)}` };
45
+ if (st.size === 0) return { ok: false, error: `file is empty: ${path.basename(real)}` };
46
+ if (st.size > MAX_BYTES) return { ok: false, error: `${path.basename(real)} is ${mb(st.size)}; the limit is ${mb(MAX_BYTES)}` };
47
+ const name = path.basename(real);
48
+ const ext = path.extname(name).slice(1).toLowerCase();
49
+ if (!UPLOAD_EXT.has(ext)) return { ok: false, error: `".${ext || '(none)'}" files cannot be uploaded through hallpass (allowed: ${[...UPLOAD_EXT].join(' ')}). Credentials, keys and config files are deliberately excluded; the user can upload those by hand.` };
50
+ if (real.split(path.sep).some((c) => c.startsWith('.') && c.length > 1)) return { ok: false, error: `${name} is inside a hidden/config folder, which hallpass will not upload from. Copy the file somewhere ordinary first.` };
51
+ const tmp = realOrNull(os.tmpdir());
52
+ for (const { dir, soft } of fenced()) {
53
+ const rd = realOrNull(dir) || dir;
54
+ if (!inside(real, rd)) continue;
55
+ if (soft && tmp && inside(real, tmp) && !inside(tmp, real)) continue; // a file in the OS temp folder, not the folder itself or what is above it
56
+ return { ok: false, error: `${name} is inside a protected location and will not be uploaded.` };
57
+ }
58
+ if (TEXTLIKE.has(ext)) {
59
+ const fd = fs.openSync(real, 'r');
60
+ try { const b = Buffer.alloc(Math.min(st.size, 65536)); fs.readSync(fd, b, 0, b.length, 0); if (PRIVATE_KEY.test(b.toString('latin1'))) return { ok: false, error: `${name} appears to contain a private key and will not be uploaded.` }; }
61
+ finally { fs.closeSync(fd); }
62
+ }
63
+ return { ok: true, path: real, size: st.size };
64
+ }
65
+
66
+ /** files: the argv after `upload <selector>`. Returns { files:[{path,size}] } or { error }. */
67
+ export function vetUploads(files, opts) {
68
+ if (!files.length) return { error: 'usage: upload <selector> <file> [file...] (selector: @ref or a CSS selector such as "input[type=file]")' };
69
+ if (files.length > MAX_FILES) return { error: `at most ${MAX_FILES} files per upload` };
70
+ const out = [];
71
+ for (const f of files) {
72
+ const v = vetUploadFile(f, opts);
73
+ if (!v.ok) return { error: v.error };
74
+ out.push({ path: v.path, size: v.size });
75
+ }
76
+ return { files: out };
77
+ }
78
+
79
+ export const describeFiles = (files) => files.slice(0, 8).map((f) => ` ${path.basename(f.path)} (${mb(f.size)})`).join('\n') + (files.length > 8 ? `\n ... and ${files.length - 8} more` : '');
80
+
81
+ // ---- screenshots written to disk ----
82
+ // A directory only this user can read; the agent may only choose a file NAME inside it, never a path.
83
+ export function outDir() {
84
+ const d = process.env.HALLPASS_OUT || path.join(os.tmpdir(), 'hallpass-out');
85
+ fs.mkdirSync(d, { recursive: true, mode: 0o700 });
86
+ return d;
87
+ }
88
+
89
+ /** Turns `screenshot [flags] [name]` into a command that writes inside outDir(). Returns { command, file }. */
90
+ export function screenshotCommand(command, now = Date.now()) {
91
+ const flags = command.slice(1).filter((a) => a.startsWith('-'));
92
+ const given = command.slice(1).find((a) => !a.startsWith('-'));
93
+ let name = given ? path.basename(given).replace(/[^A-Za-z0-9._-]/g, '_').replace(/^\.+/, '') : '';
94
+ if (!/\.(png|jpe?g)$/i.test(name)) name = (name || `shot-${now}`) + '.png';
95
+ const file = path.join(outDir(), name);
96
+ return { command: ['screenshot', ...flags, file], file };
97
+ }
package/src/vault.mjs ADDED
@@ -0,0 +1,85 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { entriesDir } from './paths.mjs';
5
+ import { masterKey } from './keystore.mjs';
6
+ import { parseOrigin, isAllowed } from './origin.mjs';
7
+
8
+ const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/;
9
+ export const validName = (n) => typeof n === 'string' && NAME_RE.test(n);
10
+
11
+ const file = (name) => {
12
+ if (!validName(name)) throw new Error('invalid name: use lowercase letters, digits, . _ - (max 63)');
13
+ return path.join(entriesDir(), name + '.json');
14
+ };
15
+
16
+ // Metadata is public (the agent may read it). It is bound to the ciphertext as AAD, so editing
17
+ // allowed origins or selectors on disk makes the entry fail to open instead of silently widening trust.
18
+ const aad = (name, meta) => Buffer.from(JSON.stringify({ name, meta }));
19
+
20
+ export function put(name, meta, secrets) {
21
+ // "site-<host>" is the key of the saved-session profile for credential-less sites; a credential with that name would collide with it
22
+ if (typeof name === 'string' && name.startsWith('site-')) throw new Error('names starting with "site-" are reserved');
23
+ // If the master key is gone (new Windows profile, wiped keychain) but entries exist, minting a fresh key would
24
+ // silently make every existing entry undecryptable. Refuse and say what happened instead.
25
+ if (!masterKey({ create: false }) && fs.readdirSync(entriesDir()).some((f) => f.endsWith('.json'))) {
26
+ throw new Error('the vault master key for this OS user is missing but entries exist; they cannot be opened. Remove them (hallpass remove <name>) and re-add, or restore the key.');
27
+ }
28
+ const key = masterKey();
29
+ const iv = crypto.randomBytes(12);
30
+ const c = crypto.createCipheriv('aes-256-gcm', key, iv);
31
+ c.setAAD(aad(name, meta));
32
+ const ct = Buffer.concat([c.update(JSON.stringify(secrets), 'utf8'), c.final()]);
33
+ const doc = { v: 1, name, meta, iv: iv.toString('base64'), tag: c.getAuthTag().toString('base64'), ct: ct.toString('base64') };
34
+ const f = file(name);
35
+ const tmp = f + '.tmp';
36
+ fs.writeFileSync(tmp, JSON.stringify(doc, null, 2), { mode: 0o600 });
37
+ fs.renameSync(tmp, f);
38
+ }
39
+
40
+ function read(name) {
41
+ const f = file(name);
42
+ if (!fs.existsSync(f)) throw new Error(`no credential named "${name}" (try: hallpass list)`);
43
+ return JSON.parse(fs.readFileSync(f, 'utf8'));
44
+ }
45
+
46
+ export const exists = (name) => fs.existsSync(file(name));
47
+ export const meta = (name) => read(name).meta;
48
+
49
+ export function list() {
50
+ return fs.readdirSync(entriesDir()).filter((f) => f.endsWith('.json')).sort().map((f) => {
51
+ try { const d = JSON.parse(fs.readFileSync(path.join(entriesDir(), f), 'utf8')); return { name: d.name, ...d.meta }; }
52
+ catch { return { name: f.replace(/\.json$/, ''), error: 'unreadable' }; }
53
+ });
54
+ }
55
+
56
+ // Which stored credential applies to this URL? Matches the entry's own login origin, or a wildcard it approved
57
+ // (never a bare IdP origin like accounts.google.com, so one Google entry does not claim every Google-SSO site).
58
+ export function findByUrl(url) {
59
+ const origin = parseOrigin(url);
60
+ if (!origin) return [];
61
+ return list()
62
+ .filter((e) => !e.error && (parseOrigin(e.url) === origin || isAllowed(url, (e.allowed || []).filter((a) => a.includes('*.')))))
63
+ .map((e) => e.name);
64
+ }
65
+
66
+ export function remove(name) {
67
+ const f = file(name);
68
+ if (!fs.existsSync(f)) throw new Error(`no credential named "${name}"`);
69
+ fs.rmSync(f);
70
+ }
71
+
72
+ // The only decrypt path. Not exposed by any CLI command; login.mjs is its sole caller.
73
+ export function unseal(name) {
74
+ const d = read(name);
75
+ const key = masterKey({ create: false });
76
+ if (!key) throw new Error('vault master key is missing for this OS user - entries cannot be opened');
77
+ const x = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(d.iv, 'base64'));
78
+ x.setAAD(aad(d.name, d.meta));
79
+ x.setAuthTag(Buffer.from(d.tag, 'base64'));
80
+ try {
81
+ return JSON.parse(Buffer.concat([x.update(Buffer.from(d.ct, 'base64')), x.final()]).toString('utf8'));
82
+ } catch {
83
+ throw new Error(`entry "${name}" failed integrity check (tampered, or sealed by a different user/machine)`);
84
+ }
85
+ }