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 const { duressPassword } = msg.payload as { duressPassword: string };764 await vault.setupDuress(duressPassword);765 return { ok: true };766 }767 case "DISABLE_DURESS": {768 await vault.disableDuress();769 return { ok: true };770 }771 case "VERIFY_MAIN_PASSWORD": {772 const { password } = msg.payload as { password: string };773 const ok = await vault.verifyMainPassword(password);774 return { ok: true, data: ok };775 }776 case "CHANGE_PASSWORD": {777 const { currentPassword, newPassword } = msg.payload as {778 currentPassword: string;779 newPassword: string;780 };781 const changed = await vault.changePassword(currentPassword, newPassword);782 return changed783 ? { ok: true }784 : { ok: false, error: "incorrect_current_password" };785 }786 case "GET_SITE_PASSWORD_POLICY": {787 const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });788 if (!tab?.id) return { ok: true, data: null };789 try {790 const response = await chrome.tabs.sendMessage(tab.id, {791 type: "GET_SITE_PASSWORD_POLICY",792 });793 return (response as MessageResponse) ?? { ok: true, data: null };794 } catch {795 return { ok: true, data: null };796 }797 }798 case "RECORD_MANUAL_SUMMON": {799 const { domain } = msg.payload as { domain: string };800 const settings = vault.getSettings();801 const existing = settings.manualSummonDomains?.[domain];802 const now = Date.now();803 await vault.updateSettings({804 manualSummonDomains: {805 ...settings.manualSummonDomains,806 [domain]: {807 firstSummonedAt: existing?.firstSummonedAt ?? now,808 summonCount: (existing?.summonCount ?? 0) + 1,809 lastSummonedAt: now,810 },811 },812 });813 return { ok: true };814 }815 case "DECLINE_CARD_SAVE": {816 const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };817 await vault.declineCardSaveOffer(last4, expMonth, expYear);818 return { ok: true };819 }820 case "IS_CARD_DECLINED": {821 const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };822 const declined = await vault.isCardDeclined(last4, expMonth, expYear);823 return { ok: true, data: declined };824 }825 case "INITIATE_FIREFOX_PASSKEY_CREATE": {826 const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {827 rpId?: string;828 rpName?: string;829 userName?: string;830 userDisplayName?: string;831 };832 if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };833 return await initiateFirefoxPasskeyCreate({834 rpId,835 rpName: rpName ?? rpId,836 userName,837 userDisplayName,838 });839 }840841 case "COMPLETE_FIREFOX_PASSKEY_CREATE": {842 const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;843 if (!payload) return { ok: false, error: "missing_payload" };844 return await completeFirefoxPasskeyCreate(payload);845 }846847 case "PASSKEY_OFFER_DECLINE": {848 const { domain } = (msg.payload ?? {}) as { domain?: string };849 if (!domain) return { ok: false, error: "domain_required" };850 await recordPasskeyOfferDecline(domain);851 return { ok: true };852 }853854 case "GET_PASSKEY_OFFER_DECLINED": {855 const { domain } = (msg.payload ?? {}) as { domain?: string };856 if (!domain) return { ok: false, error: "domain_required" };857 return { ok: true, data: await isPasskeyOfferDeclined(domain) };858 }859860 case "PASSKEY_HAS_CREDENTIALS": {861 const payload = msg.payload as {862 rpId?: string;863 allowCredentials?: Array<{ id: string; type?: string }>;864 } | undefined;865 if (!payload?.rpId) return { ok: false, error: "rpid_required" };866 return await handlePasskeyHasCredentials({867 rpId: payload.rpId,868 allowCredentials: payload.allowCredentials ?? [],869 });870 }871872 case "PASSKEY_CREATE": {873 const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;874 if (!payload?.rpId || !payload?.userName) {875 return { ok: false, error: "rpid_and_username_required" };876 }877 return await handleFirefoxPasskeyCreate(payload);878 }879880 case "PASSKEY_GET": {881 const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;882 if (!payload?.rpId) return { ok: false, error: "rpid_required" };883 return await handleFirefoxPasskeyGet(payload);884 }885886 case "PASSKEY_AUTH_RESPONSE": {887 const { requestId, approved } = (msg.payload ?? {}) as {888 requestId?: string | number;889 approved?: boolean;890 };891 if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {892 return { ok: false, error: 'requestId and approved required' };893 }894 await resolvePendingPasskeyRequest(Number(requestId), approved);895 return { ok: true };896 }897898 case "GET_PASSKEY_FOR_DOMAIN": {899 const { domain } = (msg.payload ?? {}) as { domain?: string };900 if (!domain) return { ok: false, error: "domain_required" };901 if (!vault.isUnlocked()) return { ok: true, data: null };902 const match = vault903 .getEntries()904 .find((entry) => entry.passkey?.rpId === domain);905 if (!match || !match.passkey) return { ok: true, data: null };906 907 908 return {909 ok: true,910 data: {911 rpId: match.passkey.rpId,912 userName: match.passkey.userName,913 browser: match.passkey.browser,914 },915 };916 }917918 case "DESTROY_VAULT": {919 920 921 922 923 924 vault.lock();925 await storageClear();926 await vault.clearVaultHistory();927 if (chrome.storage.session) {928 await chrome.storage.session.clear();929 }930 return { ok: true };931 }932933 case "SUBMIT_FEEDBACK": {934 const { category, message, version, browser } = msg.payload as {935 category: string;936 message: string;937 version: string;938 browser: string;939 };940 if (!message.trim()) return { ok: false, error: "message_empty" };941 if (!FEEDBACK_ENDPOINT) return { ok: true };942 if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {943 return { ok: false, error: "invalid_feedback_endpoint" };944 }945 try {946 const res = await fetch(FEEDBACK_ENDPOINT, {947 method: "POST",948 headers: { "Content-Type": "application/json" },949 body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),950 });951 return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };952 } catch (err) {953 return { ok: false, error: err instanceof Error ? err.message : "network_error" };954 }955 }956 957 case "UNLOCK_WITH_KEY": {958 const { masterKeyHex } = msg.payload as { masterKeyHex: string };959 if (!isNativePlatform()) {960 return { ok: false, error: "desktop_only_uses_password" };961 }962 try {963 const result = await vault.unlockWithKey(masterKeyHex);964 if (result.ok) {965 onVaultUnlocked();966 await publishInMemoryVault(result.entries);967 }968 return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };969 } catch {970 return { ok: false, error: "invalid_key" };971 }972 }973 974 case "GET_DERIVED_KEY": {975 if (!isNativePlatform()) {976 return { ok: false, error: "android_only" };977 }978 if (!vault.isUnlocked()) {979 return { ok: false, error: "vault_locked" };980 }981 return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };982 }983 case "GET_IDENTITY_SUGGESTIONS": {984 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };985 const entries = vault.getEntries();986 const suggestions = buildIdentitySuggestions(entries);987 return { ok: true, data: { suggestions } };988 }989 case "POPULATE_INLINE_VAULT": {990 if (!isNativePlatform()) return { ok: false };991 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };992 const entries = vault.getEntries();993 await publishInMemoryVault(entries);994 return { ok: true };995 }996 case "ML_INIT":997 return { ok: true };998999 case "ML_PREDICT_BATCH": {1000 1001 const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1002 if (!Array.isArray(featuresArray)) {1003 return { ok: false, error: "invalid_payload" };1004 }1005 return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1006 }10071008 1009 1010 1011 1012 case "CHIRP_GET_LOCAL_IDENTITY": {1013 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1014 const proCheck = await requirePro("sync");1015 if (!proCheck.allowed) return { ok: false, error: "pro_required" };1016 const masterKeyHex = vault.getDerivedKeyHex();1017 const masterKey = unhexBytes(masterKeyHex);1018 try {1019 const identity = await buildLocalIdentity(masterKey);1020 return { ok: true, data: identity };1021 } finally {1022 masterKey.fill(0);1023 }1024 }10251026 case "CHIRP_COMPLETE_PAIRING": {1027 if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1028 const proCheck = await requirePro("sync");1029 if (!proCheck.allowed) return { ok: false, error: "pro_required" };1030 const paired = (msg.payload as { paired?: unknown })?.paired;1031 if (typeof paired !== "object" || paired === null) {1032 return { ok: false, error: "invalid_payload" };1033 }1034 const candidate = paired as Record<string, unknown>;1035 if (1036 typeof candidate.deviceId !== "string" || !candidate.deviceId ||1037 typeof candidate.deviceName !== "string" || !candidate.deviceName ||1038 typeof candidate.deviceType !== "string" ||1039 typeof candidate.longTermPublicKeyHex !== "string" ||1040 !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1041 typeof candidate.pairedAt !== "number"1042 ) {1043 return { ok: false, error: "invalid_paired_device" };1044 }1045 await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1046 return { ok: true };1047 }10481049 case "CHIRP_LIST_PAIRED_DEVICES": {1050 const devices = await listPairedDevicesV3();1051 return { ok: true, data: { devices } };1052 }10531054 case "CHIRP_UNPAIR_DEVICE": {1055 const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1056 if (typeof deviceId !== "string" || !deviceId) {1057 return { ok: false, error: "invalid_payload" };1058 }1059 await removePairedDeviceByIdV3(deviceId);1060 return { ok: true };1061 }10621063 case "CHIRP_RENAME_LOCAL_DEVICE": {1064 const { name } = (msg.payload ?? {}) as { name?: string };1065 if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1066 await setDeviceNameV3(name);1067 return { ok: true };1068 }10691070 default:1071 return { ok: false, error: "unknown_message_type" };1072 }1073 } catch (err) {1074 return {1075 ok: false,1076 error: err instanceof Error ? err.message : "operation_failed",1077 };1078 }1079}10801081108210831084async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1085 const plugin = nativePlugin<{1086 setEntries?: (args: {1087 entries: Array<{1088 id: string;1089 title: string;1090 username: string;1091 email: string;1092 password: string;1093 url: string;1094 totp: string;1095 additionalUrls: string[];1096 }>;1097 }) => Promise<void>;1098 }>("InMemoryVaultPlugin");1099 if (!plugin?.setEntries) return;1100 await plugin.setEntries({1101 entries: entries.map((e) => ({1102 id: e.id,1103 title: e.title ?? "",1104 username: e.username ?? "",1105 email: (e as VaultEntry & { email?: string }).email ?? "",1106 password: e.password ?? "",1107 url: e.url ?? "",1108 totp: (e as VaultEntry & { totp?: string }).totp ?? "",1109 additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1110 })),1111 });1112}111311141115async function clearInMemoryVault(): Promise<void> {1116 const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1117 if (!plugin?.clearEntries) return;1118 await plugin.clearEntries();1119}11201121112211231124function buildIdentitySuggestions(1125 entries: VaultEntry[],1126): Array<{ email: string; username: string; count: number }> {1127 const usernameCounts = new Map<string, number>();1128 const usernameEmail = new Map<string, string>();1129 for (const entry of entries) {1130 const username = entry.username ?? "";1131 const email = (entry as VaultEntry & { email?: string }).email ?? "";1132 if (!username && !email) continue;1133 const key = username || email;1134 usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1135 if (!usernameEmail.has(key)) usernameEmail.set(key, email);1136 }1137 return Array.from(usernameCounts.entries())1138 .sort((a, b) => b[1] - a[1])1139 .map(([username, count]) => ({1140 email: usernameEmail.get(username) ?? "",1141 username,1142 count,1143 }));1144}114511461147function broadcastToContentScripts(message: { type: string }): void {1148 if (!chrome.tabs?.query) return;1149 chrome.tabs.query({}, (tabs) => {1150 for (const tab of tabs) {1151 if (tab.id !== undefined) {1152 chrome.tabs.sendMessage(tab.id, message).catch(() => {1153 1154 });1155 }1156 }1157 });1158}11591160function shouldRefreshAutoLock(type: MessageType): boolean {1161 return (1162 type !== "HAS_VAULT" &&1163 type !== "IS_UNLOCKED" &&1164 type !== "GET_VAULT_STATUS" &&1165 type !== "LOCK" &&1166 type !== "UPDATE_SETTINGS" &&1167 type !== "GET_PENDING_PASSKEY" &&1168 type !== "GET_PASSKEY_PROVIDER_STATE" &&1169 type !== "DECLINE_CARD_SAVE" &&1170 type !== "IS_CARD_DECLINED" &&1171 type !== "SUBMIT_FEEDBACK"1172 );1173}11741175function isAllowedCanaryWebhookUrl(value: string): boolean {1176 try {1177 const url = new URL(value);1178 if (url.protocol !== "https:") return false;11791180 const hostname = url.hostname.toLowerCase();1181 if (1182 hostname === "localhost" ||1183 hostname.endsWith(".localhost") ||1184 isPrivateIpv4(hostname) ||1185 isPrivateIpv6(hostname)1186 ) {1187 return false;1188 }11891190 return true;1191 } catch {1192 return false;1193 }1194}11951196function isPrivateIpv4(hostname: string): boolean {1197 if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1198 return true;1199 }12001201 const octets = hostname.split(".").map((part) => Number(part));1202 if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1203 return false;1204 }12051206 return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1207}12081209function isPrivateIpv6(hostname: string): boolean {1210 const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1211 return (1212 normalized === "::1" ||1213 normalized.startsWith("fc") ||1214 normalized.startsWith("fd") ||1215 normalized.startsWith("fe80:")1216 );1217}