/** * 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, storageGet } from "../shared/storage"; import { findInvalidWords } from "../shared/recovery-words"; import { addPairedDevice, addTrustedNetwork, clearIncomingPairingRequest, getIncomingPairingRequest, getPairedDevices, getTrustedNetworks, removePairedDevice, removeTrustedNetwork, setIncomingPairingRequest, updatePairedDevice, } from "./sync-storage"; import { getCurrentNetwork, isOnTailscale } from "./sync-network"; import { consumeRecentPairing, setActivePairingToken, } from "./pairing-server-state"; import type { Message, MessageResponse, MessageType, ProFeature, VaultEntry, } from "../shared/types"; import { isPasskeyOnly } from "../shared/types"; import type { SyncStatus, SyncableDevice } from "../shared/sync-types"; import { isNativePlatform, nativePlugin } from "../shared/native"; import { runBlobSyncSession, type SyncResult } from "./sync-coordinator"; import type { SyncDeps } from "./sync-coordinator"; import { createWebSocketSyncTransport } from "../shared/websocket-sync-transport"; import { getLocalSubnet, discoverDevice, scanForPairingPhone } from "../shared/local-network"; import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire"; /** * 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 = ""; // --------------------------------------------------------------------------- // Sync helpers // --------------------------------------------------------------------------- function buildSyncDeps(): SyncDeps { return { isVaultUnlocked: () => vault.isUnlocked(), getVaultBlobForSync: async () => { const base = await vault.getVaultBlobForSync(); if (!base) return null; const paired = await getPairedDevices(); return { ...base, devices: paired .filter(d => d.x25519PublicKey) .map(d => ({ publicKeyHex: d.x25519PublicKey, deviceName: d.displayName, pairedAt: d.pairedAt, })), }; }, applyIncomingVault: async (blob, ts, license, devices) => { const applied = await vault.applyIncomingVault(blob, ts, license); if (devices?.length) await mergeDeviceRegistry(devices); if (applied) await vault.reloadEntriesAfterSync(); return applied; }, }; } async function doVaultSync(ip: string, publicKeyHex: string): Promise { try { const transport = await createWebSocketSyncTransport(`ws://${ip}:44100`, publicKeyHex); return await runBlobSyncSession('initiator', transport, buildSyncDeps()); } catch (err) { return { status: 'errored', applied: false, error: String(err) }; } } async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise { const existing = await getPairedDevices(); const existingKeys = new Set(existing.map(d => d.x25519PublicKey)); for (const device of incoming) { if (!existingKeys.has(device.publicKeyHex)) { await addPairedDevice({ deviceId: device.publicKeyHex, displayName: device.deviceName, x25519PublicKey: device.publicKeyHex, pairedAt: device.pairedAt, lastSeenAt: 0, lastKnownIp: '', }).catch(() => {}); } } } // Background pairing scan — runs after START_PAIRING_SERVER fires on desktop. // Scans the local subnet for a phone that has accepted the pairing token, // stores it, runs the initial vault exchange, then notifies the popup. async function runPairingSubnetScan(token: string): Promise { const subnet = await getLocalSubnet(); if (!subnet) return; const found = await scanForPairingPhone(subnet, token); if (!found) return; const { ip, publicKeyHex } = found; try { await addPairedDevice({ deviceId: publicKeyHex, displayName: 'Peach', x25519PublicKey: publicKeyHex, pairedAt: Date.now(), lastSeenAt: Date.now(), lastKnownIp: ip, }); } catch { // Already paired — update IP await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() }); } // Immediate vault exchange — the free one-time transfer await doVaultSync(ip, publicKeyHex); chrome.runtime.sendMessage({ type: 'PAIRING_COMPLETED', payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip }, }).catch(() => {}); } 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), }; } }); } // Android: subscribe to SyncPlugin events. if (isNativePlatform()) { const syncPlug = nativePlugin<{ addListener: ( event: string, handler: (data: Record) => void ) => void; }>("SyncPlugin"); // Pairing probe answered — store the paired device (desktop, no IP needed // since the desktop never acts as a WS server). syncPlug?.addListener?.("peach:pair-probe-answered", (data) => { const deviceName = data.deviceName ?? "Peach"; const publicKeyHex = data.publicKeyHex ?? ""; void (async () => { const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage"); await addPairedDevice({ deviceId: publicKeyHex || (data.connectionId ?? "unknown"), displayName: deviceName, x25519PublicKey: publicKeyHex, pairedAt: Date.now(), lastSeenAt: Date.now(), }).catch(() => {}); await setPaired(); chrome.runtime.sendMessage({ type: "PAIRING_COMPLETED", payload: { deviceName }, }).catch(() => {}); })(); }); // Sync frame received — route to the waiting responder session. syncPlug?.addListener?.("peach:sync-frame", (data) => { const { connectionId, frame } = data; if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame); }); // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as // a background message so SYNC_SESSION_STARTED handler runs the responder. syncPlug?.addListener?.("peach:sync-session-started", (data) => { const { connectionId } = data; if (!connectionId) return; void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } }); }); } } 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" }); if (isNativePlatform()) await publishInMemoryVault(vault.getEntries()); } return { ok }; } 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": 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_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_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 "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": { 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 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 "GET_PAIRED_DEVICES": { const devices = await getPairedDevices(); return { ok: true, data: { devices } }; } case "GET_SYNC_STATUS": { const lastSyncRaw = await storageGet("peach_last_sync_at"); const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN; const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null; const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never'; return { ok: true, data: { status, lastSyncAt } }; } case "ACCEPT_PAIRING": { // One-time mobile→desktop transfer is free; only continuous sync gates on Pro. return { ok: true }; } case "REMOVE_PAIRED_DEVICE": { const { deviceId } = msg.payload as { deviceId: string }; await removePairedDevice(deviceId); return { ok: true }; } case "REMOVE_TRUSTED_NETWORK": { const { ssid, bssid, isTailscale } = msg.payload as any; 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 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 request = await getIncomingPairingRequest(); return { ok: true, data: request }; } case "RESPOND_INCOMING_PAIRING": { const { accept } = msg.payload as { accept: boolean }; 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_PAIRING_SERVER": { // One-time mobile→desktop transfer is free; only continuous sync gates on Pro. const token = generateSixDigitToken(); const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS; await setActivePairingToken({ token, expiresAt }); // Fire-and-forget subnet scan — finds the phone after it scans the QR // and calls SCAN_PAIRING_QR to register the token with SyncPlugin. if (!isNativePlatform()) { void runPairingSubnetScan(token); } return { ok: true, data: { token, expiresAt } }; } case "STOP_PAIRING_SERVER": { try { await setActivePairingToken(null); } catch { /* best-effort */ } return { ok: true }; } case "GET_RECENT_PAIRING": { const recent = await consumeRecentPairing(); return { ok: true, data: recent }; } 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 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 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": { const gate = await requirePro("sync"); if (!gate.allowed) return { ok: false, error: "pro_required" }; if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" }; if (isNativePlatform()) { // Phone is the server — ensure it's listening for desktop connections. syncBridge()?.ensureServerRunning?.(); return { ok: true, data: { syncedCount: 0, mode: "server" as const } }; } // Desktop: iterate all paired devices and sync with each. const paired = await getPairedDevices(); if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } }; const subnet = await getLocalSubnet(); const results: Array<{ device: string } & SyncResult> = []; for (const device of paired) { if (!device.x25519PublicKey) continue; let result: SyncResult; // Fast path — use last known IP if (device.lastKnownIp) { result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey); } else { result = { status: 'errored', applied: false, error: 'no_ip' }; } // Discovery path — scan if fast path failed if (result.status === 'errored' && subnet) { const newIp = await discoverDevice(subnet, device.x25519PublicKey); if (newIp) { await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp }); result = await doVaultSync(newIp, device.x25519PublicKey); } } if (result.status === 'completed') { await updatePairedDevice(device.x25519PublicKey, { lastSeenAt: Date.now(), lastSyncAt: Date.now(), }); } results.push({ device: device.displayName, ...result }); } const syncedCount = results.filter(r => r.status === 'completed').length; if (syncedCount > 0) { await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) }); } return { ok: true, data: { syncedCount, results } }; } // 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 }; syncBridge()?.startPairingSession?.({ token }); return { ok: true }; } // Android: desktop opened a sync connection to the phone's WS server. // Run the responder side of the vault exchange. case "SYNC_SESSION_STARTED": { if (!isNativePlatform()) return { ok: false }; if (!vault.isUnlocked()) { return { ok: false, error: "vault_locked" }; } const { connectionId } = (msg.payload ?? {}) as { connectionId?: string }; if (!connectionId) return { ok: false, error: "missing_connection_id" }; const transport = createAndroidResponderTransport(connectionId); const result = await runBlobSyncSession('responder', transport, buildSyncDeps()); if (result.applied) { await publishInMemoryVault(vault.getEntries()); } return { ok: true, data: result }; } // Android: returns the phone's WiFi IP address. case "GET_LOCAL_IP": { if (!isNativePlatform()) { return { ok: false, error: "android_only" }; } const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" }; return { ok: true, data: { ip } }; } 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 }; } // --- PNA compatibility test handlers — REMOVE BEFORE RELEASE --- case "TEST_LOCAL_WEBSOCKET": { const { ip } = (msg.payload ?? {}) as { ip?: string }; if (!ip) return { ok: false, error: "ip required" }; return new Promise((resolve) => { try { const ws = new WebSocket(`ws://${ip}:44100`); ws.onopen = () => { ws.close(); resolve({ ok: true, data: { connected: true } }); }; ws.onerror = () => resolve({ ok: false, error: "connection_failed" }); setTimeout(() => { ws.close(); resolve({ ok: false, error: "timeout" }); }, 3000); } catch (err) { resolve({ ok: false, error: String(err) }); } }); } case "TEST_SUBNET_DETECTION": { const subnet = await getLocalSubnet(); return { ok: true, data: { subnet } }; } case "TEST_SUBNET_SCAN": { const subnet = await getLocalSubnet(); if (!subnet) return { ok: false, error: "no_subnet" }; const start = Date.now(); const result = await discoverDevice(subnet, "000000000000000000000000000000000000000000000000000000000000000000"); return { ok: true, data: { elapsed: Date.now() - start, found: !!result } }; } // --- end test handlers --- 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(); } interface SyncBridge { ensureServerRunning?: () => void; startPairingSession?: (args: { token: string }) => void; getLocalIp?: () => Promise<{ ip: string }>; sendToConnection?: (args: { connectionId: string; data: string }) => Promise; addListener?: (event: string, handler: (data: Record) => void) => void; } // Resolve the Capacitor SyncPlugin at call time — module-load resolution // races with Capacitor's plugin registration on the Android WebView. function syncBridge(): SyncBridge | null { return nativePlugin("SyncPlugin"); } // Build a SyncTransport for the Android responder path — the phone's WS server // already has an open connection from the desktop. We send back via // SyncPlugin.sendToConnection and receive via the peach:sync-frame queue. const androidSyncFrameQueues = new Map void>>(); export function deliverAndroidSyncFrame(connectionId: string, frame: string): void { const queue = androidSyncFrameQueues.get(connectionId); if (queue?.length) queue.shift()!(frame); } function createAndroidResponderTransport(connectionId: string) { const pendingReceivers: Array<(frame: string) => void> = []; androidSyncFrameQueues.set(connectionId, pendingReceivers); return { send: async (data: Uint8Array) => { await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) }); }, receive: (): Promise => new Promise((res) => { pendingReceivers.push((frame) => { res(frame ? base64ToBytes(frame) : new Uint8Array(0)); }); }), close: async () => { androidSyncFrameQueues.delete(connectionId); }, }; } // 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:") ); }