askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
toolbar: Back and Forward are greyed out when there's nowhere to go
cc08c7a
1 week, 2 days ago
History
vault.ts · 10.1 KB · 273 lines
| 1 | /** |
| 2 | * A deliberately tiny password vault. |
| 3 | * |
| 4 | * - One file on disk: scrypt-derived key → AES-256-GCM over a JSON document. |
| 5 | * - Zero dependencies (node:crypto only), so it runs standalone or inside Electron. |
| 6 | * - Credentials are matched by EXACT origin (scheme + host + port). No "same |
| 7 | * registrable domain" cleverness: loose matching is how phishing pages get filled. |
| 8 | * |
| 9 | * Threat model: protects secrets at rest and from a different origin's page. It does |
| 10 | * not defend against malware running as you while the vault is unlocked. |
| 11 | */ |
| 12 | |
| 13 | import { createCipheriv, createDecipheriv, randomBytes, randomUUID, scrypt, timingSafeEqual } from "node:crypto"; |
| 14 | import { chmod, readFile, rename, writeFile } from "node:fs/promises"; |
| 15 | |
| 16 | export interface Credential { |
| 17 | id: string; |
| 18 | /** Normalized origin, e.g. "https://askrobots.com". */ |
| 19 | origin: string; |
| 20 | username: string; |
| 21 | password: string; |
| 22 | notes?: string; |
| 23 | createdAt: number; |
| 24 | updatedAt: number; |
| 25 | } |
| 26 | |
| 27 | /** What you may hand to UI/logs: everything except the password. */ |
| 28 | export type CredentialSummary = Omit<Credential, "password" | "notes">; |
| 29 | |
| 30 | export type NewCredential = Pick<Credential, "origin" | "username" | "password"> & { notes?: string }; |
| 31 | |
| 32 | interface Envelope { |
| 33 | v: 1; |
| 34 | kdf: { name: "scrypt"; salt: string; N: number; r: number; p: number }; |
| 35 | iv: string; |
| 36 | tag: string; |
| 37 | data: string; // base64 ciphertext of JSON { entries: Credential[] } |
| 38 | } |
| 39 | |
| 40 | const KDF = { N: 2 ** 15, r: 8, p: 1 } as const; |
| 41 | const KEY_LEN = 32; |
| 42 | const MIN_MASTER = 8; |
| 43 | |
| 44 | export type VaultErrorCode = "locked" | "wrong-password" | "exists" | "missing" | "corrupt" | "weak-password" | "bad-origin" | "not-found"; |
| 45 | |
| 46 | export class VaultError extends Error { |
| 47 | readonly code: VaultErrorCode; |
| 48 | constructor(code: VaultErrorCode, message: string) { |
| 49 | super(message); |
| 50 | this.name = "VaultError"; |
| 51 | this.code = code; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | /** "https://Askrobots.com:443/login?x=1" → "https://askrobots.com". Throws on non-web URLs. */ |
| 56 | export function normalizeOrigin(input: string): string { |
| 57 | let u: URL; |
| 58 | try { |
| 59 | u = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `https://${input}`); |
| 60 | } catch { |
| 61 | throw new VaultError("bad-origin", `not a URL: ${input}`); |
| 62 | } |
| 63 | if (u.protocol !== "https:" && u.protocol !== "http:") { |
| 64 | throw new VaultError("bad-origin", `only http(s) origins can hold credentials, got ${u.protocol}`); |
| 65 | } |
| 66 | return u.origin; |
| 67 | } |
| 68 | |
| 69 | function deriveKey(master: string, salt: Buffer, p: { N: number; r: number; p: number }): Promise<Buffer> { |
| 70 | return new Promise((res, rej) => |
| 71 | scrypt(master, salt, KEY_LEN, { N: p.N, r: p.r, p: p.p, maxmem: 256 * p.N * p.r }, (e, k) => (e ? rej(e) : res(k))), |
| 72 | ); |
| 73 | } |
| 74 | |
| 75 | function seal(key: Buffer, entries: Credential[]): Pick<Envelope, "iv" | "tag" | "data"> { |
| 76 | const iv = randomBytes(12); |
| 77 | const c = createCipheriv("aes-256-gcm", key, iv); |
| 78 | const data = Buffer.concat([c.update(JSON.stringify({ entries }), "utf8"), c.final()]); |
| 79 | return { iv: iv.toString("base64"), tag: c.getAuthTag().toString("base64"), data: data.toString("base64") }; |
| 80 | } |
| 81 | |
| 82 | export class Vault { |
| 83 | readonly path: string; |
| 84 | private kdf: Envelope["kdf"]; |
| 85 | private entries: Credential[] = []; |
| 86 | private key: Buffer | null = null; |
| 87 | private constructor(path: string, kdf: Envelope["kdf"]) { |
| 88 | this.path = path; |
| 89 | this.kdf = kdf; |
| 90 | } |
| 91 | |
| 92 | /** Create a new vault file. Refuses to overwrite an existing one. */ |
| 93 | static async create(path: string, master: string): Promise<Vault> { |
| 94 | if (master.length < MIN_MASTER) throw new VaultError("weak-password", `master password must be at least ${MIN_MASTER} characters`); |
| 95 | if (await Vault.exists(path)) throw new VaultError("exists", `vault already exists at ${path}`); |
| 96 | const kdf = { name: "scrypt" as const, salt: randomBytes(16).toString("base64"), ...KDF }; |
| 97 | const v = new Vault(path, kdf); |
| 98 | v.key = await deriveKey(master, Buffer.from(kdf.salt, "base64"), kdf); |
| 99 | await v.save(); |
| 100 | return v; |
| 101 | } |
| 102 | |
| 103 | /** Open and decrypt. Throws "wrong-password" on a bad master password. */ |
| 104 | static async unlock(path: string, master: string): Promise<Vault> { |
| 105 | let env: Envelope; |
| 106 | try { |
| 107 | env = JSON.parse(await readFile(path, "utf8")) as Envelope; |
| 108 | } catch (e) { |
| 109 | if ((e as NodeJS.ErrnoException).code === "ENOENT") throw new VaultError("missing", `no vault at ${path}`); |
| 110 | throw new VaultError("corrupt", `unreadable vault file: ${(e as Error).message}`); |
| 111 | } |
| 112 | if (env.v !== 1 || env.kdf?.name !== "scrypt") throw new VaultError("corrupt", "unsupported vault format"); |
| 113 | const key = await deriveKey(master, Buffer.from(env.kdf.salt, "base64"), env.kdf); |
| 114 | try { |
| 115 | const d = createDecipheriv("aes-256-gcm", key, Buffer.from(env.iv, "base64")); |
| 116 | d.setAuthTag(Buffer.from(env.tag, "base64")); |
| 117 | const json = Buffer.concat([d.update(Buffer.from(env.data, "base64")), d.final()]).toString("utf8"); |
| 118 | const v = new Vault(path, env.kdf); |
| 119 | v.key = key; |
| 120 | v.entries = (JSON.parse(json) as { entries: Credential[] }).entries; |
| 121 | return v; |
| 122 | } catch { |
| 123 | // GCM auth failure: either the wrong key or a tampered file — indistinguishable by design. |
| 124 | throw new VaultError("wrong-password", "wrong master password (or the vault file was modified)"); |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | static async exists(path: string): Promise<boolean> { |
| 129 | try { |
| 130 | await readFile(path); |
| 131 | return true; |
| 132 | } catch { |
| 133 | return false; |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | get unlocked(): boolean { |
| 138 | return this.key !== null; |
| 139 | } |
| 140 | |
| 141 | /** Forget the key and decrypted entries. The instance is unusable afterwards. */ |
| 142 | lock(): void { |
| 143 | this.key?.fill(0); |
| 144 | this.key = null; |
| 145 | this.entries = []; |
| 146 | } |
| 147 | |
| 148 | private need(): Buffer { |
| 149 | if (!this.key) throw new VaultError("locked", "vault is locked"); |
| 150 | return this.key; |
| 151 | } |
| 152 | |
| 153 | private async save(): Promise<void> { |
| 154 | const key = this.need(); |
| 155 | const env: Envelope = { v: 1, kdf: this.kdf, ...seal(key, this.entries) }; |
| 156 | // Write-then-rename so a crash never leaves a half-written (undecryptable) vault. |
| 157 | const tmp = `${this.path}.tmp`; |
| 158 | await writeFile(tmp, JSON.stringify(env), { mode: 0o600 }); |
| 159 | await rename(tmp, this.path); |
| 160 | await chmod(this.path, 0o600).catch(() => {}); |
| 161 | } |
| 162 | |
| 163 | /** Add — or, if (origin, username) already exists, update the password in place. */ |
| 164 | async add(c: NewCredential): Promise<CredentialSummary> { |
| 165 | this.need(); |
| 166 | const origin = normalizeOrigin(c.origin); |
| 167 | const now = Date.now(); |
| 168 | let e = this.entries.find((x) => x.origin === origin && x.username === c.username); |
| 169 | if (e) { |
| 170 | e.password = c.password; |
| 171 | if (c.notes !== undefined) e.notes = c.notes; |
| 172 | e.updatedAt = now; |
| 173 | } else { |
| 174 | e = { id: randomUUID(), origin, username: c.username, password: c.password, ...(c.notes !== undefined ? { notes: c.notes } : {}), createdAt: now, updatedAt: now }; |
| 175 | this.entries.push(e); |
| 176 | } |
| 177 | await this.save(); |
| 178 | return summarize(e); |
| 179 | } |
| 180 | |
| 181 | /** Metadata for every entry (no secrets), sorted by origin then username. */ |
| 182 | list(): CredentialSummary[] { |
| 183 | this.need(); |
| 184 | return this.entries.map(summarize).sort((a, b) => a.origin.localeCompare(b.origin) || a.username.localeCompare(b.username)); |
| 185 | } |
| 186 | |
| 187 | /** Entries whose origin EXACTLY equals the page's origin. Summaries only. */ |
| 188 | find(url: string): CredentialSummary[] { |
| 189 | this.need(); |
| 190 | let origin: string; |
| 191 | try { |
| 192 | origin = normalizeOrigin(url); |
| 193 | } catch { |
| 194 | return []; |
| 195 | } |
| 196 | return this.list().filter((e) => e.origin === origin); |
| 197 | } |
| 198 | |
| 199 | /** The secret. Callers must have already matched the origin (see find). */ |
| 200 | get(id: string): Credential { |
| 201 | this.need(); |
| 202 | const e = this.entries.find((x) => x.id === id); |
| 203 | if (!e) throw new VaultError("not-found", `no credential ${id}`); |
| 204 | return { ...e }; |
| 205 | } |
| 206 | |
| 207 | /** Secret for a page, only if its origin matches exactly. Never cross-origin. */ |
| 208 | getFor(url: string, id: string): Credential { |
| 209 | const c = this.get(id); |
| 210 | if (normalizeOrigin(url) !== c.origin) throw new VaultError("bad-origin", `credential is for ${c.origin}, not ${normalizeOrigin(url)}`); |
| 211 | return c; |
| 212 | } |
| 213 | |
| 214 | async remove(id: string): Promise<void> { |
| 215 | this.need(); |
| 216 | const n = this.entries.length; |
| 217 | this.entries = this.entries.filter((e) => e.id !== id); |
| 218 | if (this.entries.length === n) throw new VaultError("not-found", `no credential ${id}`); |
| 219 | await this.save(); |
| 220 | } |
| 221 | |
| 222 | /** Re-encrypt under a new master password (fresh salt). */ |
| 223 | async changeMaster(next: string): Promise<void> { |
| 224 | this.need(); |
| 225 | if (next.length < MIN_MASTER) throw new VaultError("weak-password", `master password must be at least ${MIN_MASTER} characters`); |
| 226 | this.kdf = { name: "scrypt", salt: randomBytes(16).toString("base64"), ...KDF }; |
| 227 | this.key?.fill(0); |
| 228 | this.key = await deriveKey(next, Buffer.from(this.kdf.salt, "base64"), this.kdf); |
| 229 | await this.save(); |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | function summarize(e: Credential): CredentialSummary { |
| 234 | const { password: _p, notes: _n, ...rest } = e; |
| 235 | return rest; |
| 236 | } |
| 237 | |
| 238 | const SETS = { |
| 239 | lower: "abcdefghijkmnopqrstuvwxyz", // no l |
| 240 | upper: "ABCDEFGHJKLMNPQRSTUVWXYZ", // no I, O |
| 241 | digit: "23456789", // no 0, 1 |
| 242 | symbol: "!@#$%^&*-_=+?", |
| 243 | } as const; |
| 244 | |
| 245 | /** Cryptographically random password with at least one of each class. */ |
| 246 | export function generatePassword(length = 20, opts: { symbols?: boolean } = {}): string { |
| 247 | const sets = [SETS.lower, SETS.upper, SETS.digit, ...(opts.symbols === false ? [] : [SETS.symbol])]; |
| 248 | if (length < sets.length) throw new RangeError(`length must be at least ${sets.length}`); |
| 249 | const all = sets.join(""); |
| 250 | const pick = (chars: string) => chars[randomInt(chars.length)]!; |
| 251 | const out = sets.map(pick); |
| 252 | while (out.length < length) out.push(pick(all)); |
| 253 | for (let i = out.length - 1; i > 0; i--) { |
| 254 | const j = randomInt(i + 1); |
| 255 | [out[i], out[j]] = [out[j]!, out[i]!]; |
| 256 | } |
| 257 | return out.join(""); |
| 258 | } |
| 259 | |
| 260 | // Unbiased random int in [0, n) via rejection sampling. |
| 261 | function randomInt(n: number): number { |
| 262 | const max = Math.floor(0x1_0000_0000 / n) * n; |
| 263 | for (;;) { |
| 264 | const x = randomBytes(4).readUInt32BE(0); |
| 265 | if (x < max) return x % n; |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | /** Constant-time string compare (used by callers comparing tokens). */ |
| 270 | export function safeEqual(a: string, b: string): boolean { |
| 271 | const x = Buffer.from(a), y = Buffer.from(b); |
| 272 | return x.length === y.length && timingSafeEqual(x, y); |
| 273 | } |