123456789101112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import { runSelfTest } from "./self-test";15import * as vault from "./vault";16import {17 handleEstimateCodexPages,18 handleGetCodexVaultData,19 handleRestoreFromCodex,20} from "./codex-handlers";21import type { CodexRestorePayload } from "../shared/codex-types";22import {23 activateLicense,24 deactivateLicense,25 getLicenseInfo,26 getLicenseKey,27 isProUser,28 markCelebrationPlayed,29 shouldPlayCelebration,30} from "./license";31import {32 completeFirefoxPasskeyCreate,33 getPasskeyProviderState,34 getPendingPasskeyRequest,35 handleFirefoxPasskeyCreate,36 handleFirefoxPasskeyGet,37 handlePasskeyHasCredentials,38 initiateFirefoxPasskeyCreate,39 isPasskeyOfferDeclined,40 onVaultUnlocked,41 recordPasskeyOfferDecline,42 resolvePendingPasskeyRequest,43 setPasskeyProviderEnabled,44} from "./passkey";45import { buildAdvancedHealthReport } from "./health";46import { storageClear } from "../shared/storage";47import { findInvalidWords } from "../shared/recovery-words";48import type {49 Message,50 MessageResponse,51 MessageType,52 ProFeature,53 VaultEntry,54} from "../shared/types";55import { isPasskeyOnly } from "../shared/types";56import { isNativePlatform, nativePlugin } from "../shared/native";57import { predictBatch as mlPredictBatch } from "./ml";58import type { MLFieldFeatures } from "../shared/ml";59import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";60import {61 listPairedDevices as listPairedDevicesV3,62 removePairedDeviceById as removePairedDeviceByIdV3,63 upsertPairedDevice as upsertPairedDeviceV3,64} from "./paired-devices";6566function unhexBytes(hex: string): Uint8Array {67 if (hex.length % 2 !== 0) throw new Error("invalid hex");68 const out = new Uint8Array(hex.length / 2);69 for (let i = 0; i < out.length; i++) {70 out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);71 }72 return out;73}7475767778798081async function requirePro(82 feature: ProFeature,83 trigger: "user" | "background" = "user"84): Promise<{ allowed: boolean }> {85 if (await isProUser()) return { allowed: true };8687 if (trigger === "user") {88 89 chrome.runtime90 .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })91 .catch(() => {92 93 });94 } else {95 96 97 98 if (chrome.storage.session) {99 chrome.storage.session100 .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })101 .catch(() => {});102 }103 }104105 return { allowed: false };106}107108109110111112113114115const FEEDBACK_ENDPOINT = "";116117const PRIVATE_IPV4_RANGES = [118 { prefix: "10." },119 { prefix: "127." },120 { prefix: "169.254." },121 { prefix: "192.168." },122];123124export function setupMessageHandler(): void {125 chrome.runtime.onMessage.addListener(126 (msg: unknown, sender, sendResponse) => {127 if (!isMessage(msg)) {128 sendResponse({ ok: false, error: "invalid_message" });129 return true;130 }131 handleMessage(msg, sender)132 .then(sendResponse)133 .catch((err) =>134 sendResponse({135 ok: false,136 error: err instanceof Error ? err.message : String(err),137 })138 );139 return true;140 }141 );142143 144 145 146 const reg = (globalThis as any).__peachRegisterMessageHandler;147 if (typeof reg === "function") {148 reg(async (m: unknown) => {149 if (!isMessage(m)) return { ok: false, error: "invalid_message" };150 try {151 return await handleMessage(m);152 } catch (err) {153 return {154 ok: false,155 error: err instanceof Error ? err.message : String(err),156 };157 }158 });159 }160161}162163function isMessage(m: unknown): m is Message {164 return typeof m === "object" && m !== null && "type" in m;165}166167export async function handleMessage(168 msg: Message,169 sender: Partial<chrome.runtime.MessageSender> = {}170): Promise<MessageResponse> {171 try {172 173 174 175 176 if (177 sender.id !== undefined &&178 sender.id !== chrome.runtime.id179 ) {180 return { ok: false, error: "invalid_sender" };181 }182183 if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {184 touchAutoLock();185 }186187 switch (msg.type) {188 case "CREATE_VAULT": {189 const { password } = msg.payload as { password: string };190 await vault.createVault(password);191 await setupAutoLock();192 broadcastToContentScripts({ type: "VAULT_UNLOCKED" });193 onVaultUnlocked();194 return { ok: true };195 }196 case "UNLOCK": {197 const { password } = msg.payload as { password: string };198 const ok = await vault.unlock(password);199 if (ok) {200 201 202 const kat = await runSelfTest();203 if (!kat.ok) {204 console.error("[Peach] Crypto self-test FAILED:", kat.error);205 await vault.lock();206 return { ok: false, error: "self_test_failed" };207 }208 await setupAutoLock();209 broadcastToContentScripts({ type: "VAULT_UNLOCKED" });210 onVaultUnlocked();211 if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());212 return { ok: true };213 }214 215 216 217 const failure = vault.consumeLastUnlockFailureReason();218 if (failure) {219 return {220 ok: false,221 error: "vault_corrupted",222 canRestoreFromHistory: true,223 } as MessageResponse;224 }225 return { ok: false };226 }227 case "VALIDATE_RECOVERY_WORDS": {228 const { words } = msg.payload as { words: string[] };229 const invalid = findInvalidWords(words);230 return { ok: true, data: { valid: invalid.length === 0, invalid } };231 }232 case "GET_RECOVERY_WORDS": {233 234 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };235 try {236 const words = await vault.getRecoveryWords();237 return { ok: true, data: words };238 } catch (e) {239 240 return { ok: false, error: "recovery_not_setup" };241 }242 }243 case "RECOVER_WITH_WORDS": {244 245 246 const { words, newPassword } = msg.payload as {247 words: string[];248 newPassword: string;249 };250 const stored = await vault.loadSlotA();251 if (!stored) return { ok: false, error: "no_vault" };252 if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {253 return { ok: false, error: "recovery_not_setup" };254 }255 256 try {257 await vault.unwrapRootKeyForRecovery(258 stored.recovery_wrapped_root_key,259 stored.recovery_nonce ?? "",260 stored.recovery_tag ?? "",261 stored.recovery_salt,262 words263 );264 } catch {265 return { ok: false, error: "invalid_recovery_words" };266 }267 268 const newSalt = vault.generateSalt();269 const newKey = await vault.deriveKey(newPassword, newSalt);270 271 272 await vault.rewrapRootKeyForPassword(newKey, newSalt);273 274 await vault.changePasswordWithNewKey(newSalt, newKey);275 await setupAutoLock();276 broadcastToContentScripts({ type: "VAULT_UNLOCKED" });277 return { ok: true };278 }279 case "LOCK":280 vault.lock();281 if (isNativePlatform()) await clearInMemoryVault();282 return { ok: true };283 case "IS_UNLOCKED":284 return { ok: true, data: vault.isUnlocked() };285 case "GET_VAULT_STATUS":286 return { ok: true, unlocked: vault.isUnlocked() };287 case "HAS_VAULT":288 return { ok: true, data: await vault.hasVault() };289 case "GET_ENTRIES":290 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };291 return { ok: true, data: vault.getEntries() };292 case "ADD_ENTRY": {293 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };294 const payload = msg.payload;295 if (!payload || typeof payload !== "object" || Array.isArray(payload)) {296 return { ok: false, error: "invalid_payload" };297 }298 const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);299 return { ok: true, data: entry };300 }301 case "BATCH_ADD_ENTRIES": {302 const payload = msg.payload as { entries?: unknown } | null | undefined;303 if (!payload || typeof payload !== "object" || Array.isArray(payload)) {304 return { ok: false, error: "invalid_payload" };305 }306 if (!Array.isArray(payload.entries)) {307 return { ok: false, error: "invalid_payload" };308 }309 const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);310 return { ok: true, data: added };311 }312 case "RESTORE_ENTRIES": {313 const payload = msg.payload as314 | { entries?: unknown; mode?: unknown; settings?: unknown }315 | null316 | undefined;317 if (!payload || typeof payload !== "object" || Array.isArray(payload)) {318 return { ok: false, error: "invalid_payload" };319 }320 if (!Array.isArray(payload.entries)) {321 return { ok: false, error: "invalid_payload" };322 }323 if (payload.mode !== "replace" && payload.mode !== "merge") {324 return { ok: false, error: "invalid_payload" };325 }326 const summary = await vault.restoreEntries(327 payload.entries as Parameters<typeof vault.restoreEntries>[0],328 payload.mode329 );330 if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {331 await vault.updateSettings(payload.settings as vault.VaultSettings);332 }333 return { ok: true, data: summary };334 }335 case "CLEAR_VAULT_ENTRIES": {336 await vault.clearVaultEntries("REPLACE_ALL");337 return { ok: true };338 }339 case "GET_VAULT_HISTORY": {340 const snapshots = await vault.getVaultHistory();341 return { ok: true, data: snapshots };342 }343 case "RESTORE_VAULT_SNAPSHOT": {344 const { snapshotId } = msg.payload as { snapshotId: string };345 const result = await vault.restoreVaultSnapshot(snapshotId);346 if (!result.ok) return { ok: false, error: result.error };347 broadcastToContentScripts({ type: "VAULT_LOCKED" });348 return { ok: true };349 }350 case "COUNT_DUPLICATES": {351 return { ok: true, data: vault.countDuplicates() };352 }353 case "DEDUPLICATE_ENTRIES": {354 const removed = await vault.deduplicateEntries();355 return { ok: true, data: removed };356 }357 case "UPDATE_ENTRY": {358 const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;359 if (!payload || typeof payload !== "object" || Array.isArray(payload)) {360 return { ok: false, error: "invalid_payload" };361 }362 const { id, patch } = payload;363 if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {364 return { ok: false, error: "invalid_payload" };365 }366 367 368 369 370 const incomingCanary = (patch as { canary?: unknown }).canary;371 if (incomingCanary && typeof incomingCanary === "object") {372 const existing = vault.getEntryById(id);373 if (!existing?.canary) {374 const gate = await requirePro("canary_entry");375 if (!gate.allowed) return { ok: false, error: "pro_required" };376 }377 }378 await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);379 return { ok: true };380 }381 case "ADD_ADDITIONAL_URL": {382 const { id, url } = msg.payload as { id: string; url: string };383 const trimmed = typeof url === "string" ? url.trim() : "";384 if (!trimmed) return { ok: false, error: "url_required" };385 const existing = vault.getEntryById(id);386 if (!existing) return { ok: false, error: "entry_not_found" };387 if (existing.type !== "login") return { ok: false, error: "login_entries_only" };388 const merged = [...(existing.additionalUrls ?? []), trimmed];389 await vault.updateEntry(id, { additionalUrls: merged });390 return { ok: true };391 }392 case "DELETE_ENTRY": {393 const { id } = msg.payload as { id: string };394 await vault.deleteEntry(id);395 return { ok: true };396 }397 case "GET_DELETED_ENTRIES":398 return { ok: true, data: vault.getDeletedEntries() };399 case "RESTORE_ENTRY": {400 const { id } = msg.payload as { id: string };401 await vault.restoreEntry(id);402 return { ok: true };403 }404 case "PURGE_ENTRY": {405 const { id } = msg.payload as { id: string };406 await vault.purgeEntry(id);407 return { ok: true };408 }409 case "PURGE_EXPIRED_TRASH": {410 const { retentionMs } = msg.payload as { retentionMs: number };411 const purged = await vault.purgeExpiredTrash(retentionMs);412 return { ok: true, data: purged };413 }414 case "SAVE_NOTE": {415 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };416 const { id, title, body } = msg.payload as { id?: string; title: string; body: string };417 const now = Date.now();418 if (id) {419 const existing = vault.getEntryById(id);420 if (!existing) return { ok: false, error: "not_found" };421 await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });422 return { ok: true, data: vault.getEntryById(id) };423 } else {424 const entry = await vault.addEntry({425 type: "note",426 title: title || "Untitled",427 notes: body,428 createdAt: now,429 modifiedAt: now,430 } as any);431 return { ok: true, data: entry };432 }433 }434 case "DELETE_NOTE": {435 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };436 const { id } = msg.payload as { id: string };437 await vault.deleteEntry(id);438 return { ok: true };439 }440 case "GET_NOTES": {441 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };442 const notes = vault.getEntries().filter(443 (e) => e.type === "note" && !e.deletedAt444 );445 return { ok: true, data: notes } as MessageResponse;446 }447 case "SEARCH_VAULT": {448 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };449 450 451 const { query } = (msg.payload ?? {}) as { query?: unknown };452 if (typeof query !== "string") {453 return { ok: false, error: "invalid_payload" };454 }455 const q = query.toLowerCase();456 const searchResults = vault.getEntries().filter(457 (e) =>458 !e.deletedAt &&459 (e.title.toLowerCase().includes(q) ||460 e.notes?.toLowerCase().includes(q) ||461 e.username?.toLowerCase().includes(q))462 );463 return { ok: true, data: searchResults } as MessageResponse;464 }465 case "AUTOFILL_QUERY": {466 if (!vault.isUnlocked()) {467 return { ok: false, error: "vault_locked" };468 }469 const { domain, includeAll, kind } = msg.payload as {470 domain: string;471 includeAll?: boolean;472 kind?: "login" | "card";473 };474 475 476 477 478 if (kind === "card") {479 const cards = vault.getEntries().filter((e) => e.type === "card");480 return {481 ok: true,482 data: cards.map((e) => ({483 id: e.id,484 title: e.cardNickname || e.title,485 cardholderName: e.cardholderName,486 last4: e.last4,487 expMonth: e.expMonth,488 expYear: e.expYear,489 network: e.network,490 })),491 };492 }493 494 495 496 497 498 const matches = (499 includeAll500 ? vault501 .getEntries()502 .filter((entry) => entry.type !== "note" && entry.type !== "card")503 : vault.queryDomain(domain)504 ).filter((entry) => !isPasskeyOnly(entry));505 return {506 ok: true,507 data: matches.map((e) =>508 includeAll509 ? {510 id: e.id,511 title: e.title,512 hasPasskey: e.passkey !== undefined,513 }514 : {515 id: e.id,516 title: e.title,517 username: e.username,518 email: e.email,519 url: e.url,520 hasTotp: Boolean(e.totp),521 hasPasskey: e.passkey !== undefined,522 }523 ),524 };525 }526 case "GET_ENTRY_FOR_FILL": {527 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };528 const { id } = msg.payload as { id: string };529 const entry = vault.getEntryById(id);530 if (!entry) return { ok: false, error: "entry_not_found" };531 532 533 534 if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };535 536 537 538 const { passkey: _strippedPasskey, ...safeEntry } = entry;539 return { ok: true, data: safeEntry };540 }541 case "COPY": {542 543 544 545 const { text, label, alreadyWritten } = (msg.payload ?? {}) as {546 text?: unknown;547 label?: unknown;548 alreadyWritten?: unknown;549 };550 if (typeof text !== "string" || typeof label !== "string") {551 return { ok: false, error: "invalid_payload" };552 }553 await copyToClipboard(text, label, Boolean(alreadyWritten));554 return { ok: true };555 }556 case "CHECK_ALL_BREACHES": {557 const allEntries = vault.getEntries();558 const results: Record<string, number> = {};559 for (const entry of allEntries) {560 if (entry.type === "note") continue;561 if (!entry.password) continue;562 results[entry.id] = await vault.checkBreach(entry.password);563 564 await new Promise((r) => setTimeout(r, 200));565 }566 567 for (const [id, count] of Object.entries(results)) {568 const entry = vault.getEntryById(id);569 if (entry && (entry.breach ?? 0) !== count) {570 await vault.updateEntry(id, { breach: count > 0 ? count : undefined });571 }572 }573 return { ok: true, data: results };574 }575 case "GET_SETTINGS":576 return { ok: true, data: await vault.ensureSettingsLoaded() };577 case "UPDATE_SETTINGS": {578 const patch = msg.payload;579 if (!patch || typeof patch !== "object" || Array.isArray(patch)) {580 return { ok: false, error: "invalid_payload" };581 }582 await vault.updateSettings(patch as vault.VaultSettings);583 if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {584 await setupAutoLock();585 if (vault.isUnlocked()) touchAutoLock();586 }587 return { ok: true };588 }589 case "GET_PENDING_PASSKEY":590 return { ok: true, data: await getPendingPasskeyRequest() };591 case "APPROVE_PASSKEY": {592 const { requestId } = msg.payload as { requestId: number };593 await resolvePendingPasskeyRequest(requestId, true);594 return { ok: true };595 }596 case "DENY_PASSKEY": {597 const { requestId } = msg.payload as { requestId: number };598 await resolvePendingPasskeyRequest(requestId, false);599 return { ok: true };600 }601 case "GET_PASSKEY_PROVIDER_STATE":602 return { ok: true, data: await getPasskeyProviderState() };603 case "SET_PASSKEY_PROVIDER_ENABLED": {604 const { enabled } = msg.payload as { enabled: boolean };605 606 607 if (enabled) {608 const gate = await requirePro("passkeys");609 if (!gate.allowed) return { ok: false, error: "pro_required" };610 }611 return { ok: true, data: await setPasskeyProviderEnabled(enabled) };612 }613 614 615 616 617 618 619 case "FIRE_CANARY_PING": {620 621 622 623 624 const { webhookUrl, entryTitle, trigger } = msg.payload as {625 webhookUrl: string;626 entryTitle: string;627 trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";628 };629 if (!isAllowedCanaryWebhookUrl(webhookUrl)) {630 return { ok: false, error: "invalid_webhook_url" };631 }632 const body = JSON.stringify({633 event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",634 entry: entryTitle,635 trigger,636 timestamp: new Date().toISOString(),637 source: "peach-extension",638 });639 if (trigger === "test") {640 641 642 643 644 645 try {646 const res = await fetch(webhookUrl, {647 method: "POST",648 headers: { "Content-Type": "application/json" },649 body,650 });651 return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };652 } catch (err) {653 return { ok: false, error: err instanceof Error ? err.message : "network_error" };654 }655 }656 657 fetch(webhookUrl, {658 method: "POST",659 headers: { "Content-Type": "application/json" },660 body,661 }).catch(() => {});662 return { ok: true };663 }664 case "ACTIVATE_LICENSE": {665 const { key } = msg.payload as { key: string };666 const licenseInfo = await activateLicense(key);667 return { ok: true, data: licenseInfo };668 }669 case "GET_LICENSE": {670 const licenseInfo = await getLicenseInfo();671 return { ok: true, data: licenseInfo };672 }673 case "GET_LICENSE_KEY": {674 const key = await getLicenseKey();675 return { ok: true, data: key };676 }677 case "DEACTIVATE_LICENSE": {678 await deactivateLicense();679 return { ok: true };680 }681 case "SHOULD_PLAY_CELEBRATION": {682 const should = await shouldPlayCelebration();683 return { ok: true, data: should };684 }685 case "MARK_CELEBRATION_PLAYED": {686 await markCelebrationPlayed();687 return { ok: true };688 }689 case "GET_CODEX_VAULT_DATA": {690 691 692 const gate = await requirePro("codex");693 if (!gate.allowed) return { ok: false, error: "pro_required" };694 return await handleGetCodexVaultData();695 }696 case "ESTIMATE_CODEX_PAGES": {697 const gate = await requirePro("codex");698 if (!gate.allowed) return { ok: false, error: "pro_required" };699 return await handleEstimateCodexPages();700 }701 case "RESTORE_FROM_CODEX": {702 703 704 705 const payload = msg.payload as CodexRestorePayload;706 return await handleRestoreFromCodex(payload);707 }708 case "OPEN_PRO_GATE": {709 710 const { feature } = (msg.payload ?? {}) as { feature?: string };711 if (chrome.storage.session) {712 await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });713 }714 try { await chrome.action.openPopup(); } catch { }715 return { ok: true };716 }717 case "GET_IDENTITIES": {718 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };719 return { ok: true, data: vault.getIdentities() };720 }721 case "TOUCH_AUTO_LOCK": {722 723 724 return { ok: true };725 }726 case "GET_ADVANCED_HEALTH_REPORT": {727 const gate = await requirePro("advanced_health");728 if (!gate.allowed) return { ok: false, error: "pro_required" };729 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };730 const report = await buildAdvancedHealthReport(vault.getEntries());731 return { ok: true, data: report };732 }733 case "IS_DURESS_ENABLED": {734 const enabled = await vault.isDuressEnabled();735 return { ok: true, data: enabled };736 }737 case "SETUP_DURESS": {738 739 740 741 742 const gate = await requirePro("duress_vault");743 if (!gate.allowed) return { ok: false, error: "pro_required" };744 745 746 747 if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };748 const { duressPassword } = msg.payload as { duressPassword: string };749 await vault.setupDuress(duressPassword);750 return { ok: true };751 }752 case "DISABLE_DURESS": {753 await vault.disableDuress();754 return { ok: true };755 }756 case "VERIFY_MAIN_PASSWORD": {757 const { password } = msg.payload as { password: string };758 const ok = await vault.verifyMainPassword(password);759 return { ok: true, data: ok };760 }761 case "CHANGE_PASSWORD": {762 const { currentPassword, newPassword } = msg.payload as {763 currentPassword: string;764 newPassword: string;765 };766 const changed = await vault.changePassword(currentPassword, newPassword);767 return changed768 ? { ok: true }769 : { ok: false, error: "incorrect_current_password" };770 }771 case "GET_SITE_PASSWORD_POLICY": {772 const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });773 if (!tab?.id) return { ok: true, data: null };774 try {775 const response = await chrome.tabs.sendMessage(tab.id, {776 type: "GET_SITE_PASSWORD_POLICY",777 });778 return (response as MessageResponse) ?? { ok: true, data: null };779 } catch {780 return { ok: true, data: null };781 }782 }783 case "RECORD_MANUAL_SUMMON": {784 const { domain } = msg.payload as { domain: string };785 const settings = vault.getSettings();786 const existing = settings.manualSummonDomains?.[domain];787 const now = Date.now();788 await vault.updateSettings({789 manualSummonDomains: {790 ...settings.manualSummonDomains,791 [domain]: {792 firstSummonedAt: existing?.firstSummonedAt ?? now,793 summonCount: (existing?.summonCount ?? 0) + 1,794 lastSummonedAt: now,795 },796 },797 });798 return { ok: true };799 }800 case "DECLINE_CARD_SAVE": {801 const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };802 await vault.declineCardSaveOffer(last4, expMonth, expYear);803 return { ok: true };804 }805 case "IS_CARD_DECLINED": {806 const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };807 const declined = await vault.isCardDeclined(last4, expMonth, expYear);808 return { ok: true, data: declined };809 }810 case "INITIATE_FIREFOX_PASSKEY_CREATE": {811 const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {812 rpId?: string;813 rpName?: string;814 userName?: string;815 userDisplayName?: string;816 };817 if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };818 return await initiateFirefoxPasskeyCreate({819 rpId,820 rpName: rpName ?? rpId,821 userName,822 userDisplayName,823 });824 }825826 case "COMPLETE_FIREFOX_PASSKEY_CREATE": {827 const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;828 if (!payload) return { ok: false, error: "missing_payload" };829 return await completeFirefoxPasskeyCreate(payload);830 }831832 case "PASSKEY_OFFER_DECLINE": {833 const { domain } = (msg.payload ?? {}) as { domain?: string };834 if (!domain) return { ok: false, error: "domain_required" };835 await recordPasskeyOfferDecline(domain);836 return { ok: true };837 }838839 case "GET_PASSKEY_OFFER_DECLINED": {840 const { domain } = (msg.payload ?? {}) as { domain?: string };841 if (!domain) return { ok: false, error: "domain_required" };842 return { ok: true, data: await isPasskeyOfferDeclined(domain) };843 }844845 case "PASSKEY_HAS_CREDENTIALS": {846 const payload = msg.payload as {847 rpId?: string;848 allowCredentials?: Array<{ id: string; type?: string }>;849 } | undefined;850 if (!payload?.rpId) return { ok: false, error: "rpid_required" };851 return await handlePasskeyHasCredentials({852 rpId: payload.rpId,853 allowCredentials: payload.allowCredentials ?? [],854 });855 }856857 case "PASSKEY_CREATE": {858 const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;859 if (!payload?.rpId || !payload?.userName) {860 return { ok: false, error: "rpid_and_username_required" };861 }862 return await handleFirefoxPasskeyCreate(payload);863 }864865 case "PASSKEY_GET": {866 const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;867 if (!payload?.rpId) return { ok: false, error: "rpid_required" };868 return await handleFirefoxPasskeyGet(payload);869 }870871 case "PASSKEY_AUTH_RESPONSE": {872 const { requestId, approved } = (msg.payload ?? {}) as {873 requestId?: string | number;874 approved?: boolean;875 };876 if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {877 return { ok: false, error: 'requestId and approved required' };878 }879 await resolvePendingPasskeyRequest(Number(requestId), approved);880 return { ok: true };881 }882883 case "GET_PASSKEY_FOR_DOMAIN": {884 const { domain } = (msg.payload ?? {}) as { domain?: string };885 if (!domain) return { ok: false, error: "domain_required" };886 if (!vault.isUnlocked()) return { ok: true, data: null };887 const match = vault888 .getEntries()889 .find((entry) => entry.passkey?.rpId === domain);890 if (!match || !match.passkey) return { ok: true, data: null };891 892 893 return {894 ok: true,895 data: {896 rpId: match.passkey.rpId,897 userName: match.passkey.userName,898 browser: match.passkey.browser,899 },900 };901 }902903 case "DESTROY_VAULT": {904 905 906 907 908 909 vault.lock();910 await storageClear();911 await vault.clearVaultHistory();912 if (chrome.storage.session) {913 await chrome.storage.session.clear();914 }915 return { ok: true };916 }917918 case "SUBMIT_FEEDBACK": {919 const { category, message, version, browser } = msg.payload as {920 category: string;921 message: string;922 version: string;923 browser: string;924 };925 if (!message.trim()) return { ok: false, error: "message_empty" };926 if (!FEEDBACK_ENDPOINT) return { ok: true };927 if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {928 return { ok: false, error: "invalid_feedback_endpoint" };929 }930 try {931 const res = await fetch(FEEDBACK_ENDPOINT, {932 method: "POST",933 headers: { "Content-Type": "application/json" },934 body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),935 });936 return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };937 } catch (err) {938 return { ok: false, error: err instanceof Error ? err.message : "network_error" };939 }940 }941 942 case "UNLOCK_WITH_KEY": {943 const { masterKeyHex } = msg.payload as { masterKeyHex: string };944 if (!isNativePlatform()) {945 return { ok: false, error: "desktop_only_uses_password" };946 }947 try {948 const result = await vault.unlockWithKey(masterKeyHex);949 if (result.ok) {950 onVaultUnlocked();951 await publishInMemoryVault(result.entries);952 }953 return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };954 } catch {955 return { ok: false, error: "invalid_key" };956 }957 }958 959 case "GET_DERIVED_KEY": {960 if (!isNativePlatform()) {961 return { ok: false, error: "android_only" };962 }963 if (!vault.isUnlocked()) {964 return { ok: false, error: "vault_locked" };965 }966 return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };967 }968 case "GET_IDENTITY_SUGGESTIONS": {969 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };970 const entries = vault.getEntries();971 const suggestions = buildIdentitySuggestions(entries);972 return { ok: true, data: { suggestions } };973 }974 case "POPULATE_INLINE_VAULT": {975 if (!isNativePlatform()) return { ok: false };976 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };977 const entries = vault.getEntries();978 await publishInMemoryVault(entries);979 return { ok: true };980 }981 case "ML_INIT":982 return { ok: true };983984 case "ML_PREDICT_BATCH": {985 986 const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };987 if (!Array.isArray(featuresArray)) {988 return { ok: false, error: "invalid_payload" };989 }990 return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };991 }992993 994 995 996 997 case "CHIRP_GET_LOCAL_IDENTITY": {998 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };999 const proCheck = await requirePro("sync");1000 if (!proCheck.allowed) return { ok: false, error: "pro_required" };1001 const masterKeyHex = vault.getDerivedKeyHex();1002 const masterKey = unhexBytes(masterKeyHex);1003 try {1004 const identity = await buildLocalIdentity(masterKey);1005 return { ok: true, data: identity };1006 } finally {1007 masterKey.fill(0);1008 }1009 }10101011 case "CHIRP_COMPLETE_PAIRING": {1012 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1013 const proCheck = await requirePro("sync");1014 if (!proCheck.allowed) return { ok: false, error: "pro_required" };1015 const paired = (msg.payload as { paired?: unknown })?.paired;1016 if (typeof paired !== "object" || paired === null) {1017 return { ok: false, error: "invalid_payload" };1018 }1019 const candidate = paired as Record<string, unknown>;1020 if (1021 typeof candidate.deviceId !== "string" || !candidate.deviceId ||1022 typeof candidate.deviceName !== "string" || !candidate.deviceName ||1023 typeof candidate.deviceType !== "string" ||1024 typeof candidate.longTermPublicKeyHex !== "string" ||1025 !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1026 typeof candidate.pairedAt !== "number"1027 ) {1028 return { ok: false, error: "invalid_paired_device" };1029 }1030 await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1031 return { ok: true };1032 }10331034 case "CHIRP_LIST_PAIRED_DEVICES": {1035 const devices = await listPairedDevicesV3();1036 return { ok: true, data: { devices } };1037 }10381039 case "CHIRP_UNPAIR_DEVICE": {1040 const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1041 if (typeof deviceId !== "string" || !deviceId) {1042 return { ok: false, error: "invalid_payload" };1043 }1044 await removePairedDeviceByIdV3(deviceId);1045 return { ok: true };1046 }10471048 case "CHIRP_RENAME_LOCAL_DEVICE": {1049 const { name } = (msg.payload ?? {}) as { name?: string };1050 if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1051 await setDeviceNameV3(name);1052 return { ok: true };1053 }10541055 default:1056 return { ok: false, error: "unknown_message_type" };1057 }1058 } catch (err) {1059 return {1060 ok: false,1061 error: err instanceof Error ? err.message : "operation_failed",1062 };1063 }1064}10651066106710681069async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1070 const plugin = nativePlugin<{1071 setEntries?: (args: {1072 entries: Array<{1073 id: string;1074 title: string;1075 username: string;1076 email: string;1077 password: string;1078 url: string;1079 totp: string;1080 additionalUrls: string[];1081 }>;1082 }) => Promise<void>;1083 }>("InMemoryVaultPlugin");1084 if (!plugin?.setEntries) return;1085 await plugin.setEntries({1086 entries: entries.map((e) => ({1087 id: e.id,1088 title: e.title ?? "",1089 username: e.username ?? "",1090 email: (e as VaultEntry & { email?: string }).email ?? "",1091 password: e.password ?? "",1092 url: e.url ?? "",1093 totp: (e as VaultEntry & { totp?: string }).totp ?? "",1094 additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1095 })),1096 });1097}109810991100async function clearInMemoryVault(): Promise<void> {1101 const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1102 if (!plugin?.clearEntries) return;1103 await plugin.clearEntries();1104}11051106110711081109function buildIdentitySuggestions(1110 entries: VaultEntry[],1111): Array<{ email: string; username: string; count: number }> {1112 const usernameCounts = new Map<string, number>();1113 const usernameEmail = new Map<string, string>();1114 for (const entry of entries) {1115 const username = entry.username ?? "";1116 const email = (entry as VaultEntry & { email?: string }).email ?? "";1117 if (!username && !email) continue;1118 const key = username || email;1119 usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1120 if (!usernameEmail.has(key)) usernameEmail.set(key, email);1121 }1122 return Array.from(usernameCounts.entries())1123 .sort((a, b) => b[1] - a[1])1124 .map(([username, count]) => ({1125 email: usernameEmail.get(username) ?? "",1126 username,1127 count,1128 }));1129}113011311132function broadcastToContentScripts(message: { type: string }): void {1133 if (!chrome.tabs?.query) return;1134 chrome.tabs.query({}, (tabs) => {1135 for (const tab of tabs) {1136 if (tab.id !== undefined) {1137 chrome.tabs.sendMessage(tab.id, message).catch(() => {1138 1139 });1140 }1141 }1142 });1143}11441145function shouldRefreshAutoLock(type: MessageType): boolean {1146 return (1147 type !== "HAS_VAULT" &&1148 type !== "IS_UNLOCKED" &&1149 type !== "GET_VAULT_STATUS" &&1150 type !== "LOCK" &&1151 type !== "UPDATE_SETTINGS" &&1152 type !== "GET_PENDING_PASSKEY" &&1153 type !== "GET_PASSKEY_PROVIDER_STATE" &&1154 type !== "DECLINE_CARD_SAVE" &&1155 type !== "IS_CARD_DECLINED" &&1156 type !== "SUBMIT_FEEDBACK"1157 );1158}11591160function isAllowedCanaryWebhookUrl(value: string): boolean {1161 try {1162 const url = new URL(value);1163 if (url.protocol !== "https:") return false;11641165 const hostname = url.hostname.toLowerCase();1166 if (1167 hostname === "localhost" ||1168 hostname.endsWith(".localhost") ||1169 isPrivateIpv4(hostname) ||1170 isPrivateIpv6(hostname)1171 ) {1172 return false;1173 }11741175 return true;1176 } catch {1177 return false;1178 }1179}11801181function isPrivateIpv4(hostname: string): boolean {1182 if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1183 return true;1184 }11851186 const octets = hostname.split(".").map((part) => Number(part));1187 if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1188 return false;1189 }11901191 return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1192}11931194function isPrivateIpv6(hostname: string): boolean {1195 const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1196 return (1197 normalized === "::1" ||1198 normalized.startsWith("fc") ||1199 normalized.startsWith("fd") ||1200 normalized.startsWith("fe80:")1201 );1202}