123456789101112import { copyToClipboard, getEffectiveClearSeconds } from "./clipboard";13import { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import { computeVaultId } from "../shared/sync-identity";16import {17 getPendingVouchedDevice,18 listPendingVouchedDevices,19 removePendingVouchedDevice,20} from "./pending-vouched-devices";21import { isRecoveryConfirmPending } from "./recovery-pending";22import { setupAutoLock, touchAutoLock } from "./alarms";23import { runSelfTest } from "./self-test";24import * as vault from "./vault";25import {26 handleEstimateCodexPages,27 handleGetCodexVaultData,28 handleRestoreFromCodex,29} from "./codex-handlers";30import type { CodexRestorePayload } from "../shared/codex-types";31import {32 activateLicense,33 deactivateLicense,34 getLicenseInfo,35 getLicenseKey,36 isProUser,37 markCelebrationPlayed,38 shouldPlayCelebration,39} from "./license";40import {41 completeFirefoxPasskeyCreate,42 getPasskeyProviderState,43 getPendingPasskeyRequest,44 handleFirefoxPasskeyCreate,45 handleFirefoxPasskeyGet,46 handlePasskeyHasCredentials,47 initiateFirefoxPasskeyCreate,48 isPasskeyOfferDeclined,49 onVaultUnlocked,50 recordPasskeyOfferDecline,51 resolvePendingPasskeyRequest,52 setPasskeyProviderEnabled,53} from "./passkey";54import { buildAdvancedHealthReport } from "./health";55import { storageClear } from "../shared/storage";56import { findInvalidWords } from "../shared/recovery-words";57import type {58 Message,59 MessageResponse,60 MessageType,61 ProFeature,62 VaultEntry,63} from "../shared/types";64import { isPasskeyOnly } from "../shared/types";65import { generateTOTP } from "../crypto/totp";66import { isValidRpId } from "../shared/passkey-utils";67import { isNativePlatform, nativePlugin } from "../shared/native";68import { predictBatch as mlPredictBatch } from "./ml";69import type { MLFieldFeatures } from "../shared/ml";70import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";71import {72 listPairedDevices as listPairedDevicesV3,73 removePairedDeviceById as removePairedDeviceByIdV3,74 upsertPairedDevice as upsertPairedDeviceV3,75} from "./paired-devices";767778798081declare const __PEACH_E2E_PASSKEYS__: boolean;82const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;8384let nativeSyncRunnerBootstrapped = false;8586function unhexBytes(hex: string): Uint8Array {87 if (hex.length % 2 !== 0) throw new Error("invalid hex");88 const out = new Uint8Array(hex.length / 2);89 for (let i = 0; i < out.length; i++) {90 out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);91 }92 return out;93}949596979899100101async function requirePro(102 feature: ProFeature,103 trigger: "user" | "background" = "user"104): Promise<{ allowed: boolean }> {105 if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };106 if (await isProUser()) return { allowed: true };107108 if (trigger === "user") {109 110 chrome.runtime111 .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })112 .catch(() => {113 114 });115 } else {116 117 118 119 if (chrome.storage.session) {120 chrome.storage.session121 .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })122 .catch(() => {});123 }124 }125126 return { allowed: false };127}128129130131132133134135136const FEEDBACK_ENDPOINT = "";137138139140141142const DESTRUCTIVE_MESSAGE_TYPES: ReadonlySet<string> = new Set([143 "DESTROY_VAULT",144 "CLEAR_VAULT_ENTRIES",145 "RESTORE_VAULT_SNAPSHOT",146 "RESTORE_FROM_CODEX",147]);148149150const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; 151152const PRIVATE_IPV4_RANGES = [153 { prefix: "10." },154 { prefix: "127." },155 { prefix: "169.254." },156 { prefix: "192.168." },157];158159export function setupMessageHandler(): void {160 chrome.runtime.onMessage.addListener(161 (msg: unknown, sender, sendResponse) => {162 if (!isMessage(msg)) {163 sendResponse({ ok: false, error: "invalid_message" });164 return true;165 }166 handleMessage(msg, sender)167 .then(sendResponse)168 .catch((err) =>169 sendResponse({170 ok: false,171 error: err instanceof Error ? err.message : String(err),172 })173 );174 return true;175 }176 );177178 179 180 181 const reg = (globalThis as any).__peachRegisterMessageHandler;182 if (typeof reg === "function") {183 reg(async (m: unknown) => {184 if (!isMessage(m)) return { ok: false, error: "invalid_message" };185 try {186 return await handleMessage(m);187 } catch (err) {188 return {189 ok: false,190 error: err instanceof Error ? err.message : String(err),191 };192 }193 });194 }195 if (isNativePlatform()) {196 void bootstrapNativeSyncRunner();197 }198}199200async function bootstrapNativeSyncRunner(): Promise<void> {201 if (nativeSyncRunnerBootstrapped) return;202 nativeSyncRunnerBootstrapped = true;203 try {204 const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");205 const { productionSyncRunner } = await import("./chirp-sync-runner");206 setSyncRunner(productionSyncRunner);207 await hydratePersistedSyncState();208 } catch (err) {209 nativeSyncRunnerBootstrapped = false;210 console.warn("[Peach] failed to bootstrap native sync runner:", err);211 }212}213214function isMessage(m: unknown): m is Message {215 return typeof m === "object" && m !== null && "type" in m;216}217218219220221222223224225226function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {227 if (sender.origin) return sender.origin;228 if (sender.url) {229 try { return new URL(sender.url).origin; } catch { return undefined; }230 }231 return undefined;232}233234235236237238let restoreReady: Promise<void> = Promise.resolve();239240241export function setRestoreReady(p: Promise<unknown>): void {242 restoreReady = p.then(() => undefined, () => undefined);243}244245export async function handleMessage(246 msg: Message,247 sender: Partial<chrome.runtime.MessageSender> = {}248): Promise<MessageResponse> {249 try {250 251 252 253 254 255 256 await restoreReady;257 258 259 260 261 if (262 sender.id !== undefined &&263 sender.id !== chrome.runtime.id264 ) {265 return { ok: false, error: "invalid_sender" };266 }267268 269 270 271 272 273 274 if (DESTRUCTIVE_MESSAGE_TYPES.has(msg.type)) {275 const extensionOrigin = chrome.runtime.getURL("");276 if (!sender.url?.startsWith(extensionOrigin)) {277 return { ok: false, error: "invalid_sender" };278 }279 }280281 if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {282 touchAutoLock();283 }284285 switch (msg.type) {286 case "CREATE_VAULT": {287 const { password } = msg.payload as { password: string };288 289 290 291 292 if (typeof password !== "string" || password.length === 0) {293 return { ok: false, error: "invalid_payload" };294 }295 await vault.createVault(password);296 await setupAutoLock();297 broadcastToContentScripts({ type: "VAULT_UNLOCKED" });298 onVaultUnlocked();299 return { ok: true };300 }301 case "CREATE_VAULT_FROM_ROOT_KEY": {302 const { password, rootKeyHex } = (msg.payload ?? {}) as {303 password?: unknown;304 rootKeyHex?: unknown;305 };306 if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {307 return { ok: false, error: "invalid_payload" };308 }309310 try {311 const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);312 await setupAutoLock();313 broadcastToContentScripts({ type: "VAULT_UNLOCKED" });314 onVaultUnlocked();315 return { ok: true, vaultId };316 } catch (err) {317 return { ok: false, error: err instanceof Error ? err.message : String(err) };318 }319 }320 case "UNLOCK": {321 const { password } = msg.payload as { password: string };322 const ok = await vault.unlock(password);323 if (ok) {324 325 326 const kat = await runSelfTest();327 if (!kat.ok) {328 console.error("[Peach] Crypto self-test FAILED:", kat.error);329 await vault.lock();330 return { ok: false, error: "self_test_failed" };331 }332 await setupAutoLock();333 broadcastToContentScripts({ type: "VAULT_UNLOCKED" });334 onVaultUnlocked();335 if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());336 return { ok: true };337 }338 339 340 341 const failure = vault.consumeLastUnlockFailureReason();342 if (failure) {343 return {344 ok: false,345 error: "vault_corrupted",346 canRestoreFromHistory: true,347 } as MessageResponse;348 }349 return { ok: false };350 }351 case "VALIDATE_RECOVERY_WORDS": {352 const { words } = msg.payload as { words: string[] };353 const invalid = findInvalidWords(words);354 return { ok: true, data: { valid: invalid.length === 0, invalid } };355 }356 case "GET_RECOVERY_WORDS": {357 358 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };359 360 361 362 363 364 365 366 367 if (!(await isRecoveryConfirmPending())) {368 const { password } = (msg.payload ?? {}) as { password?: string };369 if (typeof password !== "string" || !password) {370 return { ok: false, error: "password_required" };371 }372 if (!(await vault.verifyMainPassword(password))) {373 return { ok: false, error: "wrong_password" };374 }375 }376 try {377 const words = await vault.getRecoveryWords();378 return { ok: true, data: words };379 } catch (e) {380 381 return { ok: false, error: "recovery_not_setup" };382 }383 }384 case "RECOVER_WITH_WORDS": {385 386 387 const { words, newPassword } = msg.payload as {388 words: string[];389 newPassword: string;390 };391 const stored = await vault.loadSlotA();392 if (!stored) return { ok: false, error: "no_vault" };393 if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {394 return { ok: false, error: "recovery_not_setup" };395 }396 397 try {398 await vault.unwrapRootKeyForRecovery(399 stored.recovery_wrapped_root_key,400 stored.recovery_nonce ?? "",401 stored.recovery_tag ?? "",402 stored.recovery_salt,403 words404 );405 } catch {406 return { ok: false, error: "invalid_recovery_words" };407 }408 409 const newSalt = vault.generateSalt();410 const newKey = await vault.deriveKey(newPassword, newSalt);411 412 413 await vault.rewrapRootKeyForPassword(newKey, newSalt);414 415 await vault.changePasswordWithNewKey(newSalt, newKey);416 await setupAutoLock();417 broadcastToContentScripts({ type: "VAULT_UNLOCKED" });418 return { ok: true };419 }420 case "LOCK":421 vault.lock();422 if (isNativePlatform()) await clearInMemoryVault();423 return { ok: true };424 case "IS_UNLOCKED":425 return { ok: true, data: vault.isUnlocked() };426 case "GET_VAULT_STATUS":427 return { ok: true, unlocked: vault.isUnlocked() };428 case "HAS_VAULT":429 return { ok: true, data: await vault.hasVault() };430 case "GET_ENTRIES":431 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };432 return { ok: true, data: vault.getEntries() };433 case "ADD_ENTRY": {434 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };435 const payload = msg.payload;436 if (!payload || typeof payload !== "object" || Array.isArray(payload)) {437 return { ok: false, error: "invalid_payload" };438 }439 const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);440 return { ok: true, data: entry };441 }442 case "BATCH_ADD_ENTRIES": {443 const payload = msg.payload as { entries?: unknown } | null | undefined;444 if (!payload || typeof payload !== "object" || Array.isArray(payload)) {445 return { ok: false, error: "invalid_payload" };446 }447 if (!Array.isArray(payload.entries)) {448 return { ok: false, error: "invalid_payload" };449 }450 const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);451 return { ok: true, data: added };452 }453 case "RESTORE_ENTRIES": {454 const payload = msg.payload as455 | { entries?: unknown; mode?: unknown; settings?: unknown }456 | null457 | undefined;458 if (!payload || typeof payload !== "object" || Array.isArray(payload)) {459 return { ok: false, error: "invalid_payload" };460 }461 if (!Array.isArray(payload.entries)) {462 return { ok: false, error: "invalid_payload" };463 }464 if (payload.mode !== "replace" && payload.mode !== "merge") {465 return { ok: false, error: "invalid_payload" };466 }467 const summary = await vault.restoreEntries(468 payload.entries as Parameters<typeof vault.restoreEntries>[0],469 payload.mode470 );471 if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {472 await vault.updateSettings(payload.settings as vault.VaultSettings);473 }474 return { ok: true, data: summary };475 }476 case "CLEAR_VAULT_ENTRIES": {477 await vault.clearVaultEntries("REPLACE_ALL");478 return { ok: true };479 }480 case "GET_VAULT_HISTORY": {481 const snapshots = await vault.getVaultHistory();482 return { ok: true, data: snapshots };483 }484 case "RESTORE_VAULT_SNAPSHOT": {485 const { snapshotId } = msg.payload as { snapshotId: string };486 const result = await vault.restoreVaultSnapshot(snapshotId);487 if (!result.ok) return { ok: false, error: result.error };488 broadcastToContentScripts({ type: "VAULT_LOCKED" });489 return { ok: true };490 }491 case "COUNT_DUPLICATES": {492 return { ok: true, data: vault.countDuplicates() };493 }494 case "DEDUPLICATE_ENTRIES": {495 const removed = await vault.deduplicateEntries();496 return { ok: true, data: removed };497 }498 case "UPDATE_ENTRY": {499 const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;500 if (!payload || typeof payload !== "object" || Array.isArray(payload)) {501 return { ok: false, error: "invalid_payload" };502 }503 const { id, patch } = payload;504 if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {505 return { ok: false, error: "invalid_payload" };506 }507 508 509 510 511 const incomingCanary = (patch as { canary?: unknown }).canary;512 if (incomingCanary && typeof incomingCanary === "object") {513 const existing = vault.getEntryById(id);514 if (!existing?.canary) {515 const gate = await requirePro("canary_entry");516 if (!gate.allowed) return { ok: false, error: "pro_required" };517 }518 }519 await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);520 return { ok: true };521 }522 case "ADD_ADDITIONAL_URL": {523 const { id, url } = msg.payload as { id: string; url: string };524 const trimmed = typeof url === "string" ? url.trim() : "";525 if (!trimmed) return { ok: false, error: "url_required" };526 const existing = vault.getEntryById(id);527 if (!existing) return { ok: false, error: "entry_not_found" };528 if (existing.type !== "login") return { ok: false, error: "login_entries_only" };529 const merged = [...(existing.additionalUrls ?? []), trimmed];530 await vault.updateEntry(id, { additionalUrls: merged });531 return { ok: true };532 }533 case "DELETE_ENTRY": {534 const { id } = msg.payload as { id: string };535 await vault.deleteEntry(id);536 return { ok: true };537 }538 case "GET_DELETED_ENTRIES":539 return { ok: true, data: vault.getDeletedEntries() };540 case "RESTORE_ENTRY": {541 const { id } = msg.payload as { id: string };542 await vault.restoreEntry(id);543 return { ok: true };544 }545 case "PURGE_ENTRY": {546 const { id } = msg.payload as { id: string };547 await vault.purgeEntry(id);548 return { ok: true };549 }550 case "PURGE_EXPIRED_TRASH": {551 const { retentionMs } = msg.payload as { retentionMs: number };552 const purged = await vault.purgeExpiredTrash(retentionMs);553 return { ok: true, data: purged };554 }555 case "SAVE_NOTE": {556 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };557 const { id, title, body } = msg.payload as { id?: string; title: string; body: string };558 const now = Date.now();559 if (id) {560 const existing = vault.getEntryById(id);561 if (!existing) return { ok: false, error: "not_found" };562 await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });563 return { ok: true, data: vault.getEntryById(id) };564 } else {565 566 567 568 const entry = await vault.addEntry({569 type: "note",570 title: title || "Untitled",571 notes: body,572 });573 return { ok: true, data: entry };574 }575 }576 case "DELETE_NOTE": {577 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };578 const { id } = msg.payload as { id: string };579 await vault.deleteEntry(id);580 return { ok: true };581 }582 case "GET_NOTES": {583 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };584 const notes = vault.getEntries().filter(585 (e) => e.type === "note" && !e.deletedAt586 );587 return { ok: true, data: notes } as MessageResponse;588 }589 case "SEARCH_VAULT": {590 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };591 592 593 const { query } = (msg.payload ?? {}) as { query?: unknown };594 if (typeof query !== "string") {595 return { ok: false, error: "invalid_payload" };596 }597 const q = query.toLowerCase();598 const searchResults = vault.getEntries().filter(599 (e) =>600 !e.deletedAt &&601 (e.title.toLowerCase().includes(q) ||602 e.notes?.toLowerCase().includes(q) ||603 e.username?.toLowerCase().includes(q))604 );605 return { ok: true, data: searchResults } as MessageResponse;606 }607 case "AUTOFILL_QUERY": {608 if (!vault.isUnlocked()) {609 return { ok: false, error: "vault_locked" };610 }611 let { includeAll } = msg.payload as { includeAll?: boolean };612 const { domain, kind, userGesture } = msg.payload as {613 domain: string;614 kind?: "login" | "card" | "totp";615 userGesture?: boolean;616 };617 618 619 620 621 622 623 624 if (includeAll && userGesture !== true) {625 includeAll = false;626 }627 628 629 630 631 if (kind === "card") {632 const cards = vault.getEntries().filter((e) => e.type === "card");633 return {634 ok: true,635 data: cards.map((e) => ({636 id: e.id,637 title: e.cardNickname || e.title,638 cardholderName: e.cardholderName,639 last4: e.last4,640 expMonth: e.expMonth,641 expYear: e.expYear,642 network: e.network,643 })),644 };645 }646 if (kind === "totp") {647 const matches = (648 includeAll649 ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")650 : vault.queryDomain(domain)651 ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));652 return {653 ok: true,654 data: matches.map((e) => ({655 id: e.id,656 title: e.title,657 username: e.username,658 email: e.email,659 url: e.url,660 hasTotp: true,661 })),662 };663 }664 665 666 667 668 669 const matches = (670 includeAll671 ? vault672 .getEntries()673 .filter((entry) => entry.type !== "note" && entry.type !== "card")674 : vault.queryDomain(domain)675 ).filter((entry) => !isPasskeyOnly(entry));676 return {677 ok: true,678 data: matches.map((e) =>679 includeAll680 ? {681 id: e.id,682 title: e.title,683 684 685 686 687 688 username: e.username,689 email: e.email,690 url: e.url,691 hasPasskey: e.passkey !== undefined,692 }693 : {694 id: e.id,695 title: e.title,696 username: e.username,697 email: e.email,698 url: e.url,699 hasTotp: Boolean(e.totp),700 hasPasskey: e.passkey !== undefined,701 }702 ),703 };704 }705 case "GET_ENTRY_FOR_FILL": {706 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };707 const { id, explicitSummon } = msg.payload as {708 id: string;709 explicitSummon?: boolean;710 };711 const entry = vault.getEntryById(id);712 if (!entry) return { ok: false, error: "entry_not_found" };713 714 715 716 if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };717718 719 720 721 722 if (sender.tab !== undefined || sender.url !== undefined) {723 let senderDomain: string | null = null;724 try {725 const rawUrl = sender.tab?.url ?? sender.url ?? "";726 senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;727 } catch {728 senderDomain = null;729 }730 if (!senderDomain) return { ok: false, error: "origin_unverified" };731732 const entryDomains = new Set<string>();733 const primary = extractDomain(entry.url ?? "");734 if (primary) entryDomains.add(primary);735 for (const extra of entry.additionalUrls ?? []) {736 const d = extractDomain(extra);737 if (d) entryDomains.add(d);738 }739740 741 742 743 if (explicitSummon !== true && !entryDomains.has(senderDomain)) {744 745 return { ok: false, error: "entry_not_found" };746 }747 }748 749 750 751 752 753 754 755 756 757 758 const {759 passkey: _strippedPasskey,760 totp: seed,761 totpAlgorithm,762 totpDigits,763 totpPeriod,764 passwordHistory: _ph,765 ...safeEntry766 } = entry;767 let totpCode: string | undefined;768 let totpRemaining: number | undefined;769 if (seed) {770 try {771 772 773 const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);774 totpCode = generated.code;775 totpRemaining = generated.remaining;776 } catch {777 totpCode = undefined;778 }779 }780 return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };781 }782 783 784 785 786 787 788 case "GET_ENTRY_FOR_EDIT": {789 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };790 const { id, explicitSummon } = msg.payload as {791 id: string;792 explicitSummon?: boolean;793 };794 const entry = vault.getEntryById(id);795 if (!entry) return { ok: false, error: "entry_not_found" };796797 798 799 800 801 802 803 804 805 if (sender.tab !== undefined || sender.url !== undefined) {806 let senderDomain: string | null = null;807 try {808 const rawUrl = sender.tab?.url ?? sender.url ?? "";809 senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;810 } catch {811 senderDomain = null;812 }813 if (senderDomain) {814 const entryDomains = new Set<string>();815 const primary = extractDomain(entry.url ?? "");816 if (primary) entryDomains.add(primary);817 for (const extra of entry.additionalUrls ?? []) {818 const d = extractDomain(extra);819 if (d) entryDomains.add(d);820 }821 if (explicitSummon !== true && !entryDomains.has(senderDomain)) {822 return { ok: false, error: "entry_not_found" }; 823 }824 }825 }826827 const { passkey: _passkey, ...safeEntry } = entry;828 return { ok: true, data: safeEntry };829 }830 case "COPY": {831 832 833 834 const { text, label, alreadyWritten } = (msg.payload ?? {}) as {835 text?: unknown;836 label?: unknown;837 alreadyWritten?: unknown;838 };839 if (typeof text !== "string" || typeof label !== "string") {840 return { ok: false, error: "invalid_payload" };841 }842 await copyToClipboard(text, label, Boolean(alreadyWritten));843 return { ok: true, clearSeconds: getEffectiveClearSeconds() };844 }845 case "CHECK_ALL_BREACHES": {846 const allEntries = vault.getEntries();847 const results: Record<string, number> = {};848 for (const entry of allEntries) {849 if (entry.type === "note") continue;850 if (!entry.password) continue;851 results[entry.id] = await vault.checkBreach(entry.password);852 853 await new Promise((r) => setTimeout(r, 200));854 }855 856 for (const [id, count] of Object.entries(results)) {857 const entry = vault.getEntryById(id);858 if (entry && (entry.breach ?? 0) !== count) {859 await vault.updateEntry(id, { breach: count > 0 ? count : undefined });860 }861 }862 return { ok: true, data: results };863 }864 case "GET_SETTINGS":865 return { ok: true, data: await vault.ensureSettingsLoaded() };866 case "UPDATE_SETTINGS": {867 const patch = msg.payload;868 if (!patch || typeof patch !== "object" || Array.isArray(patch)) {869 return { ok: false, error: "invalid_payload" };870 }871 await vault.updateSettings(patch as vault.VaultSettings);872 if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {873 await setupAutoLock();874 if (vault.isUnlocked()) touchAutoLock();875 }876 return { ok: true };877 }878 case "GET_PENDING_PASSKEY":879 return { ok: true, data: await getPendingPasskeyRequest() };880 case "APPROVE_PASSKEY": {881 const { requestId } = msg.payload as { requestId: number };882 await resolvePendingPasskeyRequest(requestId, true);883 return { ok: true };884 }885 case "DENY_PASSKEY": {886 const { requestId } = msg.payload as { requestId: number };887 await resolvePendingPasskeyRequest(requestId, false);888 return { ok: true };889 }890 case "GET_PASSKEY_PROVIDER_STATE":891 return { ok: true, data: await getPasskeyProviderState() };892 case "SET_PASSKEY_PROVIDER_ENABLED": {893 const { enabled } = msg.payload as { enabled: boolean };894 895 896 if (enabled) {897 const gate = await requirePro("passkeys");898 if (!gate.allowed) return { ok: false, error: "pro_required" };899 }900 return { ok: true, data: await setPasskeyProviderEnabled(enabled) };901 }902 903 904 905 906 907 908 case "FIRE_CANARY_PING": {909 910 911 912 913 const { webhookUrl, entryTitle, trigger } = msg.payload as {914 webhookUrl: string;915 entryTitle: string;916 trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";917 };918 if (!isAllowedCanaryWebhookUrl(webhookUrl)) {919 return { ok: false, error: "invalid_webhook_url" };920 }921 922 923 924 925 926 927 928 if (trigger !== "test") {929 const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;930 const stored = await chrome.storage.local.get(rlKey);931 const last = (stored as Record<string, unknown>)[rlKey];932 if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {933 return { ok: true, data: { rateLimited: true } };934 }935 await chrome.storage.local.set({ [rlKey]: Date.now() });936 }937 const body = JSON.stringify({938 event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",939 entry: entryTitle,940 trigger,941 timestamp: new Date().toISOString(),942 source: "peach-extension",943 });944 if (trigger === "test") {945 946 947 948 949 950 try {951 const res = await fetch(webhookUrl, {952 method: "POST",953 headers: { "Content-Type": "application/json" },954 body,955 });956 return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };957 } catch (err) {958 return { ok: false, error: err instanceof Error ? err.message : "network_error" };959 }960 }961 962 fetch(webhookUrl, {963 method: "POST",964 headers: { "Content-Type": "application/json" },965 body,966 }).catch(() => {});967 return { ok: true };968 }969 case "ACTIVATE_LICENSE": {970 const { key } = msg.payload as { key: string };971 const licenseInfo = await activateLicense(key);972 return { ok: true, data: licenseInfo };973 }974 case "GET_LICENSE": {975 const licenseInfo = await getLicenseInfo();976 return { ok: true, data: licenseInfo };977 }978 case "GET_LICENSE_KEY": {979 const key = await getLicenseKey();980 return { ok: true, data: key };981 }982 case "DEACTIVATE_LICENSE": {983 await deactivateLicense();984 return { ok: true };985 }986 case "SHOULD_PLAY_CELEBRATION": {987 const should = await shouldPlayCelebration();988 return { ok: true, data: should };989 }990 case "MARK_CELEBRATION_PLAYED": {991 await markCelebrationPlayed();992 return { ok: true };993 }994 case "GET_CODEX_VAULT_DATA": {995 996 997 const gate = await requirePro("codex");998 if (!gate.allowed) return { ok: false, error: "pro_required" };999 return await handleGetCodexVaultData();1000 }1001 case "ESTIMATE_CODEX_PAGES": {1002 const gate = await requirePro("codex");1003 if (!gate.allowed) return { ok: false, error: "pro_required" };1004 return await handleEstimateCodexPages();1005 }1006 case "RESTORE_FROM_CODEX": {1007 1008 1009 1010 const payload = msg.payload as CodexRestorePayload;1011 return await handleRestoreFromCodex(payload);1012 }1013 case "OPEN_PRO_GATE": {1014 1015 const { feature } = (msg.payload ?? {}) as { feature?: string };1016 if (chrome.storage.session) {1017 await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1018 }1019 try { await chrome.action.openPopup(); } catch { }1020 return { ok: true };1021 }1022 case "OPEN_POPUP": {1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 if (chrome.storage.session) {1033 await chrome.storage.session.set({ peach_inline_unlock: true });1034 }1035 try { await chrome.action.openPopup(); } catch { }1036 return { ok: true };1037 }1038 case "GET_IDENTITIES": {1039 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1040 return { ok: true, data: vault.getIdentities() };1041 }1042 case "TOUCH_AUTO_LOCK": {1043 1044 1045 return { ok: true };1046 }1047 case "GET_ADVANCED_HEALTH_REPORT": {1048 const gate = await requirePro("advanced_health");1049 if (!gate.allowed) return { ok: false, error: "pro_required" };1050 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1051 const report = await buildAdvancedHealthReport(vault.getEntries());1052 return { ok: true, data: report };1053 }1054 case "IS_DURESS_ENABLED": {1055 const enabled = await vault.isDuressEnabled();1056 return { ok: true, data: enabled };1057 }1058 case "SETUP_DURESS": {1059 1060 1061 1062 1063 const gate = await requirePro("duress_vault");1064 if (!gate.allowed) return { ok: false, error: "pro_required" };1065 1066 1067 1068 if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1069 const { duressPassword } = msg.payload as { duressPassword: string };1070 await vault.setupDuress(duressPassword);1071 return { ok: true };1072 }1073 case "DISABLE_DURESS": {1074 await vault.disableDuress();1075 return { ok: true };1076 }1077 case "VERIFY_MAIN_PASSWORD": {1078 const { password } = msg.payload as { password: string };1079 const ok = await vault.verifyMainPassword(password);1080 return { ok: true, data: ok };1081 }1082 case "CHANGE_PASSWORD": {1083 const { currentPassword, newPassword } = msg.payload as {1084 currentPassword: string;1085 newPassword: string;1086 };1087 const changed = await vault.changePassword(currentPassword, newPassword);1088 return changed1089 ? { ok: true }1090 : { ok: false, error: "incorrect_current_password" };1091 }1092 case "GET_SITE_PASSWORD_POLICY": {1093 const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1094 if (!tab?.id) return { ok: true, data: null };1095 try {1096 const response = await chrome.tabs.sendMessage(tab.id, {1097 type: "GET_SITE_PASSWORD_POLICY",1098 });1099 return (response as MessageResponse) ?? { ok: true, data: null };1100 } catch {1101 return { ok: true, data: null };1102 }1103 }1104 case "RECORD_MANUAL_SUMMON": {1105 const { domain } = msg.payload as { domain: string };1106 const settings = vault.getSettings();1107 const existing = settings.manualSummonDomains?.[domain];1108 const now = Date.now();1109 await vault.updateSettings({1110 manualSummonDomains: {1111 ...settings.manualSummonDomains,1112 [domain]: {1113 firstSummonedAt: existing?.firstSummonedAt ?? now,1114 summonCount: (existing?.summonCount ?? 0) + 1,1115 lastSummonedAt: now,1116 },1117 },1118 });1119 return { ok: true };1120 }1121 case "DECLINE_CARD_SAVE": {1122 const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1123 await vault.declineCardSaveOffer(last4, expMonth, expYear);1124 return { ok: true };1125 }1126 case "IS_CARD_DECLINED": {1127 const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1128 const declined = await vault.isCardDeclined(last4, expMonth, expYear);1129 return { ok: true, data: declined };1130 }1131 case "INITIATE_FIREFOX_PASSKEY_CREATE": {1132 const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1133 rpId?: string;1134 rpName?: string;1135 userName?: string;1136 userDisplayName?: string;1137 };1138 if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1139 return await initiateFirefoxPasskeyCreate({1140 rpId,1141 rpName: rpName ?? rpId,1142 userName,1143 userDisplayName,1144 });1145 }11461147 case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1148 const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1149 if (!payload) return { ok: false, error: "missing_payload" };1150 return await completeFirefoxPasskeyCreate(payload);1151 }11521153 case "PASSKEY_OFFER_DECLINE": {1154 const { domain } = (msg.payload ?? {}) as { domain?: string };1155 if (!domain) return { ok: false, error: "domain_required" };1156 await recordPasskeyOfferDecline(domain);1157 return { ok: true };1158 }11591160 case "GET_PASSKEY_OFFER_DECLINED": {1161 const { domain } = (msg.payload ?? {}) as { domain?: string };1162 if (!domain) return { ok: false, error: "domain_required" };1163 return { ok: true, data: await isPasskeyOfferDeclined(domain) };1164 }11651166 case "PASSKEY_HAS_CREDENTIALS": {1167 const payload = msg.payload as {1168 rpId?: string;1169 allowCredentials?: Array<{ id: string; type?: string }>;1170 } | undefined;1171 if (!payload?.rpId) return { ok: false, error: "rpid_required" };1172 return await handlePasskeyHasCredentials({1173 rpId: payload.rpId,1174 allowCredentials: payload.allowCredentials ?? [],1175 }, attestedSenderOrigin(sender));1176 }11771178 case "PASSKEY_CREATE": {1179 const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1180 if (!payload?.rpId || !payload?.userName) {1181 return { ok: false, error: "rpid_and_username_required" };1182 }1183 return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1184 }11851186 case "PASSKEY_GET": {1187 const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1188 if (!payload?.rpId) return { ok: false, error: "rpid_required" };1189 return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1190 }11911192 case "PASSKEY_AUTH_RESPONSE": {1193 const { requestId, approved } = (msg.payload ?? {}) as {1194 requestId?: string | number;1195 approved?: boolean;1196 };1197 if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1198 return { ok: false, error: 'requestId and approved required' };1199 }1200 await resolvePendingPasskeyRequest(Number(requestId), approved);1201 return { ok: true };1202 }12031204 case "GET_PASSKEY_FOR_DOMAIN": {1205 const { domain } = (msg.payload ?? {}) as { domain?: string };1206 if (!domain) return { ok: false, error: "domain_required" };1207 1208 1209 1210 const origin = attestedSenderOrigin(sender);1211 if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1212 if (!vault.isUnlocked()) return { ok: true, data: null };1213 const match = vault1214 .getEntries()1215 .find((entry) => entry.passkey?.rpId === domain);1216 if (!match || !match.passkey) return { ok: true, data: null };1217 1218 1219 return {1220 ok: true,1221 data: {1222 rpId: match.passkey.rpId,1223 userName: match.passkey.userName,1224 browser: match.passkey.browser,1225 },1226 };1227 }12281229 case "DESTROY_VAULT": {1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 const preserved = await chrome.storage.local.get([1241 "peach_license",1242 "peach_pro_celebrated",1243 ]);1244 vault.lock();1245 await storageClear();1246 await vault.clearVaultHistory();1247 const toRestore: Record<string, unknown> = {};1248 if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1249 if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1250 if (Object.keys(toRestore).length > 0) {1251 await chrome.storage.local.set(toRestore);1252 }1253 if (chrome.storage.session) {1254 await chrome.storage.session.clear();1255 }1256 return { ok: true };1257 }12581259 case "SUBMIT_FEEDBACK": {1260 const { category, message, version, browser } = msg.payload as {1261 category: string;1262 message: string;1263 version: string;1264 browser: string;1265 };1266 if (!message.trim()) return { ok: false, error: "message_empty" };1267 if (!FEEDBACK_ENDPOINT) return { ok: true };1268 if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1269 return { ok: false, error: "invalid_feedback_endpoint" };1270 }1271 try {1272 const res = await fetch(FEEDBACK_ENDPOINT, {1273 method: "POST",1274 headers: { "Content-Type": "application/json" },1275 body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1276 });1277 return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1278 } catch (err) {1279 return { ok: false, error: err instanceof Error ? err.message : "network_error" };1280 }1281 }1282 1283 case "UNLOCK_WITH_KEY": {1284 const { masterKeyHex } = msg.payload as { masterKeyHex: string };1285 if (!isNativePlatform()) {1286 return { ok: false, error: "desktop_only_uses_password" };1287 }1288 try {1289 const result = await vault.unlockWithKey(masterKeyHex);1290 if (result.ok) {1291 onVaultUnlocked();1292 await publishInMemoryVault(result.entries);1293 }1294 return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1295 } catch {1296 return { ok: false, error: "invalid_key" };1297 }1298 }1299 1300 case "GET_DERIVED_KEY": {1301 if (!isNativePlatform()) {1302 return { ok: false, error: "android_only" };1303 }1304 if (!vault.isUnlocked()) {1305 return { ok: false, error: "vault_locked" };1306 }1307 return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1308 }1309 case "GET_IDENTITY_SUGGESTIONS": {1310 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1311 const entries = vault.getEntries();1312 const suggestions = buildIdentitySuggestions(entries);1313 return { ok: true, data: { suggestions } };1314 }1315 case "POPULATE_INLINE_VAULT": {1316 if (!isNativePlatform()) return { ok: false };1317 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1318 const entries = vault.getEntries();1319 await publishInMemoryVault(entries);1320 return { ok: true };1321 }1322 case "ML_INIT":1323 return { ok: true };13241325 case "ML_PREDICT_BATCH": {1326 1327 const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1328 if (!Array.isArray(featuresArray)) {1329 return { ok: false, error: "invalid_payload" };1330 }1331 return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1332 }13331334 1335 1336 1337 1338 case "CHIRP_GET_LOCAL_IDENTITY": {1339 1340 1341 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1342 1343 1344 const masterKeyHex = vault.getRootKeyHex();1345 if (!masterKeyHex) return { ok: false, error: "vault_locked" };1346 const masterKey = unhexBytes(masterKeyHex);1347 try {1348 const identity = await buildLocalIdentity(masterKey);1349 1350 1351 if (await isProUser()) {1352 const license = await getLicenseKey();1353 if (license) (identity as { license?: string }).license = license;1354 }1355 return { ok: true, data: identity };1356 } finally {1357 masterKey.fill(0);1358 }1359 }13601361 case "CHIRP_GET_ADOPTION_MATERIAL": {1362 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1363 const rootKeyHex = vault.getRootKeyHex();1364 if (!rootKeyHex) return { ok: false, error: "vault_locked" };1365 const rootKeyBytes = unhexBytes(rootKeyHex);1366 try {1367 const data: { rootKeyHex: string; vaultId: string; license?: string } = {1368 rootKeyHex,1369 vaultId: await computeVaultId(rootKeyBytes),1370 };1371 if (await isProUser()) {1372 const license = await getLicenseKey();1373 if (license) data.license = license;1374 }1375 return { ok: true, data };1376 } finally {1377 rootKeyBytes.fill(0);1378 }1379 }13801381 case "CHIRP_COMPLETE_PAIRING": {1382 1383 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1384 const paired = (msg.payload as { paired?: unknown })?.paired;1385 if (typeof paired !== "object" || paired === null) {1386 return { ok: false, error: "invalid_payload" };1387 }1388 const candidate = paired as Record<string, unknown>;1389 if (1390 typeof candidate.deviceId !== "string" || !candidate.deviceId ||1391 typeof candidate.deviceName !== "string" || !candidate.deviceName ||1392 typeof candidate.deviceType !== "string" ||1393 typeof candidate.longTermPublicKeyHex !== "string" ||1394 !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1395 (1396 candidate.signingPublicKeyHex !== undefined &&1397 (1398 typeof candidate.signingPublicKeyHex !== "string" ||1399 !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1400 )1401 ) ||1402 typeof candidate.pairedAt !== "number"1403 ) {1404 return { ok: false, error: "invalid_paired_device" };1405 }1406 await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1407 return { ok: true };1408 }14091410 case "CHIRP_LIST_PAIRED_DEVICES": {1411 const devices = await listPairedDevicesV3();1412 return { ok: true, data: { devices } };1413 }14141415 case "CHIRP_UNPAIR_DEVICE": {1416 const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1417 if (typeof deviceId !== "string" || !deviceId) {1418 return { ok: false, error: "invalid_payload" };1419 }1420 await removePairedDeviceByIdV3(deviceId);1421 return { ok: true };1422 }14231424 case "CHIRP_RENAME_LOCAL_DEVICE": {1425 const { name } = (msg.payload ?? {}) as { name?: string };1426 if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1427 await setDeviceNameV3(name);1428 return { ok: true };1429 }14301431 1432 1433 1434 1435 case "PAIR_WITH_CODE": {1436 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1437 const { code } = (msg.payload ?? {}) as { code?: string };1438 if (typeof code !== "string" || !/\d/.test(code)) {1439 return { ok: false, error: "invalid_payload" };1440 }1441 const { startCodePairing, isCodePairingInFlight } = await import(1442 "./code-pairing-bg"1443 );1444 if (isCodePairingInFlight()) return { ok: false, error: "pairing_in_progress" };1445 startCodePairing(code);1446 return { ok: true };1447 }14481449 case "CODE_PAIR_CONFIRM": {1450 const { confirmed } = (msg.payload ?? {}) as { confirmed?: boolean };1451 const { resolveCodePairingConfirm } = await import("./code-pairing-bg");1452 resolveCodePairingConfirm(confirmed === true);1453 return { ok: true };1454 }14551456 case "TRIGGER_SYNC": {1457 const payload = (msg.payload ?? {}) as {1458 reason?: "vault_change" | "foreground" | "manual" | "mdns";1459 force?: boolean;1460 deviceId?: string;1461 discoveredIp?: string;1462 discoveredPort?: number;1463 };1464 const reason = payload.reason ?? "foreground";14651466 1467 1468 1469 if (1470 reason === "mdns" &&1471 typeof payload.deviceId === "string" &&1472 typeof payload.discoveredIp === "string"1473 ) {1474 const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1475 const device = await findPairedDeviceById(payload.deviceId);1476 if (device?.longTermPublicKeyHex) {1477 await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1478 }1479 }14801481 const { triggerSyncIfReachable } = await import("./sync-trigger");1482 void triggerSyncIfReachable({ reason, force: payload.force === true });1483 return { ok: true };1484 }14851486 case "GET_SYNC_STATE": {1487 const { getSyncState } = await import("./sync-trigger");1488 return { ok: true, data: getSyncState() };1489 }14901491 case "GET_SYNC_ALERTS": {1492 const { consume } = (msg.payload ?? {}) as { consume?: boolean };1493 const alerts = await getPendingSyncAlerts();1494 1495 1496 1497 if (consume) await clearPendingSyncAlerts();1498 return { ok: true, data: alerts };1499 }15001501 case "GET_PENDING_VOUCHED_DEVICES": {1502 return { ok: true, data: await listPendingVouchedDevices() };1503 }1504 case "CONFIRM_VOUCHED_DEVICE": {1505 const { deviceId } = msg.payload as { deviceId: string };1506 const pending = await getPendingVouchedDevice(deviceId);1507 if (!pending) return { ok: false, error: "not_pending" };1508 await upsertPairedDeviceV3({1509 deviceId: pending.deviceId,1510 deviceName: pending.deviceName,1511 deviceType:1512 pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1513 longTermPublicKeyHex: pending.longTermPublicKeyHex,1514 signingPublicKeyHex: pending.signingPublicKeyHex,1515 wsPort: pending.wsPort,1516 pairedAt: pending.pairedAt,1517 trustSource: "vouched",1518 });1519 await removePendingVouchedDevice(deviceId);1520 return { ok: true };1521 }1522 case "REJECT_VOUCHED_DEVICE": {1523 const { deviceId } = msg.payload as { deviceId: string };1524 await removePendingVouchedDevice(deviceId);1525 return { ok: true };1526 }1527 case "ROTATE_SYNC_IDENTITY": {1528 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1529 const result = await vault.rotateSyncIdentity();1530 return result.ok ? { ok: true } : { ok: false, error: result.error };1531 }15321533 default:1534 return { ok: false, error: "unknown_message_type" };1535 }1536 } catch (err) {1537 return {1538 ok: false,1539 error: err instanceof Error ? err.message : "operation_failed",1540 };1541 }1542}15431544154515461547async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1548 const plugin = nativePlugin<{1549 setEntries?: (args: {1550 entries: Array<{1551 id: string;1552 title: string;1553 username: string;1554 email: string;1555 password: string;1556 url: string;1557 totp: string;1558 additionalUrls: string[];1559 }>;1560 }) => Promise<void>;1561 }>("InMemoryVaultPlugin");1562 if (!plugin?.setEntries) return;1563 await plugin.setEntries({1564 entries: entries.map((e) => ({1565 id: e.id,1566 title: e.title ?? "",1567 username: e.username ?? "",1568 email: (e as VaultEntry & { email?: string }).email ?? "",1569 password: e.password ?? "",1570 url: e.url ?? "",1571 totp: (e as VaultEntry & { totp?: string }).totp ?? "",1572 additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1573 })),1574 });1575}157615771578async function clearInMemoryVault(): Promise<void> {1579 const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1580 if (!plugin?.clearEntries) return;1581 await plugin.clearEntries();1582}15831584158515861587function buildIdentitySuggestions(1588 entries: VaultEntry[],1589): Array<{ email: string; username: string; count: number }> {1590 const usernameCounts = new Map<string, number>();1591 const usernameEmail = new Map<string, string>();1592 for (const entry of entries) {1593 const username = entry.username ?? "";1594 const email = (entry as VaultEntry & { email?: string }).email ?? "";1595 if (!username && !email) continue;1596 const key = username || email;1597 usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1598 if (!usernameEmail.has(key)) usernameEmail.set(key, email);1599 }1600 return Array.from(usernameCounts.entries())1601 .sort((a, b) => b[1] - a[1])1602 .map(([username, count]) => ({1603 email: usernameEmail.get(username) ?? "",1604 username,1605 count,1606 }));1607}160816091610function broadcastToContentScripts(message: { type: string }): void {1611 if (!chrome.tabs?.query) return;1612 chrome.tabs.query({}, (tabs) => {1613 for (const tab of tabs) {1614 if (tab.id !== undefined) {1615 chrome.tabs.sendMessage(tab.id, message).catch(() => {1616 1617 });1618 }1619 }1620 });1621}16221623function shouldRefreshAutoLock(type: MessageType): boolean {1624 return (1625 type !== "HAS_VAULT" &&1626 type !== "IS_UNLOCKED" &&1627 type !== "GET_VAULT_STATUS" &&1628 type !== "LOCK" &&1629 type !== "UPDATE_SETTINGS" &&1630 type !== "GET_PENDING_PASSKEY" &&1631 type !== "GET_PASSKEY_PROVIDER_STATE" &&1632 type !== "DECLINE_CARD_SAVE" &&1633 type !== "IS_CARD_DECLINED" &&1634 type !== "SUBMIT_FEEDBACK"1635 );1636}16371638function isAllowedCanaryWebhookUrl(value: string): boolean {1639 try {1640 const url = new URL(value);1641 if (url.protocol !== "https:") return false;16421643 const hostname = url.hostname.toLowerCase();1644 if (1645 hostname === "localhost" ||1646 hostname.endsWith(".localhost") ||1647 isPrivateIpv4(hostname) ||1648 isPrivateIpv6(hostname)1649 ) {1650 return false;1651 }16521653 return true;1654 } catch {1655 return false;1656 }1657}16581659function isPrivateIpv4(hostname: string): boolean {1660 if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1661 return true;1662 }16631664 const octets = hostname.split(".").map((part) => Number(part));1665 if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1666 return false;1667 }16681669 return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1670}16711672function isPrivateIpv6(hostname: string): boolean {1673 const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1674 return (1675 normalized === "::1" ||1676 normalized.startsWith("fc") ||1677 normalized.startsWith("fd") ||1678 normalized.startsWith("fe80:")1679 );1680}