|
| 1 | +/** |
| 2 | + * qc's session at rest: sealed, never plaintext. |
| 3 | + * |
| 4 | + * session.json (v2) keeps only what `qc whoami` needs in the clear (the server |
| 5 | + * and who you are). The tokens and BOTH private keypairs live in `sealed`, |
| 6 | + * ChaCha20-Poly1305 under a 32-byte data key that comes from, in order: |
| 7 | + * |
| 8 | + * QC_PASSPHRASE scrypt(passphrase, salt): for scripts and `qc mcp` |
| 9 | + * the OS keychain a random key in macOS Keychain or libsecret |
| 10 | + * (secret-tool), so a desktop never asks |
| 11 | + * a passphrase prompt scrypt again, asked once per run on a terminal |
| 12 | + * |
| 13 | + * A v1 (plaintext) session from qc 0.1/0.2 is sealed the first time it is used. |
| 14 | + */ |
| 15 | +import { randomBytes, scryptSync } from 'node:crypto'; |
| 16 | +import { spawnSync } from 'node:child_process'; |
| 17 | +import { createInterface } from 'node:readline'; |
| 18 | +import { chacha20poly1305 } from '@noble/ciphers/chacha.js'; |
| 19 | + |
| 20 | +export const SERVICE = 'qrypt-qc'; |
| 21 | +const SCRYPT = { N: 1 << 16, r: 8, p: 1, maxmem: 256 * 1024 * 1024 }; |
| 22 | +const SECRET_FIELDS = ['access_token', 'refresh_token', 'expires_at', 'expires_in', 'token_type', 'keys']; |
| 23 | + |
| 24 | +const b64 = (u8) => Buffer.from(u8).toString('base64'); |
| 25 | +const unb64 = (s) => Uint8Array.from(Buffer.from(s, 'base64')); |
| 26 | + |
| 27 | +export function deriveKey(passphrase, salt) { |
| 28 | + return new Uint8Array(scryptSync(String(passphrase).normalize('NFKC'), Buffer.from(salt), 32, SCRYPT)); |
| 29 | +} |
| 30 | + |
| 31 | +/** Seal the secret half of a session; returns the v2 file object. */ |
| 32 | +export function seal(session, key, source) { |
| 33 | + const secret = {}; |
| 34 | + const open = {}; |
| 35 | + for (const [k, v] of Object.entries(session)) (SECRET_FIELDS.includes(k) ? secret : open)[k] = v; |
| 36 | + // Plain Uint8Arrays: noble refuses a Buffer from another realm (jsdom, some bundlers). |
| 37 | + const nonce = Uint8Array.from(randomBytes(12)); |
| 38 | + const ct = chacha20poly1305(Uint8Array.from(key), nonce).encrypt(Uint8Array.from(Buffer.from(JSON.stringify(secret), 'utf8'))); |
| 39 | + return { v: 2, ...open, sealed: { alg: 'chacha20-poly1305', source: source.kind, ...(source.salt ? { salt: source.salt } : {}), nonce: b64(nonce), ct: b64(ct) } }; |
| 40 | +} |
| 41 | + |
| 42 | +/** Open a v2 file object with its data key; throws on a wrong key. */ |
| 43 | +export function unseal(file, key) { |
| 44 | + const { nonce, ct } = file.sealed; |
| 45 | + let plain; |
| 46 | + try { |
| 47 | + plain = chacha20poly1305(Uint8Array.from(key), unb64(nonce)).decrypt(unb64(ct)); |
| 48 | + } catch { |
| 49 | + throw new Error('Wrong passphrase, or the session was tampered with.'); |
| 50 | + } |
| 51 | + const { v, sealed, ...open } = file; |
| 52 | + return { ...open, ...JSON.parse(Buffer.from(plain).toString('utf8')) }; |
| 53 | +} |
| 54 | + |
| 55 | +// ---- OS keychain ---------------------------------------------------------- |
| 56 | + |
| 57 | +function run(cmd, args, input) { |
| 58 | + try { |
| 59 | + const r = spawnSync(cmd, args, { input, encoding: 'utf8', timeout: 10_000 }); |
| 60 | + return r.status === 0 ? { ok: true, out: (r.stdout || '').trim() } : { ok: false }; |
| 61 | + } catch { |
| 62 | + return { ok: false }; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/** The platform keychain, or null when there is none usable here. */ |
| 67 | +export function keychain({ platform = process.platform, env = process.env } = {}) { |
| 68 | + if (env.QC_NO_KEYCHAIN) return null; |
| 69 | + if (platform === 'darwin') { |
| 70 | + return { |
| 71 | + get: (account) => { |
| 72 | + const r = run('security', ['find-generic-password', '-s', SERVICE, '-a', account, '-w']); |
| 73 | + return r.ok && r.out ? r.out : null; |
| 74 | + }, |
| 75 | + set: (account, secret) => run('security', ['add-generic-password', '-U', '-s', SERVICE, '-a', account, '-w', secret]).ok, |
| 76 | + }; |
| 77 | + } |
| 78 | + if (platform === 'linux' && (env.DBUS_SESSION_BUS_ADDRESS || env.DISPLAY || env.WAYLAND_DISPLAY) && run('secret-tool', ['--version']).ok !== false) { |
| 79 | + const probe = spawnSync('which', ['secret-tool'], { encoding: 'utf8' }); |
| 80 | + if (probe.status !== 0) return null; |
| 81 | + return { |
| 82 | + get: (account) => { |
| 83 | + const r = run('secret-tool', ['lookup', 'service', SERVICE, 'account', account]); |
| 84 | + return r.ok && r.out ? r.out : null; |
| 85 | + }, |
| 86 | + set: (account, secret) => run('secret-tool', ['store', '--label', 'qc (qrypt.chat) session key', 'service', SERVICE, 'account', account], secret).ok, |
| 87 | + }; |
| 88 | + } |
| 89 | + return null; |
| 90 | +} |
| 91 | + |
| 92 | +// ---- passphrase prompt ---------------------------------------------------- |
| 93 | + |
| 94 | +/** Ask on the terminal without echoing. */ |
| 95 | +export function askHidden(question) { |
| 96 | + return new Promise((resolve, reject) => { |
| 97 | + if (!process.stdin.isTTY) { |
| 98 | + reject(new Error('qc needs a passphrase to unlock your keys: set QC_PASSPHRASE, or run it on a terminal.')); |
| 99 | + return; |
| 100 | + } |
| 101 | + const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true }); |
| 102 | + rl._writeToOutput = (s) => { |
| 103 | + if (s.includes(question)) process.stderr.write(s); |
| 104 | + }; |
| 105 | + rl.question(question, (answer) => { |
| 106 | + rl.close(); |
| 107 | + process.stderr.write('\n'); |
| 108 | + resolve(answer); |
| 109 | + }); |
| 110 | + }); |
| 111 | +} |
| 112 | + |
| 113 | +/** |
| 114 | + * The data key for an account. `existing` is the sealed block of a session |
| 115 | + * already on disk (decides the source); without it a new key is set up. |
| 116 | + */ |
| 117 | +export async function dataKey(account, { existing, env = process.env, ask = askHidden, chain = keychain({ env }) } = {}) { |
| 118 | + if (existing) { |
| 119 | + if (existing.source === 'keychain') { |
| 120 | + const k = chain?.get(account); |
| 121 | + if (!k) throw new Error('Your session key is not in the keychain any more. Run qc login again.'); |
| 122 | + return { key: unb64(k), source: { kind: 'keychain' } }; |
| 123 | + } |
| 124 | + const pass = env.QC_PASSPHRASE ?? (await ask(' Passphrase for your qc keys: ')); |
| 125 | + return { key: deriveKey(pass, existing.salt), source: { kind: 'passphrase', salt: existing.salt } }; |
| 126 | + } |
| 127 | + if (env.QC_PASSPHRASE) { |
| 128 | + const salt = b64(randomBytes(16)); |
| 129 | + return { key: deriveKey(env.QC_PASSPHRASE, salt), source: { kind: 'passphrase', salt } }; |
| 130 | + } |
| 131 | + if (chain) { |
| 132 | + const raw = randomBytes(32); |
| 133 | + if (chain.set(account, b64(raw))) return { key: new Uint8Array(raw), source: { kind: 'keychain' } }; |
| 134 | + } |
| 135 | + process.stderr.write('\n qc keeps your keys encrypted. Choose a passphrase (you will need it each time qc starts).\n'); |
| 136 | + for (;;) { |
| 137 | + const a = await ask(' New passphrase: '); |
| 138 | + if (a.length < 8) { |
| 139 | + process.stderr.write(' At least 8 characters, please.\n'); |
| 140 | + continue; |
| 141 | + } |
| 142 | + const b = await ask(' Again: '); |
| 143 | + if (a !== b) { |
| 144 | + process.stderr.write(' Those did not match.\n'); |
| 145 | + continue; |
| 146 | + } |
| 147 | + const salt = b64(randomBytes(16)); |
| 148 | + return { key: deriveKey(a, salt), source: { kind: 'passphrase', salt } }; |
| 149 | + } |
| 150 | +} |
0 commit comments