/** * messages.ts — the only background message handler. * * All `chrome.runtime.onMessage` handling for the service worker lives here. * Do not handle messages inline in entry.ts, alarms.ts, or any other * background file. Every background-bound MessageType in shared/types.ts * must have a case below. Content-script-bound message types (PING, * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and * intentionally have no case here — they are sent *to* content scripts. */ import { copyToClipboard, getEffectiveClearSeconds } from "./clipboard"; import { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts"; import { extractDomain } from "../shared/domain"; import { getPendingVouchedDevice, listPendingVouchedDevices, removePendingVouchedDevice, } from "./pending-vouched-devices"; import { isRecoveryConfirmPending } from "./recovery-pending"; import { setupAutoLock, touchAutoLock } from "./alarms"; import { runSelfTest } from "./self-test"; import * as vault from "./vault"; import { handleEstimateCodexPages, handleGetCodexVaultData, handleRestoreFromCodex, } from "./codex-handlers"; import type { CodexRestorePayload } from "../shared/codex-types"; import { activateLicense, deactivateLicense, getLicenseInfo, getLicenseKey, isProUser, markCelebrationPlayed, shouldPlayCelebration, } from "./license"; import { completeFirefoxPasskeyCreate, getPasskeyProviderState, getPendingPasskeyRequest, handleFirefoxPasskeyCreate, handleFirefoxPasskeyGet, handlePasskeyHasCredentials, initiateFirefoxPasskeyCreate, isPasskeyOfferDeclined, onVaultUnlocked, recordPasskeyOfferDecline, resolvePendingPasskeyRequest, setPasskeyProviderEnabled, } from "./passkey"; import { buildAdvancedHealthReport } from "./health"; import { storageClear } from "../shared/storage"; import { findInvalidWords } from "../shared/recovery-words"; import type { Message, MessageResponse, MessageType, ProFeature, VaultEntry, } from "../shared/types"; import { isPasskeyOnly } from "../shared/types"; import { generateTOTP } from "../crypto/totp"; import { isValidRpId } from "../shared/passkey-utils"; import { predictBatch as mlPredictBatch } from "./ml"; import type { MLFieldFeatures } from "../shared/ml"; import { buildLocalIdentity, getOrCreateDeviceId, setDeviceName as setDeviceNameV3, } from "./device-identity"; import { isDeviceRevoked, listPairedDevices as listPairedDevicesV3, renamePairedDevice as renamePairedDeviceV3, revokeDeviceById as revokeDeviceByIdV3, upsertPairedDevice as upsertPairedDeviceV3, } from "./paired-devices"; // Sync and pairing are imported statically, never with `await import()`. // `import()` throws `TypeError: import() is disallowed on // ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper // reports the failure through `window.dispatchEvent`, which does not exist in // a worker either — so the real reason was replaced by "window is not defined" // and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails // the build if a runtime import() reappears anywhere in the worker's graph. import { cancelRelayAdoptionSource, isRelayAdoptionSourceInFlight, resolveSourceSasConfirmation, startRelayAdoptionReceiver, startRelayAdoptionSource, } from "./relay-adoption-bg"; import { getSyncSettings, setRelayUrl, setSyncMode, type SyncMode, } from "./sync-settings"; import { getSyncState, triggerSyncIfReachable, } from "./sync-trigger"; // Compile-time E2E flag, folded to a literal by Vite's `define` (false in // every production build — verified in the bundled output). Mirrors the // create-path bypass in passkey.ts so the Playwright passkey smoke can enable // the provider without a real Pro licence; the gate is fully intact for users. declare const __PEACH_E2E_PASSKEYS__: boolean; const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true; function unhexBytes(hex: string): Uint8Array { if (hex.length % 2 !== 0) throw new Error("invalid hex"); const out = new Uint8Array(hex.length / 2); for (let i = 0; i < out.length; i++) { out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); } return out; } /** * The single Pro gate. Every gated handler calls this first; the broadcast * lets the popup react (navigate to the License section, highlight the * relevant feature). Background never touches the popup view directly — * the popup owns navigation. See Projects.md "Pro gate rule". */ async function requirePro( feature: ProFeature, trigger: "user" | "background" = "user" ): Promise<{ allowed: boolean }> { if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true }; if (await isProUser()) return { allowed: true }; if (trigger === "user") { // User deliberately triggered this feature — redirect the popup immediately. chrome.runtime .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } }) .catch(() => { // Popup may be closed — the gate signal is best-effort. }); } else { // Background trigger (e.g. passive sync initiation) — no popup is open. // Queue a notice so the next popup open shows a soft banner instead of // silently failing. if (chrome.storage.session) { chrome.storage.session .set({ pendingProNotice: { feature, triggeredAt: Date.now() } }) .catch(() => {}); } } return { allowed: false }; } // --------------------------------------------------------------------------- // PCH-01-018: operations that irreversibly destroy or replace vault contents, // handlers that store passkey material, and handlers that return sensitive // credential material (e.g. the Pro license key). These are gated to trusted // extension-page senders in handleMessage; the confirmation UX otherwise // lives only in the popup. Keep this in sync when adding new destructive or // sensitive handlers. (Codex Security 2026-08-04: GET_ADOPTION_MATERIAL and // COMPLETE_PAIRING were gated here, then deleted outright — they had no // legitimate senders; adoption runs in-background via relay-adoption-bg.ts. // Audit 2026-08-20 #4: GET_LOCAL_IDENTITY gated here — it returns the Pro // license key, which a compromised content script could exfiltrate. // PB-26-001: GET_CODEX_VAULT_DATA gated here — it returns the encrypted vault // slots and (with a fresh password proof) the recovery words, i.e. everything // needed to reconstruct the root key. ESTIMATE_CODEX_PAGES is gated for // symmetry (it is popup-only and reveals vault size). const PRIVILEGED_MESSAGE_TYPES: ReadonlySet = new Set([ "DESTROY_VAULT", "CLEAR_VAULT_ENTRIES", "RESTORE_VAULT_SNAPSHOT", "RESTORE_FROM_CODEX", "COMPLETE_FIREFOX_PASSKEY_CREATE", "UNLOCK_WITH_PIN", "SETUP_PIN", "DISABLE_PIN", "GET_LOCAL_IDENTITY", "GET_CODEX_VAULT_DATA", "ESTIMATE_CODEX_PAGES", ]); // LV-3: minimum interval between non-test canary pings per webhook+entry. const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour const PRIVATE_IPV4_RANGES = [ { prefix: "10." }, { prefix: "127." }, { prefix: "169.254." }, { prefix: "192.168." }, ]; export function setupMessageHandler(): void { chrome.runtime.onMessage.addListener( (msg: unknown, sender, sendResponse) => { if (!isMessage(msg)) { sendResponse({ ok: false, error: "invalid_message" }); return true; } handleMessage(msg, sender) .then(sendResponse) .catch((err) => sendResponse({ ok: false, error: err instanceof Error ? err.message : String(err), }) ); return true; } ); } function isMessage(m: unknown): m is Message { return typeof m === "object" && m !== null && "type" in m; } /** * The browser-attested origin of the page that originated this message. A web * page cannot call chrome.runtime.sendMessage directly (no externally_connectable), * so every page-driven message arrives via the content-script relay and the * browser stamps `sender.origin`/`sender.url` with the real frame origin — a * value the page cannot forge. This is the ONLY trustworthy origin for passkey * rpId<->origin enforcement; payload-supplied origins are attacker-controlled. */ function attestedSenderOrigin(sender: Partial): string | undefined { if (sender.origin) return sender.origin; if (sender.url) { try { return new URL(sender.url).origin; } catch { return undefined; } } return undefined; } // Resolves once restoreFromSession() has run, so handlers see the correct // post-restore unlock state. entry.ts registers this BEFORE the message // handler so the onMessage listener is added synchronously at SW startup // (MV3 requirement) while unlock-dependent handlers still wait for restore. let restoreReady: Promise = Promise.resolve(); /** Called by entry.ts at startup with the in-flight restoreFromSession promise. */ export function setRestoreReady(p: Promise): void { restoreReady = p.then(() => undefined, () => undefined); } export async function handleMessage( msg: Message, sender: Partial = {} ): Promise { try { // Wait for session-restore to finish before reading any unlock/vault state. // On a cold SW start the popup's first message arrives while restore is // still in flight; without this gate IS_UNLOCKED would report locked (a // spurious lock screen) and the storage reads could race. The onMessage // listener itself is registered synchronously (entry.ts) so this gate, not // listener registration, is what absorbs the cold-start window. await restoreReady; // Validate sender — only allow messages from our extension pages/scripts. // `sender.id` is undefined for messages originating from extension UI // (popup/options), which is legitimate; reject only when it is defined // and does not match our extension id. if ( sender.id !== undefined && sender.id !== chrome.runtime.id ) { return { ok: false, error: "invalid_sender" }; } // PCH-01-018: destructive and sensitive operations must originate from a // trusted extension page (popup/options), never from a content script. The // sender.id check above only proves the message came from *our* extension — // a content script injected into an attacker page passes it. A single // XSS-class bug in the injected UI would otherwise escalate to vault // destruction, root-key exfiltration, or attacker device registration. // Extension pages carry an extension-origin sender.url; content scripts // carry a page URL. if (PRIVILEGED_MESSAGE_TYPES.has(msg.type)) { const extensionOrigin = chrome.runtime.getURL(""); if (!sender.url?.startsWith(extensionOrigin)) { return { ok: false, error: "invalid_sender" }; } } if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) { touchAutoLock(); } switch (msg.type) { case "CREATE_VAULT": { const { password } = msg.payload as { password: string }; // Refuse to create a vault under an empty master password — the derived // key would be publicly known and the at-rest AES-GCM protection void // (audit HIGH; the CSV-import path previously passed ""). Length/strength // policy lives in the onboarding UI; this is the non-negotiable floor. if (typeof password !== "string" || password.length === 0) { return { ok: false, error: "invalid_payload" }; } await vault.createVault(password); await setupAutoLock(); broadcastToContentScripts({ type: "VAULT_UNLOCKED" }); onVaultUnlocked(); return { ok: true }; } case "CREATE_VAULT_FROM_ROOT_KEY": { const { password, rootKeyHex } = (msg.payload ?? {}) as { password?: unknown; rootKeyHex?: unknown; }; if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") { return { ok: false, error: "invalid_payload" }; } try { const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex); await setupAutoLock(); broadcastToContentScripts({ type: "VAULT_UNLOCKED" }); onVaultUnlocked(); return { ok: true, vaultId }; } catch (err) { return { ok: false, error: err instanceof Error ? err.message : String(err) }; } } case "UNLOCK": { const { password } = msg.payload as { password: string }; const ok = await vault.unlock(password); if (ok) { // KAT: verify the WebCrypto stack is healthy before the user relies on it. // Runs after unlock so latency is hidden behind the vault-load time. const kat = await runSelfTest(); if (!kat.ok) { console.error("[Peach] Crypto self-test FAILED:", kat.error); await vault.lock(); return { ok: false, error: "self_test_failed" }; } await vault.updateSettings({ pinPreferred: false }); await setupAutoLock(); broadcastToContentScripts({ type: "VAULT_UNLOCKED" }); onVaultUnlocked(); return { ok: true }; } // Distinguish corruption from wrong password so the popup can offer // a history-restore path instead of falsely accusing the user of // mistyping (M7/COR-007). const failure = vault.consumeLastUnlockFailureReason(); if (failure) { return { ok: false, error: "vault_corrupted", canRestoreFromHistory: true, } as MessageResponse; } return { ok: false }; } case "UNLOCK_WITH_PIN": { const { pin } = (msg.payload ?? {}) as { pin?: unknown }; if (typeof pin !== "string") return { ok: false, error: "invalid_payload" }; const ok = await vault.unlockWithPin(pin); if (!ok) return { ok: false }; const kat = await runSelfTest(); if (!kat.ok) { await vault.lock(); return { ok: false, error: "self_test_failed" }; } await vault.updateSettings({ pinPreferred: true }); await setupAutoLock(); broadcastToContentScripts({ type: "VAULT_UNLOCKED" }); onVaultUnlocked(); return { ok: true }; } case "VALIDATE_RECOVERY_WORDS": { const { words } = msg.payload as { words: string[] }; const invalid = findInvalidWords(words); return { ok: true, data: { valid: invalid.length === 0, invalid } }; } case "GET_RECOVERY_WORDS": { // Must be unlocked and have recovery set up (vault must be v2.12+). if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; // LV-4: the recovery words re-derive the ROOT KEY — the highest- // value secret in the vault. A session unlock (which may be hours // old on a shared machine) is not enough; require a fresh password // proof, matching the 1Password/Bitwarden pattern for revealing // escrow material. EXEMPTION: the create-vault / rotation confirmation // window (peach_recovery_pending) shows the words immediately after // the user authenticated, and that confirmation UI has no password to // resend — skip the re-auth there only. if (!(await isRecoveryConfirmPending())) { const { password } = (msg.payload ?? {}) as { password?: string }; if (typeof password !== "string" || !password) { return { ok: false, error: "password_required" }; } if (!(await vault.verifyMainPassword(password))) { return { ok: false, error: "wrong_password" }; } } try { const words = await vault.getRecoveryWords(); return { ok: true, data: words }; } catch { return { ok: false, error: "recovery_not_setup" }; } } case "RECOVER_WITH_WORDS": { // User has lost their password but has their 12 recovery words. // We: (1) validate the words, (2) re-encrypt vault with new password. const { words, newPassword } = msg.payload as { words: string[]; newPassword: string; }; const stored = await vault.loadSlotA(); if (!stored) return { ok: false, error: "no_vault" }; if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) { return { ok: false, error: "recovery_not_setup" }; } // Unwrap the root key from the recovery escrow. try { await vault.unwrapRootKeyForRecovery( stored.recovery_wrapped_root_key, stored.recovery_nonce ?? "", stored.recovery_tag ?? "", stored.recovery_salt, words ); } catch { return { ok: false, error: "invalid_recovery_words" }; } // Re-key: derive fresh salt + key from new password. const newSalt = vault.generateSalt(); const newKey = await vault.deriveKey(newPassword, newSalt); // Re-wrap root key under the new password's derived key so the same // recovery words continue to work after the password change. await vault.rewrapRootKeyForPassword(newKey, newSalt); // Re-encrypt vault entries with the new key. await vault.changePasswordWithNewKey(newSalt, newKey); await setupAutoLock(); broadcastToContentScripts({ type: "VAULT_UNLOCKED" }); return { ok: true }; } case "LOCK": vault.lock(); return { ok: true }; case "IS_UNLOCKED": return { ok: true, data: vault.isUnlocked() }; case "GET_VAULT_STATUS": return { ok: true, unlocked: vault.isUnlocked() }; case "HAS_VAULT": return { ok: true, data: await vault.hasVault() }; case "GET_ENTRIES": if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; return { ok: true, data: vault.getEntries() }; case "ADD_ENTRY": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const payload = msg.payload; if (!payload || typeof payload !== "object" || Array.isArray(payload)) { return { ok: false, error: "invalid_payload" }; } const entry = await vault.addEntry(payload as Parameters[0]); return { ok: true, data: entry }; } case "BATCH_ADD_ENTRIES": { const payload = msg.payload as { entries?: unknown } | null | undefined; if (!payload || typeof payload !== "object" || Array.isArray(payload)) { return { ok: false, error: "invalid_payload" }; } if (!Array.isArray(payload.entries)) { return { ok: false, error: "invalid_payload" }; } const added = await vault.batchAddEntries(payload.entries as Parameters[0]); return { ok: true, data: added }; } case "RESTORE_ENTRIES": { const payload = msg.payload as | { entries?: unknown; mode?: unknown; settings?: unknown } | null | undefined; if (!payload || typeof payload !== "object" || Array.isArray(payload)) { return { ok: false, error: "invalid_payload" }; } if (!Array.isArray(payload.entries)) { return { ok: false, error: "invalid_payload" }; } if (payload.mode !== "replace" && payload.mode !== "merge") { return { ok: false, error: "invalid_payload" }; } const summary = await vault.restoreEntries( payload.entries as Parameters[0], payload.mode ); if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) { await vault.updateSettings(payload.settings as vault.VaultSettings); } return { ok: true, data: summary }; } case "CLEAR_VAULT_ENTRIES": { await vault.clearVaultEntries("REPLACE_ALL"); return { ok: true }; } case "GET_VAULT_HISTORY": { const snapshots = await vault.getVaultHistory(); return { ok: true, data: snapshots }; } case "RESTORE_VAULT_SNAPSHOT": { const { snapshotId } = msg.payload as { snapshotId: string }; const result = await vault.restoreVaultSnapshot(snapshotId); if (!result.ok) return { ok: false, error: result.error }; broadcastToContentScripts({ type: "VAULT_LOCKED" }); return { ok: true }; } case "COUNT_DUPLICATES": { return { ok: true, data: vault.countDuplicates() }; } case "DEDUPLICATE_ENTRIES": { const removed = await vault.deduplicateEntries(); return { ok: true, data: removed }; } case "UPDATE_ENTRY": { const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined; if (!payload || typeof payload !== "object" || Array.isArray(payload)) { return { ok: false, error: "invalid_payload" }; } const { id, patch } = payload; if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) { return { ok: false, error: "invalid_payload" }; } // Single enforcement point for the Canary Entries Pro gate. Only // gates the transition into a canary entry — clearing/disabling a // canary (`canary: undefined`) is always allowed, so existing // canary entries remain manageable. const incomingCanary = (patch as { canary?: unknown }).canary; if (incomingCanary && typeof incomingCanary === "object") { const existing = vault.getEntryById(id); if (!existing?.canary) { const gate = await requirePro("canary_entry"); if (!gate.allowed) return { ok: false, error: "pro_required" }; } } await vault.updateEntry(id, patch as Parameters[1]); return { ok: true }; } case "ADD_ADDITIONAL_URL": { const { id, url } = msg.payload as { id: string; url: string }; const trimmed = typeof url === "string" ? url.trim() : ""; if (!trimmed) return { ok: false, error: "url_required" }; const existing = vault.getEntryById(id); if (!existing) return { ok: false, error: "entry_not_found" }; if (existing.type !== "login") return { ok: false, error: "login_entries_only" }; const merged = [...(existing.additionalUrls ?? []), trimmed]; await vault.updateEntry(id, { additionalUrls: merged }); return { ok: true }; } case "DELETE_ENTRY": { const { id } = msg.payload as { id: string }; await vault.deleteEntry(id); return { ok: true }; } case "GET_DELETED_ENTRIES": return { ok: true, data: vault.getDeletedEntries() }; case "RESTORE_ENTRY": { const { id } = msg.payload as { id: string }; await vault.restoreEntry(id); return { ok: true }; } case "PURGE_ENTRY": { const { id } = msg.payload as { id: string }; await vault.purgeEntry(id); return { ok: true }; } case "PURGE_EXPIRED_TRASH": { const { retentionMs } = msg.payload as { retentionMs: number }; const purged = await vault.purgeExpiredTrash(retentionMs); return { ok: true, data: purged }; } case "SAVE_NOTE": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const { id, title, body } = msg.payload as { id?: string; title: string; body: string }; const now = Date.now(); if (id) { const existing = vault.getEntryById(id); if (!existing) return { ok: false, error: "not_found" }; await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now }); return { ok: true, data: vault.getEntryById(id) }; } else { // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt // (EntryDraft omits both), so passing them was the only reason the // `as any` cast existed. Dropping them makes the call type-check. const entry = await vault.addEntry({ type: "note", title: title || "Untitled", notes: body, }); return { ok: true, data: entry }; } } case "DELETE_NOTE": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const { id } = msg.payload as { id: string }; await vault.deleteEntry(id); return { ok: true }; } case "GET_NOTES": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const notes = vault.getEntries().filter( (e) => e.type === "note" && !e.deletedAt ); return { ok: true, data: notes } as MessageResponse; } case "SEARCH_VAULT": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; // AUD-002: shape-validate the payload before calling string methods. // A raw cast lets a malformed message crash the handler with TypeError. const { query } = (msg.payload ?? {}) as { query?: unknown }; if (typeof query !== "string") { return { ok: false, error: "invalid_payload" }; } const q = query.toLowerCase(); const searchResults = vault.getEntries().filter( (e) => !e.deletedAt && (e.title.toLowerCase().includes(q) || e.notes?.toLowerCase().includes(q) || e.username?.toLowerCase().includes(q)) ); return { ok: true, data: searchResults } as MessageResponse; } case "AUTOFILL_QUERY": { if (!vault.isUnlocked()) { return { ok: false, error: "vault_locked" }; } let { includeAll } = msg.payload as { includeAll?: boolean }; const { domain, kind, userGesture } = msg.payload as { domain: string; kind?: "login" | "card" | "totp"; userGesture?: boolean; }; // MV-2: the vault-wide inventory (every title/username/email/url) // may only leave the background on an explicit user gesture — the // user opening the search affordance — never on passive form focus. // userGesture is self-declared by our own content script; the value // of this gate is that PASSIVE code paths (which never set it) // cannot ship the inventory, shrinking what a compromised page that // merely triggers focus events can observe. if (includeAll && userGesture !== true) { includeAll = false; } // kind="card": return saved cards as compact summaries for the // inline card silver platter. Cards are not domain-scoped — every // saved card is a candidate on every checkout page — so domain is // ignored when kind === "card". if (kind === "card") { const cards = vault.getEntries().filter((e) => e.type === "card"); return { ok: true, data: cards.map((e) => ({ id: e.id, title: e.cardNickname || e.title, cardholderName: e.cardholderName, last4: e.last4, expMonth: e.expMonth, expYear: e.expYear, network: e.network, })), }; } if (kind === "totp") { const matches = ( includeAll ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card") : vault.queryDomain(domain) ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp)); return { ok: true, data: matches.map((e) => ({ id: e.id, title: e.title, username: e.username, email: e.email, url: e.url, hasTotp: true, })), }; } // The inline selector fills username+password into a form. Passkey- // only entries have no password to fill; sign-in for those goes // through the WebAuthn path instead. Filter them out everywhere so // the user doesn't see four "GitHub" rows that mostly do nothing. // Notes and cards never belonged here either. const matches = ( includeAll ? vault .getEntries() .filter((entry) => entry.type !== "note" && entry.type !== "card") : vault.queryDomain(domain) ).filter((entry) => !isPasskeyOnly(entry)); return { ok: true, data: matches.map((e) => includeAll ? { id: e.id, title: e.title, // username/email/url shipped so the inline popup's search // affordance can match on them, not just titles. No secrets // cross the boundary — same shape as the domain-matched // response below minus hasTotp (which the search list // doesn't surface). username: e.username, email: e.email, url: e.url, hasPasskey: e.passkey !== undefined, } : { id: e.id, title: e.title, username: e.username, email: e.email, url: e.url, hasTotp: Boolean(e.totp), hasPasskey: e.passkey !== undefined, } ), }; } case "GET_ENTRY_FOR_FILL": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const { id, explicitSummon } = msg.payload as { id: string; explicitSummon?: boolean; }; const entry = vault.getEntryById(id); if (!entry) return { ok: false, error: "entry_not_found" }; // Passkey-only entries (passkey credential, no password) cannot be // filled into a form — sign-in goes through the WebAuthn path. A // login that ALSO has a passkey is still fillable for its password. if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" }; // MV-1: re-validate the entry against the requesting frame's origin. // sender.url / sender.tab.url are browser-attested — a page cannot // forge them. PB-26-005: the FRAME url (sender.url) is authoritative // for an all_frames content script; the top-frame tab.url would // misattribute a cross-origin iframe's request to the top page. When // the request does not come from a tab at all (popup surfaces use // GET_ENTRY_FOR_EDIT, not this), refuse. if (sender.tab !== undefined || sender.url !== undefined) { let senderDomain: string | null = null; try { const rawUrl = sender.url ?? sender.tab?.url ?? ""; senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null; } catch { senderDomain = null; } if (!senderDomain) return { ok: false, error: "origin_unverified" }; const entryDomains = new Set(); const primary = extractDomain(entry.url ?? ""); if (primary) entryDomains.add(primary); for (const extra of entry.additionalUrls ?? []) { const d = extractDomain(extra); if (d) entryDomains.add(d); } // explicitSummon=true means the user actively picked this entry // from the cross-domain search affordance — an intentional // off-domain fill. Passive fill paths must stay domain-bound. if (explicitSummon !== true && !entryDomains.has(senderDomain)) { // Domain mismatch — refuse silently (no oracle about which ids exist). return { ok: false, error: "entry_not_found" }; } } // Strip the passkey credential AND the raw base32 TOTP seed from the // response. Content scripts never need either: the private key is the // authenticator's, and handing over the TOTP seed would let a // compromised content script mint valid codes indefinitely (SEV-3-C). // Generate the *current* 6-digit code here in the background and send // only that, plus the seconds left so the UI can render a countdown. // Also drop passwordHistory: filling needs only the *current* password. // Handing every past password to a content script during passive // autofill on an arbitrary page would widen the blast radius of a // compromised page far beyond the one credential being filled. const { passkey: _strippedPasskey, totp: seed, totpAlgorithm, totpDigits, totpPeriod, passwordHistory: _ph, ...safeEntry } = entry; let totpCode: string | undefined; let totpRemaining: number | undefined; if (seed) { try { // PCH-01-019: honour stored algorithm/digits/period (defaults apply // when these are undefined, i.e. RFC-default bare-seed entries). const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod); totpCode = generated.code; totpRemaining = generated.remaining; } catch { totpCode = undefined; } } return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } }; } // Trusted full-entry fetch for Peach's own inline-popup surfaces that // genuinely need the raw TOTP seed: the edit form (which re-saves the // seed and would otherwise wipe it) and nothing else. Unlike // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside // the inline popup, never during passive autofill on an arbitrary page. // The passkey credential is still stripped — the edit form never touches it. case "GET_ENTRY_FOR_EDIT": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const { id, explicitSummon } = msg.payload as { id: string; explicitSummon?: boolean; }; const entry = vault.getEntryById(id); if (!entry) return { ok: false, error: "entry_not_found" }; // PCH-01-006: re-validate the browser-attested sender origin, mirroring // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and // full password history — at least as sensitive as the fill response — so // the boundary must be enforced here, not only by UI reachability. Today // the sole caller is the popup (no sender.tab, so this is a structural // no-op), but a future tab-context caller or an id leak would otherwise // inherit a full-credential oracle. Unlike the fill path we SKIP (not // refuse) when no sender domain resolves, to keep the popup caller working. // PB-26-005: the frame url (sender.url) is authoritative over the // top-frame sender.tab.url — mirrors the fill path. if (sender.tab !== undefined || sender.url !== undefined) { let senderDomain: string | null = null; try { const rawUrl = sender.url ?? sender.tab?.url ?? ""; senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null; } catch { senderDomain = null; } if (senderDomain) { const entryDomains = new Set(); const primary = extractDomain(entry.url ?? ""); if (primary) entryDomains.add(primary); for (const extra of entry.additionalUrls ?? []) { const d = extractDomain(extra); if (d) entryDomains.add(d); } if (explicitSummon !== true && !entryDomains.has(senderDomain)) { return { ok: false, error: "entry_not_found" }; // no id oracle } } } const { passkey: _passkey, ...safeEntry } = entry; return { ok: true, data: safeEntry }; } case "COPY": { // AUD-002: shape-validate the payload before passing to the clipboard // helper. A raw cast lets a malformed message reach the clipboard API // with a non-string and throw. const { text, label, alreadyWritten } = (msg.payload ?? {}) as { text?: unknown; label?: unknown; alreadyWritten?: unknown; }; if (typeof text !== "string" || typeof label !== "string") { return { ok: false, error: "invalid_payload" }; } await copyToClipboard(text, label, Boolean(alreadyWritten)); return { ok: true, clearSeconds: getEffectiveClearSeconds() }; } case "CHECK_ALL_BREACHES": { const allEntries = vault.getEntries(); const results: Record = {}; for (const entry of allEntries) { if (entry.type === "note") continue; if (!entry.password) continue; results[entry.id] = await vault.checkBreach(entry.password); // Small delay — be a good citizen to the HIBP API await new Promise((r) => setTimeout(r, 200)); } // Persist any non-zero counts back to entries for (const [id, count] of Object.entries(results)) { const entry = vault.getEntryById(id); if (entry && (entry.breach ?? 0) !== count) { await vault.updateEntry(id, { breach: count > 0 ? count : undefined }); } } return { ok: true, data: results }; } case "GET_SETTINGS": return { ok: true, data: await vault.ensureSettingsLoaded() }; case "UPDATE_SETTINGS": { const patch = msg.payload; if (!patch || typeof patch !== "object" || Array.isArray(patch)) { return { ok: false, error: "invalid_payload" }; } await vault.updateSettings(patch as vault.VaultSettings); if (typeof (patch as Record).autoLockMinutes === "number") { await setupAutoLock(); if (vault.isUnlocked()) touchAutoLock(); } return { ok: true }; } case "SETUP_PIN": { const { currentPassword, pin } = (msg.payload ?? {}) as { currentPassword?: unknown; pin?: unknown; }; if (typeof currentPassword !== "string" || typeof pin !== "string") { return { ok: false, error: "invalid_payload" }; } return (await vault.setupPinUnlock(currentPassword, pin)) ? { ok: true } : { ok: false, error: "incorrect_current_password" }; } case "DISABLE_PIN": { const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown }; if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" }; return (await vault.disablePinUnlock(currentPassword)) ? { ok: true } : { ok: false, error: "incorrect_current_password" }; } case "GET_PENDING_PASSKEY": return { ok: true, data: await getPendingPasskeyRequest() }; case "APPROVE_PASSKEY": { const { requestId } = msg.payload as { requestId: number }; await resolvePendingPasskeyRequest(requestId, true); return { ok: true }; } case "DENY_PASSKEY": { const { requestId } = msg.payload as { requestId: number }; await resolvePendingPasskeyRequest(requestId, false); return { ok: true }; } case "GET_PASSKEY_PROVIDER_STATE": return { ok: true, data: await getPasskeyProviderState() }; case "SET_PASSKEY_PROVIDER_ENABLED": { const { enabled } = msg.payload as { enabled: boolean }; // Disabling is always free; gating fires only when a free user is // trying to turn passkey interception on. if (enabled) { const gate = await requirePro("passkeys"); if (!gate.allowed) return { ok: false, error: "pro_required" }; } return { ok: true, data: await setPasskeyProviderEnabled(enabled) }; } // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS // endpoint. Intentional product behavior — users configure their own // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private // IPs, and non-HTTPS schemes, but cannot defend against every DNS- // rebinding case. The UI under CanarySection (Entry.tsx) discloses to // users that the entry title leaves the device when the canary fires. case "FIRE_CANARY_PING": { // Canary alert fires unconditionally for any entry with canary: true. // The Pro gate only governs creation/flagging of canary entries; once // an entry is flagged, the alert path is a security property and must // never be license-gated. const { webhookUrl, entryTitle, trigger } = msg.payload as { webhookUrl: string; entryTitle: string; trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test"; }; if (!isAllowedCanaryWebhookUrl(webhookUrl)) { return { ok: false, error: "invalid_webhook_url" }; } // LV-3: debounce non-test pings per (webhook, entry) so a page that // strobes focus/fill events can't turn the canary into a request // firehose at the user's endpoint. Test pings are exempt — they are // explicit user clicks in the settings UI and are awaited for // feedback. The FIRST ping in a window always goes out, so the // dead-man's-switch property (canary fires on access) is preserved; // only repeats within the window are coalesced. if (trigger !== "test") { const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`; const stored = await chrome.storage.local.get(rlKey); const last = (stored as Record)[rlKey]; if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) { return { ok: true, data: { rateLimited: true } }; } await chrome.storage.local.set({ [rlKey]: Date.now() }); } const body = JSON.stringify({ event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed", entry: entryTitle, trigger, timestamp: new Date().toISOString(), source: "peach-extension", }); if (trigger === "test") { // Permitted outbound fetch: user-configured canary alert endpoint // (validated by isAllowedCanaryWebhookUrl above). This is the // only non-HIBP outbound call in the extension — see // Projects.md §3.7. Test pings are awaited so the UI can show // success/failure. try { const res = await fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body, }); return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` }; } catch (err) { return { ok: false, error: err instanceof Error ? err.message : "network_error" }; } } // Non-test triggers are fire-and-forget fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body, }).catch(() => {}); return { ok: true }; } case "ACTIVATE_LICENSE": { const { key } = msg.payload as { key: string }; const licenseInfo = await activateLicense(key); return { ok: true, data: licenseInfo }; } case "GET_LICENSE": { const licenseInfo = await getLicenseInfo(); return { ok: true, data: licenseInfo }; } case "GET_LICENSE_KEY": { const key = await getLicenseKey(); return { ok: true, data: key }; } case "DEACTIVATE_LICENSE": { await deactivateLicense(); return { ok: true }; } case "SHOULD_PLAY_CELEBRATION": { const should = await shouldPlayCelebration(); return { ok: true, data: should }; } case "MARK_CELEBRATION_PLAYED": { await markCelebrationPlayed(); return { ok: true }; } case "GET_CODEX_VAULT_DATA": { // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the // popup navigates to the License section without further coordination. // Also privileged-page-gated (PB-26-001), and recoveryWords inside the // snapshot additionally require a fresh master-password proof. const gate = await requirePro("codex"); if (!gate.allowed) return { ok: false, error: "pro_required" }; const { password } = (msg.payload ?? {}) as { password?: string }; return await handleGetCodexVaultData(password); } case "ESTIMATE_CODEX_PAGES": { const gate = await requirePro("codex"); if (!gate.allowed) return { ok: false, error: "pro_required" }; return await handleEstimateCodexPages(); } case "RESTORE_FROM_CODEX": { // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still // be able to restore a vault that was printed by a Pro user. // DO NOT add a Pro gate here. const payload = msg.payload as CodexRestorePayload; return await handleRestoreFromCodex(payload); } case "OPEN_PRO_GATE": { // Content script requests: open popup and navigate to License section. const { feature } = (msg.payload ?? {}) as { feature?: string }; if (chrome.storage.session) { await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } }); } try { await chrome.action.openPopup(); } catch { /* badge fallback */ } return { ok: true }; } case "OPEN_POPUP": { // Content script asks to open the trusted extension popup — used by the // inline locked bubble so the master password is entered in the popup, // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a // user gesture + Chrome 127+/Firefox; on failure the user clicks the // toolbar icon. The badge already signals Peach needs attention. // // Set a session flag so the popup knows it was opened for inline unlock // and should close itself once the vault is unlocked (returning the user // to the inline autofill selector on the page). if (chrome.storage.session) { await chrome.storage.session.set({ peach_inline_unlock: true }); } try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ } return { ok: true }; } case "OPEN_DETACHED_POPUP": { // A window created by the action popup and then orphaned with // window.close() is cascaded shut by Chrome, so the file-picker // flows (OS dialogs that dismiss the popup on focus loss) ask the SW // to open the standalone window instead — the SW has no window to be // associated with. The query string is allowlisted so this can never // open an arbitrary URL. const { route } = (msg.payload ?? {}) as { route?: string }; const search = route === "peachscript" ? "?restore=peachscript" : route === "csv" ? "?restore=csv" : route === "codex-pdf" ? "?codex=pdf" : null; if (!search) return { ok: false, error: "bad_route" }; try { const popupHtml = chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html"; await chrome.windows.create({ url: chrome.runtime.getURL(`${popupHtml}${search}`), type: "popup", width: 320, height: 550, }); return { ok: true, data: { detached: true } }; } catch { return { ok: false }; } } case "GET_IDENTITIES": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; return { ok: true, data: vault.getIdentities() }; } case "TOUCH_AUTO_LOCK": { // touchAutoLock() is already called by shouldRefreshAutoLock above; // this case just gives the popup a typed message to keep the session alive. return { ok: true }; } case "GET_ADVANCED_HEALTH_REPORT": { const gate = await requirePro("advanced_health"); if (!gate.allowed) return { ok: false, error: "pro_required" }; if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const report = await buildAdvancedHealthReport(vault.getEntries()); return { ok: true, data: report }; } case "IS_DURESS_ENABLED": { const enabled = await vault.isDuressEnabled(); return { ok: true, data: enabled }; } case "SETUP_DURESS": { // Single enforcement point for the Duress Vault Pro gate. Free users // who somehow reach this handler are rejected here; the popup also // pre-checks isPro() to avoid showing the setup form to free users, // but server-side is the actual security boundary. const gate = await requirePro("duress_vault"); if (!gate.allowed) return { ok: false, error: "pro_required" }; // MV3 service workers restart after inactivity, losing the in-memory // derived key. Detect this before calling setupDuress so the popup // can show a meaningful prompt to re-lock and re-unlock. if (!vault.isUnlocked()) return { ok: false, error: "session_expired" }; const { duressPassword } = msg.payload as { duressPassword: string }; await vault.setupDuress(duressPassword); return { ok: true }; } case "DISABLE_DURESS": { await vault.disableDuress(); return { ok: true }; } case "VERIFY_MAIN_PASSWORD": { const { password } = msg.payload as { password: string }; const ok = await vault.verifyMainPassword(password); return { ok: true, data: ok }; } case "CHANGE_PASSWORD": { const { currentPassword, newPassword } = msg.payload as { currentPassword: string; newPassword: string; }; const changed = await vault.changePassword(currentPassword, newPassword); return changed ? { ok: true } : { ok: false, error: "incorrect_current_password" }; } case "GET_SITE_PASSWORD_POLICY": { const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (!tab?.id) return { ok: true, data: null }; try { const response = await chrome.tabs.sendMessage(tab.id, { type: "GET_SITE_PASSWORD_POLICY", }); return (response as MessageResponse) ?? { ok: true, data: null }; } catch { return { ok: true, data: null }; } } case "RECORD_MANUAL_SUMMON": { const { domain } = msg.payload as { domain: string }; const settings = vault.getSettings(); const existing = settings.manualSummonDomains?.[domain]; const now = Date.now(); await vault.updateSettings({ manualSummonDomains: { ...settings.manualSummonDomains, [domain]: { firstSummonedAt: existing?.firstSummonedAt ?? now, summonCount: (existing?.summonCount ?? 0) + 1, lastSummonedAt: now, }, }, }); return { ok: true }; } case "DECLINE_CARD_SAVE": { const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string }; await vault.declineCardSaveOffer(last4, expMonth, expYear); return { ok: true }; } case "IS_CARD_DECLINED": { const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string }; const declined = await vault.isCardDeclined(last4, expMonth, expYear); return { ok: true, data: declined }; } case "INITIATE_FIREFOX_PASSKEY_CREATE": { const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as { rpId?: string; rpName?: string; userName?: string; userDisplayName?: string; }; if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" }; return await initiateFirefoxPasskeyCreate({ rpId, rpName: rpName ?? rpId, userName, userDisplayName, }, attestedSenderOrigin(sender)); } case "COMPLETE_FIREFOX_PASSKEY_CREATE": { const payload = msg.payload as Parameters[0] | undefined; if (!payload) return { ok: false, error: "missing_payload" }; return await completeFirefoxPasskeyCreate(payload); } case "PASSKEY_OFFER_DECLINE": { const { domain } = (msg.payload ?? {}) as { domain?: string }; if (!domain) return { ok: false, error: "domain_required" }; await recordPasskeyOfferDecline(domain); return { ok: true }; } case "GET_PASSKEY_OFFER_DECLINED": { const { domain } = (msg.payload ?? {}) as { domain?: string }; if (!domain) return { ok: false, error: "domain_required" }; return { ok: true, data: await isPasskeyOfferDeclined(domain) }; } case "PASSKEY_HAS_CREDENTIALS": { const payload = msg.payload as { rpId?: string; allowCredentials?: Array<{ id: string; type?: string }>; } | undefined; if (!payload?.rpId) return { ok: false, error: "rpid_required" }; return await handlePasskeyHasCredentials({ rpId: payload.rpId, allowCredentials: payload.allowCredentials ?? [], }, attestedSenderOrigin(sender)); } case "PASSKEY_CREATE": { const payload = msg.payload as Parameters[0] | undefined; if (!payload?.rpId || !payload?.userName) { return { ok: false, error: "rpid_and_username_required" }; } return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender)); } case "PASSKEY_GET": { const payload = msg.payload as Parameters[0] | undefined; if (!payload?.rpId) return { ok: false, error: "rpid_required" }; return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender)); } case "PASSKEY_AUTH_RESPONSE": { const { requestId, approved } = (msg.payload ?? {}) as { requestId?: string | number; approved?: boolean; }; if (requestId === undefined || requestId === null || typeof approved !== 'boolean') { return { ok: false, error: 'requestId and approved required' }; } await resolvePendingPasskeyRequest(Number(requestId), approved); return { ok: true }; } case "GET_PASSKEY_FOR_DOMAIN": { const { domain } = (msg.payload ?? {}) as { domain?: string }; if (!domain) return { ok: false, error: "domain_required" }; // Scope to the caller's own origin: a page may only ask about passkeys // for a domain it actually owns, so an arbitrary page cannot enumerate // which sites the user holds passkeys for or read the username (audit MEDIUM). const origin = attestedSenderOrigin(sender); if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null }; if (!vault.isUnlocked()) return { ok: true, data: null }; const match = vault .getEntries() .find((entry) => entry.passkey?.rpId === domain); if (!match || !match.passkey) return { ok: true, data: null }; // Slim shape — only the fields State 11 needs. Never expose private // key material, even though this is locked behind isUnlocked. return { ok: true, data: { rpId: match.passkey.rpId, userName: match.passkey.userName, browser: match.passkey.browser, }, }; } case "DESTROY_VAULT": { // Irreversible by design. Lock zeroes the derived key + in-memory entries; // storage.local.clear() wipes every Peach key (slots, settings, license, // onboarded flag, history, sync state, declined cards, recall, etc.); // session.clear() wipes pending passkey requests + pro-notice queues. // Caller (Panic.tsx) handles UI navigation back to onboarding. // // The Pro license is the one thing that must survive: the user paid for // it, and destroying a vault (panic wipe, fresh start) is not a refund. // Capture it before the clear and restore it after. peach_pro_celebrated // rides along so the Pro celebration doesn't replay on the next unlock. const preserved = await chrome.storage.local.get([ "peach_license", "peach_pro_celebrated", ]); vault.lock(); await storageClear(); await vault.clearVaultHistory(); const toRestore: Record = {}; if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license; if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated; if (Object.keys(toRestore).length > 0) { await chrome.storage.local.set(toRestore); } if (chrome.storage.session) { await chrome.storage.session.clear(); } return { ok: true }; } case "GET_IDENTITY_SUGGESTIONS": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const entries = vault.getEntries(); const suggestions = buildIdentitySuggestions(entries); return { ok: true, data: { suggestions } }; } case "ML_INIT": return { ok: true }; case "ML_PREDICT_BATCH": { // AUD-002: shape-validate before forwarding to the ML helper. const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown }; if (!Array.isArray(featuresArray)) { return { ok: false, error: "invalid_payload" }; } return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) }; } // ── Vault sync (v3) ─────────────────────────────────────────────── // Returns the public-facing local identity needed by the popup to // drive Phase-1 audio pairing. The private long-term key never // leaves the background. case "GET_LOCAL_IDENTITY": { // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a // Pro license from an already-Pro peer (at least one device must be Pro). if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; // Identity derives from the stable root key, not the password-derived // key, so pairing survives a master-password change (SEV-2-B). const masterKeyHex = vault.getRootKeyHex(); if (!masterKeyHex) return { ok: false, error: "vault_locked" }; const masterKey = unhexBytes(masterKeyHex); try { const identity = await buildLocalIdentity(masterKey); // If this device is Pro, advertise the signed license so the peer can // activate it after SAS confirmation — pairing carries Pro across. if (await isProUser()) { const license = await getLicenseKey(); if (license) (identity as { license?: string }).license = license; } return { ok: true, data: identity }; } finally { masterKey.fill(0); } } case "LIST_PAIRED_DEVICES": { const devices = await listPairedDevicesV3(); return { ok: true, data: { devices } }; } case "RENAME_PAIRED_DEVICE": { const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string }; if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") { return { ok: false, error: "invalid_payload" }; } await renamePairedDeviceV3(deviceId, name); return { ok: true }; } case "UNPAIR_DEVICE": { const { deviceId } = (msg.payload ?? {}) as { deviceId?: string }; if (typeof deviceId !== "string" || !deviceId) { return { ok: false, error: "invalid_payload" }; } // Removing a device REVOKES it rather than just dropping the local // row: a plain removal is undone the moment any other peer vouches it // back through a manifest, which is exactly what the relay makes easy. await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId()); // Sync against the remaining hosts — the unpaired device no longer // matters but the next alarm tick is up to ten minutes away. void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined); return { ok: true }; } case "RENAME_LOCAL_DEVICE": { const { name } = (msg.payload ?? {}) as { name?: string }; if (typeof name !== "string") return { ok: false, error: "invalid_payload" }; await setDeviceNameV3(name); return { ok: true }; } // ── Relay pairing ───────────────────────────────────────────────────── // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK // session runs in the background; the SAS and the terminal result reach // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes. case "START_ADOPTION_SOURCE": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; if (isRelayAdoptionSourceInFlight()) { return { ok: false, error: "adoption_source_in_progress" }; } try { return { ok: true, data: await startRelayAdoptionSource() }; } catch (error) { return { ok: false, error: error instanceof Error ? error.message : "adoption_source_failed", }; } } // Onboarding receiver — empty extension shows a QR, phone scans and // sends the vault. The popup supplies the local-only password here so // the background can wrap the adopted root key at rest without ever // asking the user to retype it. case "START_ADOPTION_RECEIVER": { if (isRelayAdoptionSourceInFlight()) { return { ok: false, error: "adoption_receiver_in_progress" }; } const password = (msg.payload as { password?: unknown } | undefined)?.password; if (typeof password !== "string" || password.length === 0) { return { ok: false, error: "invalid_payload" }; } try { return { ok: true, data: await startRelayAdoptionReceiver(password) }; } catch (error) { return { ok: false, error: error instanceof Error ? error.message : "adoption_receiver_failed", }; } } // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow). // The receiver now auto-accepts the SAS (both sides derive it from the // same Noise handshake hash, so the codes match by construction) so // the popup never has a SAS screen to tap on. The id round-trips the // same way so a stale late response can't approve the wrong session. // Popup→bg counterpart for the source flow: Confirm/Cancel on the // source's SAS screen. // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel // on the source's SAS screen. The id round-trips the same way so a stale // late response can't approve the wrong session. case "SOURCE_SAS_DECISION": { const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined; if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") { return { ok: false, error: "invalid_payload" }; } return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) }; } case "CANCEL_ADOPTION_SOURCE": { cancelRelayAdoptionSource(); return { ok: true }; } case "TRIGGER_SYNC": { const payload = (msg.payload ?? {}) as { reason?: "vault_change" | "foreground" | "manual"; force?: boolean; }; const reason = payload.reason ?? "foreground"; void triggerSyncIfReachable({ reason, force: payload.force === true }); return { ok: true }; } case "GET_SYNC_STATE": { return { ok: true, data: getSyncState() }; } case "GET_SYNC_SETTINGS": { return { ok: true, data: await getSyncSettings() }; } case "SET_SYNC_SETTINGS": { const payload = (msg.payload ?? {}) as { mode?: unknown; relayUrl?: unknown; }; try { // A custom relay URL implies private mode; Peach's own relay stays // public. See setRelayUrl. if (payload.relayUrl !== undefined) { if (typeof payload.relayUrl !== "string") { return { ok: false, error: "invalid_relay_url" }; } return { ok: true, data: await setRelayUrl(payload.relayUrl) }; } if (payload.mode !== undefined) { if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") { return { ok: false, error: "invalid_sync_mode" }; } return { ok: true, data: await setSyncMode(payload.mode as SyncMode) }; } return { ok: true, data: await getSyncSettings() }; } catch (error) { return { ok: false, error: error instanceof Error ? error.message : "invalid_relay_url", }; } } case "GET_SYNC_ALERTS": { const { consume } = (msg.payload ?? {}) as { consume?: boolean }; const alerts = await getPendingSyncAlerts(); // The popup reads on open and acknowledges with consume:true after // rendering, so a popup crash between read and render doesn't lose // the alerts. if (consume) await clearPendingSyncAlerts(); return { ok: true, data: alerts }; } case "GET_PENDING_VOUCHED_DEVICES": { return { ok: true, data: await listPendingVouchedDevices() }; } case "CONFIRM_VOUCHED_DEVICE": { const { deviceId } = msg.payload as { deviceId: string }; const pending = await getPendingVouchedDevice(deviceId); if (!pending) return { ok: false, error: "not_pending" }; // Last gate before a vouched device becomes a sync peer. A queue entry // can predate the revocation that names it, so revocation is re-checked // here rather than trusted to have swept the queue. if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) { await removePendingVouchedDevice(deviceId); return { ok: false, error: "device_revoked" }; } await upsertPairedDeviceV3({ deviceId: pending.deviceId, deviceName: pending.deviceName, deviceType: pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"], longTermPublicKeyHex: pending.longTermPublicKeyHex, signingPublicKeyHex: pending.signingPublicKeyHex, wsPort: pending.wsPort, pairedAt: pending.pairedAt, trustSource: "vouched", }); await removePendingVouchedDevice(deviceId); // Newly confirmed vouched device is now a sync target — kick a round // so the mesh introduction pays off without a 10-minute wait. void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined); return { ok: true }; } case "REJECT_VOUCHED_DEVICE": { const { deviceId } = msg.payload as { deviceId: string }; await removePendingVouchedDevice(deviceId); return { ok: true }; } case "ROTATE_SYNC_IDENTITY": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const result = await vault.rotateSyncIdentity(); return result.ok ? { ok: true } : { ok: false, error: result.error }; } default: return { ok: false, error: "unknown_message_type" }; } } catch (err) { return { ok: false, error: err instanceof Error ? err.message : "operation_failed", }; } } // Returns username use-counts from the vault, sorted by frequency. Each row // also carries the entry's email so the popup can suggest the email/username // pair the user has actually used together. function buildIdentitySuggestions( entries: VaultEntry[], ): Array<{ email: string; username: string; count: number }> { const usernameCounts = new Map(); const usernameEmail = new Map(); for (const entry of entries) { const username = entry.username ?? ""; const email = (entry as VaultEntry & { email?: string }).email ?? ""; if (!username && !email) continue; const key = username || email; usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1); if (!usernameEmail.has(key)) usernameEmail.set(key, email); } return Array.from(usernameCounts.entries()) .sort((a, b) => b[1] - a[1]) .map(([username, count]) => ({ email: usernameEmail.get(username) ?? "", username, count, })); } /** Notify all content scripts that the vault just became available. */ function broadcastToContentScripts(message: { type: string }): void { if (!chrome.tabs?.query) return; chrome.tabs.query({}, (tabs) => { for (const tab of tabs) { if (tab.id !== undefined) { chrome.tabs.sendMessage(tab.id, message).catch(() => { // Tab may not have a content script — silently ignore }); } } }); } function shouldRefreshAutoLock(type: MessageType): boolean { return ( type !== "HAS_VAULT" && type !== "IS_UNLOCKED" && type !== "GET_VAULT_STATUS" && type !== "LOCK" && type !== "UPDATE_SETTINGS" && type !== "GET_PENDING_PASSKEY" && type !== "GET_PASSKEY_PROVIDER_STATE" && type !== "DECLINE_CARD_SAVE" && type !== "IS_CARD_DECLINED" ); } function isAllowedCanaryWebhookUrl(value: string): boolean { try { const url = new URL(value); if (url.protocol !== "https:") return false; const hostname = url.hostname.toLowerCase(); if ( hostname === "localhost" || hostname.endsWith(".localhost") || isPrivateIpv4(hostname) || isPrivateIpv6(hostname) ) { return false; } return true; } catch { return false; } } function isPrivateIpv4(hostname: string): boolean { if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) { return true; } const octets = hostname.split(".").map((part) => Number(part)); if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) { return false; } return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31; } function isPrivateIpv6(hostname: string): boolean { const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase(); // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1] // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped // tails fail closed. (Codex Security 2026-08-04 LOW, // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a // one-shot host check. const mapped = /^::ffff:(.+)$/.exec(normalized); if (mapped) { const tail = mapped[1] ?? ""; if (tail.includes(".")) return isPrivateIpv4(tail); const parts = tail.split(":"); const [hi, lo] = parts; if ( parts.length !== 2 || !hi || !lo || !/^[0-9a-f]{1,4}$/.test(hi) || !/^[0-9a-f]{1,4}$/.test(lo) ) { return true; } const octets = [ (Number.parseInt(hi, 16) >>> 8) & 0xff, Number.parseInt(hi, 16) & 0xff, (Number.parseInt(lo, 16) >>> 8) & 0xff, Number.parseInt(lo, 16) & 0xff, ]; return isPrivateIpv4(octets.join(".")); } return ( normalized === "::1" || normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe80:") ); }