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" | "totp";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 if (kind === "totp") {494 const matches = (495 includeAll496 ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")497 : vault.queryDomain(domain)498 ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));499 return {500 ok: true,501 data: matches.map((e) => ({502 id: e.id,503 title: e.title,504 username: e.username,505 email: e.email,506 url: e.url,507 hasTotp: true,508 })),509 };510 }511 512 513 514 515 516 const matches = (517 includeAll518 ? vault519 .getEntries()520 .filter((entry) => entry.type !== "note" && entry.type !== "card")521 : vault.queryDomain(domain)522 ).filter((entry) => !isPasskeyOnly(entry));523 return {524 ok: true,525 data: matches.map((e) =>526 includeAll527 ? {528 id: e.id,529 title: e.title,530 hasPasskey: e.passkey !== undefined,531 }532 : {533 id: e.id,534 title: e.title,535 username: e.username,536 email: e.email,537 url: e.url,538 hasTotp: Boolean(e.totp),539 hasPasskey: e.passkey !== undefined,540 }541 ),542 };543 }544 case "GET_ENTRY_FOR_FILL": {545 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };546 const { id } = msg.payload as { id: string };547 const entry = vault.getEntryById(id);548 if (!entry) return { ok: false, error: "entry_not_found" };549 550 551 552 if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };553 554 555 556 const { passkey: _strippedPasskey, ...safeEntry } = entry;557 return { ok: true, data: safeEntry };558 }559 case "COPY": {560 561 562 563 const { text, label, alreadyWritten } = (msg.payload ?? {}) as {564 text?: unknown;565 label?: unknown;566 alreadyWritten?: unknown;567 };568 if (typeof text !== "string" || typeof label !== "string") {569 return { ok: false, error: "invalid_payload" };570 }571 await copyToClipboard(text, label, Boolean(alreadyWritten));572 return { ok: true };573 }574 case "CHECK_ALL_BREACHES": {575 const allEntries = vault.getEntries();576 const results: Record<string, number> = {};577 for (const entry of allEntries) {578 if (entry.type === "note") continue;579 if (!entry.password) continue;580 results[entry.id] = await vault.checkBreach(entry.password);581 582 await new Promise((r) => setTimeout(r, 200));583 }584 585 for (const [id, count] of Object.entries(results)) {586 const entry = vault.getEntryById(id);587 if (entry && (entry.breach ?? 0) !== count) {588 await vault.updateEntry(id, { breach: count > 0 ? count : undefined });589 }590 }591 return { ok: true, data: results };592 }593 case "GET_SETTINGS":594 return { ok: true, data: await vault.ensureSettingsLoaded() };595 case "UPDATE_SETTINGS": {596 const patch = msg.payload;597 if (!patch || typeof patch !== "object" || Array.isArray(patch)) {598 return { ok: false, error: "invalid_payload" };599 }600 await vault.updateSettings(patch as vault.VaultSettings);601 if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {602 await setupAutoLock();603 if (vault.isUnlocked()) touchAutoLock();604 }605 return { ok: true };606 }607 case "GET_PENDING_PASSKEY":608 return { ok: true, data: await getPendingPasskeyRequest() };609 case "APPROVE_PASSKEY": {610 const { requestId } = msg.payload as { requestId: number };611 await resolvePendingPasskeyRequest(requestId, true);612 return { ok: true };613 }614 case "DENY_PASSKEY": {615 const { requestId } = msg.payload as { requestId: number };616 await resolvePendingPasskeyRequest(requestId, false);617 return { ok: true };618 }619 case "GET_PASSKEY_PROVIDER_STATE":620 return { ok: true, data: await getPasskeyProviderState() };621 case "SET_PASSKEY_PROVIDER_ENABLED": {622 const { enabled } = msg.payload as { enabled: boolean };623 624 625 if (enabled) {626 const gate = await requirePro("passkeys");627 if (!gate.allowed) return { ok: false, error: "pro_required" };628 }629 return { ok: true, data: await setPasskeyProviderEnabled(enabled) };630 }631 632 633 634 635 636 637 case "FIRE_CANARY_PING": {638 639 640 641 642 const { webhookUrl, entryTitle, trigger } = msg.payload as {643 webhookUrl: string;644 entryTitle: string;645 trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";646 };647 if (!isAllowedCanaryWebhookUrl(webhookUrl)) {648 return { ok: false, error: "invalid_webhook_url" };649 }650 const body = JSON.stringify({651 event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",652 entry: entryTitle,653 trigger,654 timestamp: new Date().toISOString(),655 source: "peach-extension",656 });657 if (trigger === "test") {658 659 660 661 662 663 try {664 const res = await fetch(webhookUrl, {665 method: "POST",666 headers: { "Content-Type": "application/json" },667 body,668 });669 return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };670 } catch (err) {671 return { ok: false, error: err instanceof Error ? err.message : "network_error" };672 }673 }674 675 fetch(webhookUrl, {676 method: "POST",677 headers: { "Content-Type": "application/json" },678 body,679 }).catch(() => {});680 return { ok: true };681 }682 case "ACTIVATE_LICENSE": {683 const { key } = msg.payload as { key: string };684 const licenseInfo = await activateLicense(key);685 return { ok: true, data: licenseInfo };686 }687 case "GET_LICENSE": {688 const licenseInfo = await getLicenseInfo();689 return { ok: true, data: licenseInfo };690 }691 case "GET_LICENSE_KEY": {692 const key = await getLicenseKey();693 return { ok: true, data: key };694 }695 case "DEACTIVATE_LICENSE": {696 await deactivateLicense();697 return { ok: true };698 }699 case "SHOULD_PLAY_CELEBRATION": {700 const should = await shouldPlayCelebration();701 return { ok: true, data: should };702 }703 case "MARK_CELEBRATION_PLAYED": {704 await markCelebrationPlayed();705 return { ok: true };706 }707 case "GET_CODEX_VAULT_DATA": {708 709 710 const gate = await requirePro("codex");711 if (!gate.allowed) return { ok: false, error: "pro_required" };712 return await handleGetCodexVaultData();713 }714 case "ESTIMATE_CODEX_PAGES": {715 const gate = await requirePro("codex");716 if (!gate.allowed) return { ok: false, error: "pro_required" };717 return await handleEstimateCodexPages();718 }719 case "RESTORE_FROM_CODEX": {720 721 722 723 const payload = msg.payload as CodexRestorePayload;724 return await handleRestoreFromCodex(payload);725 }726 case "OPEN_PRO_GATE": {727 728 const { feature } = (msg.payload ?? {}) as { feature?: string };729 if (chrome.storage.session) {730 await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });731 }732 try { await chrome.action.openPopup(); } catch { }733 return { ok: true };734 }735 case "GET_IDENTITIES": {736 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };737 return { ok: true, data: vault.getIdentities() };738 }739 case "TOUCH_AUTO_LOCK": {740 741 742 return { ok: true };743 }744 case "GET_ADVANCED_HEALTH_REPORT": {745 const gate = await requirePro("advanced_health");746 if (!gate.allowed) return { ok: false, error: "pro_required" };747 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };748 const report = await buildAdvancedHealthReport(vault.getEntries());749 return { ok: true, data: report };750 }751 case "IS_DURESS_ENABLED": {752 const enabled = await vault.isDuressEnabled();753 return { ok: true, data: enabled };754 }755 case "SETUP_DURESS": {756 757 758 759 760 const gate = await requirePro("duress_vault");761 if (!gate.allowed) return { ok: false, error: "pro_required" };762 763 764 765 if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };766 const { duressPassword } = msg.payload as { duressPassword: string };767 await vault.setupDuress(duressPassword);768 return { ok: true };769 }770 case "DISABLE_DURESS": {771 await vault.disableDuress();772 return { ok: true };773 }774 case "VERIFY_MAIN_PASSWORD": {775 const { password } = msg.payload as { password: string };776 const ok = await vault.verifyMainPassword(password);777 return { ok: true, data: ok };778 }779 case "CHANGE_PASSWORD": {780 const { currentPassword, newPassword } = msg.payload as {781 currentPassword: string;782 newPassword: string;783 };784 const changed = await vault.changePassword(currentPassword, newPassword);785 return changed786 ? { ok: true }787 : { ok: false, error: "incorrect_current_password" };788 }789 case "GET_SITE_PASSWORD_POLICY": {790 const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });791 if (!tab?.id) return { ok: true, data: null };792 try {793 const response = await chrome.tabs.sendMessage(tab.id, {794 type: "GET_SITE_PASSWORD_POLICY",795 });796 return (response as MessageResponse) ?? { ok: true, data: null };797 } catch {798 return { ok: true, data: null };799 }800 }801 case "RECORD_MANUAL_SUMMON": {802 const { domain } = msg.payload as { domain: string };803 const settings = vault.getSettings();804 const existing = settings.manualSummonDomains?.[domain];805 const now = Date.now();806 await vault.updateSettings({807 manualSummonDomains: {808 ...settings.manualSummonDomains,809 [domain]: {810 firstSummonedAt: existing?.firstSummonedAt ?? now,811 summonCount: (existing?.summonCount ?? 0) + 1,812 lastSummonedAt: now,813 },814 },815 });816 return { ok: true };817 }818 case "DECLINE_CARD_SAVE": {819 const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };820 await vault.declineCardSaveOffer(last4, expMonth, expYear);821 return { ok: true };822 }823 case "IS_CARD_DECLINED": {824 const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };825 const declined = await vault.isCardDeclined(last4, expMonth, expYear);826 return { ok: true, data: declined };827 }828 case "INITIATE_FIREFOX_PASSKEY_CREATE": {829 const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {830 rpId?: string;831 rpName?: string;832 userName?: string;833 userDisplayName?: string;834 };835 if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };836 return await initiateFirefoxPasskeyCreate({837 rpId,838 rpName: rpName ?? rpId,839 userName,840 userDisplayName,841 });842 }843844 case "COMPLETE_FIREFOX_PASSKEY_CREATE": {845 const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;846 if (!payload) return { ok: false, error: "missing_payload" };847 return await completeFirefoxPasskeyCreate(payload);848 }849850 case "PASSKEY_OFFER_DECLINE": {851 const { domain } = (msg.payload ?? {}) as { domain?: string };852 if (!domain) return { ok: false, error: "domain_required" };853 await recordPasskeyOfferDecline(domain);854 return { ok: true };855 }856857 case "GET_PASSKEY_OFFER_DECLINED": {858 const { domain } = (msg.payload ?? {}) as { domain?: string };859 if (!domain) return { ok: false, error: "domain_required" };860 return { ok: true, data: await isPasskeyOfferDeclined(domain) };861 }862863 case "PASSKEY_HAS_CREDENTIALS": {864 const payload = msg.payload as {865 rpId?: string;866 allowCredentials?: Array<{ id: string; type?: string }>;867 } | undefined;868 if (!payload?.rpId) return { ok: false, error: "rpid_required" };869 return await handlePasskeyHasCredentials({870 rpId: payload.rpId,871 allowCredentials: payload.allowCredentials ?? [],872 });873 }874875 case "PASSKEY_CREATE": {876 const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;877 if (!payload?.rpId || !payload?.userName) {878 return { ok: false, error: "rpid_and_username_required" };879 }880 return await handleFirefoxPasskeyCreate(payload);881 }882883 case "PASSKEY_GET": {884 const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;885 if (!payload?.rpId) return { ok: false, error: "rpid_required" };886 return await handleFirefoxPasskeyGet(payload);887 }888889 case "PASSKEY_AUTH_RESPONSE": {890 const { requestId, approved } = (msg.payload ?? {}) as {891 requestId?: string | number;892 approved?: boolean;893 };894 if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {895 return { ok: false, error: 'requestId and approved required' };896 }897 await resolvePendingPasskeyRequest(Number(requestId), approved);898 return { ok: true };899 }900901 case "GET_PASSKEY_FOR_DOMAIN": {902 const { domain } = (msg.payload ?? {}) as { domain?: string };903 if (!domain) return { ok: false, error: "domain_required" };904 if (!vault.isUnlocked()) return { ok: true, data: null };905 const match = vault906 .getEntries()907 .find((entry) => entry.passkey?.rpId === domain);908 if (!match || !match.passkey) return { ok: true, data: null };909 910 911 return {912 ok: true,913 data: {914 rpId: match.passkey.rpId,915 userName: match.passkey.userName,916 browser: match.passkey.browser,917 },918 };919 }920921 case "DESTROY_VAULT": {922 923 924 925 926 927 vault.lock();928 await storageClear();929 await vault.clearVaultHistory();930 if (chrome.storage.session) {931 await chrome.storage.session.clear();932 }933 return { ok: true };934 }935936 case "SUBMIT_FEEDBACK": {937 const { category, message, version, browser } = msg.payload as {938 category: string;939 message: string;940 version: string;941 browser: string;942 };943 if (!message.trim()) return { ok: false, error: "message_empty" };944 if (!FEEDBACK_ENDPOINT) return { ok: true };945 if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {946 return { ok: false, error: "invalid_feedback_endpoint" };947 }948 try {949 const res = await fetch(FEEDBACK_ENDPOINT, {950 method: "POST",951 headers: { "Content-Type": "application/json" },952 body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),953 });954 return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };955 } catch (err) {956 return { ok: false, error: err instanceof Error ? err.message : "network_error" };957 }958 }959 960 case "UNLOCK_WITH_KEY": {961 const { masterKeyHex } = msg.payload as { masterKeyHex: string };962 if (!isNativePlatform()) {963 return { ok: false, error: "desktop_only_uses_password" };964 }965 try {966 const result = await vault.unlockWithKey(masterKeyHex);967 if (result.ok) {968 onVaultUnlocked();969 await publishInMemoryVault(result.entries);970 }971 return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };972 } catch {973 return { ok: false, error: "invalid_key" };974 }975 }976 977 case "GET_DERIVED_KEY": {978 if (!isNativePlatform()) {979 return { ok: false, error: "android_only" };980 }981 if (!vault.isUnlocked()) {982 return { ok: false, error: "vault_locked" };983 }984 return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };985 }986 case "GET_IDENTITY_SUGGESTIONS": {987 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };988 const entries = vault.getEntries();989 const suggestions = buildIdentitySuggestions(entries);990 return { ok: true, data: { suggestions } };991 }992 case "POPULATE_INLINE_VAULT": {993 if (!isNativePlatform()) return { ok: false };994 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };995 const entries = vault.getEntries();996 await publishInMemoryVault(entries);997 return { ok: true };998 }999 case "ML_INIT":1000 return { ok: true };10011002 case "ML_PREDICT_BATCH": {1003 1004 const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1005 if (!Array.isArray(featuresArray)) {1006 return { ok: false, error: "invalid_payload" };1007 }1008 return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1009 }10101011 1012 1013 1014 1015 case "CHIRP_GET_LOCAL_IDENTITY": {1016 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1017 const proCheck = await requirePro("sync");1018 if (!proCheck.allowed) return { ok: false, error: "pro_required" };1019 const masterKeyHex = vault.getDerivedKeyHex();1020 const masterKey = unhexBytes(masterKeyHex);1021 try {1022 const identity = await buildLocalIdentity(masterKey);1023 return { ok: true, data: identity };1024 } finally {1025 masterKey.fill(0);1026 }1027 }10281029 case "CHIRP_COMPLETE_PAIRING": {1030 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1031 const proCheck = await requirePro("sync");1032 if (!proCheck.allowed) return { ok: false, error: "pro_required" };1033 const paired = (msg.payload as { paired?: unknown })?.paired;1034 if (typeof paired !== "object" || paired === null) {1035 return { ok: false, error: "invalid_payload" };1036 }1037 const candidate = paired as Record<string, unknown>;1038 if (1039 typeof candidate.deviceId !== "string" || !candidate.deviceId ||1040 typeof candidate.deviceName !== "string" || !candidate.deviceName ||1041 typeof candidate.deviceType !== "string" ||1042 typeof candidate.longTermPublicKeyHex !== "string" ||1043 !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1044 typeof candidate.pairedAt !== "number"1045 ) {1046 return { ok: false, error: "invalid_paired_device" };1047 }1048 await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1049 return { ok: true };1050 }10511052 case "CHIRP_LIST_PAIRED_DEVICES": {1053 const devices = await listPairedDevicesV3();1054 return { ok: true, data: { devices } };1055 }10561057 case "CHIRP_UNPAIR_DEVICE": {1058 const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1059 if (typeof deviceId !== "string" || !deviceId) {1060 return { ok: false, error: "invalid_payload" };1061 }1062 await removePairedDeviceByIdV3(deviceId);1063 return { ok: true };1064 }10651066 case "CHIRP_RENAME_LOCAL_DEVICE": {1067 const { name } = (msg.payload ?? {}) as { name?: string };1068 if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1069 await setDeviceNameV3(name);1070 return { ok: true };1071 }10721073 default:1074 return { ok: false, error: "unknown_message_type" };1075 }1076 } catch (err) {1077 return {1078 ok: false,1079 error: err instanceof Error ? err.message : "operation_failed",1080 };1081 }1082}10831084108510861087async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1088 const plugin = nativePlugin<{1089 setEntries?: (args: {1090 entries: Array<{1091 id: string;1092 title: string;1093 username: string;1094 email: string;1095 password: string;1096 url: string;1097 totp: string;1098 additionalUrls: string[];1099 }>;1100 }) => Promise<void>;1101 }>("InMemoryVaultPlugin");1102 if (!plugin?.setEntries) return;1103 await plugin.setEntries({1104 entries: entries.map((e) => ({1105 id: e.id,1106 title: e.title ?? "",1107 username: e.username ?? "",1108 email: (e as VaultEntry & { email?: string }).email ?? "",1109 password: e.password ?? "",1110 url: e.url ?? "",1111 totp: (e as VaultEntry & { totp?: string }).totp ?? "",1112 additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1113 })),1114 });1115}111611171118async function clearInMemoryVault(): Promise<void> {1119 const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1120 if (!plugin?.clearEntries) return;1121 await plugin.clearEntries();1122}11231124112511261127function buildIdentitySuggestions(1128 entries: VaultEntry[],1129): Array<{ email: string; username: string; count: number }> {1130 const usernameCounts = new Map<string, number>();1131 const usernameEmail = new Map<string, string>();1132 for (const entry of entries) {1133 const username = entry.username ?? "";1134 const email = (entry as VaultEntry & { email?: string }).email ?? "";1135 if (!username && !email) continue;1136 const key = username || email;1137 usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1138 if (!usernameEmail.has(key)) usernameEmail.set(key, email);1139 }1140 return Array.from(usernameCounts.entries())1141 .sort((a, b) => b[1] - a[1])1142 .map(([username, count]) => ({1143 email: usernameEmail.get(username) ?? "",1144 username,1145 count,1146 }));1147}114811491150function broadcastToContentScripts(message: { type: string }): void {1151 if (!chrome.tabs?.query) return;1152 chrome.tabs.query({}, (tabs) => {1153 for (const tab of tabs) {1154 if (tab.id !== undefined) {1155 chrome.tabs.sendMessage(tab.id, message).catch(() => {1156 1157 });1158 }1159 }1160 });1161}11621163function shouldRefreshAutoLock(type: MessageType): boolean {1164 return (1165 type !== "HAS_VAULT" &&1166 type !== "IS_UNLOCKED" &&1167 type !== "GET_VAULT_STATUS" &&1168 type !== "LOCK" &&1169 type !== "UPDATE_SETTINGS" &&1170 type !== "GET_PENDING_PASSKEY" &&1171 type !== "GET_PASSKEY_PROVIDER_STATE" &&1172 type !== "DECLINE_CARD_SAVE" &&1173 type !== "IS_CARD_DECLINED" &&1174 type !== "SUBMIT_FEEDBACK"1175 );1176}11771178function isAllowedCanaryWebhookUrl(value: string): boolean {1179 try {1180 const url = new URL(value);1181 if (url.protocol !== "https:") return false;11821183 const hostname = url.hostname.toLowerCase();1184 if (1185 hostname === "localhost" ||1186 hostname.endsWith(".localhost") ||1187 isPrivateIpv4(hostname) ||1188 isPrivateIpv6(hostname)1189 ) {1190 return false;1191 }11921193 return true;1194 } catch {1195 return false;1196 }1197}11981199function isPrivateIpv4(hostname: string): boolean {1200 if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1201 return true;1202 }12031204 const octets = hostname.split(".").map((part) => Number(part));1205 if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1206 return false;1207 }12081209 return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1210}12111212function isPrivateIpv6(hostname: string): boolean {1213 const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1214 return (1215 normalized === "::1" ||1216 normalized.startsWith("fc") ||1217 normalized.startsWith("fd") ||1218 normalized.startsWith("fe80:")1219 );1220}