/** * 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 } from "./clipboard"; 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, resolveResetUrl } 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 { isNativePlatform, nativePlugin } from "../shared/native"; import { predictBatch as mlPredictBatch } from "./ml"; import type { MLFieldFeatures } from "../shared/ml"; import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity"; import { listPairedDevices as listPairedDevicesV3, removePairedDeviceById as removePairedDeviceByIdV3, upsertPairedDevice as upsertPairedDeviceV3, } from "./paired-devices"; 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 (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 }; } // --------------------------------------------------------------------------- // Feedback submission target. Empty disables network submission while the UI // continues to function as a no-op (the handler returns ok:true without // calling fetch). When set, the URL is validated by // `isAllowedCanaryWebhookUrl` before any request. // --------------------------------------------------------------------------- const FEEDBACK_ENDPOINT = ""; 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; } ); // Android: the chrome shim queues sendMessage calls until this handler is // registered. Without this hookup, every message hangs on Capacitor builds. // eslint-disable-next-line @typescript-eslint/no-explicit-any const reg = (globalThis as any).__peachRegisterMessageHandler; if (typeof reg === "function") { reg(async (m: unknown) => { if (!isMessage(m)) return { ok: false, error: "invalid_message" }; try { return await handleMessage(m); } catch (err) { return { ok: false, error: err instanceof Error ? err.message : String(err), }; } }); } } function isMessage(m: unknown): m is Message { return typeof m === "object" && m !== null && "type" in m; } export async function handleMessage( msg: Message, sender: Partial = {} ): Promise { try { // 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" }; } if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) { touchAutoLock(); } switch (msg.type) { case "CREATE_VAULT": { const { password } = msg.payload as { password: string }; await vault.createVault(password); await setupAutoLock(); broadcastToContentScripts({ type: "VAULT_UNLOCKED" }); onVaultUnlocked(); return { ok: true }; } 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 setupAutoLock(); broadcastToContentScripts({ type: "VAULT_UNLOCKED" }); onVaultUnlocked(); if (isNativePlatform()) await publishInMemoryVault(vault.getEntries()); 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 "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" }; try { const words = await vault.getRecoveryWords(); return { ok: true, data: words }; } catch (e) { // pre-v2.12 vault that hasn't migrated 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(); if (isNativePlatform()) await clearInMemoryVault(); 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 { const entry = await vault.addEntry({ type: "note", title: title || "Untitled", notes: body, createdAt: now, modifiedAt: now, } as any); 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" }; } const { domain, includeAll, kind } = msg.payload as { domain: string; includeAll?: boolean; kind?: "login" | "card"; }; // 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, })), }; } // 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, 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 } = msg.payload as { id: string }; 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" }; // Strip the passkey credential from the response — content scripts // never need the private key, and there's no reason to expose the // public credential metadata over the boundary either. const { passkey: _strippedPasskey, ...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 }; } 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 "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" }; } 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. const gate = await requirePro("codex"); if (!gate.allowed) return { ok: false, error: "pro_required" }; return await handleGetCodexVaultData(); } 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 "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 "INITIATE_PASSWORD_CHANGE": { const gate = await requirePro("smart_password_change"); if (!gate.allowed) return { ok: false, error: "pro_required" }; if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const { id } = msg.payload as { id: string }; const entry = vault.getEntryById(id); if (!entry) return { ok: false, error: "entry_not_found" }; const url = resolveResetUrl(entry); if (!url) return { ok: false, error: "no_reset_url" }; try { await chrome.tabs.create({ url }); return { ok: true, data: { url } }; } catch (err) { return { ok: false, error: err instanceof Error ? err.message : "failed_to_open_tab", }; } } 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" }; 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, }); } 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 ?? [], }); } 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); } case "PASSKEY_GET": { const payload = msg.payload as Parameters[0] | undefined; if (!payload?.rpId) return { ok: false, error: "rpid_required" }; return await handleFirefoxPasskeyGet(payload); } 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" }; 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. vault.lock(); await storageClear(); await vault.clearVaultHistory(); if (chrome.storage.session) { await chrome.storage.session.clear(); } return { ok: true }; } case "SUBMIT_FEEDBACK": { const { category, message, version, browser } = msg.payload as { category: string; message: string; version: string; browser: string; }; if (!message.trim()) return { ok: false, error: "message_empty" }; if (!FEEDBACK_ENDPOINT) return { ok: true }; if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) { return { ok: false, error: "invalid_feedback_endpoint" }; } try { const res = await fetch(FEEDBACK_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }), }); return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` }; } catch (err) { return { ok: false, error: err instanceof Error ? err.message : "network_error" }; } } // Android-only: biometric unlock with pre-derived key. case "UNLOCK_WITH_KEY": { const { masterKeyHex } = msg.payload as { masterKeyHex: string }; if (!isNativePlatform()) { return { ok: false, error: "desktop_only_uses_password" }; } try { const result = await vault.unlockWithKey(masterKeyHex); if (result.ok) { onVaultUnlocked(); await publishInMemoryVault(result.entries); } return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error }; } catch { return { ok: false, error: "invalid_key" }; } } // Android: returns current in-memory derived key as hex. Used by biometric enable flow. case "GET_DERIVED_KEY": { if (!isNativePlatform()) { return { ok: false, error: "android_only" }; } if (!vault.isUnlocked()) { return { ok: false, error: "vault_locked" }; } return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } }; } 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 "POPULATE_INLINE_VAULT": { if (!isNativePlatform()) return { ok: false }; if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const entries = vault.getEntries(); await publishInMemoryVault(entries); return { ok: true }; } 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[]) }; } // ── Chirp 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 "CHIRP_GET_LOCAL_IDENTITY": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const proCheck = await requirePro("sync"); if (!proCheck.allowed) return { ok: false, error: "pro_required" }; const masterKeyHex = vault.getDerivedKeyHex(); const masterKey = unhexBytes(masterKeyHex); try { const identity = await buildLocalIdentity(masterKey); return { ok: true, data: identity }; } finally { masterKey.fill(0); } } case "CHIRP_COMPLETE_PAIRING": { if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; const proCheck = await requirePro("sync"); if (!proCheck.allowed) return { ok: false, error: "pro_required" }; const paired = (msg.payload as { paired?: unknown })?.paired; if (typeof paired !== "object" || paired === null) { return { ok: false, error: "invalid_payload" }; } const candidate = paired as Record; if ( typeof candidate.deviceId !== "string" || !candidate.deviceId || typeof candidate.deviceName !== "string" || !candidate.deviceName || typeof candidate.deviceType !== "string" || typeof candidate.longTermPublicKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) || typeof candidate.pairedAt !== "number" ) { return { ok: false, error: "invalid_paired_device" }; } await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice); return { ok: true }; } case "CHIRP_LIST_PAIRED_DEVICES": { const devices = await listPairedDevicesV3(); return { ok: true, data: { devices } }; } case "CHIRP_UNPAIR_DEVICE": { const { deviceId } = (msg.payload ?? {}) as { deviceId?: string }; if (typeof deviceId !== "string" || !deviceId) { return { ok: false, error: "invalid_payload" }; } await removePairedDeviceByIdV3(deviceId); return { ok: true }; } case "CHIRP_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 }; } default: return { ok: false, error: "unknown_message_type" }; } } catch (err) { return { ok: false, error: err instanceof Error ? err.message : "operation_failed", }; } } // --- Mobile platform helpers --- // Android: populates the in-memory vault used by PeachAutofillService. async function publishInMemoryVault(entries: VaultEntry[]): Promise { const plugin = nativePlugin<{ setEntries?: (args: { entries: Array<{ id: string; title: string; username: string; email: string; password: string; url: string; totp: string; additionalUrls: string[]; }>; }) => Promise; }>("InMemoryVaultPlugin"); if (!plugin?.setEntries) return; await plugin.setEntries({ entries: entries.map((e) => ({ id: e.id, title: e.title ?? "", username: e.username ?? "", email: (e as VaultEntry & { email?: string }).email ?? "", password: e.password ?? "", url: e.url ?? "", totp: (e as VaultEntry & { totp?: string }).totp ?? "", additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [], })), }); } // Android: clear the autofill in-memory store on lock. async function clearInMemoryVault(): Promise { const plugin = nativePlugin<{ clearEntries?: () => Promise }>("InMemoryVaultPlugin"); if (!plugin?.clearEntries) return; await plugin.clearEntries(); } // 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" && type !== "SUBMIT_FEEDBACK" ); } 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(); return ( normalized === "::1" || normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe80:") ); }