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
site icons (favicons) in tabs, address bar suggestions and the bookmarks panel
7249579
15 hours, 50 minutes ago
History
vault-service.ts · 7.7 KB · 193 lines
| 1 | /** |
| 2 | * Main-process glue between @dbbasic/vault and the browser. |
| 3 | * |
| 4 | * Design rule: secrets never enter the chrome UI's renderer. The page's preload sends a |
| 5 | * submitted login straight to us; we hold it in memory as a pending offer and the UI |
| 6 | * only learns "there is something to save for <origin>". Filling is the reverse — the UI |
| 7 | * says "fill credential X into tab Y" and we deliver it to that page ourselves, after |
| 8 | * checking the page's REAL origin (webContents.getURL), never one supplied by the UI. |
| 9 | */ |
| 10 | |
| 11 | import { ipcMain, webContents, type BrowserWindow, type WebContents } from "electron"; |
| 12 | import { Vault, VaultError, generatePassword, normalizeOrigin, type CredentialSummary } from "@dbbasic/vault"; |
| 13 | |
| 14 | const IDLE_LOCK_MS = 10 * 60_000; |
| 15 | const PENDING_TTL_MS = 2 * 60_000; |
| 16 | |
| 17 | export type VaultResult<T> = { ok: true; data: T } | { ok: false; code: string; message: string }; |
| 18 | |
| 19 | interface Pending { |
| 20 | origin: string; |
| 21 | username: string; |
| 22 | password: string; |
| 23 | at: number; |
| 24 | } |
| 25 | |
| 26 | export interface VaultState { |
| 27 | exists: boolean; |
| 28 | unlocked: boolean; |
| 29 | count: number | null; |
| 30 | } |
| 31 | |
| 32 | export interface VaultService { |
| 33 | state(): Promise<VaultState>; |
| 34 | fill(wcId: number, id: string | undefined, submit: boolean): Promise<VaultResult<{ username: string; origin: string }>>; |
| 35 | /** Unlock for automation without a UI prompt (master from env). */ |
| 36 | unlock(master: string): Promise<VaultResult<VaultState>>; |
| 37 | } |
| 38 | |
| 39 | async function wrap<T>(fn: () => Promise<T> | T): Promise<VaultResult<T>> { |
| 40 | try { |
| 41 | return { ok: true, data: await fn() }; |
| 42 | } catch (e) { |
| 43 | if (e instanceof VaultError) return { ok: false, code: e.code, message: e.message }; |
| 44 | return { ok: false, code: "error", message: e instanceof Error ? e.message : String(e) }; |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | export function registerVault(opts: { path: string; getWindow: () => BrowserWindow | null }): VaultService { |
| 49 | let vault: Vault | null = null; |
| 50 | let lockTimer: NodeJS.Timeout | undefined; |
| 51 | const pending = new Map<number, Pending>(); // keyed by guest webContents id |
| 52 | |
| 53 | const win = () => opts.getWindow(); |
| 54 | const isOurGuest = (wc: WebContents | undefined): wc is WebContents => { |
| 55 | const w = win(); |
| 56 | return !!wc && !wc.isDestroyed() && wc.getType() === "webview" && !!w && wc.hostWebContents === w.webContents; |
| 57 | }; |
| 58 | const need = (): Vault => { |
| 59 | if (!vault?.unlocked) throw new VaultError("locked", "vault is locked"); |
| 60 | touch(); |
| 61 | return vault; |
| 62 | }; |
| 63 | |
| 64 | async function state(): Promise<VaultState> { |
| 65 | return { exists: await Vault.exists(opts.path), unlocked: !!vault?.unlocked, count: vault?.unlocked ? vault.list().length : null }; |
| 66 | } |
| 67 | const push = async () => win()?.webContents.send("vault:state", await state()); |
| 68 | |
| 69 | function lock(): void { |
| 70 | clearTimeout(lockTimer); |
| 71 | vault?.lock(); |
| 72 | vault = null; |
| 73 | void push(); |
| 74 | } |
| 75 | function touch(): void { |
| 76 | clearTimeout(lockTimer); |
| 77 | lockTimer = setTimeout(lock, IDLE_LOCK_MS); // idle auto-lock |
| 78 | } |
| 79 | const adopt = async (v: Vault) => { |
| 80 | vault = v; |
| 81 | touch(); |
| 82 | await push(); |
| 83 | return state(); |
| 84 | }; |
| 85 | |
| 86 | const originOf = (wc: WebContents) => { |
| 87 | try { |
| 88 | return normalizeOrigin(wc.getURL()); |
| 89 | } catch { |
| 90 | return null; // about:blank, file:, … — never has credentials |
| 91 | } |
| 92 | }; |
| 93 | |
| 94 | // ---- from the chrome UI -------------------------------------------------- |
| 95 | ipcMain.handle("vault:state", () => state()); |
| 96 | ipcMain.handle("vault:create", (_e, master: string) => wrap(async () => adopt(await Vault.create(opts.path, String(master))))); |
| 97 | ipcMain.handle("vault:unlock", (_e, master: string) => wrap(async () => adopt(await Vault.unlock(opts.path, String(master))))); |
| 98 | ipcMain.handle("vault:lock", () => lock()); |
| 99 | ipcMain.handle("vault:list", (_e, wcId?: number) => |
| 100 | wrap(() => { |
| 101 | const v = need(); |
| 102 | if (wcId == null) return v.list(); |
| 103 | const wc = webContents.fromId(wcId); |
| 104 | const origin = isOurGuest(wc) ? originOf(wc) : null; |
| 105 | return origin ? v.find(origin) : []; |
| 106 | }), |
| 107 | ); |
| 108 | ipcMain.handle("vault:generate", (_e, len?: number) => generatePassword(Math.min(Math.max(Number(len) || 20, 8), 64))); |
| 109 | ipcMain.handle("vault:remove", (_e, id: string) => wrap(async () => { await need().remove(String(id)); await push(); })); |
| 110 | |
| 111 | // Manual add for the page in tab `wcId` (origin comes from the page, not the UI). |
| 112 | ipcMain.handle("vault:add", (_e, a: { wcId: number; username: string; password: string }) => |
| 113 | wrap(async () => { |
| 114 | const wc = webContents.fromId(a.wcId); |
| 115 | const origin = isOurGuest(wc) ? originOf(wc) : null; |
| 116 | if (!origin) throw new VaultError("bad-origin", "this page can't hold credentials"); |
| 117 | const s = await need().add({ origin, username: String(a.username), password: String(a.password) }); |
| 118 | await push(); |
| 119 | return s; |
| 120 | }), |
| 121 | ); |
| 122 | |
| 123 | ipcMain.handle("vault:accept", (_e, wcId: number) => |
| 124 | wrap(async () => { |
| 125 | const p = pending.get(wcId); |
| 126 | if (!p || Date.now() - p.at > PENDING_TTL_MS) throw new VaultError("not-found", "nothing to save (offer expired)"); |
| 127 | const s = await need().add({ origin: p.origin, username: p.username, password: p.password }); |
| 128 | pending.delete(wcId); |
| 129 | await push(); |
| 130 | return s; |
| 131 | }), |
| 132 | ); |
| 133 | ipcMain.handle("vault:dismiss", (_e, wcId: number) => void pending.delete(wcId)); |
| 134 | ipcMain.handle("vault:fill", (_e, a: { wcId: number; id: string; submit?: boolean }) => fill(a.wcId, a.id, !!a.submit)); |
| 135 | |
| 136 | // ---- from the pages (guest preload) -------------------------------------- |
| 137 | ipcMain.on("vault:form", (e) => { |
| 138 | const wc = e.sender; |
| 139 | if (!isOurGuest(wc) || !vault?.unlocked) return; |
| 140 | const origin = originOf(wc); |
| 141 | const matches = origin ? vault.find(origin) : []; |
| 142 | if (matches.length) win()?.webContents.send("vault:offer", { kind: "fill", wcId: wc.id, origin, matches }); |
| 143 | }); |
| 144 | |
| 145 | ipcMain.on("vault:submit", async (e, p: { username?: string; password?: string }) => { |
| 146 | const wc = e.sender; |
| 147 | if (!isOurGuest(wc) || !p?.password) return; |
| 148 | const origin = originOf(wc); |
| 149 | if (!origin) return; |
| 150 | const username = String(p.username ?? ""); |
| 151 | const password = String(p.password); |
| 152 | |
| 153 | let mode: "new" | "update" | "locked" | "no-vault" = "new"; |
| 154 | if (!(await Vault.exists(opts.path))) mode = "no-vault"; |
| 155 | else if (!vault?.unlocked) mode = "locked"; |
| 156 | else { |
| 157 | const existing = vault.find(origin).find((c) => c.username === username); |
| 158 | if (existing) { |
| 159 | if (vault.get(existing.id).password === password) return; // already saved, nothing to offer |
| 160 | mode = "update"; |
| 161 | } |
| 162 | } |
| 163 | pending.set(wc.id, { origin, username, password, at: Date.now() }); |
| 164 | setTimeout(() => { |
| 165 | const cur = pending.get(wc.id); |
| 166 | if (cur && Date.now() - cur.at >= PENDING_TTL_MS) pending.delete(wc.id); |
| 167 | }, PENDING_TTL_MS + 1000); |
| 168 | win()?.webContents.send("vault:offer", { kind: "save", wcId: wc.id, origin, username, mode }); |
| 169 | }); |
| 170 | |
| 171 | async function fill(wcId: number, id: string | undefined, submit: boolean) { |
| 172 | return wrap(() => { |
| 173 | const wc = webContents.fromId(wcId); |
| 174 | if (!isOurGuest(wc)) throw new VaultError("not-found", "no such tab"); |
| 175 | const v = need(); |
| 176 | const origin = originOf(wc); |
| 177 | if (!origin) throw new VaultError("bad-origin", "this page can't hold credentials"); |
| 178 | let credId = id; |
| 179 | if (!credId) { |
| 180 | const m = v.find(origin); |
| 181 | if (m.length !== 1) throw new VaultError("not-found", m.length ? `${m.length} saved logins match — pass an id` : "no saved login for this site"); |
| 182 | credId = m[0]!.id; |
| 183 | } |
| 184 | const c = v.getFor(wc.getURL(), credId); // throws if the credential is for another origin |
| 185 | wc.send("vault:fill", { origin: c.origin, username: c.username, password: c.password, submit }); |
| 186 | return { username: c.username, origin: c.origin }; |
| 187 | }); |
| 188 | } |
| 189 | |
| 190 | return { state, fill, unlock: (m) => wrap(async () => adopt(await Vault.unlock(opts.path, m))) }; |
| 191 | } |
| 192 | |
| 193 | export type { CredentialSummary }; |