// Custos's background script (docs/BROWSER.md): an event page in Firefox, a service worker in Edge and Chrome. // It owns the connection to the native host and answers the content scripts and the popup. The origins it sends // to Custos are always the browser's (`sender.url` of the frame, `sender.tab.url` of its page), never what a page // says about itself; Custos decides which logins belong there. // // It keeps no secret at rest: nothing goes to `storage`, and a login offered for saving waits in memory only, for // its tab, until it is saved, dismissed or three minutes old. const api = globalThis.browser ?? globalThis.chrome; const HOST = 'cz.marek_novak.custos'; const SAVE_KEPT_MS = 3 * 60_000; /** Which browser this is, for Custos's card (a label only: the host knows Firefox from its arguments). */ function browserHint() { const brands = (globalThis.navigator?.userAgentData?.brands ?? []).map((b) => b.brand); if (brands.includes('Microsoft Edge')) return 'edge'; if (brands.includes('Google Chrome')) return 'chrome'; return null; } /** The native host, connected on first use; the browser keeps the background alive while it is open. */ let port = null; let seq = 0; const waiting = new Map(); function connect() { if (port) return port; port = api.runtime.connectNative(HOST); port.onMessage.addListener((msg) => { const w = waiting.get(msg?.seq); if (!w) return; waiting.delete(msg.seq); w(msg); }); port.onDisconnect.addListener((p) => { // Not registered, or the host exited: every open request fails the same way. const why = `${p?.error?.message ?? api.runtime.lastError?.message ?? ''}`; const error = /not found|forbidden|no such native application|not allowed/i.test(why) ? 'not_connected' : 'not_running'; for (const w of waiting.values()) w({ ok: false, error }); waiting.clear(); port = null; }); return port; } function ask(request) { return new Promise((resolve) => { const n = ++seq; waiting.set(n, resolve); try { connect().postMessage({ ...request, browser: browserHint(), seq: n }); } catch { waiting.delete(n); resolve({ ok: false, error: 'not_connected' }); } // Custos may wait up to a minute for an unlock or an answer on its card. setTimeout(() => { if (waiting.delete(n)) resolve({ ok: false, error: 'no_answer' }); }, 75_000); }); } /** `scheme://host[:port]` of a page or frame URL; null for anything Custos never fills. */ function originOf(url) { try { const u = new URL(url); if (u.protocol !== 'https:' && u.protocol !== 'http:') return null; return u.origin; } catch { return null; } } /** * The frame's origin and its page's, from what the browser says about the sender. Null when either is unknown, * or when the frame's real origin is not its URL's (a sandboxed frame has an opaque origin: it gets nothing). */ function placeOf(sender) { const origin = originOf(sender.url); if (!origin) return null; if (typeof sender.origin === 'string' && sender.origin !== origin) return null; const top = sender.frameId === 0 ? origin : originOf(sender.tab?.url); if (!top) return null; return { origin, top }; } // ---- logins offered for saving: in memory, per tab ---- const offers = new Map(); function offerFor(tabId) { const o = offers.get(tabId); if (o && Date.now() - o.at > SAVE_KEPT_MS) offers.delete(tabId); return offers.get(tabId) ?? null; } function showBadge(tabId) { const on = !!offerFor(tabId); Promise.resolve(api.action.setBadgeText({ tabId, text: on ? '1' : '' })).catch(() => {}); if (on) Promise.resolve(api.action.setBadgeBackgroundColor({ tabId, color: '#c9a96e' })).catch(() => {}); } api.tabs.onRemoved.addListener((tabId) => offers.delete(tabId)); /** What the popup and the page may see of an offer: never its password. */ const offerView = (o) => (o ? { host: new URL(o.origin).host, username: o.username } : null); async function save(tabId) { const o = offerFor(tabId); if (!o) return { ok: false, error: 'gone' }; offers.delete(tabId); showBadge(tabId); const r = await ask({ op: 'browser_save', origin: o.origin, top: o.top, username: o.username, password: o.password, title: o.title }); o.password = ''; return r; } async function activeTab() { const [tab] = await api.tabs.query({ active: true, currentWindow: true }); return tab ?? null; } // ---- messages from the content scripts and the popup ---- async function handle(msg, sender) { switch (msg?.kind) { case 'status': return ask({ op: 'browser_status' }); case 'match': { // From a content script: the logins for the frame it runs in, on its page. const at = placeOf(sender); if (!at) return { ok: false, error: 'no_match' }; return { ...(await ask({ op: 'browser_match', ...at })), origin: at.origin }; } case 'fill': case 'totp': { // The secrets go back to the frame that asked, and only if Custos agrees the login belongs there. const at = placeOf(sender); if (!at || typeof msg.id !== 'string') return { ok: false, error: 'no_match' }; return ask({ op: msg.kind === 'fill' ? 'browser_fill' : 'browser_totp', id: msg.id, ...at }); } case 'offer-save': { // A login form was sent with a password Custos did not fill: keep it for this tab until the person decides. const at = placeOf(sender); const tabId = sender.tab?.id; if (!at || tabId == null || typeof msg.password !== 'string' || !msg.password || msg.password.length > 4096) { return { ok: false, error: 'bad_request' }; } const username = typeof msg.username === 'string' ? msg.username.slice(0, 1024) : ''; const title = new URL(at.origin).host; offers.set(tabId, { ...at, username, password: msg.password, title, at: Date.now() }); showBadge(tabId); // The open connection keeps a service worker (Edge, Chrome) alive, and the offer with it. void ask({ op: 'browser_status' }); return { ok: true, offer: offerView(offers.get(tabId)) }; } case 'pending-save': { // The top page of the tab that sent the form, on the same site, asks whether to show the offer. const at = placeOf(sender); const o = sender.tab?.id != null ? offerFor(sender.tab.id) : null; if (!at || !o || sender.frameId !== 0 || at.top !== o.top) return { ok: true, offer: null }; return { ok: true, offer: offerView(o) }; } case 'save': // From the page's own offer: its tab's offer only. if (sender.tab?.id == null || sender.frameId !== 0) return { ok: false, error: 'bad_request' }; return save(sender.tab.id); case 'dismiss-save': if (sender.tab?.id != null) { offers.delete(sender.tab.id); showBadge(sender.tab.id); } return { ok: true }; case 'match-tab': { // From the popup: the logins for the active tab's page, and any login offered for saving there. const tab = await activeTab(); const origin = tab && originOf(tab.url); const offer = tab ? offerView(offerFor(tab.id)) : null; if (!origin) return { ok: false, error: 'no_match', tab: tab?.id ?? null, offer }; return { ...(await ask({ op: 'browser_match', origin, top: origin })), origin, tab: tab.id, offer }; } case 'totp-tab': { // From the popup: one login's 2FA code for the active tab's page. const tab = await activeTab(); const origin = tab && originOf(tab.url); if (!origin || typeof msg.id !== 'string') return { ok: false, error: 'no_match' }; return ask({ op: 'browser_totp', id: msg.id, origin, top: origin }); } case 'save-tab': { const tab = await activeTab(); return tab ? save(tab.id) : { ok: false, error: 'gone' }; } case 'dismiss-tab': { const tab = await activeTab(); if (tab) { offers.delete(tab.id); showBadge(tab.id); } return { ok: true }; } default: return { ok: false, error: 'bad_request' }; } } api.runtime.onMessage.addListener((msg, sender, reply) => { // Only this extension's own pages and content scripts reach here; pages and other extensions cannot. if (sender.id !== api.runtime.id) return false; handle(msg, sender).then(reply, () => reply({ ok: false, error: 'bad_request' })); return true; });