/** * 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 * as vault from "./vault"; import { activateLicense, deactivateLicense, getLicenseInfo, getLicenseKey, isProUser, markCelebrationPlayed, shouldPlayCelebration, } from "./license"; import { cancelFirefoxPasskeyCreate, completeFirefoxPasskeyCreate, getPasskeyProviderState, getPendingPasskeyRequest, handleFirefoxPasskeyCreate, handleFirefoxPasskeyGet, handlePasskeyHasCredentials, initiateFirefoxPasskeyCreate, isPasskeyOfferDeclined, recordPasskeyOfferDecline, resolvePendingPasskeyRequest, setPasskeyProviderEnabled, } from "./passkey"; import { buildAdvancedHealthReport, resolveResetUrl } from "./health"; import { storageClear } from "../shared/storage"; import type { Message, MessageResponse, MessageType, ProFeature, VaultEntry, } from "../shared/types"; import { isPasskeyOnly } from "../shared/types"; import type { SyncStatus } from "../shared/sync-types"; /** * 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 }; } // --------------------------------------------------------------------------- // Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and // next to the device in their paired-devices list. Default to a platform-aware // fallback when the user hasn't set one explicitly. const DEVICE_NAME_KEY = "peach_device_name"; async function getLocalDeviceName(): Promise { try { const stored = await chrome.storage.local.get(DEVICE_NAME_KEY); const value = (stored as Record)[DEVICE_NAME_KEY]; if (typeof value === "string" && value.trim()) return value.trim(); } catch { // fall through to default } return "Peach"; } // --------------------------------------------------------------------------- // 6-digit code pairing. const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000; function generateSixDigitToken(): string { // crypto.getRandomValues, not Math.random — the token is the only secret // protecting the pairing window from a same-LAN attacker. 6 decimal digits // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating // on the responder this is the right tradeoff between UX and security. const buf = new Uint32Array(1); crypto.getRandomValues(buf); const value = buf[0] % 1_000_000; return value.toString().padStart(6, "0"); } // --------------------------------------------------------------------------- // Peer discovery glue (Phase 7 popup pairing flow). const PRIVATE_IPV4_RANGES = [ { prefix: "10." }, { prefix: "127." }, { prefix: "169.254." }, { prefix: "192.168." }, ]; // 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, so the // same private-IP/HTTPS rules that gate canary webhooks apply here. const FEEDBACK_ENDPOINT = ""; 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; } 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" }); return { ok: true }; } case "UNLOCK": { const { password } = msg.payload as { password: string }; const ok = await vault.unlock(password); if (ok) { await setupAutoLock(); broadcastToContentScripts({ type: "VAULT_UNLOCKED" }); } return { ok }; } case "VALIDATE_RECOVERY_WORDS": { const { words } = msg.payload as { words: string[] }; const { findInvalidWords } = await import("../shared/recovery-words"); 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(); 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": return { ok: true, data: vault.getEntries() }; case "ADD_ENTRY": { if (!vault.isUnlocked()) return { ok: false, error: "vault locked" }; const entry = await vault.addEntry(msg.payload as any); return { ok: true, data: entry }; } case "BATCH_ADD_ENTRIES": { const { entries } = msg.payload as { entries: any[] }; const added = await vault.batchAddEntries(entries); return { ok: true, data: added }; } case "RESTORE_ENTRIES": { const { entries, mode, settings } = msg.payload as { entries: any[]; mode: "replace" | "merge"; settings?: vault.VaultSettings; }; const summary = await vault.restoreEntries(entries, mode); if (settings && typeof settings === "object") { await vault.updateSettings(settings); } 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 { id, patch } = msg.payload as any; await vault.updateEntry(id, patch); 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 "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": { const { text, label, alreadyWritten } = msg.payload as { text: string; label: string; alreadyWritten?: boolean; }; await copyToClipboard(text, label, Boolean(alreadyWritten)); return { ok: true }; } case "CHECK_BREACH": { const { password } = msg.payload as { password: string }; const count = await vault.checkBreach(password); return { ok: true, data: count }; } 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 as Record; await vault.updateSettings(patch as any); if (typeof patch.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_PASSKEYS": return { ok: true, data: vault.getEntries().filter((entry) => entry.passkey !== undefined), }; case "DELETE_PASSKEY": { const { id } = msg.payload as { id: string }; await vault.deleteEntry(id); 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) }; } case "FIRE_CANARY_PING": { 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 "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 "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": { 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 "GET_SYNC_STATE": { const { getPairedDevices, getTrustedNetworks } = await import('./sync-storage'); const { isOnTailscale } = await import('./sync-network'); const { isProUser } = await import('./license'); const { storageGet } = await import('../shared/storage'); const pairedDevices = await getPairedDevices(); const trustedNetworks = await getTrustedNetworks(); const tailscale = await isOnTailscale(); const pro = await isProUser(); let status: SyncStatus = "offline"; if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) { if (pairedDevices.length === 0) { status = "no_peers"; } else { status = "synced"; } } else { status = "not_trusted"; } const lastSyncRaw = await storageGet("peach_last_sync_at"); const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN; const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined; return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } }; } case "TRIGGER_SYNC": { const gate = await requirePro("sync"); if (!gate.allowed) return { ok: false, error: "pro_required" }; if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; return { ok: false, error: "no_native_host" }; } case "START_PAIRING": { const gate = await requirePro("sync"); if (!gate.allowed) return { ok: false, error: "pro_required" }; return { ok: true }; } case "CANCEL_PAIRING": { return { ok: true }; } case "ACCEPT_PAIRING": { const gate = await requirePro("sync"); if (!gate.allowed) return { ok: false, error: "pro_required" }; return { ok: true }; } case "REMOVE_PAIRED_DEVICE": { const { deviceId } = msg.payload as { deviceId: string }; const { removePairedDevice } = await import('./sync-storage'); await removePairedDevice(deviceId); return { ok: true }; } case "REMOVE_TRUSTED_NETWORK": { const { ssid, bssid, isTailscale } = msg.payload as any; const { removeTrustedNetwork, getTrustedNetworks } = await import('./sync-storage'); const networks = await getTrustedNetworks(); const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => (isTailscale ? n.isTailscale : n.ssid === ssid) && (!bssid || n.bssid === bssid) ); if (network) { await removeTrustedNetwork(network.addedAt); } return { ok: true }; } case "MARK_NETWORK_TRUSTED": { const { addTrustedNetwork } = await import('./sync-storage'); const { getCurrentNetwork } = await import('./sync-network'); const network = await getCurrentNetwork(); await addTrustedNetwork({ ssid: network.ssid, bssid: network.bssid, isTailscale: network.isTailscale, addedAt: Date.now(), }); return { ok: true }; } case "GET_INCOMING_PAIRING_REQUEST": { const { getIncomingPairingRequest } = await import('./sync-storage'); const request = await getIncomingPairingRequest(); return { ok: true, data: request }; } case "RESPOND_INCOMING_PAIRING": { const { accept } = msg.payload as { accept: boolean }; const { getIncomingPairingRequest, clearIncomingPairingRequest, addPairedDevice } = await import('./sync-storage'); const request = await getIncomingPairingRequest(); if (!request) return { ok: false, error: "no_pending_request" }; if (Date.now() > request.expiresAt) { await clearIncomingPairingRequest(); return { ok: false, error: "expired" }; } await clearIncomingPairingRequest(); if (accept) { await addPairedDevice({ deviceId: request.publicKeyHex, displayName: request.deviceName, x25519PublicKey: request.publicKeyHex, pairedAt: Date.now(), lastSeenAt: Date.now(), }); } return { ok: true, data: { accepted: accept, deviceName: request.deviceName } }; } case "START_PEER_DISCOVERY": { const gate = await requirePro("sync"); if (!gate.allowed) return { ok: false, error: "pro_required" }; return { ok: false, error: "no_native_host" }; } case "STOP_PEER_DISCOVERY": { return { ok: true }; } case "START_PAIRING_SERVER": { const gate = await requirePro("sync"); if (!gate.allowed) return { ok: false, error: "pro_required" }; const token = generateSixDigitToken(); const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS; const { setActivePairingToken } = await import('./pairing-server-state'); await setActivePairingToken({ token, expiresAt }); return { ok: true, data: { token, expiresAt } }; } case "STOP_PAIRING_SERVER": { try { const { setActivePairingToken } = await import("./pairing-server-state"); await setActivePairingToken(null); } catch { /* best-effort */ } return { ok: true }; } case "CONNECT_WITH_CODE": { const gate = await requirePro("sync"); if (!gate.allowed) return { ok: false, error: "pro_required" }; return { ok: false, error: "no_native_host" }; } case "GET_RECENT_PAIRING": { const { consumeRecentPairing } = await import('./pairing-server-state'); const recent = await consumeRecentPairing(); return { ok: true, data: recent }; } case "INITIATE_PAIR_WITH_PEER": { const gate = await requirePro("sync"); if (!gate.allowed) return { ok: false, error: "pro_required" }; return { ok: false, error: "no_native_host" }; } case "DEBUG_INJECT_INCOMING_PAIRING": { // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing // request into session storage so Phase 7 banner UX can be exercised // without a live native host. No Pro gate — this is a no-op in // production unless explicitly invoked from a Settings debug action. const { deviceName, publicKeyHex } = (msg.payload ?? {}) as { deviceName?: string; publicKeyHex?: string; }; if (!deviceName || !publicKeyHex) { return { ok: false, error: "missing_payload" }; } const { setIncomingPairingRequest } = await import('./sync-storage'); const now = Date.now(); await setIncomingPairingRequest({ deviceName, publicKeyHex, receivedAt: now, expiresAt: now + 60_000, }); return { ok: true }; } case "RESET_SYNC_IDENTITY": { const gate = await requirePro("sync"); if (!gate.allowed) return { ok: false, error: "pro_required" }; const { getPairedDevices, removePairedDevice } = await import('./sync-storage'); const devices = await getPairedDevices(); for (const device of devices) { await removePairedDevice(device.deviceId); } return { ok: true, data: { removedDevices: devices.length, nativePublicKey: 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 "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 is 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" }; } } case "TRIGGER_SYNC": { if (isNativePlatform()) { bridge?.ensureServerRunning?.(); return { ok: true, data: { syncedCount: 0, mode: "server" as const } }; } return await desktopTriggerSync({ getLastKnownIp: () => null }); } // 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) 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() } }; } // Android: scanned a QR containing a desktop pairing token. case "SCAN_PAIRING_QR": { if (!isNativePlatform()) { return { ok: false, error: "android_only" }; } const { token } = msg.payload as { token: string }; bridge?.startPairingSession?.({ token }); return { ok: true }; } // Android: returns the phone's WiFi IP address. case "GET_LOCAL_IP": { if (!isNativePlatform()) { return { ok: false, error: "android_only" }; } const { ip } = (await bridge?.getLocalIp?.()) ?? { ip: "" }; return { ok: true, data: { ip } }; } // Desktop: generates a pairing token and starts the subnet scan for QR pairing. case "START_PAIRING_SERVER": { if (isNativePlatform()) { return { ok: false, error: "desktop_only" }; } const arr = new Uint32Array(1); crypto.getRandomValues(arr); const token = String(100000 + (arr[0] % 900000)); activeDesktopPairingToken = token; activeDesktopPairingExpiry = Date.now() + 5 * 60 * 1000; startSubnetScan(token, { getLocalAddress: () => null }); return { ok: true, data: { token, expiresIn: 300 } }; } 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 }; } default: return { ok: false, error: "unknown message type" }; } } catch (err) { return { ok: false, error: err instanceof Error ? err.message : "operation failed", }; } } // --- Mobile platform helpers --- // Desktop: triggers sync for all paired devices. async function desktopTriggerSync(deps: { getLastKnownIp: () => string | null; }): Promise<{ ok: true; syncedCount: number } | { ok: false; error: string }> { const ip = deps.getLastKnownIp(); if (!ip) return { ok: false, error: "no_paired_devices" }; return { ok: true, syncedCount: 0 }; } // Desktop: starts background subnet scan for QR pairing. function startSubnetScan( token: string, _deps: { getLocalAddress: () => string | null; } ): void { // TODO: implement subnet scan and WebSocket pairing server } // Android: populates the in-memory vault used by PeachAutofillService. async function publishInMemoryVault(entries: VaultEntry[]): Promise { // TODO: wire up to autofill in-memory store (exists in Android, not here) } // Returns all emails and usernames from the vault, deduped and sorted by frequency. function buildIdentitySuggestions( entries: VaultEntry[], ): Array<{ email: string; username: string; count: number }> { const map = new Map(); for (const entry of entries) { if (entry.username) map.set(entry.username, (map.get(entry.username) ?? 0) + 1); } return Array.from(map.entries()) .sort((a, b) => b[1] - a[1]) .map(([username, count]) => ({ email: username, username, count })); } // Mobile bridge — runtime check to avoid importing Capacitor at the top level. // eslint-disable-next-line @typescript-eslint/no-explicit-any const bridge = (typeof (globalThis as any).Capacitor !== "undefined") ? (globalThis as any).Capacitor.Plugins.SyncPlugin : null; // eslint-disable-next-line @typescript-eslint/no-explicit-any const isNativePlatform = (): boolean => typeof (globalThis as any).Capacitor !== "undefined" && (globalThis as any).isNativePlatform(); let activeDesktopPairingToken: string | null = null; let activeDesktopPairingExpiry = 0; /** 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:") ); }