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 Canary,28 ManualSummonRecord,29 PasskeyData,30 RecoveryResult,31 SavedIdentity,32 StoredVault,33 VaultEntry,34 VaultHistory,35 VaultSnapshot,36} from "../shared/types";37import { decrypt, encrypt, zeroKey } from "./aes";38import { clearAutoLock, touchAutoLock } from "./alarms";39import { setRecoveryConfirmPending } from "./recovery-pending";40import {41 clearPairSecrets,42 dropSessionCache,43 reconcilePairSecrets,44 setSessionAllowed,45} from "./pair-secrets";4647type EntryDraft = Omit<48 VaultEntry,49 "id" | "createdAt" | "modifiedAt" | "deletedAt"50>;515253545556const SLOT_A = "peach_vault_a";57const SLOT_B = "peach_vault_b";58596061const PAD_BLOCK = 1024;6263646566const PASSWORD_HISTORY_MAX = 50;6768697071727374757677const DURESS_SLOT_SIZE = 262_144;7879let derivedKey: Uint8Array | null = null;8081828384let rootKey: Uint8Array | null = null;85let recoveryInFlight = false;86let recoverySettled: Promise<void> = Promise.resolve();87let vaultRemovalsInFlight = 0;88let vaultWritesInFlight = 0;89let vaultCreatesInFlight = 0;90let creationSettled: Promise<void> = Promise.resolve();91let vaultUnlocksInFlight = 0;92let vaultReplacementInFlight = false;93let entries: VaultEntry[] = [];94959697let tombstones = new Map<string, number>();98let domainIndex: Map<string, VaultEntry[]> = new Map();99let vaultMode: "real" | "decoy" = "real";100101102103let duressConfigured = false;104105106107108109110111112113114let lastUnlockFailureReason: string | null = null;115116export function consumeLastUnlockFailureReason(): string | null {117 const r = lastUnlockFailureReason;118 lastUnlockFailureReason = null;119 return r;120}121122123124125126export type TextSize = "small" | "medium" | "large";127128export interface VaultSettings {129 accentColor?: AccentColorName;130 theme?: "dark" | "light";131 autoLockMinutes?: number;132 clipboardClearSeconds?: number;133 lockOnClose?: boolean;134 breachMonitoring?: boolean;135 passkeyProviderEnabled?: boolean;136 trashRetentionDays?: number;137 manualSummonDomains?: Record<string, ManualSummonRecord>;138 manualSummonSalt?: string;139 declinedCardFingerprints?: string[];140141 142 metadataVersion?: 1;143 144145146147148 textSize?: TextSize;149 150151152153154 reduceMotion?: boolean;155 156 lockedSyncRequiresUnlock?: boolean;157 158 pinEnabled?: boolean;159 160 pinPreferred?: boolean;161 162163164165166167168 shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;169}170171interface StoredPinWrap {172 version: 1;173 salt: string;174 nonce: string;175 ciphertext: string;176 tag: string;177}178179const PIN_WRAP_STORAGE = "peach_pin_wrap";180const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";181const PIN_MIN_LENGTH = 4;182const PIN_MAX_LENGTH = 12;183const PIN_MAX_ATTEMPTS = 3;184185let settings: VaultSettings = {};186const CARD_DECLINE_MAX = 256;187188const CARD_DECLINE_DIGEST_HEX = 32;189190async function metadataDigest(value: string, key: string): Promise<string> {191 const bytes = new TextEncoder().encode(`${key}:${value}`);192 const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));193 return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");194}195196let inMemoryPinWrap: StoredPinWrap | null = null;197let inMemoryPinFailedAttempts = 0;198let sessionPinStorageFailed = false;199200export function getSettings(): VaultSettings {201 return settings;202}203204export async function ensureSettingsLoaded(): Promise<VaultSettings> {205 await loadSettings();206 return settings;207}208209export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {210 await loadSettings();211 212 213 214 215 const safe = Object.fromEntries(216 Object.entries(patch).filter(217 ([k]) => !["__proto__", "constructor", "prototype"].includes(k),218 ),219 ) as Partial<VaultSettings>;220 settings = { ...settings, ...safe };221 await persistSettings();222}223224function isValidPin(pin: string): boolean {225 return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);226}227228229export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {230 if (vaultCreatesInFlight) return false;231 vaultWritesInFlight++;232 try {233 if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;234 if (!(await verifyMainPassword(currentPassword))) return false;235236 const salt = generateSalt();237 const pinKey = await deriveKey(pin, salt);238 try {239 const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");240 await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });241 await updateSettings({ pinEnabled: true });242 return true;243 } finally {244 zeroKey(pinKey);245 }246 } finally { vaultWritesInFlight--; }247}248249async function clearPinUnlockStorage(): Promise<void> {250 inMemoryPinWrap = null;251 inMemoryPinFailedAttempts = 0;252 sessionPinStorageFailed = false;253 if (chrome.storage.session) {254 await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);255 }256 await updateSettings({ pinEnabled: false });257}258259260export async function disablePinUnlock(currentPassword: string): Promise<boolean> {261 if (vaultCreatesInFlight) return false;262 vaultWritesInFlight++;263 try {264 if (!derivedKey || vaultMode !== "real") return false;265 if (!(await verifyMainPassword(currentPassword))) return false;266 await clearPinUnlockStorage();267 return true;268 } finally { vaultWritesInFlight--; }269}270271272export async function unlockWithPin(pin: string): Promise<boolean> {273 vaultUnlocksInFlight++;274 try {275 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;276 if (!isValidPin(pin)) return false;277 await loadSettings();278 if (!settings.pinEnabled) return false;279280 const { stored, failedAttempts } = await loadPinState();281 if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;282 if (283 !stored ||284 stored.version !== 1 ||285 !stored.salt ||286 !stored.nonce ||287 !stored.ciphertext ||288 !stored.tag289 ) return false;290291 const pinKey = await deriveKey(pin, unhex(stored.salt));292 let unwrappedKey: Uint8Array | null = null;293 try {294 const masterKeyHex = await decrypt(295 pinKey,296 stored.nonce,297 stored.ciphertext,298 stored.tag,299 "pin_wrap_v1",300 );301 if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;302 unwrappedKey = unhex(masterKeyHex);303 const result = await unlockWithKey(masterKeyHex);304 if (!result.ok) return false;305 await resetPinFailedAttempts();306 return true;307 } catch {308 await recordPinFailure(failedAttempts + 1);309 return false;310 } finally {311 zeroKey(pinKey);312 if (unwrappedKey) zeroKey(unwrappedKey);313 }314 } finally { vaultUnlocksInFlight--; }315}316317async function savePinWrap(stored: StoredPinWrap): Promise<void> {318 inMemoryPinWrap = stored;319 inMemoryPinFailedAttempts = 0;320 sessionPinStorageFailed = !chrome.storage.session;321 if (!chrome.storage.session) return;322 try {323 await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });324 sessionPinStorageFailed = false;325 } catch {326 327 sessionPinStorageFailed = true;328 }329}330331async function loadPinState(): Promise<{332 stored: StoredPinWrap | undefined;333 failedAttempts: number;334}> {335 if (!chrome.storage.session) {336 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };337 }338 try {339 const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);340 return {341 stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??342 (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),343 failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"344 ? result[PIN_ATTEMPTS_STORAGE]345 : 0,346 };347 } catch {348 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };349 }350}351352async function recordPinFailure(failedAttempts: number): Promise<void> {353 inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);354 if (!chrome.storage.session) return;355 try {356 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });357 } catch { }358}359360async function resetPinFailedAttempts(): Promise<void> {361 inMemoryPinFailedAttempts = 0;362 if (!chrome.storage.session) return;363 try {364 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });365 } catch { }366}367368export async function getPinUnlockStatus(): Promise<{369 configured: boolean;370 available: boolean;371 attemptsRemaining: number;372}> {373 await loadSettings();374 if (!settings.pinEnabled) {375 return { configured: false, available: false, attemptsRemaining: 0 };376 }377 const { stored, failedAttempts } = await loadPinState();378 const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;379 return {380 configured: true,381 available,382 attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,383 };384}385386async function persistSettings(): Promise<void> {387 try {388 await chrome.storage.local.set({389 peach_settings: {390 ...settings,391 manualSummonDomains: undefined,392 manualSummonSalt: undefined,393 cardFingerprintSalt: undefined,394 declinedCardFingerprints: settings.declinedCardFingerprints ?? [],395 metadataVersion: 1,396 },397 });398 } catch (err) {399 throw mapStorageError(err);400 }401}402403function mapStorageError(err: unknown): Error {404 const message = err instanceof Error ? err.message : String(err);405 if (/QUOTA_BYTES|quota/i.test(message)) {406 return new Error("STORAGE_QUOTA_EXCEEDED");407 }408 return err instanceof Error ? err : new Error(message);409}410411async function loadSettings(): Promise<void> {412 const result = await chrome.storage.local.get("peach_settings");413 settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};414}415416417418function fireSyncTrigger(reason: "vault_change"): void {419 void Promise.resolve()420 .then(() => triggerSyncIfReachable({ reason }))421 .catch(() => {422 423 });424}425export function lockedSyncRequiresUnlock(): boolean {426 return settings.lockedSyncRequiresUnlock === true;427}428429let lockedSyncRefreshHook: (() => Promise<void>) | null = null;430let lockedSyncUnlockHook: (() => Promise<void>) | null = null;431let decoySyncTeardownHook: (() => void) | null = null;432export type IdentityHooks = {433 434 onSessionEnded: () => Promise<void>;435 436 onKeysRotated: () => Promise<void>;437 438 onVaultCreated: (password: string) => Promise<void>;439};440441let identityHooks: IdentityHooks | null = null;442443export function setIdentityHooks(hooks: IdentityHooks): void {444 identityHooks = hooks;445}446447async function notifyIdentitySessionEnded(): Promise<void> {448 await identityHooks?.onSessionEnded().catch((error) => {449 console.warn("[Peach] local identity cache clear failed:", error);450 });451}452453async function notifyIdentityKeysRotated(): Promise<void> {454 await identityHooks?.onKeysRotated().catch((error) => {455 console.warn("[Peach] local identity re-wrap failed:", error);456 });457}458459export type SealedBox = { nonce: string; ciphertext: string; tag: string };460export type IdentityKeyEnvelope = {461 root?: SealedBox;462 local?: SealedBox;463 pending?: SealedBox;464 pendingSalt?: string;465};466467export function setLockedSyncHooks(hooks: {468 refresh: () => Promise<void>;469 afterUnlock: () => Promise<void>;470 onDecoy?: () => void;471}): void {472 lockedSyncRefreshHook = hooks.refresh;473 lockedSyncUnlockHook = hooks.afterUnlock;474 decoySyncTeardownHook = hooks.onDecoy ?? null;475}476477async function refreshLockedSyncState(): Promise<void> {478 if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;479 await lockedSyncRefreshHook().catch((error) => {480 console.warn("[Peach sync] locked spool refresh failed:", error);481 });482}483484485486487488export async function checkBreach(password: string): Promise<number> {489 490 491 const encoder = new TextEncoder();492 const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));493 const hashHex = Array.from(new Uint8Array(hashBuffer))494 .map((b) => b.toString(16).padStart(2, "0"))495 .join("")496 .toUpperCase();497498 const prefix = hashHex.slice(0, 5);499 const suffix = hashHex.slice(5);500501 try {502 503 504 const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {505 headers: { "Add-Padding": "true" },506 });507 if (!res.ok) return 0;508 const text = await res.text();509 const match = text.split("\r\n").find((l) => l.startsWith(suffix));510 return match ? parseInt(match.split(":")[1], 10) : 0;511 } catch {512 return 0; 513 }514}515516export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {517 518 const key = await cardDeclineKey();519 if (!key) return;520 const fingerprint = await cardFingerprint(last4, expMonth, expYear);521 await loadSettings();522 settings = {523 ...settings,524 declinedCardFingerprints: [525 526 527 ...(settings.declinedCardFingerprints ?? []).filter(528 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,529 ),530 await metadataDigest(fingerprint, key),531 ].slice(-CARD_DECLINE_MAX),532 };533 await persistSettings();534}535536export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {537 await loadSettings();538 const key = await cardDeclineKey();539 if (!key) return false;540 const fingerprint = await cardFingerprint(last4, expMonth, expYear);541 const candidate = await metadataDigest(fingerprint, key);542 return (settings.declinedCardFingerprints ?? []).some(543 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,544 );545}546547548549550551552553554555556557558async function cardDeclineKey(): Promise<string | null> {559 const root = getRootKeyHex();560 if (!root) return null;561 const digest = new Uint8Array(562 await crypto.subtle.digest(563 "SHA-256",564 new TextEncoder().encode(`peach-card-decline-v1:${root}`),565 ),566 );567 return hex(digest);568}569570async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {571 const encoder = new TextEncoder();572 const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));573 return Array.from(new Uint8Array(buf).slice(0, 8))574 .map((b) => b.toString(16).padStart(2, "0"))575 .join("");576}577578function hex(buf: Uint8Array): string {579 return Array.from(buf)580 .map((b) => b.toString(16).padStart(2, "0"))581 .join("");582}583584function unhex(s: string): Uint8Array {585 const out = new Uint8Array(s.length / 2);586 for (let i = 0; i < s.length; i += 2) {587 out[i / 2] = parseInt(s.slice(i, i + 2), 16);588 }589 return out;590}591592593594595596597598599600601602603604605606607608609610611async function generateAndWrapRootKey(): Promise<{612 rawRootKey: string; 613 recoverySalt: string;614 wrappedRootKey: string;615 wrappedNonce: string;616 wrappedTag: string;617}> {618 const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));619 try {620621 622 const words = await rootKeyToWords(rootKeyBytes);623 const wordMaterial = await wordsToRootKeyMaterial(words);624 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));625 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);626627 628 629 const nonce = crypto.getRandomValues(new Uint8Array(12));630 const encoded = new TextEncoder().encode(hex(rootKeyBytes));631 const raw = await crypto.subtle.encrypt(632 {633 name: "AES-GCM",634 iv: nonce,635 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,636 tagLength: 128,637 },638 recoveryKey,639 encoded640 );641 642 const rawU8 = new Uint8Array(raw);643 const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));644 const tag = hex(rawU8.slice(rawU8.length - 16));645646 return {647 rawRootKey: hex(rootKeyBytes),648 recoverySalt: hex(recoverySalt),649 wrappedRootKey: ciphertext,650 wrappedNonce: hex(nonce),651 wrappedTag: tag,652 };653 } finally { zeroKey(rootKeyBytes); }654}655656async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{657 recoverySalt: string;658 wrappedRootKey: string;659 wrappedNonce: string;660 wrappedTag: string;661}> {662 if (rootKeyBytes.length !== 32) {663 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");664 }665666 const words = await rootKeyToWords(rootKeyBytes);667 const wordMaterial = await wordsToRootKeyMaterial(words);668 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));669 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);670 const nonce = crypto.getRandomValues(new Uint8Array(12));671 const encoded = new TextEncoder().encode(hex(rootKeyBytes));672 const raw = await crypto.subtle.encrypt(673 {674 name: "AES-GCM",675 iv: nonce,676 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,677 tagLength: 128,678 },679 recoveryKey,680 encoded,681 );682 const rawU8 = new Uint8Array(raw);683 return {684 recoverySalt: hex(recoverySalt),685 wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),686 wrappedNonce: hex(nonce),687 wrappedTag: hex(rawU8.slice(rawU8.length - 16)),688 };689}690691692693694695async function unwrapRootKeyForRecovery(696 wrappedRootKey: string,697 wrappedNonce: string,698 wrappedTag: string,699 recoverySaltHex: string,700 words: string[]701): Promise<Uint8Array> {702 const wordMaterial = await wordsToRootKeyMaterial(words);703 const recoverySalt = unhex(recoverySaltHex);704 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);705706 707 708 709 710 711 const nonceRaw = unhex(wrappedNonce);712 const ciphertextRaw = unhex(wrappedRootKey);713 const tagRaw = unhex(wrappedTag);714 715 716 const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;717 const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);718 combined.set(ciphertextRaw, 0);719 combined.set(tagRaw, ciphertextRaw.length);720 const raw = await crypto.subtle.decrypt(721 { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },722 recoveryKey,723 combined724 );725 const decryptedHex = new TextDecoder().decode(raw);726 const recovered = unhex(decryptedHex);727 if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }728 return recovered;729}730731732export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {733 if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");734 if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");735 recoveryInFlight = true;736 let settle!: () => void;737 recoverySettled = new Promise<void>((resolve) => { settle = resolve; });738 const epoch = ++vaultEpoch;739 const check = () => {740 if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");741 };742 let recoveredRoot: Uint8Array | null = null;743 let oldKey: Uint8Array | null = null;744 let newKey: Uint8Array | null = null;745 let committed = false;746 try {747 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);748 check();749 const slot = raw[SLOT_A] as StoredVault | undefined;750 if (!slot) throw new Error("no_vault");751 if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");752 try {753 recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,754 slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);755 } catch {756 throw new Error("invalid_recovery_words");757 }758 check();759 if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");760 oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");761 check();762 if (!oldKey) throw new Error("recovery_data_unavailable");763 const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");764 check();765 if (result.status !== "ok") throw new Error("recovery_data_unavailable");766 const payload = result.payload;767 await loadSettings();768 check();769 const salt = generateSalt();770 newKey = await deriveKey(newPassword, salt);771 check();772 773 const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");774 const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");775 const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);776 const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");777 check();778 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);779 check();780 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");781 const history = raw[HISTORY_KEY] as VaultHistory | undefined;782 const snapshot: VaultSnapshot = {783 id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",784 vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,785 };786 const previousStamp = Number(raw.peach_last_modified_at);787 const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,788 salt: hex(salt), recovery_vault_key: recoveryVaultKey };789 790 await chrome.storage.local.set({791 [SLOT_A]: nextSlot,792 [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },793 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),794 });795 committed = true;796 check();797 derivedKey = newKey;798 rootKey = recoveredRoot;799 newKey = null;800 recoveredRoot = null;801 entries = payload.entries;802 tombstones = payload.tombstones;803 duressConfigured = payload.duressConfigured;804 vaultMode = "real";805 buildDomainIndexSync(entries);806 await saveSessionKey(derivedKey, "real", epoch);807 if (epoch !== vaultEpoch) throw new Error("vault_locked");808 await identityHooks?.onKeysRotated();809 if (epoch !== vaultEpoch) throw new Error("vault_locked");810 await reconcilePairSecrets(rootKey);811 if (epoch !== vaultEpoch) throw new Error("vault_locked");812 await clearPinUnlockStorage();813 if (epoch !== vaultEpoch) throw new Error("vault_locked");814 touchAutoLock();815 return { committed: true, unlocked: true };816 } catch (error) {817 if (committed) {818 console.warn("[Peach] recovery password saved; unlock required:", error);819 if (derivedKey && epoch === vaultEpoch) {820 try { await lock(); }821 catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }822 }823 return { committed: true, unlocked: false };824 }825 if (derivedKey && epoch === vaultEpoch) await lock();826 throw error;827 } finally {828 if (oldKey) zeroKey(oldKey);829 if (newKey) zeroKey(newKey);830 if (recoveredRoot) zeroKey(recoveredRoot);831 recoveryInFlight = false;832 settle();833 }834}835836837export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {838 vaultRemovalsInFlight++;839 try {840 await lock();841 await recoverySettled;842 await creationSettled;843 return await remove();844 } finally {845 vaultRemovalsInFlight--;846 }847}848849850851852853854855856857858async function deriveRootKeyFromDerivedKey(859 derivedKeyBytes: Uint8Array,860 slotA: StoredVault,861): Promise<Uint8Array | null> {862 if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {863 return null;864 }865 try {866 const rootHex = await decrypt(867 derivedKeyBytes,868 slotA.pw_root_nonce,869 slotA.pw_root_ciphertext,870 slotA.pw_root_tag,871 "pw_root_v1",872 );873 return unhex(rootHex);874 } catch {875 return null;876 }877}878879export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {880 if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");881 882 883 const [root, local] = await Promise.all([884 encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),885 encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),886 ]);887 return { root, local };888}889890export async function sealIdentityKeyPreVault(891 password: string,892 ik: Uint8Array,893): Promise<IdentityKeyEnvelope> {894 const salt = generateSalt();895 const key = await deriveKey(password, salt);896 try {897 const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");898 return { pending, pendingSalt: hex(salt) };899 } finally {900 zeroKey(key);901 }902}903904905906907908909910911912export async function openIdentityKey(913 env: IdentityKeyEnvelope,914 password?: string,915): Promise<Uint8Array | null> {916 if (env.local && derivedKey) {917 const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");918 if (ik) return ik;919 }920 if (env.root && rootKey) {921 const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");922 if (ik) return ik;923 }924 if (!env.pending || !env.pendingSalt || password === undefined) return null;925 let key: Uint8Array;926 try {927 const salt = unhex(env.pendingSalt);928 key = await deriveKey(password, salt);929 salt.fill(0);930 } catch {931 return null;932 }933 try {934 return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");935 } finally {936 zeroKey(key);937 }938}939940941async function openSealedKey(942 key: Uint8Array,943 box: SealedBox,944 info: string,945): Promise<Uint8Array | null> {946 try {947 const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));948 if (value.length === 32) return value;949 value.fill(0);950 return null;951 } catch {952 return null;953 }954}955956957958async function wrapRootKeyForDerivedKey(959 derivedKeyBytes: Uint8Array,960 rootKeyBytes: Uint8Array,961): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {962 const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");963 return {964 pw_root_ciphertext: ciphertext,965 pw_root_nonce: nonce,966 pw_root_tag: tag,967 };968}969970971export async function getRecoveryWords(): Promise<string[]> {972 if (!rootKey) {973 throw new Error("recovery not set up");974 }975 return rootKeyToWords(rootKey);976}977978async function loadSlot(key: string): Promise<StoredVault | null> {979 const result = await chrome.storage.local.get(key);980 return (result as Record<string, StoredVault | undefined>)[key] ?? null;981}982983async function writeSlot(key: string, vault: StoredVault): Promise<void> {984 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");985 vaultWritesInFlight++;986 try {987 await chrome.storage.local.set({ [key]: vault });988 } catch (err) {989 throw mapStorageError(err);990 } finally {991 vaultWritesInFlight--;992 }993}99499599699799899910001001100210031004export async function rollbackAdoptedVault(): Promise<void> {1005 await withVaultRemoval(async () => {1006 try {1007 await chrome.storage.local.remove([1008 SLOT_A,1009 SLOT_B,1010 "peach_last_modified_at",1011 ]);1012 } catch (err) {1013 throw mapStorageError(err);1014 }1015 });1016}10171018async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1019 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1020 vaultWritesInFlight++;1021 try {1022 const raw = await chrome.storage.local.get("peach_last_modified_at");1023 const previous = Number(1024 (raw as Record<string, unknown>).peach_last_modified_at,1025 );1026 const next = Math.max(1027 Date.now(),1028 Number.isFinite(previous) ? previous + 1 : 0,1029 );1030 try {1031 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1032 await chrome.storage.local.set({1033 [SLOT_A]: slotA,1034 [SLOT_B]: slotB,1035 peach_last_modified_at: String(next),1036 });1037 } catch (err) {1038 throw mapStorageError(err);1039 }1040 } finally {1041 vaultWritesInFlight--;1042 }1043}104410451046104710481049105010511052let lastEntryTimestamp = 0;1053function monotonicEntryTimestamp(currentModifiedAt?: number): number {1054 const base = Math.max(1055 Date.now(),1056 (currentModifiedAt ?? 0) + 1,1057 lastEntryTimestamp + 1,1058 );1059 lastEntryTimestamp = base;1060 return base;1061}10621063async function stampLocalVaultMutation(): Promise<void> {1064 if (vaultCreatesInFlight) throw new Error("vault_changed");1065 const raw = await chrome.storage.local.get("peach_last_modified_at");1066 const previous = Number(1067 (raw as Record<string, unknown>).peach_last_modified_at,1068 );1069 const next = Math.max(1070 Date.now(),1071 Number.isFinite(previous) ? previous + 1 : 0,1072 );1073 if (vaultCreatesInFlight) throw new Error("vault_changed");1074 await chrome.storage.local.set({1075 peach_last_modified_at: String(next),1076 });1077}107810791080108110821083108410851086108710881089function padPlaintext(json: string, minBytes = 0): string {1090 const encoded = new TextEncoder().encode(json);1091 const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1092 1093 const target = Math.max(bucket, minBytes);1094 const padLen = target - encoded.length;1095 return json + " ".repeat(padLen);1096}109710981099110011011102110311041105110611071108const CSPRNG_CHUNK = 65_536;11091110function fillRandom(buf: Uint8Array): Uint8Array {1111 for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1112 const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1113 const chunk = new Uint8Array(end - offset);1114 crypto.getRandomValues(chunk);1115 buf.set(chunk, offset);1116 }1117 return buf;1118}11191120function generateNoiseBlob(ciphertextBytes: number): StoredVault {1121 const salt = crypto.getRandomValues(new Uint8Array(16));1122 const nonce = crypto.getRandomValues(new Uint8Array(12));1123 const cipher = fillRandom(new Uint8Array(ciphertextBytes));1124 const tag = crypto.getRandomValues(new Uint8Array(16));1125 return {1126 version: 1,1127 salt: hex(salt),1128 nonce: hex(nonce),1129 ciphertext: hex(cipher),1130 tag: hex(tag),1131 };1132}113311341135113611371138type VaultPayload = {1139 entries: VaultEntry[];1140 tombstones?: Record<string, number>;1141 duressConfigured?: boolean;1142};11431144type DecryptedPayload = {1145 entries: VaultEntry[];1146 tombstones: Map<string, number>;1147 duressConfigured: boolean;1148};11491150function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1151 const envelope: VaultPayload = {1152 entries,1153 tombstones: Object.fromEntries(tombstones),1154 duressConfigured: duress,1155 };1156 return padPlaintext(JSON.stringify(envelope), minBytes);1157}11581159function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1160 const result = new Map<string, number>();1161 if (raw && typeof raw === "object" && !Array.isArray(raw)) {1162 for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1163 if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1164 result.set(id, timestamp);1165 }1166 }1167 }1168 1169 1170 for (const entry of allEntries) {1171 if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1172 continue;1173 }1174 if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1175 result.set(entry.id, entry.deletedAt);1176 }1177 }1178 return result;1179}11801181function reconcileTombstones(): void {1182 const byId = new Map(entries.map((entry) => [entry.id, entry]));1183 for (const [id] of tombstones) {1184 if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1185 }1186 for (const entry of entries) {1187 if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1188 if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1189 tombstones.set(entry.id, entry.deletedAt);1190 }1191 }1192 }1193}11941195function decodePayload(plain: string): DecryptedPayload {1196 const parsed = JSON.parse(plain) as VaultPayload;1197 if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1198 throw new Error("invalid vault payload");1199 }1200 const normalized = parsed.entries.map(normalizeEntry);1201 return {1202 entries: normalized,1203 tombstones: decodeTombstones(parsed.tombstones, normalized),1204 duressConfigured: parsed.duressConfigured === true,1205 };1206}120712081209function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1210 let merged = false;1211 const transferable = new Set(["id", "type", "title", "username", "url", "passkey", "createdAt", "modifiedAt", "totp", "totpAlgorithm", "totpDigits", "totpPeriod"]);1212 for (const source of entries.filter((entry) => !entry.deletedAt && entry.passkey)) {1213 const passkey = source.passkey!;1214 if (source.type !== "login" && source.type !== "passkey") continue;1215 if (!passkey.userName || (source.username && source.username !== passkey.userName)) continue;1216 if (Object.entries(source).some(([key, value]) => !transferable.has(key) && value !== undefined && value !== "")) continue;1217 const targets = entries.filter((entry) => {1218 if (entry.deletedAt || entry.passkey || entry.type !== "login" || entry.username !== passkey.userName) return false;1219 return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {1220 if (!url) return false;1221 try {1222 return new URL(url.includes("://") ? url : `https://${url}`).hostname === passkey.rpId;1223 } catch {1224 return false;1225 }1226 });1227 });1228 if (targets.length !== 1) continue;1229 const target = targets[0]!;1230 if (source.totp && target.totp && (source.totp !== target.totp || source.totpAlgorithm !== target.totpAlgorithm || source.totpDigits !== target.totpDigits || source.totpPeriod !== target.totpPeriod)) continue;1231 target.passkey = passkey;1232 if (source.totp && !target.totp) {1233 target.totp = source.totp;1234 target.totpAlgorithm = source.totpAlgorithm;1235 target.totpDigits = source.totpDigits;1236 target.totpPeriod = source.totpPeriod;1237 }1238 const stamp = monotonicEntryTimestamp(Math.max(source.modifiedAt, target.modifiedAt));1239 target.modifiedAt = stamp;1240 source.modifiedAt = stamp;1241 source.deletedAt = stamp;1242 merged = true;1243 }1244 return { merged };1245}12461247124812491250125112521253function hasValidVaultSchema(v: unknown): v is StoredVault {1254 if (typeof v !== "object" || v === null) return false;1255 const r = v as Record<string, unknown>;1256 return (1257 r.version === 1 &&1258 typeof r.salt === "string" &&1259 typeof r.nonce === "string" &&1260 typeof r.ciphertext === "string" &&1261 typeof r.tag === "string"1262 );1263}1264const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;12651266function hasValidHistorySlot(value: unknown): value is StoredVault {1267 if (!hasValidVaultSchema(value)) return false;1268 return /^[0-9a-f]{32}$/i.test(value.salt) &&1269 /^[0-9a-f]{24}$/i.test(value.nonce) &&1270 /^[0-9a-f]+$/i.test(value.ciphertext) &&1271 value.ciphertext.length % 2 === 0 &&1272 value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1273 /^[0-9a-f]{32}$/i.test(value.tag);1274}12751276function parseHistorySlot(value: string): StoredVault | null {1277 try {1278 const parsed: unknown = JSON.parse(value);1279 return hasValidHistorySlot(parsed) ? parsed : null;1280 } catch {1281 return null;1282 }1283}12841285function isHistoryRecord(value: unknown): value is VaultSnapshot {1286 if (typeof value !== "object" || value === null) return false;1287 const record = value as Record<string, unknown>;1288 return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1289 typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1290 typeof record.reason === "string" &&1291 typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1292 typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1293 (record.entryCount === null || typeof record.entryCount === "number");1294}12951296function sanitizeHistory(value: unknown): VaultSnapshot[] {1297 if (typeof value !== "object" || value === null) return [];1298 if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1299 return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1300}13011302export type TryDecryptResult =1303 | { status: "ok"; payload: DecryptedPayload }1304 | { status: "wrong_key" }1305 | { status: "corrupted"; reason: string };1306130713081309131013111312export async function tryDecryptSlot(1313 vault: StoredVault,1314 key: Uint8Array,1315 aadTag?: string,1316): Promise<DecryptedPayload | null> {1317 const res = await tryDecryptSlotResult(vault, key, aadTag);1318 return res.status === "ok" ? res.payload : null;1319}13201321export async function tryDecryptSlotResult(1322 vault: StoredVault,1323 key: Uint8Array,1324 aadTag?: string,1325): Promise<TryDecryptResult> {1326 if (!hasValidVaultSchema(vault)) {1327 return { status: "corrupted", reason: "invalid_slot_schema" };1328 }1329 let plain: string;1330 try {1331 plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1332 } catch {1333 return { status: "wrong_key" };1334 }1335 try {1336 const parsed = JSON.parse(plain) as unknown;1337 if (typeof parsed !== "object" || parsed === null) {1338 return { status: "corrupted", reason: "invalid_payload_shape" };1339 }1340 if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1341 return { status: "corrupted", reason: "invalid_payload_shape" };1342 }1343 return { status: "ok", payload: decodePayload(plain) };1344 } catch {1345 return { status: "corrupted", reason: "invalid_payload_json" };1346 }1347}134813491350135113521353function buildDomainIndexSync(all: VaultEntry[]): void {1354 domainIndex = new Map();13551356 for (const entry of all) {1357 if (entry.deletedAt) continue;1358 if (entry.type === "note" || entry.type === "card") continue;13591360 1361 1362 1363 1364 const domains = new Set<string>();1365 const primary = extractDomain(entry.url ?? "");1366 if (primary) domains.add(primary);1367 for (const extra of entry.additionalUrls ?? []) {1368 const d = extractDomain(extra);1369 if (d) domains.add(d);1370 }1371 if (domains.size === 0) continue;13721373 for (const domain of domains) {1374 const bucket = domainIndex.get(domain) ?? [];1375 bucket.push(entry);1376 domainIndex.set(domain, bucket);1377 }1378 }1379}13801381export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1382 if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1383 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1384 vaultCreatesInFlight++;1385 let settle!: () => void;1386 creationSettled = new Promise<void>((resolve) => { settle = resolve; });1387 let nextKey: Uint8Array | null = null;1388 let nextRoot: Uint8Array | null = null;1389 let committed = false;1390 let publishedEpoch: number | null = null;1391 const epoch = vaultEpoch;1392 const check = () => {1393 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1394 };1395 try {1396 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1397 check();1398 const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1399 if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1400 const salt = generateSalt();1401 nextKey = await deriveKey(password, salt);1402 check();1403 const recovery = await generateAndWrapRootKey();1404 nextRoot = unhex(recovery.rawRootKey);1405 check();1406 const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1407 const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1408 const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1409 check();1410 const slotA: StoredVault = {1411 ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1412 recovery_vault_key: recoveryVaultKey,1413 recovery_salt: recovery.recoverySalt,1414 recovery_wrapped_root_key: recovery.wrappedRootKey,1415 recovery_nonce: recovery.wrappedNonce,1416 recovery_tag: recovery.wrappedTag,1417 };1418 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1419 check();1420 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1421 const previous = Number(raw.peach_last_modified_at);1422 const update: Record<string, unknown> = {1423 [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1424 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1425 };1426 if (occupied) {1427 const history = raw[HISTORY_KEY] as VaultHistory | undefined;1428 const snapshot: VaultSnapshot = {1429 id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1430 vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1431 };1432 update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1433 }1434 try { await chrome.storage.local.set(update); }1435 catch (error) { throw mapStorageError(error); }1436 committed = true;1437 if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1438 const previousKey = derivedKey;1439 const previousRoot = rootKey;1440 publishedEpoch = ++vaultEpoch;1441 derivedKey = nextKey;1442 rootKey = nextRoot;1443 nextKey = null;1444 nextRoot = null;1445 entries = [];1446 tombstones = new Map();1447 vaultMode = "real";1448 duressConfigured = false;1449 buildDomainIndexSync(entries);1450 if (previousKey) zeroKey(previousKey);1451 if (previousRoot) zeroKey(previousRoot);1452 await clearSessionKey();1453 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1454 await identityHooks?.onVaultCreated(password).catch((error) => {1455 console.warn("[Peach] local identity promotion failed:", error);1456 });1457 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1458 touchAutoLock();1459 return { committed: true, unlocked: true };1460 } catch (error) {1461 if (!committed) throw error;1462 console.warn("[Peach] vault saved; unlock required:", error);1463 if (publishedEpoch === vaultEpoch) {1464 await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));1465 }1466 return { committed: true, unlocked: false };1467 } finally {1468 if (nextKey) zeroKey(nextKey);1469 if (nextRoot) zeroKey(nextRoot);1470 vaultCreatesInFlight--;1471 settle();1472 }1473}1474147514761477147814791480export async function createVaultFromRootKey(1481 password: string,1482 rootKeyHex: string,1483): Promise<{ vaultId: string }> {1484 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1485 if (typeof password !== "string" || password.length === 0) {1486 throw new Error("ADOPT_INVALID_PASSWORD");1487 }1488 if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1489 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1490 }14911492 if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1493 const rootKeyBytes = unhex(rootKeyHex);1494 if (rootKeyBytes.length !== 32) {1495 rootKeyBytes.fill(0);1496 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1497 }14981499 vaultCreatesInFlight++;1500 let settle!: () => void;1501 creationSettled = new Promise<void>((resolve) => { settle = resolve; });1502 const epoch = vaultEpoch;1503 let nextDerivedKey: Uint8Array | null = null;1504 let sessionRootKey: Uint8Array | null = null;1505 let committed = false;1506 try {1507 if (await hasVault()) {1508 throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1509 }15101511 const nextEntries: VaultEntry[] = [];1512 const nextDuressConfigured = false;1513 const vaultId = await computeVaultId(rootKeyBytes);1514 const salt = generateSalt();1515 nextDerivedKey = await deriveKey(password, salt);1516 const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);15171518 sessionRootKey = new Uint8Array(rootKeyBytes);1519 const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1520 const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1521 const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1522 const slotA: StoredVault = {1523 recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),1524 version: 1,1525 salt: hex(salt),1526 nonce,1527 ciphertext,1528 tag,1529 recovery_salt: recovery.recoverySalt,1530 recovery_wrapped_root_key: recovery.wrappedRootKey,1531 recovery_nonce: recovery.wrappedNonce,1532 recovery_tag: recovery.wrappedTag,1533 ...pwRoot,1534 };1535 const slotB = generateNoiseBlob(ciphertext.length / 2);1536 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1537 await commitCreatedVaultSlots(slotA, slotB);1538 committed = true;1539 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1540 vaultEpoch++;15411542 const previousDerivedKey = derivedKey;1543 const previousRootKey = rootKey;1544 derivedKey = nextDerivedKey;1545 rootKey = sessionRootKey;1546 nextDerivedKey = null;1547 sessionRootKey = null;1548 entries = nextEntries;1549 tombstones = new Map();1550 vaultMode = "real";1551 duressConfigured = nextDuressConfigured;1552 buildDomainIndexSync(entries);1553 if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1554 if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1555 touchAutoLock();15561557 1558 1559 await identityHooks?.onVaultCreated(password).catch((error) => {1560 console.warn("[Peach] local identity promotion failed:", error);1561 });15621563 return { vaultId };1564 } catch (error) {1565 if (committed) {1566 1567 try { await lock(); }1568 finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, "peach_last_modified_at"]); }1569 }1570 throw error;1571 } finally {1572 vaultCreatesInFlight--;1573 settle();1574 rootKeyBytes.fill(0);1575 if (nextDerivedKey) zeroKey(nextDerivedKey);1576 if (sessionRootKey) sessionRootKey.fill(0);1577 }1578}15791580export async function hasVault(): Promise<boolean> {1581 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);1582 return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1583}1584158515861587158815891590export async function isDuressEnabled(): Promise<boolean> {1591 return vaultMode === "real" && duressConfigured;1592}15931594export async function setupDuress(duressPassword: string): Promise<void> {1595 if (vaultCreatesInFlight) throw new Error("vault_changed");1596 vaultWritesInFlight++;1597 try {1598 if (!derivedKey || vaultMode !== "real") {1599 throw new Error("vault must be unlocked in real mode");1600 }1601 1602 1603 1604 const slotA = await loadSlot(SLOT_A);1605 if (!slotA) throw new Error("missing slot A");16061607 const decoySalt = generateSalt();1608 const decoyKey = await deriveKey(duressPassword, decoySalt);1609 try {1610 1611 1612 1613 1614 const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1615 const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1616 await writeSlot(SLOT_B, {1617 version: 1,1618 salt: hex(decoySalt),1619 nonce,1620 ciphertext,1621 tag,1622 });1623 } finally {1624 zeroKey(decoyKey);1625 }16261627 1628 1629 duressConfigured = true;1630 await persistSlotA();1631 } finally { vaultWritesInFlight--; }1632}16331634export async function disableDuress(): Promise<void> {1635 if (vaultCreatesInFlight) throw new Error("vault_changed");1636 vaultWritesInFlight++;1637 try {1638 if (!derivedKey || vaultMode !== "real") {1639 throw new Error("vault must be unlocked in real mode");1640 }1641 1642 1643 1644 const slotA = await loadSlot(SLOT_A);1645 if (slotA) {1646 await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1647 }16481649 duressConfigured = false;1650 await persistSlotA();1651 } finally { vaultWritesInFlight--; }1652}16531654165516561657165816591660export async function verifyMainPassword(password: string): Promise<boolean> {1661 const slotA = await loadSlot(SLOT_A);1662 if (!slotA) return false;1663 const key = await deriveKey(password, unhex(slotA.salt));1664 try {1665 return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1666 } finally {1667 zeroKey(key);1668 }1669}16701671export async function unlock(password: string): Promise<boolean> {1672 return attemptUnlockWithDerive(password, deriveKey);1673}16741675async function attemptUnlockWithDerive(1676 password: string,1677 derive: typeof deriveKey,1678): Promise<boolean> {1679 vaultUnlocksInFlight++;1680 try {1681 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1682 const epoch = vaultEpoch;1683 const stale = () => epoch !== vaultEpoch;1684 1685 1686 1687 1688 1689 1690 const [slotA, slotB] = await Promise.all([1691 loadSlot(SLOT_A),1692 loadSlot(SLOT_B),1693 ]);16941695 1696 const [keyA, keyB] = await Promise.all([1697 slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1698 slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1699 ]);17001701 1702 1703 1704 const [resultA, resultB] = await Promise.all([1705 keyA && slotA1706 ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1707 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1708 keyB && slotB1709 ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1710 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1711 ]);1712 const payloadA = resultA.status === "ok" ? resultA.payload : null;1713 const payloadB = resultB.status === "ok" ? resultB.payload : null;17141715 if (stale()) {1716 if (keyA) zeroKey(keyA);1717 if (keyB) zeroKey(keyB);1718 return false;1719 }17201721 if (payloadA && keyA) {1722 if (stale()) {1723 zeroKey(keyA);1724 if (keyB) zeroKey(keyB);1725 return false;1726 }1727 derivedKey = keyA;1728 vaultMode = "real";1729 entries = payloadA.entries;1730 tombstones = payloadA.tombstones;1731 duressConfigured = payloadA.duressConfigured;1732 buildDomainIndexSync(entries);1733 await loadSettings();1734 if (stale()) {1735 await lock();1736 return false;1737 }1738 touchAutoLock();1739 if (keyB) zeroKey(keyB);17401741 1742 1743 rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;1744 if (!rootKey) {1745 await lock();1746 return false;1747 }17481749 1750 if (slotA) {1751 const escrowed = slotA.recovery_vault_key1752 ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;1753 const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);1754 if (escrowed) zeroKey(escrowed);1755 if (stale()) { await lock(); return false; }1756 if (!matches) {1757 try {1758 const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");1759 if (stale()) { await lock(); return false; }1760 await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });1761 if (stale()) { await lock(); return false; }1762 } catch (error) {1763 await lock();1764 throw error;1765 }1766 }1767 }17681769 1770 1771 await reconcilePairSecrets(rootKey);1772 if (stale()) {1773 await lock();1774 return false;1775 }1776 await lockedSyncUnlockHook?.().catch((error) => {1777 console.warn("[Peach sync] locked inbox drain failed:", error);1778 });1779 if (stale()) {1780 await lock();1781 return false;1782 }1783 await resetPinFailedAttempts();1784 if (stale()) {1785 await lock();1786 return false;1787 }1788 await saveSessionKey(keyA, "real", epoch);1789 if (stale()) return false;1790 return true;1791 }17921793 if (payloadB && keyB) {1794 if (stale()) {1795 zeroKey(keyB);1796 if (keyA) zeroKey(keyA);1797 return false;1798 }1799 derivedKey = keyB;1800 vaultMode = "decoy";1801 decoySyncTeardownHook?.();1802 1803 1804 1805 if (rootKey) {1806 rootKey.fill(0);1807 rootKey = null;1808 }1809 entries = payloadB.entries;1810 tombstones = payloadB.tombstones;1811 duressConfigured = false;1812 buildDomainIndexSync(entries);1813 await loadSettings();1814 touchAutoLock();1815 if (keyA) zeroKey(keyA);1816 1817 await dropSessionCache();1818 1819 await notifyIdentitySessionEnded();1820 if (stale()) {1821 await lock();1822 return false;1823 }1824 await saveSessionKey(keyB, "decoy", epoch);1825 if (stale()) return false;1826 return true;1827 }18281829 if (keyA) zeroKey(keyA);1830 if (keyB) zeroKey(keyB);1831 1832 1833 if (resultA.status === "corrupted") {1834 lastUnlockFailureReason = resultA.reason;1835 } else if (resultB.status === "corrupted") {1836 lastUnlockFailureReason = resultB.reason;1837 }1838 return false;1839 } finally { vaultUnlocksInFlight--; }1840}18411842184318441845184618471848const SESSION_KEY_STORAGE = "peach_session_dk";1849185018511852let sessionKeyMutation = Promise.resolve();18531854function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {1855 const task = sessionKeyMutation.then(mutation, mutation);1856 sessionKeyMutation = task.catch(() => undefined);1857 return task;1858}185918601861186218631864let sessionEscrowAvailable = true;18651866186718681869187018711872export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {1873 setSessionAllowed(sessionEscrow);1874 if (sessionEscrow) return;1875 sessionEscrowAvailable = false;1876 await clearSessionKey();1877}18781879async function saveSessionKey(1880 key: Uint8Array,1881 mode: "real" | "decoy",1882 expectedEpoch = vaultEpoch,1883): Promise<void> {1884 const session = chrome.storage.session;1885 if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1886 const stored = { keyHex: hex(key), mode };1887 await mutateSessionKey(async () => {1888 if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1889 await session.set({ [SESSION_KEY_STORAGE]: stored });1890 });1891}18921893async function clearSessionKey(): Promise<void> {1894 const session = chrome.storage.session;1895 if (!session) return;1896 await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));1897}18981899190019011902190319041905let vaultEpoch = 0;1906190719081909let restoreInFlight: Promise<boolean> | null = null;191019111912191319141915191619171918export async function restoreFromSession(): Promise<boolean> {1919 vaultUnlocksInFlight++;1920 try {1921 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1922 if (derivedKey !== null) return true;1923 if (restoreInFlight) return restoreInFlight;1924 const task = restoreFromSessionInner();1925 restoreInFlight = task;1926 try {1927 return await task;1928 } finally {1929 restoreInFlight = null;1930 }1931 } finally { vaultUnlocksInFlight--; }1932}19331934async function restoreFromSessionInner(): Promise<boolean> {1935 const epoch = vaultEpoch;1936 const stale = () => epoch !== vaultEpoch;1937 if (derivedKey !== null) return true;1938 if (!sessionEscrowAvailable) return false;1939 if (!chrome.storage.session) return false;1940 const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1941 if (stale()) return false;1942 const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1943 if (!entry?.keyHex) return false;19441945 const key = unhex(entry.keyHex);1946 const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1947 const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1948 const slot = await loadSlot(slotKey);1949 if (stale()) { zeroKey(key); return false; }1950 if (!slot) { await clearSessionKey(); return false; }19511952 const result = await tryDecryptSlotResult(slot, key, aadTag);1953 if (stale()) { zeroKey(key); return false; }1954 if (result.status !== "ok") { await clearSessionKey(); return false; }19551956 1957 1958 const payload = result.payload;1959 await loadSettings();1960 if (stale()) { zeroKey(key); return false; }19611962 1963 1964 let freshRoot: Uint8Array | null = null;1965 if (entry.mode === "real") {1966 freshRoot = await deriveRootKeyFromDerivedKey(key, slot);1967 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1968 if (!freshRoot) {1969 await lock();1970 return false;1971 }1972 }19731974 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1975 if (freshRoot) {1976 1977 await reconcilePairSecrets(freshRoot);1978 if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }1979 } else {1980 1981 await dropSessionCache();1982 1983 await notifyIdentitySessionEnded();1984 if (stale()) { zeroKey(key); return false; }1985 }1986 derivedKey = key;1987 vaultMode = entry.mode;1988 if (entry.mode === "decoy") decoySyncTeardownHook?.();1989 entries = payload.entries;1990 tombstones = payload.tombstones;1991 duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;1992 if (freshRoot) rootKey = freshRoot;1993 buildDomainIndexSync(entries);1994 touchAutoLock();19951996 await lockedSyncUnlockHook?.().catch((error) => {1997 console.warn("[Peach sync] locked inbox drain failed:", error);1998 });1999 if (stale()) return false;20002001 return true;2002}20032004export async function lock(): Promise<void> {2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 vaultEpoch++;2015 if (derivedKey) {2016 zeroKey(derivedKey);2017 derivedKey = null;2018 }2019 if (rootKey) {2020 rootKey.fill(0);2021 rootKey = null;2022 }20232024 entries = [];2025 tombstones = new Map();2026 domainIndex = new Map();2027 vaultMode = "real";2028 duressConfigured = false;2029 clearAutoLock();2030 await clearSessionKey();2031 2032 2033 await notifyIdentitySessionEnded();2034}20352036export function isUnlocked(): boolean {2037 return derivedKey !== null;2038}20392040export function isDecoyMode(): boolean {2041 return derivedKey !== null && vaultMode === "decoy";2042}20432044204520462047export async function unlockWithKey(2048 masterKeyHex: string,2049): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2050 vaultUnlocksInFlight++;2051 try {2052 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2053 const epoch = vaultEpoch;2054 const stale = () => epoch !== vaultEpoch;2055 let masterKeyBytes: Uint8Array | null = null;2056 try {2057 masterKeyBytes = unhex(masterKeyHex);2058 const stored = await loadSlot(SLOT_A);2059 if (!stored) return { ok: false, error: "invalid_key" };2060 const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2061 if (!payload || stale()) {2062 zeroKey(masterKeyBytes);2063 return { ok: false, error: "invalid_key" };2064 }20652066 derivedKey = masterKeyBytes;2067 vaultMode = "real";2068 entries = payload.entries;2069 tombstones = payload.tombstones;2070 duressConfigured = payload.duressConfigured;2071 buildDomainIndexSync(entries);2072 await loadSettings();2073 touchAutoLock();20742075 rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2076 if (!rootKey) {2077 await lock();2078 return { ok: false, error: "invalid_key" };2079 }2080 await reconcilePairSecrets(rootKey);2081 if (stale()) {2082 await lock();2083 return { ok: false, error: "invalid_key" };2084 }2085 await saveSessionKey(masterKeyBytes, "real", epoch);2086 if (stale()) return { ok: false, error: "invalid_key" };2087 return { ok: true, entries };2088 } catch {2089 if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2090 return { ok: false, error: "invalid_key" };2091 }2092 } finally { vaultUnlocksInFlight--; }2093}209420952096209720982099210021012102export async function exportDuressSlotForAdoption(): Promise<string | null> {2103 if (!(await isDuressEnabled())) return null;2104 const slotB = await loadSlot(SLOT_B);2105 if (!slotB) return null;2106 return JSON.stringify(slotB);2107}21082109211021112112211321142115export async function installAdoptedDuressSlot(json: string): Promise<void> {2116 if (vaultCreatesInFlight) throw new Error("vault_changed");2117 vaultWritesInFlight++;2118 try {2119 let parsed: StoredVault;2120 try {2121 const raw = JSON.parse(json) as unknown;2122 if (!hasValidVaultSchema(raw)) {2123 throw new Error("invalid_duress_slot_shape");2124 }2125 parsed = raw;2126 } catch (err) {2127 if (err instanceof SyntaxError) {2128 throw new Error("invalid_duress_slot_shape");2129 }2130 throw err;2131 }2132 await writeSlot(SLOT_B, parsed);2133 } finally { vaultWritesInFlight--; }2134}21352136213721382139214021412142214321442145214621472148214921502151215221532154export async function unlockFromCodex(params: {2155 slotA: string; 2156 slotB: string | null; 2157 timestamp: number;2158 masterPassphrase: string;2159}): Promise<2160 | { ok: true; entryCount: number }2161 | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2162> {2163 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2164 vaultReplacementInFlight = true;2165 try {2166 let parsedSlotA: StoredVault;2167 let parsedSlotB: StoredVault | null = null;2168 try {2169 const rawA = JSON.parse(params.slotA) as unknown;2170 if (!hasValidVaultSchema(rawA)) {2171 return { ok: false, reason: "invalid_slot_format" };2172 }2173 parsedSlotA = rawA;2174 if (params.slotB !== null) {2175 const rawB = JSON.parse(params.slotB) as unknown;2176 if (!hasValidVaultSchema(rawB)) {2177 return { ok: false, reason: "invalid_slot_format" };2178 }2179 parsedSlotB = rawB;2180 }2181 } catch {2182 return { ok: false, reason: "invalid_slot_format" };2183 }21842185 2186 2187 2188 const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2189 const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2190 if (!trialPayload) {2191 zeroKey(trialKey);2192 return { ok: false, reason: "wrong_passphrase" };2193 }2194 const hasEscrow =2195 !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2196 if (!hasEscrow) {2197 zeroKey(trialKey);2198 return { ok: false, reason: "missing_root_escrow" };2199 }2200 const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2201 if (!stagedRootKey) {2202 zeroKey(trialKey);2203 return { ok: false, reason: "wrong_passphrase" };2204 }2205 zeroKey(stagedRootKey);2206 zeroKey(trialKey);22072208 2209 const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);22102211 2212 22132214 2215 2216 await takeVaultSnapshot("restore");2217 const previousSlotA = await loadSlot(SLOT_A);2218 const previousSlotB = await loadSlot(SLOT_B);2219 let slotACommitted = false;2220 let slotBCommitted = false;2221 try {2222 await writeSlot(SLOT_A, parsedSlotA);2223 slotACommitted = true;2224 await writeSlot(SLOT_B, stagedSlotB);2225 slotBCommitted = true;2226 await chrome.storage.local.set({2227 peach_last_modified_at: String(params.timestamp),2228 });2229 } catch (err) {2230 if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2231 if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2232 throw err;2233 }22342235 2236 2237 const ok = await unlock(params.masterPassphrase);2238 if (!ok) {2239 2240 return { ok: false, reason: "wrong_passphrase" };2241 }2242 return { ok: true, entryCount: getEntries().length };2243 } finally {2244 vaultReplacementInFlight = false;2245 }2246}22472248224922502251export function getDerivedKeyHex(): string {2252 if (!derivedKey) throw new Error("vault_not_unlocked");2253 return hex(derivedKey);2254}22552256225722582259226022612262226322642265226622672268226922702271export function getRootKeyHex(): string | null {2272 return rootKey ? hex(rootKey) : null;2273}22742275export function getEntries(): VaultEntry[] {2276 if (!derivedKey) throw new Error("vault_locked");2277 return entries.filter((entry) => !entry.deletedAt);2278}22792280const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;22812282export function getIdentities(): SavedIdentity[] {2283 if (!derivedKey) throw new Error("vault_locked");2284 const active = entries.filter((e) => !e.deletedAt && e.type === "login");22852286 const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2287 const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();22882289 for (const entry of active) {2290 const domain = extractDomain(entry.url ?? "") ?? "";2291 const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;22922293 function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2294 const existing = map.get(v);2295 if (!existing || modifiedAt > existing.lastUsed) {2296 map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2297 } else {2298 map.set(v, { ...existing, count: existing.count + 1 });2299 }2300 }23012302 const uVal = entry.username?.trim();2303 if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);23042305 2306 2307 const eVal = entry.email?.trim();2308 if (eVal) tally(emailMap, eVal);2309 }23102311 const toIdentity = (type: "email" | "username") =>2312 ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2313 value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2314 });23152316 return [2317 ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2318 ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2319 ];2320}23212322export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2323 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");23242325 const now = Date.now();2326 const added: VaultEntry[] = [];2327 for (const draft of drafts) {2328 try {2329 const sanitized = sanitizeEntryDraft(draft);2330 const nextEntry: VaultEntry = {2331 ...sanitized,2332 id: crypto.randomUUID(),2333 createdAt: now,2334 modifiedAt: monotonicEntryTimestamp(),2335 };2336 entries.push(nextEntry);2337 added.push(nextEntry);2338 } catch {2339 2340 }2341 }23422343 if (added.length > 0) {2344 await persistEntries();2345 }23462347 return added;2348}234923502351235223532354235523562357export async function restoreEntries(2358 incoming: VaultEntry[],2359 mode: "replace" | "merge"2360): Promise<{ added: number; updated: number; skipped: number }> {2361 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");23622363 2364 2365 2366 if (mode === "replace" && incoming.length === 0) {2367 throw new Error("refuse to replace with empty entry set");2368 }23692370 let added = 0;2371 let updated = 0;2372 let skipped = 0;23732374 if (mode === "replace") {2375 entries = [];2376 for (const entry of incoming) {2377 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2378 if (!normalized) {2379 skipped += 1;2380 continue;2381 }2382 entries.push(normalized);2383 if (normalized.deletedAt) {2384 tombstones.set(2385 normalized.id,2386 Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2387 );2388 } else {2389 tombstones.delete(normalized.id);2390 }2391 added += 1;2392 }2393 } else {2394 const byId = new Map<string, VaultEntry>();2395 for (const e of entries) byId.set(e.id, e);23962397 for (const entry of incoming) {2398 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2399 if (!normalized) {2400 skipped += 1;2401 continue;2402 }2403 const existing = byId.get(normalized.id);2404 if (!existing) {2405 entries.push(normalized);2406 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2407 else tombstones.delete(normalized.id);2408 added += 1;2409 } else if (normalized.modifiedAt > existing.modifiedAt) {2410 const idx = entries.findIndex((e) => e.id === existing.id);2411 if (idx !== -1) {2412 entries[idx] = normalized;2413 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2414 else tombstones.delete(normalized.id);2415 updated += 1;2416 }2417 } else {2418 skipped += 1;2419 }2420 }2421 }24222423 await persistEntries("import");2424 return { added, updated, skipped };2425}242624272428242924302431243224332434243524362437243824392440244124422443const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;24442445function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {2446 if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;2447 return { ...entry, id: crypto.randomUUID() };2448}244924502451245224532454245524562457function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {2458 if (!entry || typeof entry !== "object") return null;2459 const title = typeof entry.title === "string" ? entry.title.trim() : "";2460 if (!title) return null;2461 const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();2462 const now = Date.now();2463 const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;2464 const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;24652466 2467 2468 const normalized = normalizeEntry({2469 ...entry,2470 id,2471 title,2472 type: entry.type ?? "login",2473 createdAt,2474 modifiedAt,2475 });24762477 if (normalized.passkey) {2478 normalized.passkey = sanitizePasskey(normalized.passkey);2479 }2480 if (normalized.canary) {2481 normalized.canary = sanitizeCanary(normalized.canary);2482 }2483 2484 normalized.tags = sanitizeTags(normalized.tags);24852486 2487 2488 if (2489 normalized.type === "login" &&2490 !normalized.passkey &&2491 typeof normalized.password !== "string"2492 ) {2493 return null;2494 }2495 if (entry.passkey && !normalized.passkey) {2496 2497 2498 return null;2499 }25002501 return normalized;2502}2503250425052506250725082509function sanitizePasskey(pk: unknown): PasskeyData | undefined {2510 if (!pk || typeof pk !== "object") return undefined;2511 const r = pk as Record<string, unknown>;2512 if (2513 typeof r.rpId !== "string" || !r.rpId ||2514 typeof r.credentialId !== "string" || !r.credentialId ||2515 typeof r.publicKeyCose !== "string" ||2516 typeof r.userHandle !== "string" ||2517 typeof r.userName !== "string"2518 ) {2519 return undefined;2520 }2521 return {2522 rpId: r.rpId,2523 rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2524 credentialId: r.credentialId,2525 publicKeyCose: r.publicKeyCose,2526 privateKeyJwk:2527 r.privateKeyJwk && typeof r.privateKeyJwk === "object"2528 ? (r.privateKeyJwk as JsonWebKey)2529 : undefined,2530 userHandle: r.userHandle,2531 userName: r.userName,2532 userDisplayName:2533 typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2534 algorithm: r.algorithm === -8 ? -8 : -7,2535 signCount: typeof r.signCount === "number" ? r.signCount : 0,2536 aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2537 backupEligible: r.backupEligible === true,2538 backupState: r.backupState === true,2539 lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2540 browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2541 transports: Array.isArray(r.transports)2542 ? r.transports.filter((t): t is string => typeof t === "string")2543 : undefined,2544 createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2545 };2546}25472548254925502551255225532554255525562557function sanitizeCanary(c: unknown): Canary | undefined {2558 if (!c || typeof c !== "object") return undefined;2559 const r = c as Record<string, unknown>;2560 if (typeof r.webhookUrl !== "string") return undefined;2561 let url: URL;2562 try {2563 url = new URL(r.webhookUrl);2564 } catch {2565 return undefined;2566 }2567 if (url.protocol !== "https:") return undefined;2568 return {2569 webhookUrl: url.toString(),2570 label: typeof r.label === "string" ? r.label : undefined,2571 lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2572 pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2573 };2574}25752576257725782579258025812582function sanitizeTags(tags: unknown): string[] | undefined {2583 if (!Array.isArray(tags)) return undefined;2584 const out: string[] = [];2585 for (const t of tags) {2586 if (typeof t !== "string") continue;2587 const trimmed = t.trim();2588 if (!trimmed) continue;2589 out.push(trimmed.slice(0, 256));2590 if (out.length >= 255) break;2591 }2592 return out.length > 0 ? out : undefined;2593}259425952596259725982599export async function clearVaultEntries(2600 confirmation: "REPLACE_ALL"2601): Promise<void> {2602 if (confirmation !== "REPLACE_ALL") {2603 throw new Error("clearVaultEntries requires explicit confirmation");2604 }2605 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2606 for (const entry of entries) {2607 if (!entry.deletedAt) {2608 const stamp = monotonicEntryTimestamp(Math.max(2609 entry.modifiedAt,2610 tombstones.get(entry.id) ?? 0,2611 ));2612 entry.deletedAt = stamp;2613 entry.modifiedAt = stamp;2614 tombstones.set(entry.id, stamp);2615 }2616 }2617 await persistEntries();2618}26192620export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2621 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");26222623 const sanitized = sanitizeEntryDraft(entry);2624 const now = Date.now();2625 const stamp = monotonicEntryTimestamp();2626 const nextEntry: VaultEntry = {2627 ...sanitized,2628 id: crypto.randomUUID(),2629 createdAt: now,2630 modifiedAt: stamp,2631 2632 2633 passwordChangedAt: sanitized.password ? stamp : undefined,2634 };26352636 2637 2638 2639 const rollback = entries;2640 entries = [...entries, nextEntry];2641 try {2642 await persistEntries();2643 } catch (err) {2644 entries = rollback;2645 throw err;2646 }26472648 2649 if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2650 const breachEpoch = vaultEpoch;2651 checkBreach(nextEntry.password).then(async (count) => {2652 if (count > 0 && breachEpoch === vaultEpoch && !vaultCreatesInFlight) {2653 const idx = entries.findIndex((e) => e.id === nextEntry.id);2654 if (idx !== -1) {2655 entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2656 await persistEntries();2657 }2658 }2659 });2660 }26612662 fireSyncTrigger("vault_change");26632664 return nextEntry;2665}266626672668export async function consolidatePasskeyEntries(): Promise<void> {2669 if (!derivedKey || vaultCreatesInFlight) return;2670 const epoch = vaultEpoch;2671 const rollback = entries;2672 const next = entries.map((entry) => ({ ...entry }));2673 if (!mergePasskeyOnlyIntoLogins(next).merged) return;2674 const unchanged = next.map((entry) => ({ entry, modifiedAt: entry.modifiedAt }));2675 entries = next;2676 try {2677 await persistEntries();2678 } catch (err) {2679 2680 if (epoch === vaultEpoch && entries === next && entries.length === unchanged.length &&2681 unchanged.every(({ entry, modifiedAt }, index) => entries[index] === entry && entry.modifiedAt === modifiedAt)) {2682 entries = rollback;2683 buildDomainIndexSync(entries);2684 }2685 throw err;2686 }2687}26882689export async function updateEntry(2690 id: string,2691 patch: Partial<VaultEntry>2692): Promise<void> {2693 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");26942695 const idx = entries.findIndex((entry) => entry.id === id);2696 if (idx === -1 || entries[idx].deletedAt) {2697 throw new Error("entry_not_found");2698 }26992700 const current = entries[idx];2701 const sanitizedPatch = sanitizeEntryPatch(patch);2702 2703 2704 2705 const passwordChanged =2706 "password" in patch &&2707 typeof sanitizedPatch.password === "string" &&2708 sanitizedPatch.password !== current.password;2709 const stamp = monotonicEntryTimestamp(current.modifiedAt);2710 2711 2712 2713 2714 2715 2716 2717 const priorPassword = current.password;2718 const shouldCapture =2719 passwordChanged &&2720 typeof priorPassword === "string" &&2721 priorPassword.length > 0 &&2722 current.passwordHistory?.[0]?.password !== priorPassword;2723 const nextHistory = shouldCapture2724 ? [2725 { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2726 ...(current.passwordHistory ?? []),2727 ].slice(0, PASSWORD_HISTORY_MAX)2728 : current.passwordHistory;2729 entries[idx] = {2730 ...current,2731 ...sanitizedPatch,2732 modifiedAt: stamp,2733 ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2734 };2735273627372738 2739 if (entries[idx].type === "card" && !entries[idx].cardNumber) {2740 entries[idx] = current;2741 throw new Error("card number is required for card entries");2742 }27432744 2745 2746 2747 2748 try {2749 await persistEntries();2750 } catch (err) {2751 entries[idx] = current;2752 throw err;2753 }27542755 2756 2757 if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2758 entries[idx] = { ...entries[idx], breach: undefined };2759 await persistEntries();2760 const password = entries[idx].password;2761 if (password) {2762 checkBreach(password).then(async (count) => {2763 const i = entries.findIndex((e) => e.id === id);2764 if (i !== -1 && count > 0) {2765 entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2766 await persistEntries();2767 }2768 });2769 }2770 }27712772 fireSyncTrigger("vault_change");2773}27742775export async function deleteEntry(id: string): Promise<void> {2776 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");27772778 const entry = entries.find((item) => item.id === id);2779 if (!entry || entry.deletedAt) {2780 throw new Error("entry_not_found");2781 }27822783 2784 2785 2786 const previousModifiedAt = entry.modifiedAt;2787 const previousTombstone = tombstones.get(id);2788 const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2789 entry.deletedAt = stamp;2790 entry.modifiedAt = stamp;2791 tombstones.set(id, stamp);2792 2793 2794 try {2795 await persistEntries();2796 } catch (err) {2797 delete entry.deletedAt;2798 entry.modifiedAt = previousModifiedAt;2799 if (previousTombstone === undefined) tombstones.delete(id);2800 else tombstones.set(id, previousTombstone);2801 throw err;2802 }2803 fireSyncTrigger("vault_change");2804}28052806export function getDeletedEntries(): VaultEntry[] {2807 if (!derivedKey) return [];2808 return entries.filter((e) => !!e.deletedAt);2809}281028112812export function getTombstoneManifest(): Record<string, number> {2813 if (!derivedKey) return {};2814 return Object.fromEntries(tombstones);2815}2816281728182819282028212822export async function getVaultVersion(): Promise<number> {2823 try {2824 const raw = await chrome.storage.local.get("peach_last_modified_at");2825 const v = (raw as Record<string, unknown>).peach_last_modified_at;2826 if (typeof v === "number") return v;2827 if (typeof v === "string" && v !== "") {2828 const n = Number.parseInt(v, 10);2829 return Number.isFinite(n) ? n : 0;2830 }2831 return 0;2832 } catch {2833 return 0;2834 }2835}2836283728382839284028412842284328442845284628472848export async function applyMergedRemoteEntries(2849 remoteEntries: VaultEntry[],2850 remoteTombstones: Record<string, number>,2851): Promise<{ received: number; applied: number; conflicts: number }> {2852 2853 2854 2855 2856 2857 2858 if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");28592860 const received = remoteEntries.length + Object.keys(remoteTombstones).length;2861 let applied = 0;2862 let conflicts = 0;28632864 const byId = new Map<string, VaultEntry>();2865 for (const e of entries) byId.set(e.id, e);28662867 const mergeNow = Date.now();2868 const remoteTombstoneTimes = new Map<string, number>();2869 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2870 if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {2871 remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));2872 }2873 }28742875 for (const remote of remoteEntries) {2876 const sanitized = sanitizeRestoredEntry(remote);2877 if (!sanitized) continue;2878 2879 2880 2881 sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2882 if (typeof sanitized.deletedAt === "number") {2883 sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2884 }2885 const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);2886 const localTombstoneTs = tombstones.get(sanitized.id);2887 const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);2888 if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {2889 continue;2890 }2891 const local = byId.get(sanitized.id);2892 if (!local) {2893 entries.push(sanitized);2894 byId.set(sanitized.id, sanitized);2895 tombstones.delete(sanitized.id);2896 applied += 1;2897 } else if (sanitized.modifiedAt > local.modifiedAt) {2898 const idx = entries.findIndex((e) => e.id === local.id);2899 if (idx !== -1) {2900 entries[idx] = sanitized;2901 byId.set(sanitized.id, sanitized);2902 tombstones.delete(sanitized.id);2903 applied += 1;2904 if (!local.deletedAt) conflicts += 1;2905 }2906 }2907 }29082909 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2910 if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;2911 2912 const deletedAt = remoteTombstoneTimes.get(id)!;2913 const knownTombstone = tombstones.get(id);2914 if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;2915 const local = byId.get(id);2916 if (!local) {2917 tombstones.set(id, deletedAt);2918 applied += 1;2919 continue;2920 }2921 if (local.deletedAt && local.deletedAt >= deletedAt) continue;2922 if (deletedAt < local.modifiedAt) continue;2923 const idx = entries.findIndex((e) => e.id === id);2924 if (idx !== -1) {2925 entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2926 tombstones.set(id, deletedAt);2927 applied += 1;2928 }2929 }29302931 if (applied > 0 && vaultMode === "real") {2932 await persistEntries("sync_received");2933 buildDomainIndexSync(entries);2934 2935 2936 2937 2938 try {2939 void chrome.runtime2940 .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })2941 .catch(() => undefined);2942 } catch {2943 2944 }2945 }2946 return { received, applied, conflicts };2947}29482949export async function restoreEntry(id: string): Promise<void> {2950 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2951 const entry = entries.find((e) => e.id === id && e.deletedAt);2952 if (!entry) throw new Error("deleted entry not found");2953 const previousDeletedAt = entry.deletedAt;2954 const previousModifiedAt = entry.modifiedAt;2955 const previousTombstone = tombstones.get(id);2956 delete entry.deletedAt;2957 entry.modifiedAt = monotonicEntryTimestamp(Math.max(2958 entry.modifiedAt,2959 previousTombstone ?? 0,2960 ));2961 tombstones.delete(id);2962 try {2963 await persistEntries();2964 } catch (err) {2965 entry.deletedAt = previousDeletedAt;2966 entry.modifiedAt = previousModifiedAt;2967 if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);2968 throw err;2969 }2970 buildDomainIndexSync(entries);2971}29722973export async function purgeEntry(id: string): Promise<void> {2974 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2975 const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2976 if (idx === -1) throw new Error("deleted entry not found");2977 const entry = entries[idx]!;2978 tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));2979 entries.splice(idx, 1);2980 await persistEntries();2981}298229832984export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2985 if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;2986 const cutoff = Date.now() - retentionMs;2987 const before = entries.length;2988 for (const entry of entries) {2989 if (entry.deletedAt && entry.deletedAt < cutoff) {2990 tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));2991 }2992 }2993 entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2994 const purged = before - entries.length;2995 if (purged > 0) await persistEntries();2996 return purged;2997}29982999export function queryDomain(domain: string): VaultEntry[] {3000 return domainIndex.get(domain) ?? [];3001}30023003export function getEntryById(id: string): VaultEntry | undefined {3004 return entries.find((entry) => entry.id === id && !entry.deletedAt);3005}30063007async function persistSlotA(3008 reason: VaultSnapshot["reason"] = "local_save",3009): Promise<StoredVault> {3010 if (!derivedKey) throw new Error("vault_locked");3011 const epoch = vaultEpoch;3012 const throwIfStale = () => {3013 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3014 };30153016 const slotA = await loadSlot(SLOT_A);3017 throwIfStale();3018 if (!slotA) throw new Error("missing slot A");30193020 3021 3022 await takeVaultSnapshot(reason);3023 throwIfStale();30243025 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3026 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3027 throwIfStale();30283029 3030 const nextSlotA: StoredVault = {3031 ...slotA,3032 nonce,3033 ciphertext,3034 tag,3035 3036 };30373038 3039 3040 3041 3042 3043 3044 let slotACommitted = false;3045 try {3046 throwIfStale();3047 await writeSlot(SLOT_A, nextSlotA);3048 slotACommitted = true;3049 throwIfStale();30503051 3052 3053 3054 if (!duressConfigured) {3055 throwIfStale();3056 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3057 throwIfStale();3058 }3059 3060 3061 3062 3063 3064 if (reason !== "sync_received") {3065 throwIfStale();3066 await stampLocalVaultMutation();3067 throwIfStale();3068 }3069 } catch (err) {3070 3071 3072 if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3073 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3074 throw err;3075 }30763077 return nextSlotA;3078}30793080async function persistSlotB(): Promise<void> {3081 if (!derivedKey) throw new Error("vault_locked");30823083 const slotB = await loadSlot(SLOT_B);3084 if (!slotB) throw new Error("missing slot B");30853086 3087 3088 3089 3090 const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3091 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");30923093 await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3094 3095 3096 3097 try {3098 await stampLocalVaultMutation();3099 } catch (err) {3100 await writeSlot(SLOT_B, slotB).catch(() => {});3101 throw err;3102 }3103}31043105async function persistEntries(3106 reason: VaultSnapshot["reason"] = "local_save",3107): Promise<void> {3108 if (vaultCreatesInFlight) throw new Error("vault_changed");3109 vaultWritesInFlight++;3110 try {3111 if (!derivedKey) throw new Error("vault_locked");31123113 3114 3115 const previousTombstones = tombstones;3116 const pendingTombstones = new Map(tombstones);3117 tombstones = pendingTombstones;3118 reconcileTombstones();3119 try {3120 if (vaultMode === "decoy") {3121 await persistSlotB();3122 } else {3123 await persistSlotA(reason);3124 }3125 } catch (err) {3126 if (tombstones === pendingTombstones) tombstones = previousTombstones;3127 throw err;3128 }3129 buildDomainIndexSync(entries);3130 await refreshLockedSyncState();3131 } finally { vaultWritesInFlight--; }3132}3133313431353136313731383139function allowHttpUrl(url: string | undefined): string {3140 const trimmed = url?.trim() ?? "";3141 if (!trimmed) return "";3142 try {3143 const parsed = new URL(trimmed);3144 if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3145 } catch {3146 3147 }3148 return trimmed;3149}31503151function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3152 if (!Array.isArray(values)) return undefined;3153 const seen = new Set<string>();3154 const cleaned: string[] = [];3155 for (const value of values) {3156 const trimmed = typeof value === "string" ? value.trim() : "";3157 if (!trimmed) continue;3158 if (!allowHttpUrl(trimmed)) continue;3159 const key = trimmed.toLowerCase();3160 if (seen.has(key)) continue;3161 seen.add(key);3162 cleaned.push(trimmed);3163 }3164 return cleaned.length > 0 ? cleaned : undefined;3165}31663167function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3168 const title = entry.title.trim();3169 const type: VaultEntry["type"] = entry.type ?? "login";31703171 if (!title) throw new Error("title is required");31723173 if (entry.passkey) {3174 const p = entry.passkey;3175 if (3176 !p.rpId ||3177 !p.credentialId ||3178 !p.publicKeyCose ||3179 !p.userHandle ||3180 !p.userName ||3181 (p.algorithm !== -7 && p.algorithm !== -8)3182 ) {3183 throw new Error("invalid passkey credential");3184 }3185 }3186 if (type === "card") {3187 if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3188 throw new Error("cardholder name and card number are required");3189 }3190 }31913192 return {3193 type,3194 title,3195 username: type === "login" ? entry.username?.trim() ?? "" : undefined,3196 email: type === "login" ? entry.email?.trim() || undefined : undefined,3197 password: type === "login" ? entry.password : undefined,3198 url: type === "login" ? allowHttpUrl(entry.url) : undefined,3199 additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3200 totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3201 3202 3203 totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3204 totpDigits: type === "login" ? entry.totpDigits : undefined,3205 totpPeriod: type === "login" ? entry.totpPeriod : undefined,3206 notes: entry.notes?.trim() || undefined,3207 breach: type === "login" ? entry.breach : undefined,3208 3209 3210 canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3211 tags: sanitizeTags(entry.tags),3212 passkey: entry.passkey,3213 cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3214 cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3215 expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3216 expYear: type === "card" ? entry.expYear?.trim() : undefined,3217 cvc: type === "card" ? entry.cvc?.trim() : undefined,3218 cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3219 network: type === "card" ? entry.network : undefined,3220 last4: type === "card" ? entry.last4?.trim() : undefined,3221 };3222}32233224function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3225 const nextPatch: Partial<VaultEntry> = {};32263227 if ("type" in patch) {3228 nextPatch.type = patch.type;3229 }32303231 if ("title" in patch) {3232 const title = patch.title?.trim() ?? "";3233 if (!title) throw new Error("title is required");3234 nextPatch.title = title;3235 }32363237 if ("url" in patch) {3238 nextPatch.url = allowHttpUrl(patch.url);3239 }32403241 if ("additionalUrls" in patch) {3242 const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3243 const seen = new Set<string>();3244 const cleaned: string[] = [];3245 for (const value of incoming) {3246 const trimmed = typeof value === "string" ? value.trim() : "";3247 if (!trimmed || !allowHttpUrl(trimmed)) continue;3248 const key = trimmed.toLowerCase();3249 if (seen.has(key)) continue;3250 seen.add(key);3251 cleaned.push(trimmed);3252 }3253 nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3254 }32553256 if ("username" in patch) {3257 nextPatch.username = patch.username?.trim() ?? "";3258 }32593260 if ("email" in patch) {3261 nextPatch.email = patch.email?.trim() || undefined;3262 }32633264 if ("password" in patch) {3265 const password = patch.password ?? "";3266 3267 nextPatch.password = password || undefined;3268 }32693270 if ("totp" in patch) {3271 nextPatch.totp = patch.totp?.trim() || undefined;3272 }32733274 if ("totpAlgorithm" in patch) {3275 nextPatch.totpAlgorithm = patch.totpAlgorithm;3276 }32773278 if ("totpDigits" in patch) {3279 nextPatch.totpDigits = patch.totpDigits;3280 }32813282 if ("totpPeriod" in patch) {3283 nextPatch.totpPeriod = patch.totpPeriod;3284 }32853286 if ("notes" in patch) {3287 nextPatch.notes = patch.notes?.trim() || undefined;3288 }32893290 if ("breach" in patch) {3291 nextPatch.breach = patch.breach;3292 }32933294 if ("canary" in patch) {3295 3296 3297 nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3298 }32993300 if ("passkey" in patch) {3301 3302 3303 if (patch.passkey === undefined || patch.passkey === null) {3304 nextPatch.passkey = undefined;3305 } else {3306 const sanitized = sanitizePasskey(patch.passkey);3307 if (!sanitized) throw new Error("invalid passkey credential");3308 nextPatch.passkey = sanitized;3309 }3310 }33113312 if ("tags" in patch) {3313 3314 nextPatch.tags = sanitizeTags(patch.tags);3315 }33163317 if ("cardholderName" in patch) {3318 nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3319 }3320 if ("cardNumber" in patch) {3321 const n = patch.cardNumber ?? "";3322 nextPatch.cardNumber = n || undefined;3323 }3324 if ("expMonth" in patch) {3325 nextPatch.expMonth = patch.expMonth?.trim() || undefined;3326 }3327 if ("expYear" in patch) {3328 nextPatch.expYear = patch.expYear?.trim() || undefined;3329 }3330 if ("cvc" in patch) {3331 nextPatch.cvc = patch.cvc?.trim() || undefined;3332 }3333 if ("cardNickname" in patch) {3334 nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3335 }3336 if ("network" in patch) {3337 nextPatch.network = patch.network;3338 }3339 if ("last4" in patch) {3340 nextPatch.last4 = patch.last4?.trim() || undefined;3341 }33423343 return nextPatch;3344}33453346function normalizeEntry(entry: VaultEntry): VaultEntry {3347 const base: VaultEntry = {3348 id: entry.id,3349 type: entry.type,3350 title: entry.title,3351 username: entry.username,3352 email: entry.email,3353 password: entry.password,3354 url: entry.url,3355 additionalUrls:3356 "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3357 ? entry.additionalUrls3358 : undefined,3359 totp: entry.totp,3360 3361 totpAlgorithm: entry.totpAlgorithm,3362 totpDigits: entry.totpDigits,3363 totpPeriod: entry.totpPeriod,3364 notes: entry.notes,3365 breach: entry.breach,3366 3367 3368 3369 passwordChangedAt:3370 "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3371 3372 3373 3374 passwordHistory:3375 "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3376 ? entry.passwordHistory3377 : undefined,3378 canary: entry.canary,3379 passkey: entry.passkey,3380 createdAt: entry.createdAt,3381 modifiedAt: entry.modifiedAt,3382 deletedAt: entry.deletedAt,3383 tags: entry.tags,3384 cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3385 cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3386 expMonth: "expMonth" in entry ? entry.expMonth : undefined,3387 expYear: "expYear" in entry ? entry.expYear : undefined,3388 cvc: "cvc" in entry ? entry.cvc : undefined,3389 cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3390 network: "network" in entry ? entry.network : undefined,3391 last4: "last4" in entry ? entry.last4 : undefined,3392 };33933394 return base;3395}3396339733983399340034013402function entryDupeKey(e: VaultEntry): string {3403 if (e.passkey) {3404 3405 const content = Object.fromEntries(Object.entries(e)3406 .filter(([key]) => key !== "id" && key !== "createdAt" && key !== "modifiedAt")3407 .sort(([a], [b]) => a.localeCompare(b)));3408 return `passkey|${e.passkey.rpId}|${e.passkey.credentialId}|${JSON.stringify(content)}`;3409 }3410 if (e.type === "note") return `note|${e.title.toLowerCase()}`;3411 return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3412}341334143415export function countDuplicates(): number {3416 const best = new Map<string, VaultEntry>();3417 let dupeCount = 0;3418 for (const e of entries.filter((e) => !e.deletedAt)) {3419 const key = entryDupeKey(e);3420 const existing = best.get(key);3421 if (!existing) {3422 best.set(key, e);3423 } else {3424 dupeCount++;3425 3426 if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3427 best.set(key, e);3428 }3429 }3430 }3431 return dupeCount;3432}343334343435343634373438export async function deduplicateEntries(): Promise<number> {3439 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3440 3441 3442 if (vaultMode === "decoy") {3443 throw new Error("deduplicate disabled in decoy mode");3444 }34453446 const best = new Map<string, VaultEntry>();3447 for (const e of entries.filter((en) => !en.deletedAt)) {3448 const key = entryDupeKey(e);3449 const existing = best.get(key);3450 if (!existing) {3451 best.set(key, e);3452 } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3453 best.set(key, e);3454 }3455 }34563457 const keepIds = new Set(Array.from(best.values()).map((e) => e.id));3458 let removed = 0;3459 entries = entries.map((e) => {3460 if (!e.deletedAt && !keepIds.has(e.id)) {3461 removed++;3462 const deletedAt = monotonicEntryTimestamp(Math.max(3463 e.modifiedAt,3464 tombstones.get(e.id) ?? 0,3465 ));3466 tombstones.set(e.id, deletedAt);3467 return { ...e, deletedAt };3468 }3469 return e;3470 });34713472 if (removed > 0) await persistEntries();3473 return removed;3474}347534763477347834793480348134823483const HISTORY_KEY = "peach_vault_history";3484const HISTORY_MAX = 5;348534863487348834893490function bucketEntryCount(n: number): number {3491 if (n <= 0) return 0;3492 if (n <= 10) return 10;3493 if (n <= 25) return 25;3494 if (n <= 50) return 50;3495 if (n <= 100) return 100;3496 if (n <= 250) return 250;3497 if (n <= 500) return 500;3498 return Math.ceil(n / 500) * 500;3499}35003501350235033504350535063507export async function takeVaultSnapshot(3508 reason: VaultSnapshot["reason"],3509): Promise<void> {3510 if (recoveryInFlight || vaultCreatesInFlight) return;3511 3512 3513 3514 if (vaultMode === "decoy") return;3515 vaultWritesInFlight++;3516 try {3517 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);3518 const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];3519 const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];35203521 3522 3523 3524 if (!slotA) return;35253526 const vault_a = JSON.stringify(slotA);3527 const vault_b = JSON.stringify(slotB ?? slotA);35283529 3530 3531 3532 3533 3534 3535 let entryCount: number | null = null;3536 if (derivedKey && vaultMode === "real") {3537 try {3538 entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);3539 } catch {3540 entryCount = null;3541 }3542 }35433544 const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3545 const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)3546 ? existingRaw3547 : { snapshots: [] };35483549 3550 3551 3552 const latest = history.snapshots[0];3553 if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3554 return;3555 }35563557 const snapshot: VaultSnapshot = {3558 id: crypto.randomUUID(),3559 savedAt: Date.now(),3560 reason,3561 vault_a,3562 vault_b,3563 entryCount,3564 };35653566 history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3567 if (recoveryInFlight || vaultCreatesInFlight) return;3568 await chrome.storage.local.set({ [HISTORY_KEY]: history });3569 } catch (err) {3570 3571 3572 3573 3574 console.warn('[Peach] takeVaultSnapshot failed:', err);3575 if (String(err).includes('QUOTA') || String(err).includes('quota')) {3576 try {3577 await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3578 } catch {3579 3580 }3581 }3582 } finally { vaultWritesInFlight--; }3583}358435853586export async function clearVaultHistory(): Promise<void> {3587 if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");3588 vaultWritesInFlight++;3589 try {3590 await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3591 } catch {3592 3593 } finally { vaultWritesInFlight--; }3594}359535963597export async function getVaultHistory(): Promise<VaultSnapshot[]> {3598 if (vaultMode === "decoy") return [];3599 const raw = await chrome.storage.local.get(HISTORY_KEY);3600 const value = (raw as Record<string, unknown>)[HISTORY_KEY];3601 return sanitizeHistory(value);3602}360336043605360636073608export async function restoreVaultSnapshot(3609 snapshotId: string,3610): Promise<{ ok: true } | { ok: false; error: string }> {3611 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };3612 vaultReplacementInFlight = true;3613 try {3614 if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3615 const history = await getVaultHistory();3616 const snapshot = history.find((s) => s.id === snapshotId);3617 if (!snapshot) return { ok: false, error: "snapshot_not_found" };36183619 const restoredA = parseHistorySlot(snapshot.vault_a);3620 const restoredB = parseHistorySlot(snapshot.vault_b);3621 if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };36223623 await takeVaultSnapshot("restore");3624 const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3625 const previousA = (current as Record<string, unknown>)[SLOT_A];3626 const previousB = (current as Record<string, unknown>)[SLOT_B];3627 try {3628 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };3629 await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3630 await stampLocalVaultMutation();3631 } catch {3632 try {3633 await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3634 } catch {3635 3636 }3637 return { ok: false, error: "snapshot_corrupt" };3638 }36393640 await lock();3641 return { ok: true };3642 } finally {3643 vaultReplacementInFlight = false;3644 }3645}364636473648364936503651365236533654365536563657365836593660export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3661 if (vaultCreatesInFlight) throw new Error("vault_changed");3662 vaultWritesInFlight++;3663 try {3664 if (!derivedKey || vaultMode !== "real") {3665 return { ok: false, error: "vault_locked" };3666 }3667 const slotA = await loadSlot(SLOT_A);3668 if (!slotA) return { ok: false, error: "missing_slot_a" };36693670 3671 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3672 await generateAndWrapRootKey();36733674 3675 const newRootKey = unhex(rawRootKey);3676 const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");3677 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);36783679 3680 3681 3682 3683 await takeVaultSnapshot("local_save");3684 const nextSlotA: StoredVault = {3685 ...slotA,3686 recovery_vault_key: recoveryVaultKey,3687 recovery_salt: recoverySalt,3688 recovery_wrapped_root_key: wrappedRootKey,3689 recovery_nonce: wrappedNonce,3690 recovery_tag: wrappedTag,3691 ...pwRoot,3692 };3693 await writeSlot(SLOT_A, nextSlotA);36943695 3696 if (rootKey) zeroKey(rootKey);3697 rootKey = newRootKey;36983699 3700 3701 await notifyIdentityKeysRotated();37023703 3704 3705 3706 await clearPairedDevices();3707 await clearPairSecrets();37083709 3710 await setRecoveryConfirmPending(); 37113712 await stampLocalVaultMutation();3713 return { ok: true };3714 } finally { vaultWritesInFlight--; }3715}37163717371837193720372137223723export async function changePassword(3724 currentPassword: string,3725 newPassword: string3726): Promise<boolean> {3727 if (vaultCreatesInFlight) throw new Error("vault_changed");3728 vaultWritesInFlight++;3729 try {37303731 const epoch = vaultEpoch;3732 const stale = () => epoch !== vaultEpoch;3733 if (!derivedKey || vaultMode !== "real") return false;37343735 3736 const valid = await verifyMainPassword(currentPassword);3737 if (!valid) return false;37383739 const slotA = await loadSlot(SLOT_A);3740 if (!slotA) return false;3741 if (!rootKey) return false;37423743 3744 const newSalt = generateSalt();3745 const newKey = await deriveKey(newPassword, newSalt);3746 if (stale()) {3747 zeroKey(newKey);3748 return false;3749 }37503751 3752 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3753 const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");37543755 3756 3757 3758 const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);37593760 const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");3761 const finalSlotA: StoredVault = {3762 ...slotA,3763 recovery_vault_key: recoveryVaultKey,3764 salt: hex(newSalt),3765 nonce,3766 ciphertext,3767 tag,3768 ...pwRoot,3769 };37703771 3772 3773 3774 await takeVaultSnapshot("local_save");37753776 3777 3778 3779 3780 await writeSlot(SLOT_A, finalSlotA);3781 if (stale()) {3782 zeroKey(newKey);3783 return false;3784 }37853786 3787 3788 3789 zeroKey(derivedKey);3790 derivedKey = newKey;37913792 3793 3794 3795 3796 if (stale()) {3797 await lock();3798 return false;3799 }3800 await saveSessionKey(newKey, "real", epoch);3801 if (stale()) return false;38023803 3804 3805 3806 await notifyIdentityKeysRotated();3807 if (stale()) return false;38083809 3810 3811 3812 if (!duressConfigured) {3813 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3814 }3815 await clearPinUnlockStorage();3816 await stampLocalVaultMutation();38173818 return true;3819 } finally { vaultWritesInFlight--; }3820}