123456789101112import { deriveKey, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import { clampSyncTimestamp } from "../shared/sync-limits";15import { computeVaultId } from "../shared/sync-identity";161718import { triggerSyncIfReachable } from "./sync-trigger";19import { clearPairedDevices } from "./paired-devices";20import {21 rootKeyToWords,22 wordsToRootKeyMaterial,23 deriveRecoveryKey,24} from "../shared/recovery-words";25import type {26 AccentColorName,27 BreachScanStatus,28 Canary,29 ManualSummonRecord,30 PasskeyData,31 RecoveryResult,32 SavedIdentity,33 StoredVault,34 VaultEntry,35 VaultHistory,36 VaultSnapshot,37} from "../shared/types";38import { decrypt, encrypt, zeroKey } from "./aes";39import { clearAutoLock, touchAutoLock } from "./alarms";40import { setRecoveryConfirmPending, revokeRecoveryReveal } from "./recovery-pending";41import {42 clearPairSecrets,43 dropSessionCache,44 reconcilePairSecrets,45 setSessionAllowed,46} from "./pair-secrets";4748type EntryDraft = Omit<49 VaultEntry,50 "id" | "createdAt" | "modifiedAt" | "deletedAt"51>;525354555657const SLOT_A = "peach_vault_a";58const SLOT_B = "peach_vault_b";59606162const PAD_BLOCK = 1024;6364656667const PASSWORD_HISTORY_MAX = 50;6869707172737475767778const DURESS_SLOT_SIZE = 262_144;7980let derivedKey: Uint8Array | null = null;8182838485let rootKey: Uint8Array | null = null;86let recoveryInFlight = false;87let recoverySettled: Promise<void> = Promise.resolve();88let vaultRemovalsInFlight = 0;89let vaultRemovalEpoch = 0;90let vaultWritesInFlight = 0;91let vaultCreatesInFlight = 0;92let creationSettled: Promise<void> = Promise.resolve();93let vaultUnlocksInFlight = 0;94let vaultReplacementInFlight = false;95let entries: VaultEntry[] = [];96979899let tombstones = new Map<string, number>();100let domainIndex: Map<string, VaultEntry[]> = new Map();101let vaultMode: "real" | "decoy" = "real";102103104105let duressConfigured = false;106107108109110111112113114115116let lastUnlockFailureReason: string | null = null;117118export function consumeLastUnlockFailureReason(): string | null {119 const r = lastUnlockFailureReason;120 lastUnlockFailureReason = null;121 return r;122}123124125126127128export type TextSize = "small" | "medium" | "large";129130export interface VaultSettings {131 accentColor?: AccentColorName;132 theme?: "dark" | "light";133 autoLockMinutes?: number;134 clipboardClearSeconds?: number;135 lockOnClose?: boolean;136 breachMonitoring?: boolean;137 passkeyProviderEnabled?: boolean;138 trashRetentionDays?: number;139 manualSummonDomains?: Record<string, ManualSummonRecord>;140 manualSummonSalt?: string;141 declinedCardFingerprints?: string[];142143 144 metadataVersion?: 1;145 146147148149150 textSize?: TextSize;151 152153154155156 reduceMotion?: boolean;157 158 lockedSyncRequiresUnlock?: boolean;159 160 pinEnabled?: boolean;161 162 pinPreferred?: boolean;163 164165166167168169170 shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;171}172173interface StoredPinWrap {174 version: 1;175 salt: string;176 nonce: string;177 ciphertext: string;178 tag: string;179}180181const PIN_WRAP_STORAGE = "peach_pin_wrap";182const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";183const PIN_MIN_LENGTH = 4;184const PIN_MAX_LENGTH = 12;185const PIN_MAX_ATTEMPTS = 3;186187let settings: VaultSettings = {};188const CARD_DECLINE_MAX = 256;189190const CARD_DECLINE_DIGEST_HEX = 32;191192async function metadataDigest(value: string, key: string): Promise<string> {193 const bytes = new TextEncoder().encode(`${key}:${value}`);194 const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));195 return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");196}197198let inMemoryPinWrap: StoredPinWrap | null = null;199let inMemoryPinFailedAttempts = 0;200let sessionPinStorageFailed = false;201202export function getSettings(): VaultSettings {203 return settings;204}205206export async function ensureSettingsLoaded(): Promise<VaultSettings> {207 await loadSettings();208 return settings;209}210211export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {212 await loadSettings();213 214 215 216 217 218 219 const safe = Object.fromEntries(220 Object.entries(patch).filter(221 ([k]) => ![222 "__proto__", "constructor", "prototype",223 "manualSummonDomains", "manualSummonSalt",224 ].includes(k),225 ),226 ) as Partial<VaultSettings>;227 settings = { ...settings, ...safe };228 await persistSettings();229}230231function isValidPin(pin: string): boolean {232 return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);233}234235236export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {237 if (vaultCreatesInFlight) return false;238 vaultWritesInFlight++;239 try {240 if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;241 if (!(await verifyMainPassword(currentPassword))) return false;242243 const salt = generateSalt();244 const pinKey = await deriveKey(pin, salt);245 try {246 const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");247 await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });248 await updateSettings({ pinEnabled: true });249 return true;250 } finally {251 zeroKey(pinKey);252 }253 } finally { vaultWritesInFlight--; }254}255256async function clearPinUnlockStorage(): Promise<void> {257 inMemoryPinWrap = null;258 inMemoryPinFailedAttempts = 0;259 sessionPinStorageFailed = false;260 if (chrome.storage.session) {261 await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);262 }263 await updateSettings({ pinEnabled: false });264}265266267export async function disablePinUnlock(currentPassword: string): Promise<boolean> {268 if (vaultCreatesInFlight) return false;269 vaultWritesInFlight++;270 try {271 if (!derivedKey || vaultMode !== "real") return false;272 if (!(await verifyMainPassword(currentPassword))) return false;273 await clearPinUnlockStorage();274 return true;275 } finally { vaultWritesInFlight--; }276}277278279export async function unlockWithPin(pin: string): Promise<boolean> {280 vaultUnlocksInFlight++;281 try {282 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;283 if (!isValidPin(pin)) return false;284 await loadSettings();285 if (!settings.pinEnabled) return false;286287 const { stored, failedAttempts } = await loadPinState();288 if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;289 if (290 !stored ||291 stored.version !== 1 ||292 !stored.salt ||293 !stored.nonce ||294 !stored.ciphertext ||295 !stored.tag296 ) return false;297298 const pinKey = await deriveKey(pin, unhex(stored.salt));299 let unwrappedKey: Uint8Array | null = null;300 try {301 const masterKeyHex = await decrypt(302 pinKey,303 stored.nonce,304 stored.ciphertext,305 stored.tag,306 "pin_wrap_v1",307 );308 if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;309 unwrappedKey = unhex(masterKeyHex);310 const result = await unlockWithKey(masterKeyHex);311 if (!result.ok) return false;312 await resetPinFailedAttempts();313 return true;314 } catch {315 await recordPinFailure(failedAttempts + 1);316 return false;317 } finally {318 zeroKey(pinKey);319 if (unwrappedKey) zeroKey(unwrappedKey);320 }321 } finally { vaultUnlocksInFlight--; }322}323324async function savePinWrap(stored: StoredPinWrap): Promise<void> {325 inMemoryPinWrap = stored;326 inMemoryPinFailedAttempts = 0;327 sessionPinStorageFailed = !chrome.storage.session;328 if (!chrome.storage.session) return;329 try {330 await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });331 sessionPinStorageFailed = false;332 } catch {333 334 sessionPinStorageFailed = true;335 }336}337338async function loadPinState(): Promise<{339 stored: StoredPinWrap | undefined;340 failedAttempts: number;341}> {342 if (!chrome.storage.session) {343 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };344 }345 try {346 const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);347 return {348 stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??349 (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),350 failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"351 ? result[PIN_ATTEMPTS_STORAGE]352 : 0,353 };354 } catch {355 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };356 }357}358359async function recordPinFailure(failedAttempts: number): Promise<void> {360 inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);361 if (!chrome.storage.session) return;362 try {363 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });364 } catch { }365}366367async function resetPinFailedAttempts(): Promise<void> {368 inMemoryPinFailedAttempts = 0;369 if (!chrome.storage.session) return;370 try {371 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });372 } catch { }373}374375export async function getPinUnlockStatus(): Promise<{376 configured: boolean;377 available: boolean;378 attemptsRemaining: number;379}> {380 await loadSettings();381 if (!settings.pinEnabled) {382 return { configured: false, available: false, attemptsRemaining: 0 };383 }384 const { stored, failedAttempts } = await loadPinState();385 const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;386 return {387 configured: true,388 available,389 attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,390 };391}392393async function persistSettings(): Promise<void> {394 try {395 await chrome.storage.local.set({396 peach_settings: {397 398 399 ...settings,400 cardFingerprintSalt: undefined,401 declinedCardFingerprints: settings.declinedCardFingerprints ?? [],402 metadataVersion: 1,403 },404 });405 } catch (err) {406 throw mapStorageError(err);407 }408}409410function mapStorageError(err: unknown): Error {411 const message = err instanceof Error ? err.message : String(err);412 if (/QUOTA_BYTES|quota/i.test(message)) {413 return new Error("STORAGE_QUOTA_EXCEEDED");414 }415 return err instanceof Error ? err : new Error(message);416}417418async function loadSettings(): Promise<void> {419 const result = await chrome.storage.local.get("peach_settings");420 settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};421}422423424async function clearLegacyManualSummonPlaintext(): Promise<void> {425 settings = { ...settings, manualSummonDomains: undefined, manualSummonSalt: undefined };426 await persistSettings();427}428429430431432433434435436437const RECALL_STORAGE = "peach_manual_summon_recall_v1";438const RECALL_REAL_AAD = "manual_summon_recall_v1";439const RECALL_DECOY_AAD = "manual_summon_recall_decoy_v1";440const RECALL_MAX_RECORDS = 256;441const RECALL_DOMAIN_MAX_BYTES = 253;442443444const RECALL_MAX_CLOCK_SKEW_MS = 5 * 60_000;445446interface SealedRecall {447 nonce: string;448 ciphertext: string;449 tag: string;450}451452interface StoredRecall {453 v: 1;454 real?: SealedRecall;455 decoy?: SealedRecall;456}457458let manualSummonRecall = new Map<string, ManualSummonRecord>();459let recallMutation: Promise<void> = Promise.resolve();460461function isValidRecallDomain(domain: unknown): domain is string {462 return typeof domain === "string" && domain.length > 0 &&463 new TextEncoder().encode(domain).length <= RECALL_DOMAIN_MAX_BYTES;464}465466function sanitizeSummonRecord(value: unknown, now: number): ManualSummonRecord | null {467 if (!value || typeof value !== "object") return null;468 const record = value as Record<string, unknown>;469 const firstSummonedAt = record.firstSummonedAt;470 const lastSummonedAt = record.lastSummonedAt;471 const latestAllowed = now + RECALL_MAX_CLOCK_SKEW_MS;472 for (const timestamp of [firstSummonedAt, lastSummonedAt]) {473 if (474 typeof timestamp !== "number" ||475 !Number.isSafeInteger(timestamp) ||476 timestamp < 0 ||477 timestamp > latestAllowed478 ) {479 return null;480 }481 }482 if (typeof record.summonCount !== "number" || !Number.isFinite(record.summonCount)) {483 return null;484 }485 return {486 firstSummonedAt: firstSummonedAt as number,487 lastSummonedAt: lastSummonedAt as number,488 489 summonCount: Math.min(2, Math.max(1, Math.trunc(record.summonCount))),490 };491}492493function capManualSummonRecall(494 records: Map<string, ManualSummonRecord>,495): Map<string, ManualSummonRecord> {496 if (records.size <= RECALL_MAX_RECORDS) return records;497 const kept = new Map(records);498 while (kept.size > RECALL_MAX_RECORDS) {499 let oldestDomain: string | null = null;500 let oldestAt = Number.POSITIVE_INFINITY;501 for (const [domain, record] of kept) {502 if (record.lastSummonedAt < oldestAt) {503 oldestAt = record.lastSummonedAt;504 oldestDomain = domain;505 }506 }507 if (oldestDomain === null) break;508 kept.delete(oldestDomain);509 }510 return kept;511}512513function sanitizeManualSummonRecall(value: unknown): Map<string, ManualSummonRecord> {514 const records = new Map<string, ManualSummonRecord>();515 if (!value || typeof value !== "object" || Array.isArray(value)) return records;516 const now = Date.now();517 for (const [domain, raw] of Object.entries(value as Record<string, unknown>)) {518 if (!isValidRecallDomain(domain)) continue;519 const record = sanitizeSummonRecord(raw, now);520 if (record) records.set(domain, record);521 }522 return capManualSummonRecall(records);523}524525function readStoredRecall(value: unknown): StoredRecall {526 const stored: StoredRecall = { v: 1 };527 if (!value || typeof value !== "object" || Array.isArray(value)) return stored;528 for (const mode of ["real", "decoy"] as const) {529 const member = (value as Record<string, unknown>)[mode];530 if (!member || typeof member !== "object") continue;531 const sealed = member as Record<string, unknown>;532 if (533 typeof sealed.nonce === "string" &&534 typeof sealed.ciphertext === "string" &&535 typeof sealed.tag === "string"536 ) {537 stored[mode] = { nonce: sealed.nonce, ciphertext: sealed.ciphertext, tag: sealed.tag };538 }539 }540 return stored;541}542543function recallSealContext(): { key: Uint8Array; aad: string } | null {544 if (vaultMode === "decoy") {545 return derivedKey ? { key: derivedKey, aad: RECALL_DECOY_AAD } : null;546 }547 return rootKey ? { key: rootKey, aad: RECALL_REAL_AAD } : null;548}549550function serializeRecallMutation(run: () => Promise<void>): Promise<void> {551 const task = recallMutation.then(run, run);552 recallMutation = task.then(() => undefined, () => undefined);553 return task;554}555556async function readStoredRecallFromDisk(): Promise<StoredRecall> {557 const raw = await chrome.storage.local.get(RECALL_STORAGE);558 return readStoredRecall((raw as Record<string, unknown>)[RECALL_STORAGE]);559}560561562563564function recallSealIsCurrent(565 epoch: number,566 mode: "real" | "decoy",567 sealKey: Uint8Array,568): boolean {569 return epoch === vaultEpoch && mode === vaultMode && recallSealContext()?.key === sealKey;570}571572async function loadManualSummonRecall(): Promise<void> {573 const epoch = vaultEpoch;574 const mode = vaultMode;575 const context = recallSealContext();576 manualSummonRecall = new Map();577 if (!context) return;578 let stored: StoredRecall;579 try {580 stored = await readStoredRecallFromDisk();581 } catch (error) {582 console.warn("[Peach] manual-summon recall read failed:", error);583 return;584 }585 if (epoch !== vaultEpoch || mode !== vaultMode) return;586 const member = stored[mode];587 if (!member) return;588 try {589 const plain = await decrypt(context.key, member.nonce, member.ciphertext, member.tag, context.aad);590 if (epoch !== vaultEpoch || mode !== vaultMode) return;591 manualSummonRecall = sanitizeManualSummonRecall(JSON.parse(plain));592 } catch {593 594 595 manualSummonRecall = new Map();596 }597}598599async function persistManualSummonRecall(): Promise<void> {600 const epoch = vaultEpoch;601 const mode = vaultMode;602 const context = recallSealContext();603 if (!derivedKey || !context) throw new Error("vault_locked");604 const sealKey = context.key;605 let stored: StoredRecall;606 try {607 stored = await readStoredRecallFromDisk();608 } catch (error) {609 throw mapStorageError(error);610 }611 612 613 614 let records = manualSummonRecall;615 const existing = stored[mode];616 if (existing) {617 try {618 const plain = await decrypt(sealKey, existing.nonce, existing.ciphertext, existing.tag, context.aad);619 const merged = sanitizeManualSummonRecall(JSON.parse(plain));620 for (const [domain, record] of records) merged.set(domain, record);621 records = capManualSummonRecall(merged);622 } catch {623 624 }625 }626 if (!recallSealIsCurrent(epoch, mode, sealKey)) throw new Error("vault_locked");627 const sealed = await encrypt(628 sealKey,629 JSON.stringify(Object.fromEntries(records)),630 context.aad,631 );632 if (!recallSealIsCurrent(epoch, mode, sealKey)) throw new Error("vault_locked");633 634 stored[mode] = sealed;635 try {636 await chrome.storage.local.set({ [RECALL_STORAGE]: stored });637 } catch (error) {638 throw mapStorageError(error);639 }640 641 642 if (recallSealIsCurrent(epoch, mode, sealKey)) manualSummonRecall = records;643}644645646647648649650async function rekeyManualSummonRecall(651 oldRootKey: Uint8Array,652 newRootKey: Uint8Array,653): Promise<void> {654 const epoch = vaultEpoch;655 const sealIsCurrent = (): boolean =>656 epoch === vaultEpoch && vaultMode === "real" && rootKey === oldRootKey;657 if (!sealIsCurrent()) throw new Error("vault_locked");658 const stored = await readStoredRecallFromDisk();659 let records = manualSummonRecall;660 const existing = stored.real;661 if (existing) {662 try {663 const plain = await decrypt(oldRootKey, existing.nonce, existing.ciphertext, existing.tag, RECALL_REAL_AAD);664 const merged = sanitizeManualSummonRecall(JSON.parse(plain));665 for (const [domain, record] of records) merged.set(domain, record);666 records = capManualSummonRecall(merged);667 } catch {668 669 }670 }671 if (!existing && records.size === 0) return;672 if (!sealIsCurrent()) throw new Error("vault_locked");673 stored.real = await encrypt(674 newRootKey,675 JSON.stringify(Object.fromEntries(records)),676 RECALL_REAL_AAD,677 );678 if (!sealIsCurrent()) return;679 await chrome.storage.local.set({ [RECALL_STORAGE]: stored });680 if (sealIsCurrent()) manualSummonRecall = records;681}682683684685686687async function adoptLegacyManualSummonRecall(): Promise<void> {688 if (vaultMode !== "real" || !rootKey) return;689 const legacy = sanitizeManualSummonRecall(settings.manualSummonDomains);690 if (legacy.size === 0) return;691 const epoch = vaultEpoch;692 const previous = manualSummonRecall;693 const merged = new Map(legacy);694 for (const [domain, record] of previous) merged.set(domain, record);695 manualSummonRecall = capManualSummonRecall(merged);696 try {697 await persistManualSummonRecall();698 } catch (error) {699 if (epoch === vaultEpoch && vaultMode === "real") manualSummonRecall = previous;700 throw error;701 }702 await clearLegacyManualSummonPlaintext();703}704705async function restoreManualSummonRecall(): Promise<void> {706 try {707 await loadSettings();708 } catch (error) {709 console.warn("[Peach] manual-summon recall settings read failed:", error);710 return;711 }712 try {713 await serializeRecallMutation(async () => {714 await loadManualSummonRecall();715 await adoptLegacyManualSummonRecall();716 });717 } catch (error) {718 719 console.warn("[Peach] manual-summon recall migration deferred:", error);720 }721}722723async function clearStoredManualSummonRecall(mode?: "real" | "decoy"): Promise<void> {724 if (mode === undefined) {725 manualSummonRecall = new Map();726 try {727 await chrome.storage.local.remove(RECALL_STORAGE);728 } catch (error) {729 console.warn("[Peach] manual-summon recall cleanup failed:", error);730 }731 return;732 }733 try {734 735 736 await serializeRecallMutation(async () => {737 const stored = await readStoredRecallFromDisk();738 if (!stored[mode]) return;739 delete stored[mode];740 if (stored.real || stored.decoy) {741 await chrome.storage.local.set({ [RECALL_STORAGE]: stored });742 } else {743 await chrome.storage.local.remove(RECALL_STORAGE);744 }745 });746 } catch (error) {747 console.warn("[Peach] manual-summon recall cleanup failed:", error);748 }749}750751752export function getManualSummonRecord(domain: string): ManualSummonRecord | undefined {753 const recalled = manualSummonRecall.get(domain);754 if (recalled) return recalled;755 756 if (vaultMode !== "real" || !isValidRecallDomain(domain)) return undefined;757 return sanitizeSummonRecord(settings.manualSummonDomains?.[domain], Date.now()) ?? undefined;758}759760761export async function recordManualSummon(domain: string): Promise<void> {762 if (!isValidRecallDomain(domain)) throw new Error("invalid_domain");763 vaultWritesInFlight++;764 try {765 const run = async (): Promise<void> => {766 if (!derivedKey || !recallSealContext()) throw new Error("vault_locked");767 const epoch = vaultEpoch;768 const mode = vaultMode;769 const previous = manualSummonRecall;770 const now = Date.now();771 const existing = previous.get(domain);772 const next = new Map(previous);773 next.set(domain, {774 firstSummonedAt: existing?.firstSummonedAt ?? now,775 summonCount: Math.min(2, (existing?.summonCount ?? 0) + 1),776 lastSummonedAt: now,777 });778 manualSummonRecall = capManualSummonRecall(next);779 try {780 await persistManualSummonRecall();781 } catch (error) {782 if (epoch === vaultEpoch && mode === vaultMode) manualSummonRecall = previous;783 throw error;784 }785 };786 787 await serializeRecallMutation(run);788 } finally {789 vaultWritesInFlight--;790 }791}792793794795function fireSyncTrigger(reason: "vault_change"): void {796 void Promise.resolve()797 .then(() => triggerSyncIfReachable({ reason }))798 .catch(() => {799 800 });801}802export function lockedSyncRequiresUnlock(): boolean {803 return settings.lockedSyncRequiresUnlock === true;804}805806let lockedSyncRefreshHook: (() => Promise<void>) | null = null;807let lockedSyncUnlockHook: (() => Promise<void>) | null = null;808let decoySyncTeardownHook: (() => void) | null = null;809export type IdentityHooks = {810 811 onSessionEnded: () => Promise<void>;812 813 onKeysRotated: () => Promise<void>;814 815 onVaultCreated: (password: string) => Promise<void>;816};817818let identityHooks: IdentityHooks | null = null;819820export function setIdentityHooks(hooks: IdentityHooks): void {821 identityHooks = hooks;822}823824async function notifyIdentitySessionEnded(): Promise<void> {825 await identityHooks?.onSessionEnded().catch((error) => {826 console.warn("[Peach] local identity cache clear failed:", error);827 });828}829830async function notifyIdentityKeysRotated(): Promise<void> {831 await identityHooks?.onKeysRotated().catch((error) => {832 console.warn("[Peach] local identity re-wrap failed:", error);833 });834}835836export type SealedBox = { nonce: string; ciphertext: string; tag: string };837export type IdentityKeyEnvelope = {838 root?: SealedBox;839 local?: SealedBox;840 pending?: SealedBox;841 pendingSalt?: string;842};843844export function setLockedSyncHooks(hooks: {845 refresh: () => Promise<void>;846 afterUnlock: () => Promise<void>;847 onDecoy?: () => void;848}): void {849 lockedSyncRefreshHook = hooks.refresh;850 lockedSyncUnlockHook = hooks.afterUnlock;851 decoySyncTeardownHook = hooks.onDecoy ?? null;852}853854async function refreshLockedSyncState(): Promise<void> {855 if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;856 await lockedSyncRefreshHook().catch((error) => {857 console.warn("[Peach sync] locked spool refresh failed:", error);858 });859}860861862863864865export async function checkBreach(password: string, signal?: AbortSignal): Promise<number | null> {866 const controller = new AbortController();867 let timeout: ReturnType<typeof setTimeout> | undefined;868 let onAbort: (() => void) | undefined;869 try {870 const unavailable = new Promise<null>((resolve) => {871 onAbort = () => { controller.abort(); resolve(null); };872 signal?.addEventListener("abort", onAbort, { once: true });873 timeout = setTimeout(onAbort, 8_000);874 if (signal?.aborted) onAbort();875 });876 const lookup = async (): Promise<number | null> => {877 878 const hash = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(password));879 if (controller.signal.aborted) return null;880 const hex = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();881 const res = await fetch(`https://api.pwnedpasswords.com/range/${hex.slice(0, 5)}`, {882 headers: { "Add-Padding": "true" },883 signal: controller.signal,884 });885 if (!res.ok) return null;886 const text = await res.text();887 const lines = text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");888 let count = 0;889 const seen = new Set<string>();890 for (const line of lines) {891 const match = /^([A-Fa-f0-9]{35}):([0-9]+)$/.exec(line);892 if (!match) return null;893 const suffix = match[1].toUpperCase();894 const value = Number(match[2]);895 if (!Number.isSafeInteger(value) || seen.has(suffix)) return null;896 seen.add(suffix);897 if (suffix === hex.slice(5)) count = value;898 }899 return count;900 };901 return await Promise.race([lookup(), unavailable]);902 } catch {903 return null;904 } finally {905 clearTimeout(timeout);906 if (onAbort) signal?.removeEventListener("abort", onAbort);907 }908}909910type BreachCredential = { id: string; password: string; epoch: number; key: Uint8Array };911const breachChecks = new Map<string, symbol>();912913async function checkEntryBreach(credential: BreachCredential, signal?: AbortSignal): Promise<"unknown" | "unapplied" | number> {914 const { id, password, epoch } = credential;915 const isCurrent = () => {916 const entry = entries.find((entry) => entry.id === id);917 return !signal?.aborted && epoch === vaultEpoch && credential.key === derivedKey && !vaultCreatesInFlight &&918 entry?.type === "login" && !entry.deletedAt && entry.password === password;919 };920 if (!isCurrent()) return "unapplied";921 const token = Symbol();922 breachChecks.set(id, token);923 try {924 const count = await checkBreach(password, signal);925 const idx = entries.findIndex((entry) => entry.id === id);926 const current = entries[idx];927 if (signal?.aborted || epoch !== vaultEpoch || credential.key !== derivedKey || vaultCreatesInFlight ||928 breachChecks.get(id) !== token || !current || current.deletedAt || current.type !== "login" || current.password !== password) return "unapplied";929 if (count === null) return "unknown";930 if ((current.breach ?? 0) === count) return count;931 const owner = entries;932 const next = { ...current, breach: count, modifiedAt: monotonicEntryTimestamp(current.modifiedAt) };933 entries[idx] = next;934 try {935 await persistEntries();936 } catch (error) {937 if (epoch === vaultEpoch && entries === owner && entries[idx] === next && !next.deletedAt) entries[idx] = current;938 throw error;939 }940 if (!isCurrent() || breachChecks.get(id) !== token) return "unapplied";941 fireSyncTrigger("vault_change");942 return count;943 } finally {944 if (breachChecks.get(id) === token) breachChecks.delete(id);945 }946}947948function checkEntryBreachDetached(credential: BreachCredential): void {949 void checkEntryBreach(credential).catch(() => {950 console.warn("[Peach] Could not save a breach check result");951 });952}953954function emptyBreachScan(state: BreachScanStatus["state"] = "idle"): BreachScanStatus {955 return { id: null, state, total: 0, scanned: 0, unknown: 0, unapplied: 0, breached: 0, cancelled: 0 };956}957958type BreachScan = {959 epoch: number;960 key: Uint8Array | null;961 status: BreachScanStatus;962 credentials: BreachCredential[];963 controller: AbortController;964};965let breachScan: BreachScan | null = null;966967function cancelBreachScan(): void {968 breachChecks.clear();969 const scan = breachScan;970 if (!scan) return;971 scan.controller.abort();972 scan.credentials.length = 0;973 scan.key = null;974 if (scan.status.state === "running") {975 scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;976 scan.status.state = "cancelled";977 }978}979980981export function getBreachScanStatus(): BreachScanStatus {982 if (!derivedKey) return emptyBreachScan(breachScan ? "cancelled" : "idle");983 if (!breachScan || breachScan.epoch !== vaultEpoch || breachScan.key !== derivedKey) return emptyBreachScan();984 return { ...breachScan.status };985}986987988export function startBreachScan(): BreachScanStatus {989 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");990 if (breachScan?.status.state === "running" && breachScan.epoch === vaultEpoch && breachScan.key === derivedKey) return getBreachScanStatus();991 cancelBreachScan();992 const key = derivedKey;993 const credentials = entries.filter((entry) => !entry.deletedAt && entry.type === "login" && entry.password)994 .map((entry) => ({ id: entry.id, password: entry.password!, epoch: vaultEpoch, key }));995 const scan: BreachScan = {996 epoch: vaultEpoch, key, credentials, controller: new AbortController(),997 status: { ...emptyBreachScan(credentials.length ? "running" : "complete"), id: crypto.randomUUID(), total: credentials.length },998 };999 breachScan = scan;1000 void runBreachScan(scan);1001 return { ...scan.status };1002}10031004async function runBreachScan(scan: BreachScan): Promise<void> {1005 try {1006 while (scan.credentials.length) {1007 if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;1008 const credential = scan.credentials.shift()!;1009 let result: "unknown" | "unapplied" | number;1010 try { result = await checkEntryBreach(credential, scan.controller.signal); }1011 catch { result = "unknown"; console.warn("[Peach] Could not save a breach scan result"); }1012 if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;1013 if (result === "unknown") scan.status.unknown++;1014 else if (result === "unapplied") scan.status.unapplied++;1015 else { scan.status.scanned++; if (result > 0) scan.status.breached++; }1016 if (scan.credentials.length) {1017 await new Promise<void>((resolve) => {1018 const done = () => { clearTimeout(timer); scan.controller.signal.removeEventListener("abort", done); resolve(); };1019 const timer = setTimeout(done, 200);1020 scan.controller.signal.addEventListener("abort", done, { once: true });1021 if (scan.controller.signal.aborted) done();1022 });1023 }1024 }1025 } finally {1026 scan.credentials.length = 0;1027 if (scan.status.state === "running") {1028 if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) {1029 scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;1030 scan.status.state = "cancelled";1031 } else scan.status.state = "complete";1032 }1033 }1034}10351036export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {1037 1038 const key = await cardDeclineKey();1039 if (!key) return;1040 const fingerprint = await cardFingerprint(last4, expMonth, expYear);1041 await loadSettings();1042 settings = {1043 ...settings,1044 declinedCardFingerprints: [1045 1046 1047 ...(settings.declinedCardFingerprints ?? []).filter(1048 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,1049 ),1050 await metadataDigest(fingerprint, key),1051 ].slice(-CARD_DECLINE_MAX),1052 };1053 await persistSettings();1054}10551056export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {1057 await loadSettings();1058 const key = await cardDeclineKey();1059 if (!key) return false;1060 const fingerprint = await cardFingerprint(last4, expMonth, expYear);1061 const candidate = await metadataDigest(fingerprint, key);1062 return (settings.declinedCardFingerprints ?? []).some(1063 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,1064 );1065}1066106710681069107010711072107310741075107610771078async function cardDeclineKey(): Promise<string | null> {1079 const root = getRootKeyHex();1080 if (!root) return null;1081 const digest = new Uint8Array(1082 await crypto.subtle.digest(1083 "SHA-256",1084 new TextEncoder().encode(`peach-card-decline-v1:${root}`),1085 ),1086 );1087 return hex(digest);1088}10891090async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {1091 const encoder = new TextEncoder();1092 const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));1093 return Array.from(new Uint8Array(buf).slice(0, 8))1094 .map((b) => b.toString(16).padStart(2, "0"))1095 .join("");1096}10971098function hex(buf: Uint8Array): string {1099 return Array.from(buf)1100 .map((b) => b.toString(16).padStart(2, "0"))1101 .join("");1102}11031104function unhex(s: string): Uint8Array {1105 const out = new Uint8Array(s.length / 2);1106 for (let i = 0; i < s.length; i += 2) {1107 out[i / 2] = parseInt(s.slice(i, i + 2), 16);1108 }1109 return out;1110}111111121113111411151116111711181119112011211122112311241125112611271128112911301131async function generateAndWrapRootKey(): Promise<{1132 rawRootKey: string; 1133 recoverySalt: string;1134 wrappedRootKey: string;1135 wrappedNonce: string;1136 wrappedTag: string;1137}> {1138 const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));1139 try {11401141 1142 const words = await rootKeyToWords(rootKeyBytes);1143 const wordMaterial = await wordsToRootKeyMaterial(words);1144 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));1145 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);11461147 1148 1149 const nonce = crypto.getRandomValues(new Uint8Array(12));1150 const encoded = new TextEncoder().encode(hex(rootKeyBytes));1151 const raw = await crypto.subtle.encrypt(1152 {1153 name: "AES-GCM",1154 iv: nonce,1155 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,1156 tagLength: 128,1157 },1158 recoveryKey,1159 encoded1160 );1161 1162 const rawU8 = new Uint8Array(raw);1163 const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));1164 const tag = hex(rawU8.slice(rawU8.length - 16));11651166 return {1167 rawRootKey: hex(rootKeyBytes),1168 recoverySalt: hex(recoverySalt),1169 wrappedRootKey: ciphertext,1170 wrappedNonce: hex(nonce),1171 wrappedTag: tag,1172 };1173 } finally { zeroKey(rootKeyBytes); }1174}11751176async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{1177 recoverySalt: string;1178 wrappedRootKey: string;1179 wrappedNonce: string;1180 wrappedTag: string;1181}> {1182 if (rootKeyBytes.length !== 32) {1183 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1184 }11851186 const words = await rootKeyToWords(rootKeyBytes);1187 const wordMaterial = await wordsToRootKeyMaterial(words);1188 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));1189 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);1190 const nonce = crypto.getRandomValues(new Uint8Array(12));1191 const encoded = new TextEncoder().encode(hex(rootKeyBytes));1192 const raw = await crypto.subtle.encrypt(1193 {1194 name: "AES-GCM",1195 iv: nonce,1196 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,1197 tagLength: 128,1198 },1199 recoveryKey,1200 encoded,1201 );1202 const rawU8 = new Uint8Array(raw);1203 return {1204 recoverySalt: hex(recoverySalt),1205 wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),1206 wrappedNonce: hex(nonce),1207 wrappedTag: hex(rawU8.slice(rawU8.length - 16)),1208 };1209}121012111212121312141215async function unwrapRootKeyForRecovery(1216 wrappedRootKey: string,1217 wrappedNonce: string,1218 wrappedTag: string,1219 recoverySaltHex: string,1220 words: string[]1221): Promise<Uint8Array> {1222 const wordMaterial = await wordsToRootKeyMaterial(words);1223 const recoverySalt = unhex(recoverySaltHex);1224 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);12251226 1227 1228 1229 1230 1231 const nonceRaw = unhex(wrappedNonce);1232 const ciphertextRaw = unhex(wrappedRootKey);1233 const tagRaw = unhex(wrappedTag);1234 1235 1236 const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;1237 const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);1238 combined.set(ciphertextRaw, 0);1239 combined.set(tagRaw, ciphertextRaw.length);1240 const raw = await crypto.subtle.decrypt(1241 { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },1242 recoveryKey,1243 combined1244 );1245 const decryptedHex = new TextDecoder().decode(raw);1246 const recovered = unhex(decryptedHex);1247 if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }1248 return recovered;1249}125012511252export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {1253 if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");1254 if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");1255 recoveryInFlight = true;1256 let settle!: () => void;1257 recoverySettled = new Promise<void>((resolve) => { settle = resolve; });1258 cancelBreachScan();1259 const epoch = ++vaultEpoch;1260 const check = () => {1261 if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");1262 };1263 let recoveredRoot: Uint8Array | null = null;1264 let oldKey: Uint8Array | null = null;1265 let newKey: Uint8Array | null = null;1266 let committed = false;1267 try {1268 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1269 check();1270 const slot = raw[SLOT_A] as StoredVault | undefined;1271 if (!slot) throw new Error("no_vault");1272 if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");1273 try {1274 recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,1275 slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);1276 } catch {1277 throw new Error("invalid_recovery_words");1278 }1279 check();1280 if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");1281 oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");1282 check();1283 if (!oldKey) throw new Error("recovery_data_unavailable");1284 const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");1285 check();1286 if (result.status !== "ok") throw new Error("recovery_data_unavailable");1287 const payload = result.payload;1288 await loadSettings();1289 check();1290 const salt = generateSalt();1291 newKey = await deriveKey(newPassword, salt);1292 check();1293 1294 const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");1295 const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");1296 const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);1297 const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");1298 check();1299 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1300 check();1301 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1302 const history = raw[HISTORY_KEY] as VaultHistory | undefined;1303 const snapshot: VaultSnapshot = {1304 id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",1305 vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,1306 };1307 const previousStamp = Number(raw.peach_last_modified_at);1308 const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,1309 salt: hex(salt), recovery_vault_key: recoveryVaultKey };1310 1311 await chrome.storage.local.set({1312 [SLOT_A]: nextSlot,1313 [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },1314 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),1315 });1316 committed = true;1317 check();1318 cancelBreachScan();1319 derivedKey = newKey;1320 rootKey = recoveredRoot;1321 newKey = null;1322 recoveredRoot = null;1323 entries = payload.entries;1324 tombstones = payload.tombstones;1325 duressConfigured = payload.duressConfigured;1326 vaultMode = "real";1327 manualSummonRecall = new Map();1328 buildDomainIndexSync(entries);1329 await saveSessionKey(derivedKey, "real", epoch);1330 if (epoch !== vaultEpoch) throw new Error("vault_locked");1331 await identityHooks?.onKeysRotated();1332 if (epoch !== vaultEpoch) throw new Error("vault_locked");1333 await reconcilePairSecrets(rootKey);1334 if (epoch !== vaultEpoch) throw new Error("vault_locked");1335 await clearPinUnlockStorage();1336 if (epoch !== vaultEpoch) throw new Error("vault_locked");1337 await restoreManualSummonRecall();1338 if (epoch !== vaultEpoch) throw new Error("vault_locked");1339 touchAutoLock();1340 return { committed: true, unlocked: true };1341 } catch (error) {1342 if (committed) {1343 console.warn("[Peach] recovery password saved; unlock required:", error);1344 if (derivedKey && epoch === vaultEpoch) {1345 try { await lock(); }1346 catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }1347 }1348 return { committed: true, unlocked: false };1349 }1350 if (derivedKey && epoch === vaultEpoch) await lock();1351 throw error;1352 } finally {1353 if (oldKey) zeroKey(oldKey);1354 if (newKey) zeroKey(newKey);1355 if (recoveredRoot) zeroKey(recoveredRoot);1356 recoveryInFlight = false;1357 settle();1358 }1359}136013611362export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {1363 vaultRemovalEpoch++;1364 vaultRemovalsInFlight++;1365 try {1366 await lock();1367 await recoverySettled;1368 await creationSettled;1369 return await remove();1370 } finally {1371 vaultRemovalsInFlight--;1372 }1373}13741375137613771378137913801381138213831384async function deriveRootKeyFromDerivedKey(1385 derivedKeyBytes: Uint8Array,1386 slotA: StoredVault,1387): Promise<Uint8Array | null> {1388 if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {1389 return null;1390 }1391 try {1392 const rootHex = await decrypt(1393 derivedKeyBytes,1394 slotA.pw_root_nonce,1395 slotA.pw_root_ciphertext,1396 slotA.pw_root_tag,1397 "pw_root_v1",1398 );1399 return unhex(rootHex);1400 } catch {1401 return null;1402 }1403}14041405export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {1406 if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");1407 1408 1409 const [root, local] = await Promise.all([1410 encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),1411 encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),1412 ]);1413 return { root, local };1414}14151416export async function sealIdentityKeyPreVault(1417 password: string,1418 ik: Uint8Array,1419): Promise<IdentityKeyEnvelope> {1420 const salt = generateSalt();1421 const key = await deriveKey(password, salt);1422 try {1423 const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");1424 return { pending, pendingSalt: hex(salt) };1425 } finally {1426 zeroKey(key);1427 }1428}1429143014311432143314341435143614371438export async function openIdentityKey(1439 env: IdentityKeyEnvelope,1440 password?: string,1441): Promise<Uint8Array | null> {1442 if (env.local && derivedKey) {1443 const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");1444 if (ik) return ik;1445 }1446 if (env.root && rootKey) {1447 const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");1448 if (ik) return ik;1449 }1450 if (!env.pending || !env.pendingSalt || password === undefined) return null;1451 let key: Uint8Array;1452 try {1453 const salt = unhex(env.pendingSalt);1454 key = await deriveKey(password, salt);1455 salt.fill(0);1456 } catch {1457 return null;1458 }1459 try {1460 return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");1461 } finally {1462 zeroKey(key);1463 }1464}146514661467async function openSealedKey(1468 key: Uint8Array,1469 box: SealedBox,1470 info: string,1471): Promise<Uint8Array | null> {1472 try {1473 const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));1474 if (value.length === 32) return value;1475 value.fill(0);1476 return null;1477 } catch {1478 return null;1479 }1480}1481148214831484async function wrapRootKeyForDerivedKey(1485 derivedKeyBytes: Uint8Array,1486 rootKeyBytes: Uint8Array,1487): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {1488 const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");1489 return {1490 pw_root_ciphertext: ciphertext,1491 pw_root_nonce: nonce,1492 pw_root_tag: tag,1493 };1494}149514961497export async function getRecoveryWords(): Promise<string[]> {1498 if (!rootKey) {1499 throw new Error("recovery not set up");1500 }1501 return rootKeyToWords(rootKey);1502}15031504async function loadSlot(key: string): Promise<StoredVault | null> {1505 const result = await chrome.storage.local.get(key);1506 return (result as Record<string, StoredVault | undefined>)[key] ?? null;1507}15081509async function writeSlot(key: string, vault: StoredVault): Promise<void> {1510 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1511 vaultWritesInFlight++;1512 try {1513 await chrome.storage.local.set({ [key]: vault });1514 } catch (err) {1515 throw mapStorageError(err);1516 } finally {1517 vaultWritesInFlight--;1518 }1519}15201521152215231524152515261527152815291530export async function rollbackAdoptedVault(): Promise<void> {1531 await withVaultRemoval(async () => {1532 try {1533 await chrome.storage.local.remove([1534 SLOT_A,1535 SLOT_B,1536 "peach_last_modified_at",1537 RECALL_STORAGE,1538 ]);1539 } catch (err) {1540 throw mapStorageError(err);1541 }1542 });1543}15441545async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1546 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1547 vaultWritesInFlight++;1548 try {1549 const raw = await chrome.storage.local.get("peach_last_modified_at");1550 const previous = Number(1551 (raw as Record<string, unknown>).peach_last_modified_at,1552 );1553 const next = Math.max(1554 Date.now(),1555 Number.isFinite(previous) ? previous + 1 : 0,1556 );1557 try {1558 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1559 await chrome.storage.local.set({1560 [SLOT_A]: slotA,1561 [SLOT_B]: slotB,1562 peach_last_modified_at: String(next),1563 });1564 } catch (err) {1565 throw mapStorageError(err);1566 }1567 } finally {1568 vaultWritesInFlight--;1569 }1570}157115721573157415751576157715781579let lastEntryTimestamp = 0;1580function monotonicEntryTimestamp(currentModifiedAt?: number): number {1581 const base = Math.max(1582 Date.now(),1583 (currentModifiedAt ?? 0) + 1,1584 lastEntryTimestamp + 1,1585 );1586 lastEntryTimestamp = base;1587 return base;1588}15891590async function stampLocalVaultMutation(): Promise<void> {1591 if (vaultCreatesInFlight) throw new Error("vault_changed");1592 const raw = await chrome.storage.local.get("peach_last_modified_at");1593 const previous = Number(1594 (raw as Record<string, unknown>).peach_last_modified_at,1595 );1596 const next = Math.max(1597 Date.now(),1598 Number.isFinite(previous) ? previous + 1 : 0,1599 );1600 if (vaultCreatesInFlight) throw new Error("vault_changed");1601 await chrome.storage.local.set({1602 peach_last_modified_at: String(next),1603 });1604}160516061607160816091610161116121613161416151616function padPlaintext(json: string, minBytes = 0): string {1617 const encoded = new TextEncoder().encode(json);1618 const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1619 1620 const target = Math.max(bucket, minBytes);1621 const padLen = target - encoded.length;1622 return json + " ".repeat(padLen);1623}162416251626162716281629163016311632163316341635const CSPRNG_CHUNK = 65_536;16361637function fillRandom(buf: Uint8Array): Uint8Array {1638 for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1639 const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1640 const chunk = new Uint8Array(end - offset);1641 crypto.getRandomValues(chunk);1642 buf.set(chunk, offset);1643 }1644 return buf;1645}16461647function generateNoiseBlob(ciphertextBytes: number): StoredVault {1648 const salt = crypto.getRandomValues(new Uint8Array(16));1649 const nonce = crypto.getRandomValues(new Uint8Array(12));1650 const cipher = fillRandom(new Uint8Array(ciphertextBytes));1651 const tag = crypto.getRandomValues(new Uint8Array(16));1652 return {1653 version: 1,1654 salt: hex(salt),1655 nonce: hex(nonce),1656 ciphertext: hex(cipher),1657 tag: hex(tag),1658 };1659}166016611662166316641665type VaultPayload = {1666 entries: VaultEntry[];1667 tombstones?: Record<string, number>;1668 duressConfigured?: boolean;1669};16701671type DecryptedPayload = {1672 entries: VaultEntry[];1673 tombstones: Map<string, number>;1674 duressConfigured: boolean;1675};16761677function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1678 const envelope: VaultPayload = {1679 entries,1680 tombstones: Object.fromEntries(tombstones),1681 duressConfigured: duress,1682 };1683 return padPlaintext(JSON.stringify(envelope), minBytes);1684}16851686function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1687 const result = new Map<string, number>();1688 if (raw && typeof raw === "object" && !Array.isArray(raw)) {1689 for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1690 if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1691 result.set(id, timestamp);1692 }1693 }1694 }1695 1696 1697 for (const entry of allEntries) {1698 if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1699 continue;1700 }1701 if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1702 result.set(entry.id, entry.deletedAt);1703 }1704 }1705 return result;1706}17071708function reconcileTombstones(): void {1709 const byId = new Map(entries.map((entry) => [entry.id, entry]));1710 for (const [id] of tombstones) {1711 if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1712 }1713 for (const entry of entries) {1714 if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1715 if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1716 tombstones.set(entry.id, entry.deletedAt);1717 }1718 }1719 }1720}17211722function decodePayload(plain: string): DecryptedPayload {1723 const parsed = JSON.parse(plain) as VaultPayload;1724 if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1725 throw new Error("invalid vault payload");1726 }1727 const normalized = parsed.entries.map(normalizeEntry);1728 return {1729 entries: normalized,1730 tombstones: decodeTombstones(parsed.tombstones, normalized),1731 duressConfigured: parsed.duressConfigured === true,1732 };1733}173417351736function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1737 let merged = false;1738 const transferable = new Set(["id", "type", "title", "username", "url", "passkey", "createdAt", "modifiedAt", "totp", "totpAlgorithm", "totpDigits", "totpPeriod"]);1739 for (const source of entries.filter((entry) => !entry.deletedAt && entry.passkey)) {1740 const passkey = source.passkey!;1741 if (source.type !== "login" && source.type !== "passkey") continue;1742 if (!passkey.userName || (source.username && source.username !== passkey.userName)) continue;1743 if (Object.entries(source).some(([key, value]) => !transferable.has(key) && value !== undefined && value !== "")) continue;1744 const targets = entries.filter((entry) => {1745 if (entry.deletedAt || entry.passkey || entry.type !== "login" || entry.username !== passkey.userName) return false;1746 return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {1747 if (!url) return false;1748 try {1749 return new URL(url.includes("://") ? url : `https://${url}`).hostname === passkey.rpId;1750 } catch {1751 return false;1752 }1753 });1754 });1755 if (targets.length !== 1) continue;1756 const target = targets[0]!;1757 if (source.totp && target.totp && (source.totp !== target.totp || source.totpAlgorithm !== target.totpAlgorithm || source.totpDigits !== target.totpDigits || source.totpPeriod !== target.totpPeriod)) continue;1758 target.passkey = passkey;1759 if (source.totp && !target.totp) {1760 target.totp = source.totp;1761 target.totpAlgorithm = source.totpAlgorithm;1762 target.totpDigits = source.totpDigits;1763 target.totpPeriod = source.totpPeriod;1764 }1765 const stamp = monotonicEntryTimestamp(Math.max(source.modifiedAt, target.modifiedAt));1766 target.modifiedAt = stamp;1767 source.modifiedAt = stamp;1768 source.deletedAt = stamp;1769 merged = true;1770 }1771 return { merged };1772}17731774177517761777177817791780function hasValidVaultSchema(v: unknown): v is StoredVault {1781 if (typeof v !== "object" || v === null) return false;1782 const r = v as Record<string, unknown>;1783 return (1784 r.version === 1 &&1785 typeof r.salt === "string" &&1786 typeof r.nonce === "string" &&1787 typeof r.ciphertext === "string" &&1788 typeof r.tag === "string"1789 );1790}1791const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;17921793function hasValidHistorySlot(value: unknown): value is StoredVault {1794 if (!hasValidVaultSchema(value)) return false;1795 return /^[0-9a-f]{32}$/i.test(value.salt) &&1796 /^[0-9a-f]{24}$/i.test(value.nonce) &&1797 /^[0-9a-f]+$/i.test(value.ciphertext) &&1798 value.ciphertext.length % 2 === 0 &&1799 value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1800 /^[0-9a-f]{32}$/i.test(value.tag);1801}18021803function parseHistorySlot(value: string): StoredVault | null {1804 try {1805 const parsed: unknown = JSON.parse(value);1806 return hasValidHistorySlot(parsed) ? parsed : null;1807 } catch {1808 return null;1809 }1810}18111812function isHistoryRecord(value: unknown): value is VaultSnapshot {1813 if (typeof value !== "object" || value === null) return false;1814 const record = value as Record<string, unknown>;1815 return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1816 typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1817 typeof record.reason === "string" &&1818 typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1819 typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1820 (record.entryCount === null || typeof record.entryCount === "number");1821}18221823function sanitizeHistory(value: unknown): VaultSnapshot[] {1824 if (typeof value !== "object" || value === null) return [];1825 if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1826 return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1827}18281829export type TryDecryptResult =1830 | { status: "ok"; payload: DecryptedPayload }1831 | { status: "wrong_key" }1832 | { status: "corrupted"; reason: string };1833183418351836183718381839export async function tryDecryptSlot(1840 vault: StoredVault,1841 key: Uint8Array,1842 aadTag?: string,1843): Promise<DecryptedPayload | null> {1844 const res = await tryDecryptSlotResult(vault, key, aadTag);1845 return res.status === "ok" ? res.payload : null;1846}18471848export async function tryDecryptSlotResult(1849 vault: StoredVault,1850 key: Uint8Array,1851 aadTag?: string,1852): Promise<TryDecryptResult> {1853 if (!hasValidVaultSchema(vault)) {1854 return { status: "corrupted", reason: "invalid_slot_schema" };1855 }1856 let plain: string;1857 try {1858 plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1859 } catch {1860 return { status: "wrong_key" };1861 }1862 try {1863 const parsed = JSON.parse(plain) as unknown;1864 if (typeof parsed !== "object" || parsed === null) {1865 return { status: "corrupted", reason: "invalid_payload_shape" };1866 }1867 if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1868 return { status: "corrupted", reason: "invalid_payload_shape" };1869 }1870 return { status: "ok", payload: decodePayload(plain) };1871 } catch {1872 return { status: "corrupted", reason: "invalid_payload_json" };1873 }1874}187518761877187818791880function buildDomainIndexSync(all: VaultEntry[]): void {1881 domainIndex = new Map();18821883 for (const entry of all) {1884 if (entry.deletedAt) continue;1885 if (entry.type === "note" || entry.type === "card") continue;18861887 1888 1889 1890 1891 const domains = new Set<string>();1892 const primary = extractDomain(entry.url ?? "");1893 if (primary) domains.add(primary);1894 for (const extra of entry.additionalUrls ?? []) {1895 const d = extractDomain(extra);1896 if (d) domains.add(d);1897 }1898 if (domains.size === 0) continue;18991900 for (const domain of domains) {1901 const bucket = domainIndex.get(domain) ?? [];1902 bucket.push(entry);1903 domainIndex.set(domain, bucket);1904 }1905 }1906}19071908export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1909 if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1910 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1911 vaultCreatesInFlight++;1912 let settle!: () => void;1913 creationSettled = new Promise<void>((resolve) => { settle = resolve; });1914 let nextKey: Uint8Array | null = null;1915 let nextRoot: Uint8Array | null = null;1916 let committed = false;1917 let publishedEpoch: number | null = null;1918 const epoch = vaultEpoch;1919 const check = () => {1920 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1921 };1922 try {1923 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1924 check();1925 const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1926 if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1927 const salt = generateSalt();1928 nextKey = await deriveKey(password, salt);1929 check();1930 const recovery = await generateAndWrapRootKey();1931 nextRoot = unhex(recovery.rawRootKey);1932 check();1933 const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1934 const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1935 const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1936 check();1937 const slotA: StoredVault = {1938 ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1939 recovery_vault_key: recoveryVaultKey,1940 recovery_salt: recovery.recoverySalt,1941 recovery_wrapped_root_key: recovery.wrappedRootKey,1942 recovery_nonce: recovery.wrappedNonce,1943 recovery_tag: recovery.wrappedTag,1944 };1945 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1946 check();1947 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1948 const previous = Number(raw.peach_last_modified_at);1949 const update: Record<string, unknown> = {1950 [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1951 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1952 };1953 if (occupied) {1954 const history = raw[HISTORY_KEY] as VaultHistory | undefined;1955 const snapshot: VaultSnapshot = {1956 id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1957 vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1958 };1959 update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1960 }1961 try { await chrome.storage.local.set(update); }1962 catch (error) { throw mapStorageError(error); }1963 committed = true;1964 if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1965 const previousKey = derivedKey;1966 const previousRoot = rootKey;1967 cancelBreachScan();1968 publishedEpoch = ++vaultEpoch;1969 derivedKey = nextKey;1970 rootKey = nextRoot;1971 nextKey = null;1972 nextRoot = null;1973 entries = [];1974 tombstones = new Map();1975 vaultMode = "real";1976 manualSummonRecall = new Map();1977 duressConfigured = false;1978 buildDomainIndexSync(entries);1979 if (previousKey) zeroKey(previousKey);1980 if (previousRoot) zeroKey(previousRoot);1981 await clearSessionKey();1982 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1983 await identityHooks?.onVaultCreated(password).catch((error) => {1984 console.warn("[Peach] local identity promotion failed:", error);1985 });1986 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1987 1988 1989 await clearStoredManualSummonRecall();1990 await restoreManualSummonRecall();1991 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1992 touchAutoLock();1993 return { committed: true, unlocked: true };1994 } catch (error) {1995 if (!committed) throw error;1996 console.warn("[Peach] vault saved; unlock required:", error);1997 if (publishedEpoch === vaultEpoch) {1998 await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));1999 }2000 return { committed: true, unlocked: false };2001 } finally {2002 if (nextKey) zeroKey(nextKey);2003 if (nextRoot) zeroKey(nextRoot);2004 vaultCreatesInFlight--;2005 settle();2006 }2007}2008200920102011201220132014export async function createVaultFromRootKey(2015 password: string,2016 rootKeyHex: string,2017): Promise<{ vaultId: string }> {2018 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");2019 if (typeof password !== "string" || password.length === 0) {2020 throw new Error("ADOPT_INVALID_PASSWORD");2021 }2022 if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {2023 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");2024 }20252026 if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");2027 const rootKeyBytes = unhex(rootKeyHex);2028 if (rootKeyBytes.length !== 32) {2029 rootKeyBytes.fill(0);2030 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");2031 }20322033 vaultCreatesInFlight++;2034 let settle!: () => void;2035 creationSettled = new Promise<void>((resolve) => { settle = resolve; });2036 const epoch = vaultEpoch;2037 let nextDerivedKey: Uint8Array | null = null;2038 let sessionRootKey: Uint8Array | null = null;2039 let committed = false;2040 try {2041 if (await hasVault()) {2042 throw new Error("ADOPT_VAULT_ALREADY_EXISTS");2043 }20442045 const nextEntries: VaultEntry[] = [];2046 const nextDuressConfigured = false;2047 const vaultId = await computeVaultId(rootKeyBytes);2048 const salt = generateSalt();2049 nextDerivedKey = await deriveKey(password, salt);2050 const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);20512052 sessionRootKey = new Uint8Array(rootKeyBytes);2053 const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);2054 const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");2055 const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);2056 const slotA: StoredVault = {2057 recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),2058 version: 1,2059 salt: hex(salt),2060 nonce,2061 ciphertext,2062 tag,2063 recovery_salt: recovery.recoverySalt,2064 recovery_wrapped_root_key: recovery.wrappedRootKey,2065 recovery_nonce: recovery.wrappedNonce,2066 recovery_tag: recovery.wrappedTag,2067 ...pwRoot,2068 };2069 const slotB = generateNoiseBlob(ciphertext.length / 2);2070 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");2071 await commitCreatedVaultSlots(slotA, slotB);2072 committed = true;2073 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");2074 cancelBreachScan();2075 vaultEpoch++;20762077 const previousDerivedKey = derivedKey;2078 const previousRootKey = rootKey;2079 derivedKey = nextDerivedKey;2080 rootKey = sessionRootKey;2081 nextDerivedKey = null;2082 sessionRootKey = null;2083 entries = nextEntries;2084 tombstones = new Map();2085 vaultMode = "real";2086 manualSummonRecall = new Map();2087 duressConfigured = nextDuressConfigured;2088 buildDomainIndexSync(entries);2089 if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);2090 if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);2091 touchAutoLock();20922093 2094 2095 await identityHooks?.onVaultCreated(password).catch((error) => {2096 console.warn("[Peach] local identity promotion failed:", error);2097 });2098 await clearStoredManualSummonRecall();2099 await restoreManualSummonRecall();21002101 return { vaultId };2102 } catch (error) {2103 if (committed) {2104 2105 try { await lock(); }2106 finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, RECALL_STORAGE, "peach_last_modified_at"]); }2107 }2108 throw error;2109 } finally {2110 vaultCreatesInFlight--;2111 settle();2112 rootKeyBytes.fill(0);2113 if (nextDerivedKey) zeroKey(nextDerivedKey);2114 if (sessionRootKey) sessionRootKey.fill(0);2115 }2116}21172118export async function hasVault(): Promise<boolean> {2119 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);2120 return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;2121}2122212321242125212621272128export async function isDuressEnabled(): Promise<boolean> {2129 return vaultMode === "real" && duressConfigured;2130}21312132export async function setupDuress(duressPassword: string): Promise<void> {2133 if (vaultCreatesInFlight) throw new Error("vault_changed");2134 vaultWritesInFlight++;2135 try {2136 if (!derivedKey || vaultMode !== "real") {2137 throw new Error("vault must be unlocked in real mode");2138 }2139 2140 2141 2142 const slotA = await loadSlot(SLOT_A);2143 if (!slotA) throw new Error("missing slot A");21442145 const decoySalt = generateSalt();2146 const decoyKey = await deriveKey(duressPassword, decoySalt);2147 try {2148 2149 2150 2151 2152 const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);2153 const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");2154 await writeSlot(SLOT_B, {2155 version: 1,2156 salt: hex(decoySalt),2157 nonce,2158 ciphertext,2159 tag,2160 });2161 2162 await clearStoredManualSummonRecall("decoy");2163 } finally {2164 zeroKey(decoyKey);2165 }21662167 2168 2169 duressConfigured = true;2170 await persistSlotA();2171 } finally { vaultWritesInFlight--; }2172}21732174export async function disableDuress(): Promise<void> {2175 if (vaultCreatesInFlight) throw new Error("vault_changed");2176 vaultWritesInFlight++;2177 try {2178 if (!derivedKey || vaultMode !== "real") {2179 throw new Error("vault must be unlocked in real mode");2180 }2181 2182 2183 2184 const slotA = await loadSlot(SLOT_A);2185 if (slotA) {2186 await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));2187 await clearStoredManualSummonRecall("decoy");2188 }21892190 duressConfigured = false;2191 await persistSlotA();2192 } finally { vaultWritesInFlight--; }2193}21942195219621972198219922002201export async function verifyMainPassword(password: string): Promise<boolean> {2202 const slotA = await loadSlot(SLOT_A);2203 if (!slotA) return false;2204 const key = await deriveKey(password, unhex(slotA.salt));2205 try {2206 return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;2207 } finally {2208 zeroKey(key);2209 }2210}22112212export async function unlock(password: string): Promise<boolean> {2213 return attemptUnlockWithDerive(password, deriveKey);2214}22152216async function attemptUnlockWithDerive(2217 password: string,2218 derive: typeof deriveKey,2219): Promise<boolean> {2220 vaultUnlocksInFlight++;2221 try {2222 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;2223 const epoch = vaultEpoch;2224 const stale = () => epoch !== vaultEpoch;2225 await revokeRecoveryReveal();2226 if (stale()) return false;2227 2228 2229 2230 2231 2232 2233 const [slotA, slotB] = await Promise.all([2234 loadSlot(SLOT_A),2235 loadSlot(SLOT_B),2236 ]);22372238 2239 const [keyA, keyB] = await Promise.all([2240 slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),2241 slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),2242 ]);22432244 2245 2246 2247 const [resultA, resultB] = await Promise.all([2248 keyA && slotA2249 ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")2250 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),2251 keyB && slotB2252 ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")2253 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),2254 ]);2255 const payloadA = resultA.status === "ok" ? resultA.payload : null;2256 const payloadB = resultB.status === "ok" ? resultB.payload : null;22572258 if (stale()) {2259 if (keyA) zeroKey(keyA);2260 if (keyB) zeroKey(keyB);2261 return false;2262 }22632264 if (payloadA && keyA) {2265 if (stale()) {2266 zeroKey(keyA);2267 if (keyB) zeroKey(keyB);2268 return false;2269 }2270 cancelBreachScan();2271 derivedKey = keyA;2272 vaultMode = "real";2273 manualSummonRecall = new Map();2274 entries = payloadA.entries;2275 tombstones = payloadA.tombstones;2276 duressConfigured = payloadA.duressConfigured;2277 buildDomainIndexSync(entries);2278 await loadSettings();2279 if (stale()) {2280 await lock();2281 return false;2282 }2283 touchAutoLock();2284 if (keyB) zeroKey(keyB);22852286 2287 2288 rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;2289 if (!rootKey) {2290 await lock();2291 return false;2292 }22932294 2295 if (slotA) {2296 const escrowed = slotA.recovery_vault_key2297 ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;2298 const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);2299 if (escrowed) zeroKey(escrowed);2300 if (stale()) { await lock(); return false; }2301 if (!matches) {2302 try {2303 const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");2304 if (stale()) { await lock(); return false; }2305 await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });2306 if (stale()) { await lock(); return false; }2307 } catch (error) {2308 await lock();2309 throw error;2310 }2311 }2312 }23132314 2315 2316 await reconcilePairSecrets(rootKey);2317 if (stale()) {2318 await lock();2319 return false;2320 }2321 await lockedSyncUnlockHook?.().catch((error) => {2322 console.warn("[Peach sync] locked inbox drain failed:", error);2323 });2324 if (stale()) {2325 await lock();2326 return false;2327 }2328 await resetPinFailedAttempts();2329 if (stale()) {2330 await lock();2331 return false;2332 }2333 await saveSessionKey(keyA, "real", epoch);2334 if (stale()) return false;2335 await restoreManualSummonRecall();2336 if (stale()) return false;2337 return true;2338 }23392340 if (payloadB && keyB) {2341 if (stale()) {2342 zeroKey(keyB);2343 if (keyA) zeroKey(keyA);2344 return false;2345 }2346 cancelBreachScan();2347 derivedKey = keyB;2348 vaultMode = "decoy";2349 manualSummonRecall = new Map();2350 decoySyncTeardownHook?.();2351 2352 2353 2354 if (rootKey) {2355 rootKey.fill(0);2356 rootKey = null;2357 }2358 entries = payloadB.entries;2359 tombstones = payloadB.tombstones;2360 duressConfigured = false;2361 buildDomainIndexSync(entries);2362 await loadSettings();2363 touchAutoLock();2364 if (keyA) zeroKey(keyA);2365 2366 await dropSessionCache();2367 2368 await notifyIdentitySessionEnded();2369 if (stale()) {2370 await lock();2371 return false;2372 }2373 await saveSessionKey(keyB, "decoy", epoch);2374 if (stale()) return false;2375 await restoreManualSummonRecall();2376 if (stale()) return false;2377 return true;2378 }23792380 if (keyA) zeroKey(keyA);2381 if (keyB) zeroKey(keyB);2382 2383 2384 if (resultA.status === "corrupted") {2385 lastUnlockFailureReason = resultA.reason;2386 } else if (resultB.status === "corrupted") {2387 lastUnlockFailureReason = resultB.reason;2388 }2389 return false;2390 } finally { vaultUnlocksInFlight--; }2391}23922393239423952396239723982399const SESSION_KEY_STORAGE = "peach_session_dk";2400240124022403let sessionKeyMutation = Promise.resolve();24042405function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {2406 const task = sessionKeyMutation.then(mutation, mutation);2407 sessionKeyMutation = task.catch(() => undefined);2408 return task;2409}241024112412241324142415let sessionEscrowAvailable = true;24162417241824192420242124222423export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {2424 setSessionAllowed(sessionEscrow);2425 if (sessionEscrow) return;2426 sessionEscrowAvailable = false;2427 await clearSessionKey();2428}24292430async function saveSessionKey(2431 key: Uint8Array,2432 mode: "real" | "decoy",2433 expectedEpoch = vaultEpoch,2434): Promise<void> {2435 const session = chrome.storage.session;2436 if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2437 const stored = { keyHex: hex(key), mode };2438 await mutateSessionKey(async () => {2439 if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2440 await session.set({ [SESSION_KEY_STORAGE]: stored });2441 });2442}24432444async function clearSessionKey(): Promise<void> {2445 const session = chrome.storage.session;2446 if (!session) return;2447 await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));2448}24492450245124522453245424552456let vaultEpoch = 0;2457245824592460let restoreInFlight: Promise<boolean> | null = null;246124622463246424652466246724682469export async function restoreFromSession(): Promise<boolean> {2470 vaultUnlocksInFlight++;2471 try {2472 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;2473 if (derivedKey !== null) return true;2474 if (restoreInFlight) return restoreInFlight;2475 const task = restoreFromSessionInner();2476 restoreInFlight = task;2477 try {2478 return await task;2479 } finally {2480 restoreInFlight = null;2481 }2482 } finally { vaultUnlocksInFlight--; }2483}24842485async function restoreFromSessionInner(): Promise<boolean> {2486 const epoch = vaultEpoch;2487 const stale = () => epoch !== vaultEpoch;2488 if (derivedKey !== null) return true;2489 if (!sessionEscrowAvailable) return false;2490 if (!chrome.storage.session) return false;2491 const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);2492 if (stale()) return false;2493 const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;2494 if (!entry?.keyHex) return false;24952496 const key = unhex(entry.keyHex);2497 const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;2498 const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";2499 const slot = await loadSlot(slotKey);2500 if (stale()) { zeroKey(key); return false; }2501 if (!slot) { await clearSessionKey(); return false; }25022503 const result = await tryDecryptSlotResult(slot, key, aadTag);2504 if (stale()) { zeroKey(key); return false; }2505 if (result.status !== "ok") { await clearSessionKey(); return false; }25062507 2508 2509 const payload = result.payload;2510 await loadSettings();2511 if (stale()) { zeroKey(key); return false; }25122513 2514 2515 let freshRoot: Uint8Array | null = null;2516 if (entry.mode === "real") {2517 freshRoot = await deriveRootKeyFromDerivedKey(key, slot);2518 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2519 if (!freshRoot) {2520 await lock();2521 return false;2522 }2523 }25242525 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2526 if (freshRoot) {2527 2528 await reconcilePairSecrets(freshRoot);2529 if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }2530 } else {2531 2532 await dropSessionCache();2533 2534 await notifyIdentitySessionEnded();2535 if (stale()) { zeroKey(key); return false; }2536 }2537 cancelBreachScan();2538 derivedKey = key;2539 vaultMode = entry.mode;2540 manualSummonRecall = new Map();2541 if (entry.mode === "decoy") decoySyncTeardownHook?.();2542 entries = payload.entries;2543 tombstones = payload.tombstones;2544 duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;2545 if (freshRoot) rootKey = freshRoot;2546 buildDomainIndexSync(entries);2547 touchAutoLock();25482549 await lockedSyncUnlockHook?.().catch((error) => {2550 console.warn("[Peach sync] locked inbox drain failed:", error);2551 });2552 if (stale()) return false;2553 await restoreManualSummonRecall();2554 if (stale()) return false;25552556 return true;2557}25582559export async function lock(): Promise<void> {2560 const recoveryRevoked = revokeRecoveryReveal();2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 cancelBreachScan();2571 vaultEpoch++;2572 if (derivedKey) {2573 zeroKey(derivedKey);2574 derivedKey = null;2575 }2576 if (rootKey) {2577 rootKey.fill(0);2578 rootKey = null;2579 }25802581 entries = [];2582 manualSummonRecall = new Map();2583 tombstones = new Map();2584 domainIndex = new Map();2585 vaultMode = "real";2586 duressConfigured = false;2587 clearAutoLock();2588 try {2589 chrome.runtime?.sendMessage?.({ type: "VAULT_LOCKED" })?.catch?.(() => undefined);2590 } catch { }2591 await clearSessionKey();2592 await recoveryRevoked;2593 2594 2595 await notifyIdentitySessionEnded();2596}259725982599export function getVaultEpoch(): number {2600 return vaultEpoch;2601}26022603export function isUnlocked(): boolean {2604 return derivedKey !== null;2605}26062607export function isDecoyMode(): boolean {2608 return derivedKey !== null && vaultMode === "decoy";2609}26102611261226132614export async function unlockWithKey(2615 masterKeyHex: string,2616): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2617 vaultUnlocksInFlight++;2618 try {2619 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2620 const epoch = vaultEpoch;2621 const stale = () => epoch !== vaultEpoch;2622 await revokeRecoveryReveal();2623 if (stale()) return { ok: false, error: "vault_locked" };2624 let masterKeyBytes: Uint8Array | null = null;2625 try {2626 masterKeyBytes = unhex(masterKeyHex);2627 const stored = await loadSlot(SLOT_A);2628 if (!stored) return { ok: false, error: "invalid_key" };2629 const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2630 if (!payload || stale()) {2631 zeroKey(masterKeyBytes);2632 return { ok: false, error: "invalid_key" };2633 }26342635 cancelBreachScan();2636 derivedKey = masterKeyBytes;2637 vaultMode = "real";2638 manualSummonRecall = new Map();2639 entries = payload.entries;2640 tombstones = payload.tombstones;2641 duressConfigured = payload.duressConfigured;2642 buildDomainIndexSync(entries);2643 await loadSettings();2644 touchAutoLock();26452646 rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2647 if (!rootKey) {2648 await lock();2649 return { ok: false, error: "invalid_key" };2650 }2651 await reconcilePairSecrets(rootKey);2652 if (stale()) {2653 await lock();2654 return { ok: false, error: "invalid_key" };2655 }2656 await saveSessionKey(masterKeyBytes, "real", epoch);2657 if (stale()) return { ok: false, error: "invalid_key" };2658 await restoreManualSummonRecall();2659 if (stale()) return { ok: false, error: "invalid_key" };2660 return { ok: true, entries };2661 } catch {2662 if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2663 return { ok: false, error: "invalid_key" };2664 }2665 } finally { vaultUnlocksInFlight--; }2666}266726682669267026712672267326742675export async function exportDuressSlotForAdoption(): Promise<string | null> {2676 if (!(await isDuressEnabled())) return null;2677 const slotB = await loadSlot(SLOT_B);2678 if (!slotB) return null;2679 return JSON.stringify(slotB);2680}26812682268326842685268626872688export async function installAdoptedDuressSlot(json: string): Promise<void> {2689 if (vaultCreatesInFlight) throw new Error("vault_changed");2690 vaultWritesInFlight++;2691 try {2692 let parsed: StoredVault;2693 try {2694 const raw = JSON.parse(json) as unknown;2695 if (!hasValidVaultSchema(raw)) {2696 throw new Error("invalid_duress_slot_shape");2697 }2698 parsed = raw;2699 } catch (err) {2700 if (err instanceof SyntaxError) {2701 throw new Error("invalid_duress_slot_shape");2702 }2703 throw err;2704 }2705 await writeSlot(SLOT_B, parsed);2706 2707 await clearStoredManualSummonRecall("decoy");2708 manualSummonRecall = new Map();2709 await restoreManualSummonRecall();2710 } finally { vaultWritesInFlight--; }2711}27122713271427152716271727182719272027212722272327242725272627272728272927302731export async function unlockFromCodex(params: {2732 slotA: string; 2733 slotB: string | null; 2734 timestamp: number;2735 masterPassphrase: string;2736}): Promise<2737 | { ok: true; entryCount: number }2738 | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2739> {2740 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2741 vaultReplacementInFlight = true;2742 try {2743 let parsedSlotA: StoredVault;2744 let parsedSlotB: StoredVault | null = null;2745 try {2746 const rawA = JSON.parse(params.slotA) as unknown;2747 if (!hasValidVaultSchema(rawA)) {2748 return { ok: false, reason: "invalid_slot_format" };2749 }2750 parsedSlotA = rawA;2751 if (params.slotB !== null) {2752 const rawB = JSON.parse(params.slotB) as unknown;2753 if (!hasValidVaultSchema(rawB)) {2754 return { ok: false, reason: "invalid_slot_format" };2755 }2756 parsedSlotB = rawB;2757 }2758 } catch {2759 return { ok: false, reason: "invalid_slot_format" };2760 }27612762 2763 2764 2765 const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2766 const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2767 if (!trialPayload) {2768 zeroKey(trialKey);2769 return { ok: false, reason: "wrong_passphrase" };2770 }2771 const hasEscrow =2772 !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2773 if (!hasEscrow) {2774 zeroKey(trialKey);2775 return { ok: false, reason: "missing_root_escrow" };2776 }2777 const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2778 if (!stagedRootKey) {2779 zeroKey(trialKey);2780 return { ok: false, reason: "wrong_passphrase" };2781 }2782 zeroKey(stagedRootKey);2783 zeroKey(trialKey);27842785 2786 const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);27872788 2789 27902791 2792 2793 await takeVaultSnapshot("restore");2794 const previousSlotA = await loadSlot(SLOT_A);2795 const previousSlotB = await loadSlot(SLOT_B);2796 let slotACommitted = false;2797 let slotBCommitted = false;2798 try {2799 await writeSlot(SLOT_A, parsedSlotA);2800 slotACommitted = true;2801 await writeSlot(SLOT_B, stagedSlotB);2802 slotBCommitted = true;2803 await chrome.storage.local.set({2804 peach_last_modified_at: String(params.timestamp),2805 });2806 } catch (err) {2807 if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2808 if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2809 throw err;2810 }28112812 2813 2814 const ok = await unlock(params.masterPassphrase);2815 if (!ok) {2816 2817 return { ok: false, reason: "wrong_passphrase" };2818 }2819 return { ok: true, entryCount: getEntries().length };2820 } finally {2821 vaultReplacementInFlight = false;2822 }2823}28242825282628272828export function getDerivedKeyHex(): string {2829 if (!derivedKey) throw new Error("vault_not_unlocked");2830 return hex(derivedKey);2831}28322833283428352836283728382839284028412842284328442845284628472848export function getRootKeyHex(): string | null {2849 return rootKey ? hex(rootKey) : null;2850}28512852export function getEntries(): VaultEntry[] {2853 if (!derivedKey) throw new Error("vault_locked");2854 return entries.filter((entry) => !entry.deletedAt);2855}28562857const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;28582859export function getIdentities(): SavedIdentity[] {2860 if (!derivedKey) throw new Error("vault_locked");2861 const active = entries.filter((e) => !e.deletedAt && e.type === "login");28622863 const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2864 const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();28652866 for (const entry of active) {2867 const domain = extractDomain(entry.url ?? "") ?? "";2868 const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;28692870 function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2871 const existing = map.get(v);2872 if (!existing || modifiedAt > existing.lastUsed) {2873 map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2874 } else {2875 map.set(v, { ...existing, count: existing.count + 1 });2876 }2877 }28782879 const uVal = entry.username?.trim();2880 if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);28812882 2883 2884 const eVal = entry.email?.trim();2885 if (eVal) tally(emailMap, eVal);2886 }28872888 const toIdentity = (type: "email" | "username") =>2889 ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2890 value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2891 });28922893 return [2894 ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2895 ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2896 ];2897}28982899export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2900 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29012902 const now = Date.now();2903 const added: VaultEntry[] = [];2904 for (const draft of drafts) {2905 try {2906 const sanitized = sanitizeEntryDraft(draft);2907 const nextEntry: VaultEntry = {2908 ...sanitized,2909 id: crypto.randomUUID(),2910 createdAt: now,2911 modifiedAt: monotonicEntryTimestamp(),2912 };2913 entries.push(nextEntry);2914 added.push(nextEntry);2915 } catch {2916 2917 }2918 }29192920 if (added.length > 0) {2921 await persistEntries();2922 }29232924 return added;2925}292629272928292929302931293229332934export async function restoreEntries(2935 incoming: VaultEntry[],2936 mode: "replace" | "merge"2937): Promise<{ added: number; updated: number; skipped: number }> {2938 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29392940 2941 2942 2943 if (mode === "replace" && incoming.length === 0) {2944 throw new Error("refuse to replace with empty entry set");2945 }29462947 let added = 0;2948 let updated = 0;2949 let skipped = 0;29502951 if (mode === "replace") {2952 entries = [];2953 for (const entry of incoming) {2954 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2955 if (!normalized) {2956 skipped += 1;2957 continue;2958 }2959 entries.push(normalized);2960 if (normalized.deletedAt) {2961 tombstones.set(2962 normalized.id,2963 Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2964 );2965 } else {2966 tombstones.delete(normalized.id);2967 }2968 added += 1;2969 }2970 } else {2971 const byId = new Map<string, VaultEntry>();2972 for (const e of entries) byId.set(e.id, e);29732974 for (const entry of incoming) {2975 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2976 if (!normalized) {2977 skipped += 1;2978 continue;2979 }2980 const existing = byId.get(normalized.id);2981 if (!existing) {2982 entries.push(normalized);2983 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2984 else tombstones.delete(normalized.id);2985 added += 1;2986 } else if (normalized.modifiedAt > existing.modifiedAt) {2987 const idx = entries.findIndex((e) => e.id === existing.id);2988 if (idx !== -1) {2989 entries[idx] = normalized;2990 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2991 else tombstones.delete(normalized.id);2992 updated += 1;2993 }2994 } else {2995 skipped += 1;2996 }2997 }2998 }29993000 await persistEntries("import");3001 return { added, updated, skipped };3002}300330043005300630073008300930103011301230133014301530163017301830193020const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;30213022function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {3023 if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;3024 return { ...entry, id: crypto.randomUUID() };3025}302630273028302930303031303230333034function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {3035 if (!entry || typeof entry !== "object") return null;3036 const title = typeof entry.title === "string" ? entry.title.trim() : "";3037 if (!title) return null;3038 const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();3039 const now = Date.now();3040 const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;3041 const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;30423043 3044 3045 const normalized = normalizeEntry({3046 ...entry,3047 id,3048 title,3049 type: entry.type ?? "login",3050 createdAt,3051 modifiedAt,3052 });30533054 if (normalized.passkey) {3055 normalized.passkey = sanitizePasskey(normalized.passkey);3056 }3057 if (normalized.canary) {3058 normalized.canary = sanitizeCanary(normalized.canary);3059 }3060 3061 normalized.tags = sanitizeTags(normalized.tags);30623063 3064 3065 if (3066 normalized.type === "login" &&3067 !normalized.passkey &&3068 typeof normalized.password !== "string"3069 ) {3070 return null;3071 }3072 if (entry.passkey && !normalized.passkey) {3073 3074 3075 return null;3076 }30773078 return normalized;3079}3080308130823083308430853086function sanitizePasskey(pk: unknown): PasskeyData | undefined {3087 if (!pk || typeof pk !== "object") return undefined;3088 const r = pk as Record<string, unknown>;3089 if (3090 typeof r.rpId !== "string" || !r.rpId ||3091 typeof r.credentialId !== "string" || !r.credentialId ||3092 typeof r.publicKeyCose !== "string" ||3093 typeof r.userHandle !== "string" ||3094 typeof r.userName !== "string"3095 ) {3096 return undefined;3097 }3098 return {3099 rpId: r.rpId,3100 rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,3101 credentialId: r.credentialId,3102 publicKeyCose: r.publicKeyCose,3103 privateKeyJwk:3104 r.privateKeyJwk && typeof r.privateKeyJwk === "object"3105 ? (r.privateKeyJwk as JsonWebKey)3106 : undefined,3107 userHandle: r.userHandle,3108 userName: r.userName,3109 userDisplayName:3110 typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,3111 algorithm: r.algorithm === -8 ? -8 : -7,3112 signCount: typeof r.signCount === "number" ? r.signCount : 0,3113 aaguid: typeof r.aaguid === "string" ? r.aaguid : "",3114 backupEligible: r.backupEligible === true,3115 backupState: r.backupState === true,3116 lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,3117 browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,3118 transports: Array.isArray(r.transports)3119 ? r.transports.filter((t): t is string => typeof t === "string")3120 : undefined,3121 createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),3122 };3123}31243125312631273128312931303131313231333134function sanitizeCanary(c: unknown): Canary | undefined {3135 if (!c || typeof c !== "object") return undefined;3136 const r = c as Record<string, unknown>;3137 if (typeof r.webhookUrl !== "string") return undefined;3138 let url: URL;3139 try {3140 url = new URL(r.webhookUrl);3141 } catch {3142 return undefined;3143 }3144 if (url.protocol !== "https:") return undefined;3145 return {3146 webhookUrl: url.toString(),3147 label: typeof r.label === "string" ? r.label : undefined,3148 lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,3149 pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,3150 };3151}31523153315431553156315731583159function sanitizeTags(tags: unknown): string[] | undefined {3160 if (!Array.isArray(tags)) return undefined;3161 const out: string[] = [];3162 for (const t of tags) {3163 if (typeof t !== "string") continue;3164 const trimmed = t.trim();3165 if (!trimmed) continue;3166 out.push(trimmed.slice(0, 256));3167 if (out.length >= 255) break;3168 }3169 return out.length > 0 ? out : undefined;3170}317131723173317431753176export async function clearVaultEntries(3177 confirmation: "REPLACE_ALL"3178): Promise<void> {3179 if (confirmation !== "REPLACE_ALL") {3180 throw new Error("clearVaultEntries requires explicit confirmation");3181 }3182 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3183 for (const entry of entries) {3184 if (!entry.deletedAt) {3185 const stamp = monotonicEntryTimestamp(Math.max(3186 entry.modifiedAt,3187 tombstones.get(entry.id) ?? 0,3188 ));3189 entry.deletedAt = stamp;3190 entry.modifiedAt = stamp;3191 tombstones.set(entry.id, stamp);3192 }3193 }3194 await persistEntries();3195}31963197export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {3198 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3199 const epoch = vaultEpoch;3200 const key = derivedKey;32013202 const sanitized = sanitizeEntryDraft(entry);3203 const now = Date.now();3204 const stamp = monotonicEntryTimestamp();3205 const nextEntry: VaultEntry = {3206 ...sanitized,3207 id: crypto.randomUUID(),3208 createdAt: now,3209 modifiedAt: stamp,3210 3211 3212 passwordChangedAt: sanitized.password ? stamp : undefined,3213 };32143215 3216 3217 3218 const rollback = entries;3219 entries = [...entries, nextEntry];3220 try {3221 await persistEntries();3222 } catch (err) {3223 entries = rollback;3224 throw err;3225 }32263227 if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password && epoch === vaultEpoch) {3228 checkEntryBreachDetached({ id: nextEntry.id, password: nextEntry.password, epoch, key });3229 }32303231 fireSyncTrigger("vault_change");32323233 return nextEntry;3234}323532363237export async function consolidatePasskeyEntries(): Promise<void> {3238 if (!derivedKey || vaultCreatesInFlight) return;3239 const epoch = vaultEpoch;3240 const rollback = entries;3241 const next = entries.map((entry) => ({ ...entry }));3242 if (!mergePasskeyOnlyIntoLogins(next).merged) return;3243 const unchanged = next.map((entry) => ({ entry, modifiedAt: entry.modifiedAt }));3244 entries = next;3245 try {3246 await persistEntries();3247 } catch (err) {3248 3249 if (epoch === vaultEpoch && entries === next && entries.length === unchanged.length &&3250 unchanged.every(({ entry, modifiedAt }, index) => entries[index] === entry && entry.modifiedAt === modifiedAt)) {3251 entries = rollback;3252 buildDomainIndexSync(entries);3253 }3254 throw err;3255 }3256}32573258export async function updateEntry(3259 id: string,3260 patch: Partial<VaultEntry>3261): Promise<void> {3262 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");32633264 const idx = entries.findIndex((entry) => entry.id === id);3265 if (idx === -1 || entries[idx].deletedAt) {3266 throw new Error("entry_not_found");3267 }32683269 const current = entries[idx];3270 const owner = entries;3271 const epoch = vaultEpoch;3272 const key = derivedKey;3273 const sanitizedPatch = sanitizeEntryPatch(patch);3274 3275 3276 3277 const passwordChanged =3278 "password" in patch &&3279 typeof sanitizedPatch.password === "string" &&3280 sanitizedPatch.password !== current.password;3281 const stamp = monotonicEntryTimestamp(current.modifiedAt);3282 3283 3284 3285 3286 3287 3288 3289 const priorPassword = current.password;3290 const shouldCapture =3291 passwordChanged &&3292 typeof priorPassword === "string" &&3293 priorPassword.length > 0 &&3294 current.passwordHistory?.[0]?.password !== priorPassword;3295 const nextHistory = shouldCapture3296 ? [3297 { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },3298 ...(current.passwordHistory ?? []),3299 ].slice(0, PASSWORD_HISTORY_MAX)3300 : current.passwordHistory;3301 const next = {3302 ...current,3303 ...sanitizedPatch,3304 modifiedAt: stamp,3305 ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),3306 };3307 entries[idx] = next;33083309 3310 if (entries[idx].type === "card" && !entries[idx].cardNumber) {3311 entries[idx] = current;3312 throw new Error("card number is required for card entries");3313 }33143315 3316 3317 3318 3319 try {3320 await persistEntries();3321 } catch (err) {3322 if (epoch === vaultEpoch && entries === owner && entries[idx] === next && next.modifiedAt === stamp && !next.deletedAt) entries[idx] = current;3323 throw err;3324 }33253326 if (passwordChanged && settings.breachMonitoring !== false && next.type === "login" && next.password && epoch === vaultEpoch) {3327 checkEntryBreachDetached({ id, password: next.password, epoch, key });3328 }33293330 fireSyncTrigger("vault_change");3331}33323333export async function deleteEntry(id: string): Promise<void> {3334 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");33353336 const entry = entries.find((item) => item.id === id);3337 if (!entry || entry.deletedAt) {3338 throw new Error("entry_not_found");3339 }33403341 3342 3343 3344 const previousModifiedAt = entry.modifiedAt;3345 const previousTombstone = tombstones.get(id);3346 const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));3347 entry.deletedAt = stamp;3348 entry.modifiedAt = stamp;3349 tombstones.set(id, stamp);3350 3351 3352 try {3353 await persistEntries();3354 } catch (err) {3355 delete entry.deletedAt;3356 entry.modifiedAt = previousModifiedAt;3357 if (previousTombstone === undefined) tombstones.delete(id);3358 else tombstones.set(id, previousTombstone);3359 throw err;3360 }3361 fireSyncTrigger("vault_change");3362}33633364export function getDeletedEntries(): VaultEntry[] {3365 if (!derivedKey) return [];3366 return entries.filter((e) => !!e.deletedAt);3367}336833693370export function getTombstoneManifest(): Record<string, number> {3371 if (!derivedKey) return {};3372 return Object.fromEntries(tombstones);3373}3374337533763377337833793380export async function getVaultVersion(): Promise<number> {3381 try {3382 const raw = await chrome.storage.local.get("peach_last_modified_at");3383 const v = (raw as Record<string, unknown>).peach_last_modified_at;3384 if (typeof v === "number") return v;3385 if (typeof v === "string" && v !== "") {3386 const n = Number.parseInt(v, 10);3387 return Number.isFinite(n) ? n : 0;3388 }3389 return 0;3390 } catch {3391 return 0;3392 }3393}3394339533963397339833993400340134023403340434053406export async function applyMergedRemoteEntries(3407 remoteEntries: VaultEntry[],3408 remoteTombstones: Record<string, number>,3409): Promise<{ received: number; applied: number; conflicts: number }> {3410 3411 3412 3413 3414 3415 3416 if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");34173418 const received = remoteEntries.length + Object.keys(remoteTombstones).length;3419 let applied = 0;3420 let conflicts = 0;34213422 const byId = new Map<string, VaultEntry>();3423 for (const e of entries) byId.set(e.id, e);34243425 const mergeNow = Date.now();3426 const remoteTombstoneTimes = new Map<string, number>();3427 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3428 if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {3429 remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));3430 }3431 }34323433 for (const remote of remoteEntries) {3434 const sanitized = sanitizeRestoredEntry(remote);3435 if (!sanitized) continue;3436 3437 3438 3439 sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);3440 if (typeof sanitized.deletedAt === "number") {3441 sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);3442 }3443 const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);3444 const localTombstoneTs = tombstones.get(sanitized.id);3445 const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);3446 if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {3447 continue;3448 }3449 const local = byId.get(sanitized.id);3450 if (!local) {3451 entries.push(sanitized);3452 byId.set(sanitized.id, sanitized);3453 tombstones.delete(sanitized.id);3454 applied += 1;3455 } else if (sanitized.modifiedAt > local.modifiedAt) {3456 const idx = entries.findIndex((e) => e.id === local.id);3457 if (idx !== -1) {3458 entries[idx] = sanitized;3459 byId.set(sanitized.id, sanitized);3460 tombstones.delete(sanitized.id);3461 applied += 1;3462 if (!local.deletedAt) conflicts += 1;3463 }3464 }3465 }34663467 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3468 if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;3469 3470 const deletedAt = remoteTombstoneTimes.get(id)!;3471 const knownTombstone = tombstones.get(id);3472 if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;3473 const local = byId.get(id);3474 if (!local) {3475 tombstones.set(id, deletedAt);3476 applied += 1;3477 continue;3478 }3479 if (local.deletedAt && local.deletedAt >= deletedAt) continue;3480 if (deletedAt < local.modifiedAt) continue;3481 const idx = entries.findIndex((e) => e.id === id);3482 if (idx !== -1) {3483 entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };3484 tombstones.set(id, deletedAt);3485 applied += 1;3486 }3487 }34883489 if (applied > 0 && vaultMode === "real") {3490 await persistEntries("sync_received");3491 buildDomainIndexSync(entries);3492 3493 3494 3495 3496 try {3497 void chrome.runtime3498 .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })3499 .catch(() => undefined);3500 } catch {3501 3502 }3503 }3504 return { received, applied, conflicts };3505}35063507export async function restoreEntry(id: string): Promise<void> {3508 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3509 const entry = entries.find((e) => e.id === id && e.deletedAt);3510 if (!entry) throw new Error("deleted entry not found");3511 const previousDeletedAt = entry.deletedAt;3512 const previousModifiedAt = entry.modifiedAt;3513 const previousTombstone = tombstones.get(id);3514 delete entry.deletedAt;3515 entry.modifiedAt = monotonicEntryTimestamp(Math.max(3516 entry.modifiedAt,3517 previousTombstone ?? 0,3518 ));3519 tombstones.delete(id);3520 try {3521 await persistEntries();3522 } catch (err) {3523 entry.deletedAt = previousDeletedAt;3524 entry.modifiedAt = previousModifiedAt;3525 if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);3526 throw err;3527 }3528 buildDomainIndexSync(entries);3529}35303531export async function purgeEntry(id: string): Promise<void> {3532 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3533 const idx = entries.findIndex((e) => e.id === id && e.deletedAt);3534 if (idx === -1) throw new Error("deleted entry not found");3535 const entry = entries[idx]!;3536 tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));3537 entries.splice(idx, 1);3538 await persistEntries();3539}354035413542export async function purgeExpiredTrash(retentionMs: number): Promise<number> {3543 if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;3544 const cutoff = Date.now() - retentionMs;3545 const before = entries.length;3546 for (const entry of entries) {3547 if (entry.deletedAt && entry.deletedAt < cutoff) {3548 tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));3549 }3550 }3551 entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));3552 const purged = before - entries.length;3553 if (purged > 0) await persistEntries();3554 return purged;3555}35563557export function queryDomain(domain: string): VaultEntry[] {3558 return domainIndex.get(domain) ?? [];3559}35603561export function getEntryById(id: string): VaultEntry | undefined {3562 return entries.find((entry) => entry.id === id && !entry.deletedAt);3563}35643565async function persistSlotA(3566 reason: VaultSnapshot["reason"] = "local_save",3567): Promise<StoredVault> {3568 if (!derivedKey) throw new Error("vault_locked");3569 const epoch = vaultEpoch;3570 const throwIfStale = () => {3571 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3572 };35733574 const slotA = await loadSlot(SLOT_A);3575 throwIfStale();3576 if (!slotA) throw new Error("missing slot A");35773578 3579 3580 await takeVaultSnapshot(reason);3581 throwIfStale();35823583 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3584 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3585 throwIfStale();35863587 3588 const nextSlotA: StoredVault = {3589 ...slotA,3590 nonce,3591 ciphertext,3592 tag,3593 3594 };35953596 3597 3598 3599 3600 3601 3602 let slotACommitted = false;3603 try {3604 throwIfStale();3605 await writeSlot(SLOT_A, nextSlotA);3606 slotACommitted = true;3607 throwIfStale();36083609 3610 3611 3612 if (!duressConfigured) {3613 throwIfStale();3614 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3615 throwIfStale();3616 }3617 3618 3619 3620 3621 3622 if (reason !== "sync_received") {3623 throwIfStale();3624 await stampLocalVaultMutation();3625 throwIfStale();3626 }3627 } catch (err) {3628 3629 3630 if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3631 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3632 throw err;3633 }36343635 return nextSlotA;3636}36373638async function persistSlotB(): Promise<void> {3639 if (!derivedKey) throw new Error("vault_locked");36403641 const slotB = await loadSlot(SLOT_B);3642 if (!slotB) throw new Error("missing slot B");36433644 3645 3646 3647 3648 const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3649 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");36503651 await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3652 3653 3654 3655 try {3656 await stampLocalVaultMutation();3657 } catch (err) {3658 await writeSlot(SLOT_B, slotB).catch(() => {});3659 throw err;3660 }3661}36623663async function persistEntries(3664 reason: VaultSnapshot["reason"] = "local_save",3665): Promise<void> {3666 if (vaultCreatesInFlight) throw new Error("vault_changed");3667 vaultWritesInFlight++;3668 try {3669 if (!derivedKey) throw new Error("vault_locked");36703671 3672 3673 const previousTombstones = tombstones;3674 const pendingTombstones = new Map(tombstones);3675 tombstones = pendingTombstones;3676 reconcileTombstones();3677 try {3678 if (vaultMode === "decoy") {3679 await persistSlotB();3680 } else {3681 await persistSlotA(reason);3682 }3683 } catch (err) {3684 if (tombstones === pendingTombstones) tombstones = previousTombstones;3685 throw err;3686 }3687 buildDomainIndexSync(entries);3688 await refreshLockedSyncState();3689 } finally { vaultWritesInFlight--; }3690}3691369236933694369536963697function allowHttpUrl(url: string | undefined): string {3698 const trimmed = url?.trim() ?? "";3699 if (!trimmed) return "";3700 try {3701 const parsed = new URL(trimmed);3702 if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3703 } catch {3704 3705 }3706 return trimmed;3707}37083709function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3710 if (!Array.isArray(values)) return undefined;3711 const seen = new Set<string>();3712 const cleaned: string[] = [];3713 for (const value of values) {3714 const trimmed = typeof value === "string" ? value.trim() : "";3715 if (!trimmed) continue;3716 if (!allowHttpUrl(trimmed)) continue;3717 const key = trimmed.toLowerCase();3718 if (seen.has(key)) continue;3719 seen.add(key);3720 cleaned.push(trimmed);3721 }3722 return cleaned.length > 0 ? cleaned : undefined;3723}37243725function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3726 const title = entry.title.trim();3727 const type: VaultEntry["type"] = entry.type ?? "login";37283729 if (!title) throw new Error("title is required");37303731 if (entry.passkey) {3732 const p = entry.passkey;3733 if (3734 !p.rpId ||3735 !p.credentialId ||3736 !p.publicKeyCose ||3737 !p.userHandle ||3738 !p.userName ||3739 (p.algorithm !== -7 && p.algorithm !== -8)3740 ) {3741 throw new Error("invalid passkey credential");3742 }3743 }3744 if (type === "card") {3745 if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3746 throw new Error("cardholder name and card number are required");3747 }3748 }37493750 return {3751 type,3752 title,3753 username: type === "login" ? entry.username?.trim() ?? "" : undefined,3754 email: type === "login" ? entry.email?.trim() || undefined : undefined,3755 password: type === "login" ? entry.password : undefined,3756 url: type === "login" ? allowHttpUrl(entry.url) : undefined,3757 additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3758 totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3759 3760 3761 totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3762 totpDigits: type === "login" ? entry.totpDigits : undefined,3763 totpPeriod: type === "login" ? entry.totpPeriod : undefined,3764 notes: entry.notes?.trim() || undefined,3765 breach: type === "login" ? entry.breach : undefined,3766 3767 3768 canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3769 tags: sanitizeTags(entry.tags),3770 passkey: entry.passkey,3771 cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3772 cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3773 expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3774 expYear: type === "card" ? entry.expYear?.trim() : undefined,3775 cvc: type === "card" ? entry.cvc?.trim() : undefined,3776 cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3777 network: type === "card" ? entry.network : undefined,3778 last4: type === "card" ? entry.last4?.trim() : undefined,3779 };3780}37813782function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3783 const nextPatch: Partial<VaultEntry> = {};37843785 if ("type" in patch) {3786 nextPatch.type = patch.type;3787 }37883789 if ("title" in patch) {3790 const title = patch.title?.trim() ?? "";3791 if (!title) throw new Error("title is required");3792 nextPatch.title = title;3793 }37943795 if ("url" in patch) {3796 nextPatch.url = allowHttpUrl(patch.url);3797 }37983799 if ("additionalUrls" in patch) {3800 const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3801 const seen = new Set<string>();3802 const cleaned: string[] = [];3803 for (const value of incoming) {3804 const trimmed = typeof value === "string" ? value.trim() : "";3805 if (!trimmed || !allowHttpUrl(trimmed)) continue;3806 const key = trimmed.toLowerCase();3807 if (seen.has(key)) continue;3808 seen.add(key);3809 cleaned.push(trimmed);3810 }3811 nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3812 }38133814 if ("username" in patch) {3815 nextPatch.username = patch.username?.trim() ?? "";3816 }38173818 if ("email" in patch) {3819 nextPatch.email = patch.email?.trim() || undefined;3820 }38213822 if ("password" in patch) {3823 const password = patch.password ?? "";3824 3825 nextPatch.password = password || undefined;3826 }38273828 if ("totp" in patch) {3829 nextPatch.totp = patch.totp?.trim() || undefined;3830 }38313832 if ("totpAlgorithm" in patch) {3833 nextPatch.totpAlgorithm = patch.totpAlgorithm;3834 }38353836 if ("totpDigits" in patch) {3837 nextPatch.totpDigits = patch.totpDigits;3838 }38393840 if ("totpPeriod" in patch) {3841 nextPatch.totpPeriod = patch.totpPeriod;3842 }38433844 if ("notes" in patch) {3845 nextPatch.notes = patch.notes?.trim() || undefined;3846 }38473848 if ("breach" in patch) {3849 nextPatch.breach = patch.breach;3850 }38513852 if ("canary" in patch) {3853 3854 3855 nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3856 }38573858 if ("passkey" in patch) {3859 3860 3861 if (patch.passkey === undefined || patch.passkey === null) {3862 nextPatch.passkey = undefined;3863 } else {3864 const sanitized = sanitizePasskey(patch.passkey);3865 if (!sanitized) throw new Error("invalid passkey credential");3866 nextPatch.passkey = sanitized;3867 }3868 }38693870 if ("tags" in patch) {3871 3872 nextPatch.tags = sanitizeTags(patch.tags);3873 }38743875 if ("cardholderName" in patch) {3876 nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3877 }3878 if ("cardNumber" in patch) {3879 const n = patch.cardNumber ?? "";3880 nextPatch.cardNumber = n || undefined;3881 }3882 if ("expMonth" in patch) {3883 nextPatch.expMonth = patch.expMonth?.trim() || undefined;3884 }3885 if ("expYear" in patch) {3886 nextPatch.expYear = patch.expYear?.trim() || undefined;3887 }3888 if ("cvc" in patch) {3889 nextPatch.cvc = patch.cvc?.trim() || undefined;3890 }3891 if ("cardNickname" in patch) {3892 nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3893 }3894 if ("network" in patch) {3895 nextPatch.network = patch.network;3896 }3897 if ("last4" in patch) {3898 nextPatch.last4 = patch.last4?.trim() || undefined;3899 }39003901 return nextPatch;3902}39033904function normalizeEntry(entry: VaultEntry): VaultEntry {3905 const base: VaultEntry = {3906 id: entry.id,3907 type: entry.type,3908 title: entry.title,3909 username: entry.username,3910 email: entry.email,3911 password: entry.password,3912 url: entry.url,3913 additionalUrls:3914 "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3915 ? entry.additionalUrls3916 : undefined,3917 totp: entry.totp,3918 3919 totpAlgorithm: entry.totpAlgorithm,3920 totpDigits: entry.totpDigits,3921 totpPeriod: entry.totpPeriod,3922 notes: entry.notes,3923 breach: entry.breach,3924 3925 3926 3927 passwordChangedAt:3928 "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3929 3930 3931 3932 passwordHistory:3933 "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3934 ? entry.passwordHistory3935 : undefined,3936 canary: entry.canary,3937 passkey: entry.passkey,3938 createdAt: entry.createdAt,3939 modifiedAt: entry.modifiedAt,3940 deletedAt: entry.deletedAt,3941 tags: entry.tags,3942 cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3943 cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3944 expMonth: "expMonth" in entry ? entry.expMonth : undefined,3945 expYear: "expYear" in entry ? entry.expYear : undefined,3946 cvc: "cvc" in entry ? entry.cvc : undefined,3947 cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3948 network: "network" in entry ? entry.network : undefined,3949 last4: "last4" in entry ? entry.last4 : undefined,3950 };39513952 return base;3953}3954395539563957395839593960function entryDupeKey(e: VaultEntry): string {3961 if (e.passkey) {3962 3963 const content = Object.fromEntries(Object.entries(e)3964 .filter(([key]) => key !== "id" && key !== "createdAt" && key !== "modifiedAt")3965 .sort(([a], [b]) => a.localeCompare(b)));3966 return `passkey|${e.passkey.rpId}|${e.passkey.credentialId}|${JSON.stringify(content)}`;3967 }3968 if (e.type === "note") return `note|${e.title.toLowerCase()}`;3969 return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3970}397139723973export function countDuplicates(): number {3974 const best = new Map<string, VaultEntry>();3975 let dupeCount = 0;3976 for (const e of entries.filter((e) => !e.deletedAt)) {3977 const key = entryDupeKey(e);3978 const existing = best.get(key);3979 if (!existing) {3980 best.set(key, e);3981 } else {3982 dupeCount++;3983 3984 if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3985 best.set(key, e);3986 }3987 }3988 }3989 return dupeCount;3990}399139923993399439953996export async function deduplicateEntries(): Promise<number> {3997 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3998 3999 4000 if (vaultMode === "decoy") {4001 throw new Error("deduplicate disabled in decoy mode");4002 }40034004 const best = new Map<string, VaultEntry>();4005 for (const e of entries.filter((en) => !en.deletedAt)) {4006 const key = entryDupeKey(e);4007 const existing = best.get(key);4008 if (!existing) {4009 best.set(key, e);4010 } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {4011 best.set(key, e);4012 }4013 }40144015 const keepIds = new Set(Array.from(best.values()).map((e) => e.id));4016 let removed = 0;4017 entries = entries.map((e) => {4018 if (!e.deletedAt && !keepIds.has(e.id)) {4019 removed++;4020 const deletedAt = monotonicEntryTimestamp(Math.max(4021 e.modifiedAt,4022 tombstones.get(e.id) ?? 0,4023 ));4024 tombstones.set(e.id, deletedAt);4025 return { ...e, deletedAt };4026 }4027 return e;4028 });40294030 if (removed > 0) await persistEntries();4031 return removed;4032}403340344035403640374038403940404041const HISTORY_KEY = "peach_vault_history";4042const HISTORY_MAX = 5;404340444045404640474048function bucketEntryCount(n: number): number {4049 if (n <= 0) return 0;4050 if (n <= 10) return 10;4051 if (n <= 25) return 25;4052 if (n <= 50) return 50;4053 if (n <= 100) return 100;4054 if (n <= 250) return 250;4055 if (n <= 500) return 500;4056 return Math.ceil(n / 500) * 500;4057}40584059406040614062406340644065export async function takeVaultSnapshot(4066 reason: VaultSnapshot["reason"],4067): Promise<void> {4068 if (recoveryInFlight || vaultCreatesInFlight) return;4069 4070 4071 4072 if (vaultMode === "decoy") return;4073 vaultWritesInFlight++;4074 try {4075 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);4076 const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];4077 const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];40784079 4080 4081 4082 if (!slotA) return;40834084 const vault_a = JSON.stringify(slotA);4085 const vault_b = JSON.stringify(slotB ?? slotA);40864087 4088 4089 4090 4091 4092 4093 let entryCount: number | null = null;4094 if (derivedKey && vaultMode === "real") {4095 try {4096 entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);4097 } catch {4098 entryCount = null;4099 }4100 }41014102 const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];4103 const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)4104 ? existingRaw4105 : { snapshots: [] };41064107 4108 4109 4110 const latest = history.snapshots[0];4111 if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {4112 return;4113 }41144115 const snapshot: VaultSnapshot = {4116 id: crypto.randomUUID(),4117 savedAt: Date.now(),4118 reason,4119 vault_a,4120 vault_b,4121 entryCount,4122 };41234124 history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);4125 if (recoveryInFlight || vaultCreatesInFlight) return;4126 await chrome.storage.local.set({ [HISTORY_KEY]: history });4127 } catch (err) {4128 4129 4130 4131 4132 console.warn('[Peach] takeVaultSnapshot failed:', err);4133 if (String(err).includes('QUOTA') || String(err).includes('quota')) {4134 try {4135 await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });4136 } catch {4137 4138 }4139 }4140 } finally { vaultWritesInFlight--; }4141}414241434144export async function clearVaultHistory(): Promise<void> {4145 if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");4146 vaultWritesInFlight++;4147 try {4148 await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });4149 } catch {4150 4151 } finally { vaultWritesInFlight--; }4152}415341544155export async function getVaultHistory(): Promise<VaultSnapshot[]> {4156 if (vaultMode === "decoy") return [];4157 const raw = await chrome.storage.local.get(HISTORY_KEY);4158 const value = (raw as Record<string, unknown>)[HISTORY_KEY];4159 return sanitizeHistory(value);4160}416141624163416441654166export async function restoreVaultSnapshot(4167 snapshotId: string,4168): Promise<{ ok: true } | { ok: false; error: string }> {4169 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };4170 vaultReplacementInFlight = true;4171 try {4172 if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };4173 const history = await getVaultHistory();4174 const snapshot = history.find((s) => s.id === snapshotId);4175 if (!snapshot) return { ok: false, error: "snapshot_not_found" };41764177 const restoredA = parseHistorySlot(snapshot.vault_a);4178 const restoredB = parseHistorySlot(snapshot.vault_b);4179 if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };41804181 await takeVaultSnapshot("restore");4182 const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);4183 const previousA = (current as Record<string, unknown>)[SLOT_A];4184 const previousB = (current as Record<string, unknown>)[SLOT_B];4185 try {4186 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };4187 await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });4188 await stampLocalVaultMutation();4189 } catch {4190 try {4191 await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });4192 } catch {4193 4194 }4195 return { ok: false, error: "snapshot_corrupt" };4196 }41974198 await lock();4199 return { ok: true };4200 } finally {4201 vaultReplacementInFlight = false;4202 }4203}420442054206420742084209421042114212421342144215421642174218export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {4219 if (vaultCreatesInFlight) throw new Error("vault_changed");4220 const rotationEpoch = vaultEpoch;4221 const removalEpoch = vaultRemovalEpoch;4222 vaultWritesInFlight++;4223 try {4224 if (!derivedKey || vaultMode !== "real") {4225 return { ok: false, error: "vault_locked" };4226 }4227 const slotA = await loadSlot(SLOT_A);4228 if (!slotA) return { ok: false, error: "missing_slot_a" };42294230 4231 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =4232 await generateAndWrapRootKey();42334234 4235 const newRootKey = unhex(rawRootKey);4236 const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");4237 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);42384239 4240 4241 4242 4243 await takeVaultSnapshot("local_save");4244 const nextSlotA: StoredVault = {4245 ...slotA,4246 recovery_vault_key: recoveryVaultKey,4247 recovery_salt: recoverySalt,4248 recovery_wrapped_root_key: wrappedRootKey,4249 recovery_nonce: wrappedNonce,4250 recovery_tag: wrappedTag,4251 ...pwRoot,4252 };4253 await writeSlot(SLOT_A, nextSlotA);42544255 4256 if (rotationEpoch === vaultEpoch && derivedKey && rootKey) {4257 const oldRootKey = rootKey;4258 4259 4260 4261 4262 await serializeRecallMutation(async () => {4263 await rekeyManualSummonRecall(oldRootKey, newRootKey).catch((error) => {4264 console.warn("[Peach] manual-summon recall re-key failed:", error);4265 });4266 if (rootKey === oldRootKey) {4267 rootKey = newRootKey;4268 zeroKey(oldRootKey);4269 } else {4270 zeroKey(newRootKey);4271 }4272 });4273 } else {4274 zeroKey(newRootKey);4275 }42764277 4278 4279 await notifyIdentityKeysRotated();42804281 4282 4283 4284 await clearPairedDevices();4285 await clearPairSecrets();42864287 4288 if (removalEpoch === vaultRemovalEpoch) {4289 await setRecoveryConfirmPending(rotationEpoch === vaultEpoch && isUnlocked());4290 touchAutoLock();4291 }42924293 await stampLocalVaultMutation();4294 return { ok: true };4295 } finally { vaultWritesInFlight--; }4296}42974298429943004301430243034304export async function changePassword(4305 currentPassword: string,4306 newPassword: string4307): Promise<boolean> {4308 if (vaultCreatesInFlight) throw new Error("vault_changed");4309 vaultWritesInFlight++;4310 try {43114312 const epoch = vaultEpoch;4313 const stale = () => epoch !== vaultEpoch;4314 if (!derivedKey || vaultMode !== "real") return false;43154316 4317 const valid = await verifyMainPassword(currentPassword);4318 if (!valid) return false;43194320 const slotA = await loadSlot(SLOT_A);4321 if (!slotA) return false;4322 if (!rootKey) return false;43234324 4325 const newSalt = generateSalt();4326 const newKey = await deriveKey(newPassword, newSalt);4327 if (stale()) {4328 zeroKey(newKey);4329 return false;4330 }43314332 4333 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);4334 const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");43354336 4337 4338 4339 const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);43404341 const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");4342 const finalSlotA: StoredVault = {4343 ...slotA,4344 recovery_vault_key: recoveryVaultKey,4345 salt: hex(newSalt),4346 nonce,4347 ciphertext,4348 tag,4349 ...pwRoot,4350 };43514352 4353 4354 4355 await takeVaultSnapshot("local_save");43564357 4358 4359 4360 4361 await writeSlot(SLOT_A, finalSlotA);4362 if (stale()) {4363 zeroKey(newKey);4364 return false;4365 }43664367 4368 4369 4370 zeroKey(derivedKey);4371 cancelBreachScan();4372 derivedKey = newKey;43734374 4375 4376 4377 4378 if (stale()) {4379 await lock();4380 return false;4381 }4382 await saveSessionKey(newKey, "real", epoch);4383 if (stale()) return false;43844385 4386 4387 4388 await notifyIdentityKeysRotated();4389 if (stale()) return false;43904391 4392 4393 4394 if (!duressConfigured) {4395 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));4396 }4397 await clearPinUnlockStorage();4398 await stampLocalVaultMutation();43994400 return true;4401 } finally { vaultWritesInFlight--; }4402}