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, resolveResetUrl } 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 "INITIATE_PASSWORD_CHANGE": {734 const gate = await requirePro("smart_password_change");735 if (!gate.allowed) return { ok: false, error: "pro_required" };736 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };737 const { id } = msg.payload as { id: string };738 const entry = vault.getEntryById(id);739 if (!entry) return { ok: false, error: "entry_not_found" };740 const url = resolveResetUrl(entry);741 if (!url) return { ok: false, error: "no_reset_url" };742 try {743 await chrome.tabs.create({ url });744 return { ok: true, data: { url } };745 } catch (err) {746 return {747 ok: false,748 error: err instanceof Error ? err.message : "failed_to_open_tab",749 };750 }751 }752 case "IS_DURESS_ENABLED": {753 const enabled = await vault.isDuressEnabled();754 return { ok: true, data: enabled };755 }756 case "SETUP_DURESS": {757 758 759 760 761 const gate = await requirePro("duress_vault");762 if (!gate.allowed) return { ok: false, error: "pro_required" };763 764 765 766 if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };767 const { duressPassword } = msg.payload as { duressPassword: string };768 await vault.setupDuress(duressPassword);769 return { ok: true };770 }771 case "DISABLE_DURESS": {772 await vault.disableDuress();773 return { ok: true };774 }775 case "VERIFY_MAIN_PASSWORD": {776 const { password } = msg.payload as { password: string };777 const ok = await vault.verifyMainPassword(password);778 return { ok: true, data: ok };779 }780 case "CHANGE_PASSWORD": {781 const { currentPassword, newPassword } = msg.payload as {782 currentPassword: string;783 newPassword: string;784 };785 const changed = await vault.changePassword(currentPassword, newPassword);786 return changed787 ? { ok: true }788 : { ok: false, error: "incorrect_current_password" };789 }790 case "GET_SITE_PASSWORD_POLICY": {791 const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });792 if (!tab?.id) return { ok: true, data: null };793 try {794 const response = await chrome.tabs.sendMessage(tab.id, {795 type: "GET_SITE_PASSWORD_POLICY",796 });797 return (response as MessageResponse) ?? { ok: true, data: null };798 } catch {799 return { ok: true, data: null };800 }801 }802 case "RECORD_MANUAL_SUMMON": {803 const { domain } = msg.payload as { domain: string };804 const settings = vault.getSettings();805 const existing = settings.manualSummonDomains?.[domain];806 const now = Date.now();807 await vault.updateSettings({808 manualSummonDomains: {809 ...settings.manualSummonDomains,810 [domain]: {811 firstSummonedAt: existing?.firstSummonedAt ?? now,812 summonCount: (existing?.summonCount ?? 0) + 1,813 lastSummonedAt: now,814 },815 },816 });817 return { ok: true };818 }819 case "DECLINE_CARD_SAVE": {820 const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };821 await vault.declineCardSaveOffer(last4, expMonth, expYear);822 return { ok: true };823 }824 case "IS_CARD_DECLINED": {825 const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };826 const declined = await vault.isCardDeclined(last4, expMonth, expYear);827 return { ok: true, data: declined };828 }829 case "INITIATE_FIREFOX_PASSKEY_CREATE": {830 const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {831 rpId?: string;832 rpName?: string;833 userName?: string;834 userDisplayName?: string;835 };836 if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };837 return await initiateFirefoxPasskeyCreate({838 rpId,839 rpName: rpName ?? rpId,840 userName,841 userDisplayName,842 });843 }844845 case "COMPLETE_FIREFOX_PASSKEY_CREATE": {846 const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;847 if (!payload) return { ok: false, error: "missing_payload" };848 return await completeFirefoxPasskeyCreate(payload);849 }850851 case "PASSKEY_OFFER_DECLINE": {852 const { domain } = (msg.payload ?? {}) as { domain?: string };853 if (!domain) return { ok: false, error: "domain_required" };854 await recordPasskeyOfferDecline(domain);855 return { ok: true };856 }857858 case "GET_PASSKEY_OFFER_DECLINED": {859 const { domain } = (msg.payload ?? {}) as { domain?: string };860 if (!domain) return { ok: false, error: "domain_required" };861 return { ok: true, data: await isPasskeyOfferDeclined(domain) };862 }863864 case "PASSKEY_HAS_CREDENTIALS": {865 const payload = msg.payload as {866 rpId?: string;867 allowCredentials?: Array<{ id: string; type?: string }>;868 } | undefined;869 if (!payload?.rpId) return { ok: false, error: "rpid_required" };870 return await handlePasskeyHasCredentials({871 rpId: payload.rpId,872 allowCredentials: payload.allowCredentials ?? [],873 });874 }875876 case "PASSKEY_CREATE": {877 const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;878 if (!payload?.rpId || !payload?.userName) {879 return { ok: false, error: "rpid_and_username_required" };880 }881 return await handleFirefoxPasskeyCreate(payload);882 }883884 case "PASSKEY_GET": {885 const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;886 if (!payload?.rpId) return { ok: false, error: "rpid_required" };887 return await handleFirefoxPasskeyGet(payload);888 }889890 case "PASSKEY_AUTH_RESPONSE": {891 const { requestId, approved } = (msg.payload ?? {}) as {892 requestId?: string | number;893 approved?: boolean;894 };895 if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {896 return { ok: false, error: 'requestId and approved required' };897 }898 await resolvePendingPasskeyRequest(Number(requestId), approved);899 return { ok: true };900 }901902 case "GET_PASSKEY_FOR_DOMAIN": {903 const { domain } = (msg.payload ?? {}) as { domain?: string };904 if (!domain) return { ok: false, error: "domain_required" };905 if (!vault.isUnlocked()) return { ok: true, data: null };906 const match = vault907 .getEntries()908 .find((entry) => entry.passkey?.rpId === domain);909 if (!match || !match.passkey) return { ok: true, data: null };910 911 912 return {913 ok: true,914 data: {915 rpId: match.passkey.rpId,916 userName: match.passkey.userName,917 browser: match.passkey.browser,918 },919 };920 }921922 case "DESTROY_VAULT": {923 924 925 926 927 928 vault.lock();929 await storageClear();930 await vault.clearVaultHistory();931 if (chrome.storage.session) {932 await chrome.storage.session.clear();933 }934 return { ok: true };935 }936937 case "SUBMIT_FEEDBACK": {938 const { category, message, version, browser } = msg.payload as {939 category: string;940 message: string;941 version: string;942 browser: string;943 };944 if (!message.trim()) return { ok: false, error: "message_empty" };945 if (!FEEDBACK_ENDPOINT) return { ok: true };946 if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {947 return { ok: false, error: "invalid_feedback_endpoint" };948 }949 try {950 const res = await fetch(FEEDBACK_ENDPOINT, {951 method: "POST",952 headers: { "Content-Type": "application/json" },953 body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),954 });955 return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };956 } catch (err) {957 return { ok: false, error: err instanceof Error ? err.message : "network_error" };958 }959 }960 961 case "UNLOCK_WITH_KEY": {962 const { masterKeyHex } = msg.payload as { masterKeyHex: string };963 if (!isNativePlatform()) {964 return { ok: false, error: "desktop_only_uses_password" };965 }966 try {967 const result = await vault.unlockWithKey(masterKeyHex);968 if (result.ok) {969 onVaultUnlocked();970 await publishInMemoryVault(result.entries);971 }972 return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };973 } catch {974 return { ok: false, error: "invalid_key" };975 }976 }977 978 case "GET_DERIVED_KEY": {979 if (!isNativePlatform()) {980 return { ok: false, error: "android_only" };981 }982 if (!vault.isUnlocked()) {983 return { ok: false, error: "vault_locked" };984 }985 return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };986 }987 case "GET_IDENTITY_SUGGESTIONS": {988 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };989 const entries = vault.getEntries();990 const suggestions = buildIdentitySuggestions(entries);991 return { ok: true, data: { suggestions } };992 }993 case "POPULATE_INLINE_VAULT": {994 if (!isNativePlatform()) return { ok: false };995 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };996 const entries = vault.getEntries();997 await publishInMemoryVault(entries);998 return { ok: true };999 }1000 case "ML_INIT":1001 return { ok: true };10021003 case "ML_PREDICT_BATCH": {1004 1005 const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1006 if (!Array.isArray(featuresArray)) {1007 return { ok: false, error: "invalid_payload" };1008 }1009 return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1010 }10111012 1013 1014 1015 1016 case "CHIRP_GET_LOCAL_IDENTITY": {1017 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1018 const proCheck = await requirePro("sync");1019 if (!proCheck.allowed) return { ok: false, error: "pro_required" };1020 const masterKeyHex = vault.getDerivedKeyHex();1021 const masterKey = unhexBytes(masterKeyHex);1022 try {1023 const identity = await buildLocalIdentity(masterKey);1024 return { ok: true, data: identity };1025 } finally {1026 masterKey.fill(0);1027 }1028 }10291030 case "CHIRP_COMPLETE_PAIRING": {1031 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1032 const proCheck = await requirePro("sync");1033 if (!proCheck.allowed) return { ok: false, error: "pro_required" };1034 const paired = (msg.payload as { paired?: unknown })?.paired;1035 if (typeof paired !== "object" || paired === null) {1036 return { ok: false, error: "invalid_payload" };1037 }1038 const candidate = paired as Record<string, unknown>;1039 if (1040 typeof candidate.deviceId !== "string" || !candidate.deviceId ||1041 typeof candidate.deviceName !== "string" || !candidate.deviceName ||1042 typeof candidate.deviceType !== "string" ||1043 typeof candidate.longTermPublicKeyHex !== "string" ||1044 !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1045 typeof candidate.pairedAt !== "number"1046 ) {1047 return { ok: false, error: "invalid_paired_device" };1048 }1049 await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1050 return { ok: true };1051 }10521053 case "CHIRP_LIST_PAIRED_DEVICES": {1054 const devices = await listPairedDevicesV3();1055 return { ok: true, data: { devices } };1056 }10571058 case "CHIRP_UNPAIR_DEVICE": {1059 const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1060 if (typeof deviceId !== "string" || !deviceId) {1061 return { ok: false, error: "invalid_payload" };1062 }1063 await removePairedDeviceByIdV3(deviceId);1064 return { ok: true };1065 }10661067 case "CHIRP_RENAME_LOCAL_DEVICE": {1068 const { name } = (msg.payload ?? {}) as { name?: string };1069 if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1070 await setDeviceNameV3(name);1071 return { ok: true };1072 }10731074 default:1075 return { ok: false, error: "unknown_message_type" };1076 }1077 } catch (err) {1078 return {1079 ok: false,1080 error: err instanceof Error ? err.message : "operation_failed",1081 };1082 }1083}10841085108610871088async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1089 const plugin = nativePlugin<{1090 setEntries?: (args: {1091 entries: Array<{1092 id: string;1093 title: string;1094 username: string;1095 email: string;1096 password: string;1097 url: string;1098 totp: string;1099 additionalUrls: string[];1100 }>;1101 }) => Promise<void>;1102 }>("InMemoryVaultPlugin");1103 if (!plugin?.setEntries) return;1104 await plugin.setEntries({1105 entries: entries.map((e) => ({1106 id: e.id,1107 title: e.title ?? "",1108 username: e.username ?? "",1109 email: (e as VaultEntry & { email?: string }).email ?? "",1110 password: e.password ?? "",1111 url: e.url ?? "",1112 totp: (e as VaultEntry & { totp?: string }).totp ?? "",1113 additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1114 })),1115 });1116}111711181119async function clearInMemoryVault(): Promise<void> {1120 const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1121 if (!plugin?.clearEntries) return;1122 await plugin.clearEntries();1123}11241125112611271128function buildIdentitySuggestions(1129 entries: VaultEntry[],1130): Array<{ email: string; username: string; count: number }> {1131 const usernameCounts = new Map<string, number>();1132 const usernameEmail = new Map<string, string>();1133 for (const entry of entries) {1134 const username = entry.username ?? "";1135 const email = (entry as VaultEntry & { email?: string }).email ?? "";1136 if (!username && !email) continue;1137 const key = username || email;1138 usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1139 if (!usernameEmail.has(key)) usernameEmail.set(key, email);1140 }1141 return Array.from(usernameCounts.entries())1142 .sort((a, b) => b[1] - a[1])1143 .map(([username, count]) => ({1144 email: usernameEmail.get(username) ?? "",1145 username,1146 count,1147 }));1148}114911501151function broadcastToContentScripts(message: { type: string }): void {1152 if (!chrome.tabs?.query) return;1153 chrome.tabs.query({}, (tabs) => {1154 for (const tab of tabs) {1155 if (tab.id !== undefined) {1156 chrome.tabs.sendMessage(tab.id, message).catch(() => {1157 1158 });1159 }1160 }1161 });1162}11631164function shouldRefreshAutoLock(type: MessageType): boolean {1165 return (1166 type !== "HAS_VAULT" &&1167 type !== "IS_UNLOCKED" &&1168 type !== "GET_VAULT_STATUS" &&1169 type !== "LOCK" &&1170 type !== "UPDATE_SETTINGS" &&1171 type !== "GET_PENDING_PASSKEY" &&1172 type !== "GET_PASSKEY_PROVIDER_STATE" &&1173 type !== "DECLINE_CARD_SAVE" &&1174 type !== "IS_CARD_DECLINED" &&1175 type !== "SUBMIT_FEEDBACK"1176 );1177}11781179function isAllowedCanaryWebhookUrl(value: string): boolean {1180 try {1181 const url = new URL(value);1182 if (url.protocol !== "https:") return false;11831184 const hostname = url.hostname.toLowerCase();1185 if (1186 hostname === "localhost" ||1187 hostname.endsWith(".localhost") ||1188 isPrivateIpv4(hostname) ||1189 isPrivateIpv6(hostname)1190 ) {1191 return false;1192 }11931194 return true;1195 } catch {1196 return false;1197 }1198}11991200function isPrivateIpv4(hostname: string): boolean {1201 if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1202 return true;1203 }12041205 const octets = hostname.split(".").map((part) => Number(part));1206 if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1207 return false;1208 }12091210 return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1211}12121213function isPrivateIpv6(hostname: string): boolean {1214 const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1215 return (1216 normalized === "::1" ||1217 normalized.startsWith("fc") ||1218 normalized.startsWith("fd") ||1219 normalized.startsWith("fe80:")1220 );1221}