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}1207120812091210121112121213121412151216121712181219122012211222122312241225122612271228function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1229 let merged = false;1230 const now = Date.now();12311232 const candidates = entries.filter((e) => !e.deletedAt && e.passkey);1233 const byRpId = new Map<string, VaultEntry[]>();1234 for (const e of candidates) {1235 const rpId = e.passkey!.rpId;1236 const list = byRpId.get(rpId);1237 if (list) list.push(e);1238 else byRpId.set(rpId, [e]);1239 }12401241 for (const [rpId, group] of byRpId) {1242 if (group.length === 0) continue;1243 group.sort((a, b) => {1244 const aT =1245 a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;1246 const bT =1247 b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;1248 return bT - aT;1249 });1250 const winner = group[0]!;12511252 1253 1254 1255 const loginTarget = entries.find((e) => {1256 if (e.deletedAt || e.passkey || e.type !== "login") return false;1257 if (e.url && extractDomain(e.url) === rpId) return true;1258 for (const extra of e.additionalUrls ?? []) {1259 if (extractDomain(extra) === rpId) return true;1260 }1261 return false;1262 });12631264 if (loginTarget) {1265 loginTarget.passkey = winner.passkey;1266 1267 1268 1269 if (!loginTarget.totp && winner.totp) {1270 loginTarget.totp = winner.totp;1271 loginTarget.totpAlgorithm = winner.totpAlgorithm;1272 loginTarget.totpDigits = winner.totpDigits;1273 loginTarget.totpPeriod = winner.totpPeriod;1274 }1275 loginTarget.modifiedAt = now;1276 for (const dup of group) {1277 if (!dup.deletedAt) {1278 dup.deletedAt = now;1279 dup.modifiedAt = now;1280 }1281 }1282 merged = true;1283 } else if (group.length > 1) {1284 for (let i = 1; i < group.length; i += 1) {1285 const dup = group[i]!;1286 if (!dup.deletedAt) {1287 dup.deletedAt = now;1288 dup.modifiedAt = now;1289 }1290 }1291 merged = true;1292 }1293 }12941295 return { merged };1296}12971298129913001301130213031304function hasValidVaultSchema(v: unknown): v is StoredVault {1305 if (typeof v !== "object" || v === null) return false;1306 const r = v as Record<string, unknown>;1307 return (1308 r.version === 1 &&1309 typeof r.salt === "string" &&1310 typeof r.nonce === "string" &&1311 typeof r.ciphertext === "string" &&1312 typeof r.tag === "string"1313 );1314}1315const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;13161317function hasValidHistorySlot(value: unknown): value is StoredVault {1318 if (!hasValidVaultSchema(value)) return false;1319 return /^[0-9a-f]{32}$/i.test(value.salt) &&1320 /^[0-9a-f]{24}$/i.test(value.nonce) &&1321 /^[0-9a-f]+$/i.test(value.ciphertext) &&1322 value.ciphertext.length % 2 === 0 &&1323 value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1324 /^[0-9a-f]{32}$/i.test(value.tag);1325}13261327function parseHistorySlot(value: string): StoredVault | null {1328 try {1329 const parsed: unknown = JSON.parse(value);1330 return hasValidHistorySlot(parsed) ? parsed : null;1331 } catch {1332 return null;1333 }1334}13351336function isHistoryRecord(value: unknown): value is VaultSnapshot {1337 if (typeof value !== "object" || value === null) return false;1338 const record = value as Record<string, unknown>;1339 return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1340 typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1341 typeof record.reason === "string" &&1342 typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1343 typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1344 (record.entryCount === null || typeof record.entryCount === "number");1345}13461347function sanitizeHistory(value: unknown): VaultSnapshot[] {1348 if (typeof value !== "object" || value === null) return [];1349 if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1350 return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1351}13521353export type TryDecryptResult =1354 | { status: "ok"; payload: DecryptedPayload }1355 | { status: "wrong_key" }1356 | { status: "corrupted"; reason: string };1357135813591360136113621363export async function tryDecryptSlot(1364 vault: StoredVault,1365 key: Uint8Array,1366 aadTag?: string,1367): Promise<DecryptedPayload | null> {1368 const res = await tryDecryptSlotResult(vault, key, aadTag);1369 return res.status === "ok" ? res.payload : null;1370}13711372export async function tryDecryptSlotResult(1373 vault: StoredVault,1374 key: Uint8Array,1375 aadTag?: string,1376): Promise<TryDecryptResult> {1377 if (!hasValidVaultSchema(vault)) {1378 return { status: "corrupted", reason: "invalid_slot_schema" };1379 }1380 let plain: string;1381 try {1382 plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1383 } catch {1384 return { status: "wrong_key" };1385 }1386 try {1387 const parsed = JSON.parse(plain) as unknown;1388 if (typeof parsed !== "object" || parsed === null) {1389 return { status: "corrupted", reason: "invalid_payload_shape" };1390 }1391 if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1392 return { status: "corrupted", reason: "invalid_payload_shape" };1393 }1394 return { status: "ok", payload: decodePayload(plain) };1395 } catch {1396 return { status: "corrupted", reason: "invalid_payload_json" };1397 }1398}139914001401140214031404function buildDomainIndexSync(all: VaultEntry[]): void {1405 domainIndex = new Map();14061407 for (const entry of all) {1408 if (entry.deletedAt) continue;1409 if (entry.type === "note" || entry.type === "card") continue;14101411 1412 1413 1414 1415 const domains = new Set<string>();1416 const primary = extractDomain(entry.url ?? "");1417 if (primary) domains.add(primary);1418 for (const extra of entry.additionalUrls ?? []) {1419 const d = extractDomain(extra);1420 if (d) domains.add(d);1421 }1422 if (domains.size === 0) continue;14231424 for (const domain of domains) {1425 const bucket = domainIndex.get(domain) ?? [];1426 bucket.push(entry);1427 domainIndex.set(domain, bucket);1428 }1429 }1430}14311432export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1433 if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1434 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1435 vaultCreatesInFlight++;1436 let settle!: () => void;1437 creationSettled = new Promise<void>((resolve) => { settle = resolve; });1438 let nextKey: Uint8Array | null = null;1439 let nextRoot: Uint8Array | null = null;1440 let committed = false;1441 let publishedEpoch: number | null = null;1442 const epoch = vaultEpoch;1443 const check = () => {1444 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1445 };1446 try {1447 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1448 check();1449 const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1450 if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1451 const salt = generateSalt();1452 nextKey = await deriveKey(password, salt);1453 check();1454 const recovery = await generateAndWrapRootKey();1455 nextRoot = unhex(recovery.rawRootKey);1456 check();1457 const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1458 const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1459 const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1460 check();1461 const slotA: StoredVault = {1462 ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1463 recovery_vault_key: recoveryVaultKey,1464 recovery_salt: recovery.recoverySalt,1465 recovery_wrapped_root_key: recovery.wrappedRootKey,1466 recovery_nonce: recovery.wrappedNonce,1467 recovery_tag: recovery.wrappedTag,1468 };1469 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1470 check();1471 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1472 const previous = Number(raw.peach_last_modified_at);1473 const update: Record<string, unknown> = {1474 [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1475 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1476 };1477 if (occupied) {1478 const history = raw[HISTORY_KEY] as VaultHistory | undefined;1479 const snapshot: VaultSnapshot = {1480 id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1481 vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1482 };1483 update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1484 }1485 try { await chrome.storage.local.set(update); }1486 catch (error) { throw mapStorageError(error); }1487 committed = true;1488 if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1489 const previousKey = derivedKey;1490 const previousRoot = rootKey;1491 publishedEpoch = ++vaultEpoch;1492 derivedKey = nextKey;1493 rootKey = nextRoot;1494 nextKey = null;1495 nextRoot = null;1496 entries = [];1497 tombstones = new Map();1498 vaultMode = "real";1499 duressConfigured = false;1500 buildDomainIndexSync(entries);1501 if (previousKey) zeroKey(previousKey);1502 if (previousRoot) zeroKey(previousRoot);1503 await clearSessionKey();1504 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1505 await identityHooks?.onVaultCreated(password).catch((error) => {1506 console.warn("[Peach] local identity promotion failed:", error);1507 });1508 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1509 touchAutoLock();1510 return { committed: true, unlocked: true };1511 } catch (error) {1512 if (!committed) throw error;1513 console.warn("[Peach] vault saved; unlock required:", error);1514 if (publishedEpoch === vaultEpoch) {1515 await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));1516 }1517 return { committed: true, unlocked: false };1518 } finally {1519 if (nextKey) zeroKey(nextKey);1520 if (nextRoot) zeroKey(nextRoot);1521 vaultCreatesInFlight--;1522 settle();1523 }1524}1525152615271528152915301531export async function createVaultFromRootKey(1532 password: string,1533 rootKeyHex: string,1534): Promise<{ vaultId: string }> {1535 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1536 if (typeof password !== "string" || password.length === 0) {1537 throw new Error("ADOPT_INVALID_PASSWORD");1538 }1539 if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1540 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1541 }15421543 if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1544 const rootKeyBytes = unhex(rootKeyHex);1545 if (rootKeyBytes.length !== 32) {1546 rootKeyBytes.fill(0);1547 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1548 }15491550 vaultCreatesInFlight++;1551 let settle!: () => void;1552 creationSettled = new Promise<void>((resolve) => { settle = resolve; });1553 const epoch = vaultEpoch;1554 let nextDerivedKey: Uint8Array | null = null;1555 let sessionRootKey: Uint8Array | null = null;1556 let committed = false;1557 try {1558 if (await hasVault()) {1559 throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1560 }15611562 const nextEntries: VaultEntry[] = [];1563 const nextDuressConfigured = false;1564 const vaultId = await computeVaultId(rootKeyBytes);1565 const salt = generateSalt();1566 nextDerivedKey = await deriveKey(password, salt);1567 const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);15681569 sessionRootKey = new Uint8Array(rootKeyBytes);1570 const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1571 const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1572 const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1573 const slotA: StoredVault = {1574 recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),1575 version: 1,1576 salt: hex(salt),1577 nonce,1578 ciphertext,1579 tag,1580 recovery_salt: recovery.recoverySalt,1581 recovery_wrapped_root_key: recovery.wrappedRootKey,1582 recovery_nonce: recovery.wrappedNonce,1583 recovery_tag: recovery.wrappedTag,1584 ...pwRoot,1585 };1586 const slotB = generateNoiseBlob(ciphertext.length / 2);1587 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1588 await commitCreatedVaultSlots(slotA, slotB);1589 committed = true;1590 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1591 vaultEpoch++;15921593 const previousDerivedKey = derivedKey;1594 const previousRootKey = rootKey;1595 derivedKey = nextDerivedKey;1596 rootKey = sessionRootKey;1597 nextDerivedKey = null;1598 sessionRootKey = null;1599 entries = nextEntries;1600 tombstones = new Map();1601 vaultMode = "real";1602 duressConfigured = nextDuressConfigured;1603 buildDomainIndexSync(entries);1604 if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1605 if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1606 touchAutoLock();16071608 1609 1610 await identityHooks?.onVaultCreated(password).catch((error) => {1611 console.warn("[Peach] local identity promotion failed:", error);1612 });16131614 return { vaultId };1615 } catch (error) {1616 if (committed) {1617 1618 try { await lock(); }1619 finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, "peach_last_modified_at"]); }1620 }1621 throw error;1622 } finally {1623 vaultCreatesInFlight--;1624 settle();1625 rootKeyBytes.fill(0);1626 if (nextDerivedKey) zeroKey(nextDerivedKey);1627 if (sessionRootKey) sessionRootKey.fill(0);1628 }1629}16301631export async function hasVault(): Promise<boolean> {1632 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);1633 return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1634}1635163616371638163916401641export async function isDuressEnabled(): Promise<boolean> {1642 return vaultMode === "real" && duressConfigured;1643}16441645export async function setupDuress(duressPassword: string): Promise<void> {1646 if (vaultCreatesInFlight) throw new Error("vault_changed");1647 vaultWritesInFlight++;1648 try {1649 if (!derivedKey || vaultMode !== "real") {1650 throw new Error("vault must be unlocked in real mode");1651 }1652 1653 1654 1655 const slotA = await loadSlot(SLOT_A);1656 if (!slotA) throw new Error("missing slot A");16571658 const decoySalt = generateSalt();1659 const decoyKey = await deriveKey(duressPassword, decoySalt);1660 try {1661 1662 1663 1664 1665 const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1666 const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1667 await writeSlot(SLOT_B, {1668 version: 1,1669 salt: hex(decoySalt),1670 nonce,1671 ciphertext,1672 tag,1673 });1674 } finally {1675 zeroKey(decoyKey);1676 }16771678 1679 1680 duressConfigured = true;1681 await persistSlotA();1682 } finally { vaultWritesInFlight--; }1683}16841685export async function disableDuress(): Promise<void> {1686 if (vaultCreatesInFlight) throw new Error("vault_changed");1687 vaultWritesInFlight++;1688 try {1689 if (!derivedKey || vaultMode !== "real") {1690 throw new Error("vault must be unlocked in real mode");1691 }1692 1693 1694 1695 const slotA = await loadSlot(SLOT_A);1696 if (slotA) {1697 await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1698 }16991700 duressConfigured = false;1701 await persistSlotA();1702 } finally { vaultWritesInFlight--; }1703}17041705170617071708170917101711export async function verifyMainPassword(password: string): Promise<boolean> {1712 const slotA = await loadSlot(SLOT_A);1713 if (!slotA) return false;1714 const key = await deriveKey(password, unhex(slotA.salt));1715 try {1716 return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1717 } finally {1718 zeroKey(key);1719 }1720}17211722export async function unlock(password: string): Promise<boolean> {1723 return attemptUnlockWithDerive(password, deriveKey);1724}17251726async function attemptUnlockWithDerive(1727 password: string,1728 derive: typeof deriveKey,1729): Promise<boolean> {1730 vaultUnlocksInFlight++;1731 try {1732 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1733 const epoch = vaultEpoch;1734 const stale = () => epoch !== vaultEpoch;1735 1736 1737 1738 1739 1740 1741 const [slotA, slotB] = await Promise.all([1742 loadSlot(SLOT_A),1743 loadSlot(SLOT_B),1744 ]);17451746 1747 const [keyA, keyB] = await Promise.all([1748 slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1749 slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1750 ]);17511752 1753 1754 1755 const [resultA, resultB] = await Promise.all([1756 keyA && slotA1757 ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1758 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1759 keyB && slotB1760 ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1761 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1762 ]);1763 const payloadA = resultA.status === "ok" ? resultA.payload : null;1764 const payloadB = resultB.status === "ok" ? resultB.payload : null;17651766 if (stale()) {1767 if (keyA) zeroKey(keyA);1768 if (keyB) zeroKey(keyB);1769 return false;1770 }17711772 if (payloadA && keyA) {1773 if (stale()) {1774 zeroKey(keyA);1775 if (keyB) zeroKey(keyB);1776 return false;1777 }1778 derivedKey = keyA;1779 vaultMode = "real";1780 entries = payloadA.entries;1781 tombstones = payloadA.tombstones;1782 duressConfigured = payloadA.duressConfigured;1783 buildDomainIndexSync(entries);1784 await loadSettings();1785 if (stale()) {1786 await lock();1787 return false;1788 }1789 touchAutoLock();1790 if (keyB) zeroKey(keyB);17911792 1793 1794 rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;1795 if (!rootKey) {1796 await lock();1797 return false;1798 }17991800 1801 if (slotA) {1802 const escrowed = slotA.recovery_vault_key1803 ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;1804 const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);1805 if (escrowed) zeroKey(escrowed);1806 if (stale()) { await lock(); return false; }1807 if (!matches) {1808 try {1809 const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");1810 if (stale()) { await lock(); return false; }1811 await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });1812 if (stale()) { await lock(); return false; }1813 } catch (error) {1814 await lock();1815 throw error;1816 }1817 }1818 }18191820 1821 1822 await reconcilePairSecrets(rootKey);1823 if (stale()) {1824 await lock();1825 return false;1826 }1827 await lockedSyncUnlockHook?.().catch((error) => {1828 console.warn("[Peach sync] locked inbox drain failed:", error);1829 });1830 if (stale()) {1831 await lock();1832 return false;1833 }1834 await resetPinFailedAttempts();1835 if (stale()) {1836 await lock();1837 return false;1838 }1839 await saveSessionKey(keyA, "real", epoch);1840 if (stale()) return false;1841 return true;1842 }18431844 if (payloadB && keyB) {1845 if (stale()) {1846 zeroKey(keyB);1847 if (keyA) zeroKey(keyA);1848 return false;1849 }1850 derivedKey = keyB;1851 vaultMode = "decoy";1852 decoySyncTeardownHook?.();1853 1854 1855 1856 if (rootKey) {1857 rootKey.fill(0);1858 rootKey = null;1859 }1860 entries = payloadB.entries;1861 tombstones = payloadB.tombstones;1862 duressConfigured = false;1863 buildDomainIndexSync(entries);1864 await loadSettings();1865 touchAutoLock();1866 if (keyA) zeroKey(keyA);1867 1868 await dropSessionCache();1869 1870 await notifyIdentitySessionEnded();1871 if (stale()) {1872 await lock();1873 return false;1874 }1875 await saveSessionKey(keyB, "decoy", epoch);1876 if (stale()) return false;1877 return true;1878 }18791880 if (keyA) zeroKey(keyA);1881 if (keyB) zeroKey(keyB);1882 1883 1884 if (resultA.status === "corrupted") {1885 lastUnlockFailureReason = resultA.reason;1886 } else if (resultB.status === "corrupted") {1887 lastUnlockFailureReason = resultB.reason;1888 }1889 return false;1890 } finally { vaultUnlocksInFlight--; }1891}18921893189418951896189718981899const SESSION_KEY_STORAGE = "peach_session_dk";1900190119021903let sessionKeyMutation = Promise.resolve();19041905function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {1906 const task = sessionKeyMutation.then(mutation, mutation);1907 sessionKeyMutation = task.catch(() => undefined);1908 return task;1909}191019111912191319141915let sessionEscrowAvailable = true;19161917191819191920192119221923export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {1924 setSessionAllowed(sessionEscrow);1925 if (sessionEscrow) return;1926 sessionEscrowAvailable = false;1927 await clearSessionKey();1928}19291930async function saveSessionKey(1931 key: Uint8Array,1932 mode: "real" | "decoy",1933 expectedEpoch = vaultEpoch,1934): Promise<void> {1935 const session = chrome.storage.session;1936 if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1937 const stored = { keyHex: hex(key), mode };1938 await mutateSessionKey(async () => {1939 if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1940 await session.set({ [SESSION_KEY_STORAGE]: stored });1941 });1942}19431944async function clearSessionKey(): Promise<void> {1945 const session = chrome.storage.session;1946 if (!session) return;1947 await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));1948}19491950195119521953195419551956let vaultEpoch = 0;1957195819591960let restoreInFlight: Promise<boolean> | null = null;196119621963196419651966196719681969export async function restoreFromSession(): Promise<boolean> {1970 vaultUnlocksInFlight++;1971 try {1972 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1973 if (derivedKey !== null) return true;1974 if (restoreInFlight) return restoreInFlight;1975 const task = restoreFromSessionInner();1976 restoreInFlight = task;1977 try {1978 return await task;1979 } finally {1980 restoreInFlight = null;1981 }1982 } finally { vaultUnlocksInFlight--; }1983}19841985async function restoreFromSessionInner(): Promise<boolean> {1986 const epoch = vaultEpoch;1987 const stale = () => epoch !== vaultEpoch;1988 if (derivedKey !== null) return true;1989 if (!sessionEscrowAvailable) return false;1990 if (!chrome.storage.session) return false;1991 const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1992 if (stale()) return false;1993 const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1994 if (!entry?.keyHex) return false;19951996 const key = unhex(entry.keyHex);1997 const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1998 const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1999 const slot = await loadSlot(slotKey);2000 if (stale()) { zeroKey(key); return false; }2001 if (!slot) { await clearSessionKey(); return false; }20022003 const result = await tryDecryptSlotResult(slot, key, aadTag);2004 if (stale()) { zeroKey(key); return false; }2005 if (result.status !== "ok") { await clearSessionKey(); return false; }20062007 2008 2009 const payload = result.payload;2010 await loadSettings();2011 if (stale()) { zeroKey(key); return false; }20122013 2014 2015 let freshRoot: Uint8Array | null = null;2016 if (entry.mode === "real") {2017 freshRoot = await deriveRootKeyFromDerivedKey(key, slot);2018 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2019 if (!freshRoot) {2020 await lock();2021 return false;2022 }2023 }20242025 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2026 if (freshRoot) {2027 2028 await reconcilePairSecrets(freshRoot);2029 if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }2030 } else {2031 2032 await dropSessionCache();2033 2034 await notifyIdentitySessionEnded();2035 if (stale()) { zeroKey(key); return false; }2036 }2037 derivedKey = key;2038 vaultMode = entry.mode;2039 if (entry.mode === "decoy") decoySyncTeardownHook?.();2040 entries = payload.entries;2041 tombstones = payload.tombstones;2042 duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;2043 if (freshRoot) rootKey = freshRoot;2044 buildDomainIndexSync(entries);2045 touchAutoLock();20462047 await lockedSyncUnlockHook?.().catch((error) => {2048 console.warn("[Peach sync] locked inbox drain failed:", error);2049 });2050 if (stale()) return false;20512052 return true;2053}20542055export async function lock(): Promise<void> {2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 vaultEpoch++;2066 if (derivedKey) {2067 zeroKey(derivedKey);2068 derivedKey = null;2069 }2070 if (rootKey) {2071 rootKey.fill(0);2072 rootKey = null;2073 }20742075 entries = [];2076 tombstones = new Map();2077 domainIndex = new Map();2078 vaultMode = "real";2079 duressConfigured = false;2080 clearAutoLock();2081 await clearSessionKey();2082 2083 2084 await notifyIdentitySessionEnded();2085}20862087export function isUnlocked(): boolean {2088 return derivedKey !== null;2089}20902091export function isDecoyMode(): boolean {2092 return derivedKey !== null && vaultMode === "decoy";2093}20942095209620972098export async function unlockWithKey(2099 masterKeyHex: string,2100): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2101 vaultUnlocksInFlight++;2102 try {2103 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2104 const epoch = vaultEpoch;2105 const stale = () => epoch !== vaultEpoch;2106 let masterKeyBytes: Uint8Array | null = null;2107 try {2108 masterKeyBytes = unhex(masterKeyHex);2109 const stored = await loadSlot(SLOT_A);2110 if (!stored) return { ok: false, error: "invalid_key" };2111 const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2112 if (!payload || stale()) {2113 zeroKey(masterKeyBytes);2114 return { ok: false, error: "invalid_key" };2115 }21162117 derivedKey = masterKeyBytes;2118 vaultMode = "real";2119 entries = payload.entries;2120 tombstones = payload.tombstones;2121 duressConfigured = payload.duressConfigured;2122 buildDomainIndexSync(entries);2123 await loadSettings();2124 touchAutoLock();21252126 rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2127 if (!rootKey) {2128 await lock();2129 return { ok: false, error: "invalid_key" };2130 }2131 await reconcilePairSecrets(rootKey);2132 if (stale()) {2133 await lock();2134 return { ok: false, error: "invalid_key" };2135 }2136 await saveSessionKey(masterKeyBytes, "real", epoch);2137 if (stale()) return { ok: false, error: "invalid_key" };2138 return { ok: true, entries };2139 } catch {2140 if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2141 return { ok: false, error: "invalid_key" };2142 }2143 } finally { vaultUnlocksInFlight--; }2144}214521462147214821492150215121522153export async function exportDuressSlotForAdoption(): Promise<string | null> {2154 if (!(await isDuressEnabled())) return null;2155 const slotB = await loadSlot(SLOT_B);2156 if (!slotB) return null;2157 return JSON.stringify(slotB);2158}21592160216121622163216421652166export async function installAdoptedDuressSlot(json: string): Promise<void> {2167 if (vaultCreatesInFlight) throw new Error("vault_changed");2168 vaultWritesInFlight++;2169 try {2170 let parsed: StoredVault;2171 try {2172 const raw = JSON.parse(json) as unknown;2173 if (!hasValidVaultSchema(raw)) {2174 throw new Error("invalid_duress_slot_shape");2175 }2176 parsed = raw;2177 } catch (err) {2178 if (err instanceof SyntaxError) {2179 throw new Error("invalid_duress_slot_shape");2180 }2181 throw err;2182 }2183 await writeSlot(SLOT_B, parsed);2184 } finally { vaultWritesInFlight--; }2185}21862187218821892190219121922193219421952196219721982199220022012202220322042205export async function unlockFromCodex(params: {2206 slotA: string; 2207 slotB: string | null; 2208 timestamp: number;2209 masterPassphrase: string;2210}): Promise<2211 | { ok: true; entryCount: number }2212 | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2213> {2214 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2215 vaultReplacementInFlight = true;2216 try {2217 let parsedSlotA: StoredVault;2218 let parsedSlotB: StoredVault | null = null;2219 try {2220 const rawA = JSON.parse(params.slotA) as unknown;2221 if (!hasValidVaultSchema(rawA)) {2222 return { ok: false, reason: "invalid_slot_format" };2223 }2224 parsedSlotA = rawA;2225 if (params.slotB !== null) {2226 const rawB = JSON.parse(params.slotB) as unknown;2227 if (!hasValidVaultSchema(rawB)) {2228 return { ok: false, reason: "invalid_slot_format" };2229 }2230 parsedSlotB = rawB;2231 }2232 } catch {2233 return { ok: false, reason: "invalid_slot_format" };2234 }22352236 2237 2238 2239 const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2240 const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2241 if (!trialPayload) {2242 zeroKey(trialKey);2243 return { ok: false, reason: "wrong_passphrase" };2244 }2245 const hasEscrow =2246 !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2247 if (!hasEscrow) {2248 zeroKey(trialKey);2249 return { ok: false, reason: "missing_root_escrow" };2250 }2251 const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2252 if (!stagedRootKey) {2253 zeroKey(trialKey);2254 return { ok: false, reason: "wrong_passphrase" };2255 }2256 zeroKey(stagedRootKey);2257 zeroKey(trialKey);22582259 2260 const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);22612262 2263 22642265 2266 2267 await takeVaultSnapshot("restore");2268 const previousSlotA = await loadSlot(SLOT_A);2269 const previousSlotB = await loadSlot(SLOT_B);2270 let slotACommitted = false;2271 let slotBCommitted = false;2272 try {2273 await writeSlot(SLOT_A, parsedSlotA);2274 slotACommitted = true;2275 await writeSlot(SLOT_B, stagedSlotB);2276 slotBCommitted = true;2277 await chrome.storage.local.set({2278 peach_last_modified_at: String(params.timestamp),2279 });2280 } catch (err) {2281 if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2282 if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2283 throw err;2284 }22852286 2287 2288 const ok = await unlock(params.masterPassphrase);2289 if (!ok) {2290 2291 return { ok: false, reason: "wrong_passphrase" };2292 }2293 return { ok: true, entryCount: getEntries().length };2294 } finally {2295 vaultReplacementInFlight = false;2296 }2297}22982299230023012302export function getDerivedKeyHex(): string {2303 if (!derivedKey) throw new Error("vault_not_unlocked");2304 return hex(derivedKey);2305}23062307230823092310231123122313231423152316231723182319232023212322export function getRootKeyHex(): string | null {2323 return rootKey ? hex(rootKey) : null;2324}23252326export function getEntries(): VaultEntry[] {2327 if (!derivedKey) throw new Error("vault_locked");2328 return entries.filter((entry) => !entry.deletedAt);2329}23302331const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;23322333export function getIdentities(): SavedIdentity[] {2334 if (!derivedKey) throw new Error("vault_locked");2335 const active = entries.filter((e) => !e.deletedAt && e.type === "login");23362337 const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2338 const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();23392340 for (const entry of active) {2341 const domain = extractDomain(entry.url ?? "") ?? "";2342 const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;23432344 function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2345 const existing = map.get(v);2346 if (!existing || modifiedAt > existing.lastUsed) {2347 map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2348 } else {2349 map.set(v, { ...existing, count: existing.count + 1 });2350 }2351 }23522353 const uVal = entry.username?.trim();2354 if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);23552356 2357 2358 const eVal = entry.email?.trim();2359 if (eVal) tally(emailMap, eVal);2360 }23612362 const toIdentity = (type: "email" | "username") =>2363 ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2364 value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2365 });23662367 return [2368 ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2369 ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2370 ];2371}23722373export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2374 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");23752376 const now = Date.now();2377 const added: VaultEntry[] = [];2378 for (const draft of drafts) {2379 try {2380 const sanitized = sanitizeEntryDraft(draft);2381 const nextEntry: VaultEntry = {2382 ...sanitized,2383 id: crypto.randomUUID(),2384 createdAt: now,2385 modifiedAt: monotonicEntryTimestamp(),2386 };2387 entries.push(nextEntry);2388 added.push(nextEntry);2389 } catch {2390 2391 }2392 }23932394 if (added.length > 0) {2395 await persistEntries();2396 }23972398 return added;2399}240024012402240324042405240624072408export async function restoreEntries(2409 incoming: VaultEntry[],2410 mode: "replace" | "merge"2411): Promise<{ added: number; updated: number; skipped: number }> {2412 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");24132414 2415 2416 2417 if (mode === "replace" && incoming.length === 0) {2418 throw new Error("refuse to replace with empty entry set");2419 }24202421 let added = 0;2422 let updated = 0;2423 let skipped = 0;24242425 if (mode === "replace") {2426 entries = [];2427 for (const entry of incoming) {2428 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2429 if (!normalized) {2430 skipped += 1;2431 continue;2432 }2433 entries.push(normalized);2434 if (normalized.deletedAt) {2435 tombstones.set(2436 normalized.id,2437 Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2438 );2439 } else {2440 tombstones.delete(normalized.id);2441 }2442 added += 1;2443 }2444 } else {2445 const byId = new Map<string, VaultEntry>();2446 for (const e of entries) byId.set(e.id, e);24472448 for (const entry of incoming) {2449 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2450 if (!normalized) {2451 skipped += 1;2452 continue;2453 }2454 const existing = byId.get(normalized.id);2455 if (!existing) {2456 entries.push(normalized);2457 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2458 else tombstones.delete(normalized.id);2459 added += 1;2460 } else if (normalized.modifiedAt > existing.modifiedAt) {2461 const idx = entries.findIndex((e) => e.id === existing.id);2462 if (idx !== -1) {2463 entries[idx] = normalized;2464 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2465 else tombstones.delete(normalized.id);2466 updated += 1;2467 }2468 } else {2469 skipped += 1;2470 }2471 }2472 }24732474 await persistEntries("import");2475 return { added, updated, skipped };2476}247724782479248024812482248324842485248624872488248924902491249224932494const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;24952496function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {2497 if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;2498 return { ...entry, id: crypto.randomUUID() };2499}250025012502250325042505250625072508function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {2509 if (!entry || typeof entry !== "object") return null;2510 const title = typeof entry.title === "string" ? entry.title.trim() : "";2511 if (!title) return null;2512 const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();2513 const now = Date.now();2514 const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;2515 const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;25162517 2518 2519 const normalized = normalizeEntry({2520 ...entry,2521 id,2522 title,2523 type: entry.type ?? "login",2524 createdAt,2525 modifiedAt,2526 });25272528 if (normalized.passkey) {2529 normalized.passkey = sanitizePasskey(normalized.passkey);2530 }2531 if (normalized.canary) {2532 normalized.canary = sanitizeCanary(normalized.canary);2533 }2534 2535 normalized.tags = sanitizeTags(normalized.tags);25362537 2538 2539 if (2540 normalized.type === "login" &&2541 !normalized.passkey &&2542 typeof normalized.password !== "string"2543 ) {2544 return null;2545 }2546 if (entry.passkey && !normalized.passkey) {2547 2548 2549 return null;2550 }25512552 return normalized;2553}2554255525562557255825592560function sanitizePasskey(pk: unknown): PasskeyData | undefined {2561 if (!pk || typeof pk !== "object") return undefined;2562 const r = pk as Record<string, unknown>;2563 if (2564 typeof r.rpId !== "string" || !r.rpId ||2565 typeof r.credentialId !== "string" || !r.credentialId ||2566 typeof r.publicKeyCose !== "string" ||2567 typeof r.userHandle !== "string" ||2568 typeof r.userName !== "string"2569 ) {2570 return undefined;2571 }2572 return {2573 rpId: r.rpId,2574 rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2575 credentialId: r.credentialId,2576 publicKeyCose: r.publicKeyCose,2577 privateKeyJwk:2578 r.privateKeyJwk && typeof r.privateKeyJwk === "object"2579 ? (r.privateKeyJwk as JsonWebKey)2580 : undefined,2581 userHandle: r.userHandle,2582 userName: r.userName,2583 userDisplayName:2584 typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2585 algorithm: r.algorithm === -8 ? -8 : -7,2586 signCount: typeof r.signCount === "number" ? r.signCount : 0,2587 aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2588 backupEligible: r.backupEligible === true,2589 backupState: r.backupState === true,2590 lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2591 browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2592 transports: Array.isArray(r.transports)2593 ? r.transports.filter((t): t is string => typeof t === "string")2594 : undefined,2595 createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2596 };2597}25982599260026012602260326042605260626072608function sanitizeCanary(c: unknown): Canary | undefined {2609 if (!c || typeof c !== "object") return undefined;2610 const r = c as Record<string, unknown>;2611 if (typeof r.webhookUrl !== "string") return undefined;2612 let url: URL;2613 try {2614 url = new URL(r.webhookUrl);2615 } catch {2616 return undefined;2617 }2618 if (url.protocol !== "https:") return undefined;2619 return {2620 webhookUrl: url.toString(),2621 label: typeof r.label === "string" ? r.label : undefined,2622 lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2623 pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2624 };2625}26262627262826292630263126322633function sanitizeTags(tags: unknown): string[] | undefined {2634 if (!Array.isArray(tags)) return undefined;2635 const out: string[] = [];2636 for (const t of tags) {2637 if (typeof t !== "string") continue;2638 const trimmed = t.trim();2639 if (!trimmed) continue;2640 out.push(trimmed.slice(0, 256));2641 if (out.length >= 255) break;2642 }2643 return out.length > 0 ? out : undefined;2644}264526462647264826492650export async function clearVaultEntries(2651 confirmation: "REPLACE_ALL"2652): Promise<void> {2653 if (confirmation !== "REPLACE_ALL") {2654 throw new Error("clearVaultEntries requires explicit confirmation");2655 }2656 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2657 for (const entry of entries) {2658 if (!entry.deletedAt) {2659 const stamp = monotonicEntryTimestamp(Math.max(2660 entry.modifiedAt,2661 tombstones.get(entry.id) ?? 0,2662 ));2663 entry.deletedAt = stamp;2664 entry.modifiedAt = stamp;2665 tombstones.set(entry.id, stamp);2666 }2667 }2668 await persistEntries();2669}26702671export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2672 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");26732674 const sanitized = sanitizeEntryDraft(entry);2675 const now = Date.now();2676 const stamp = monotonicEntryTimestamp();2677 const nextEntry: VaultEntry = {2678 ...sanitized,2679 id: crypto.randomUUID(),2680 createdAt: now,2681 modifiedAt: stamp,2682 2683 2684 passwordChangedAt: sanitized.password ? stamp : undefined,2685 };26862687 2688 2689 2690 const rollback = entries;2691 entries = [...entries, nextEntry];2692 try {2693 await persistEntries();2694 } catch (err) {2695 entries = rollback;2696 throw err;2697 }26982699 2700 if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2701 const breachEpoch = vaultEpoch;2702 checkBreach(nextEntry.password).then(async (count) => {2703 if (count > 0 && breachEpoch === vaultEpoch && !vaultCreatesInFlight) {2704 const idx = entries.findIndex((e) => e.id === nextEntry.id);2705 if (idx !== -1) {2706 entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2707 await persistEntries();2708 }2709 }2710 });2711 }27122713 fireSyncTrigger("vault_change");27142715 return nextEntry;2716}27172718271927202721272227232724export async function consolidatePasskeyEntries(): Promise<void> {2725 if (!derivedKey || vaultCreatesInFlight) return;2726 const { merged } = mergePasskeyOnlyIntoLogins(entries);2727 if (merged) {2728 await persistEntries();2729 }2730}27312732export async function updateEntry(2733 id: string,2734 patch: Partial<VaultEntry>2735): Promise<void> {2736 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");27372738 const idx = entries.findIndex((entry) => entry.id === id);2739 if (idx === -1 || entries[idx].deletedAt) {2740 throw new Error("entry_not_found");2741 }27422743 const current = entries[idx];2744 const sanitizedPatch = sanitizeEntryPatch(patch);2745 2746 2747 2748 const passwordChanged =2749 "password" in patch &&2750 typeof sanitizedPatch.password === "string" &&2751 sanitizedPatch.password !== current.password;2752 const stamp = monotonicEntryTimestamp(current.modifiedAt);2753 2754 2755 2756 2757 2758 2759 2760 const priorPassword = current.password;2761 const shouldCapture =2762 passwordChanged &&2763 typeof priorPassword === "string" &&2764 priorPassword.length > 0 &&2765 current.passwordHistory?.[0]?.password !== priorPassword;2766 const nextHistory = shouldCapture2767 ? [2768 { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2769 ...(current.passwordHistory ?? []),2770 ].slice(0, PASSWORD_HISTORY_MAX)2771 : current.passwordHistory;2772 entries[idx] = {2773 ...current,2774 ...sanitizedPatch,2775 modifiedAt: stamp,2776 ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2777 };2778277927802781 2782 if (entries[idx].type === "card" && !entries[idx].cardNumber) {2783 entries[idx] = current;2784 throw new Error("card number is required for card entries");2785 }27862787 2788 2789 2790 2791 try {2792 await persistEntries();2793 } catch (err) {2794 entries[idx] = current;2795 throw err;2796 }27972798 2799 2800 if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2801 entries[idx] = { ...entries[idx], breach: undefined };2802 await persistEntries();2803 const password = entries[idx].password;2804 if (password) {2805 checkBreach(password).then(async (count) => {2806 const i = entries.findIndex((e) => e.id === id);2807 if (i !== -1 && count > 0) {2808 entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2809 await persistEntries();2810 }2811 });2812 }2813 }28142815 fireSyncTrigger("vault_change");2816}28172818export async function deleteEntry(id: string): Promise<void> {2819 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");28202821 const entry = entries.find((item) => item.id === id);2822 if (!entry || entry.deletedAt) {2823 throw new Error("entry_not_found");2824 }28252826 2827 2828 2829 const previousModifiedAt = entry.modifiedAt;2830 const previousTombstone = tombstones.get(id);2831 const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2832 entry.deletedAt = stamp;2833 entry.modifiedAt = stamp;2834 tombstones.set(id, stamp);2835 2836 2837 try {2838 await persistEntries();2839 } catch (err) {2840 delete entry.deletedAt;2841 entry.modifiedAt = previousModifiedAt;2842 if (previousTombstone === undefined) tombstones.delete(id);2843 else tombstones.set(id, previousTombstone);2844 throw err;2845 }2846 fireSyncTrigger("vault_change");2847}28482849export function getDeletedEntries(): VaultEntry[] {2850 if (!derivedKey) return [];2851 return entries.filter((e) => !!e.deletedAt);2852}285328542855export function getTombstoneManifest(): Record<string, number> {2856 if (!derivedKey) return {};2857 return Object.fromEntries(tombstones);2858}2859286028612862286328642865export async function getVaultVersion(): Promise<number> {2866 try {2867 const raw = await chrome.storage.local.get("peach_last_modified_at");2868 const v = (raw as Record<string, unknown>).peach_last_modified_at;2869 if (typeof v === "number") return v;2870 if (typeof v === "string" && v !== "") {2871 const n = Number.parseInt(v, 10);2872 return Number.isFinite(n) ? n : 0;2873 }2874 return 0;2875 } catch {2876 return 0;2877 }2878}2879288028812882288328842885288628872888288928902891export async function applyMergedRemoteEntries(2892 remoteEntries: VaultEntry[],2893 remoteTombstones: Record<string, number>,2894): Promise<{ received: number; applied: number; conflicts: number }> {2895 2896 2897 2898 2899 2900 2901 if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");29022903 const received = remoteEntries.length + Object.keys(remoteTombstones).length;2904 let applied = 0;2905 let conflicts = 0;29062907 const byId = new Map<string, VaultEntry>();2908 for (const e of entries) byId.set(e.id, e);29092910 const mergeNow = Date.now();2911 const remoteTombstoneTimes = new Map<string, number>();2912 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2913 if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {2914 remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));2915 }2916 }29172918 for (const remote of remoteEntries) {2919 const sanitized = sanitizeRestoredEntry(remote);2920 if (!sanitized) continue;2921 2922 2923 2924 sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2925 if (typeof sanitized.deletedAt === "number") {2926 sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2927 }2928 const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);2929 const localTombstoneTs = tombstones.get(sanitized.id);2930 const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);2931 if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {2932 continue;2933 }2934 const local = byId.get(sanitized.id);2935 if (!local) {2936 entries.push(sanitized);2937 byId.set(sanitized.id, sanitized);2938 tombstones.delete(sanitized.id);2939 applied += 1;2940 } else if (sanitized.modifiedAt > local.modifiedAt) {2941 const idx = entries.findIndex((e) => e.id === local.id);2942 if (idx !== -1) {2943 entries[idx] = sanitized;2944 byId.set(sanitized.id, sanitized);2945 tombstones.delete(sanitized.id);2946 applied += 1;2947 if (!local.deletedAt) conflicts += 1;2948 }2949 }2950 }29512952 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2953 if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;2954 2955 const deletedAt = remoteTombstoneTimes.get(id)!;2956 const knownTombstone = tombstones.get(id);2957 if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;2958 const local = byId.get(id);2959 if (!local) {2960 tombstones.set(id, deletedAt);2961 applied += 1;2962 continue;2963 }2964 if (local.deletedAt && local.deletedAt >= deletedAt) continue;2965 if (deletedAt < local.modifiedAt) continue;2966 const idx = entries.findIndex((e) => e.id === id);2967 if (idx !== -1) {2968 entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2969 tombstones.set(id, deletedAt);2970 applied += 1;2971 }2972 }29732974 if (applied > 0 && vaultMode === "real") {2975 await persistEntries("sync_received");2976 buildDomainIndexSync(entries);2977 2978 2979 2980 2981 try {2982 void chrome.runtime2983 .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })2984 .catch(() => undefined);2985 } catch {2986 2987 }2988 }2989 return { received, applied, conflicts };2990}29912992export async function restoreEntry(id: string): Promise<void> {2993 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2994 const entry = entries.find((e) => e.id === id && e.deletedAt);2995 if (!entry) throw new Error("deleted entry not found");2996 const previousDeletedAt = entry.deletedAt;2997 const previousModifiedAt = entry.modifiedAt;2998 const previousTombstone = tombstones.get(id);2999 delete entry.deletedAt;3000 entry.modifiedAt = monotonicEntryTimestamp(Math.max(3001 entry.modifiedAt,3002 previousTombstone ?? 0,3003 ));3004 tombstones.delete(id);3005 try {3006 await persistEntries();3007 } catch (err) {3008 entry.deletedAt = previousDeletedAt;3009 entry.modifiedAt = previousModifiedAt;3010 if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);3011 throw err;3012 }3013 buildDomainIndexSync(entries);3014}30153016export async function purgeEntry(id: string): Promise<void> {3017 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3018 const idx = entries.findIndex((e) => e.id === id && e.deletedAt);3019 if (idx === -1) throw new Error("deleted entry not found");3020 const entry = entries[idx]!;3021 tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));3022 entries.splice(idx, 1);3023 await persistEntries();3024}302530263027export async function purgeExpiredTrash(retentionMs: number): Promise<number> {3028 if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;3029 const cutoff = Date.now() - retentionMs;3030 const before = entries.length;3031 for (const entry of entries) {3032 if (entry.deletedAt && entry.deletedAt < cutoff) {3033 tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));3034 }3035 }3036 entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));3037 const purged = before - entries.length;3038 if (purged > 0) await persistEntries();3039 return purged;3040}30413042export function queryDomain(domain: string): VaultEntry[] {3043 return domainIndex.get(domain) ?? [];3044}30453046export function getEntryById(id: string): VaultEntry | undefined {3047 return entries.find((entry) => entry.id === id && !entry.deletedAt);3048}30493050async function persistSlotA(3051 reason: VaultSnapshot["reason"] = "local_save",3052): Promise<StoredVault> {3053 if (!derivedKey) throw new Error("vault_locked");3054 const epoch = vaultEpoch;3055 const throwIfStale = () => {3056 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3057 };30583059 const slotA = await loadSlot(SLOT_A);3060 throwIfStale();3061 if (!slotA) throw new Error("missing slot A");30623063 3064 3065 await takeVaultSnapshot(reason);3066 throwIfStale();30673068 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3069 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3070 throwIfStale();30713072 3073 const nextSlotA: StoredVault = {3074 ...slotA,3075 nonce,3076 ciphertext,3077 tag,3078 3079 };30803081 3082 3083 3084 3085 3086 3087 let slotACommitted = false;3088 try {3089 throwIfStale();3090 await writeSlot(SLOT_A, nextSlotA);3091 slotACommitted = true;3092 throwIfStale();30933094 3095 3096 3097 if (!duressConfigured) {3098 throwIfStale();3099 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3100 throwIfStale();3101 }3102 3103 3104 3105 3106 3107 if (reason !== "sync_received") {3108 throwIfStale();3109 await stampLocalVaultMutation();3110 throwIfStale();3111 }3112 } catch (err) {3113 3114 3115 if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3116 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3117 throw err;3118 }31193120 return nextSlotA;3121}31223123async function persistSlotB(): Promise<void> {3124 if (!derivedKey) throw new Error("vault_locked");31253126 const slotB = await loadSlot(SLOT_B);3127 if (!slotB) throw new Error("missing slot B");31283129 3130 3131 3132 3133 const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3134 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");31353136 await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3137 3138 3139 3140 try {3141 await stampLocalVaultMutation();3142 } catch (err) {3143 await writeSlot(SLOT_B, slotB).catch(() => {});3144 throw err;3145 }3146}31473148async function persistEntries(3149 reason: VaultSnapshot["reason"] = "local_save",3150): Promise<void> {3151 if (vaultCreatesInFlight) throw new Error("vault_changed");3152 vaultWritesInFlight++;3153 try {3154 if (!derivedKey) throw new Error("vault_locked");31553156 3157 3158 const previousTombstones = tombstones;3159 tombstones = new Map(tombstones);3160 reconcileTombstones();3161 try {3162 if (vaultMode === "decoy") {3163 await persistSlotB();3164 } else {3165 await persistSlotA(reason);3166 }3167 } catch (err) {3168 tombstones = previousTombstones;3169 throw err;3170 }3171 buildDomainIndexSync(entries);3172 await refreshLockedSyncState();3173 } finally { vaultWritesInFlight--; }3174}3175317631773178317931803181function allowHttpUrl(url: string | undefined): string {3182 const trimmed = url?.trim() ?? "";3183 if (!trimmed) return "";3184 try {3185 const parsed = new URL(trimmed);3186 if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3187 } catch {3188 3189 }3190 return trimmed;3191}31923193function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3194 if (!Array.isArray(values)) return undefined;3195 const seen = new Set<string>();3196 const cleaned: string[] = [];3197 for (const value of values) {3198 const trimmed = typeof value === "string" ? value.trim() : "";3199 if (!trimmed) continue;3200 if (!allowHttpUrl(trimmed)) continue;3201 const key = trimmed.toLowerCase();3202 if (seen.has(key)) continue;3203 seen.add(key);3204 cleaned.push(trimmed);3205 }3206 return cleaned.length > 0 ? cleaned : undefined;3207}32083209function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3210 const title = entry.title.trim();3211 const type: VaultEntry["type"] = entry.type ?? "login";32123213 if (!title) throw new Error("title is required");32143215 if (entry.passkey) {3216 const p = entry.passkey;3217 if (3218 !p.rpId ||3219 !p.credentialId ||3220 !p.publicKeyCose ||3221 !p.userHandle ||3222 !p.userName ||3223 (p.algorithm !== -7 && p.algorithm !== -8)3224 ) {3225 throw new Error("invalid passkey credential");3226 }3227 }3228 if (type === "card") {3229 if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3230 throw new Error("cardholder name and card number are required");3231 }3232 }32333234 return {3235 type,3236 title,3237 username: type === "login" ? entry.username?.trim() ?? "" : undefined,3238 email: type === "login" ? entry.email?.trim() || undefined : undefined,3239 password: type === "login" ? entry.password : undefined,3240 url: type === "login" ? allowHttpUrl(entry.url) : undefined,3241 additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3242 totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3243 3244 3245 totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3246 totpDigits: type === "login" ? entry.totpDigits : undefined,3247 totpPeriod: type === "login" ? entry.totpPeriod : undefined,3248 notes: entry.notes?.trim() || undefined,3249 breach: type === "login" ? entry.breach : undefined,3250 3251 3252 canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3253 tags: sanitizeTags(entry.tags),3254 passkey: entry.passkey,3255 cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3256 cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3257 expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3258 expYear: type === "card" ? entry.expYear?.trim() : undefined,3259 cvc: type === "card" ? entry.cvc?.trim() : undefined,3260 cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3261 network: type === "card" ? entry.network : undefined,3262 last4: type === "card" ? entry.last4?.trim() : undefined,3263 };3264}32653266function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3267 const nextPatch: Partial<VaultEntry> = {};32683269 if ("type" in patch) {3270 nextPatch.type = patch.type;3271 }32723273 if ("title" in patch) {3274 const title = patch.title?.trim() ?? "";3275 if (!title) throw new Error("title is required");3276 nextPatch.title = title;3277 }32783279 if ("url" in patch) {3280 nextPatch.url = allowHttpUrl(patch.url);3281 }32823283 if ("additionalUrls" in patch) {3284 const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3285 const seen = new Set<string>();3286 const cleaned: string[] = [];3287 for (const value of incoming) {3288 const trimmed = typeof value === "string" ? value.trim() : "";3289 if (!trimmed || !allowHttpUrl(trimmed)) continue;3290 const key = trimmed.toLowerCase();3291 if (seen.has(key)) continue;3292 seen.add(key);3293 cleaned.push(trimmed);3294 }3295 nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3296 }32973298 if ("username" in patch) {3299 nextPatch.username = patch.username?.trim() ?? "";3300 }33013302 if ("email" in patch) {3303 nextPatch.email = patch.email?.trim() || undefined;3304 }33053306 if ("password" in patch) {3307 const password = patch.password ?? "";3308 3309 nextPatch.password = password || undefined;3310 }33113312 if ("totp" in patch) {3313 nextPatch.totp = patch.totp?.trim() || undefined;3314 }33153316 if ("totpAlgorithm" in patch) {3317 nextPatch.totpAlgorithm = patch.totpAlgorithm;3318 }33193320 if ("totpDigits" in patch) {3321 nextPatch.totpDigits = patch.totpDigits;3322 }33233324 if ("totpPeriod" in patch) {3325 nextPatch.totpPeriod = patch.totpPeriod;3326 }33273328 if ("notes" in patch) {3329 nextPatch.notes = patch.notes?.trim() || undefined;3330 }33313332 if ("breach" in patch) {3333 nextPatch.breach = patch.breach;3334 }33353336 if ("canary" in patch) {3337 3338 3339 nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3340 }33413342 if ("passkey" in patch) {3343 3344 3345 if (patch.passkey === undefined || patch.passkey === null) {3346 nextPatch.passkey = undefined;3347 } else {3348 const sanitized = sanitizePasskey(patch.passkey);3349 if (!sanitized) throw new Error("invalid passkey credential");3350 nextPatch.passkey = sanitized;3351 }3352 }33533354 if ("tags" in patch) {3355 3356 nextPatch.tags = sanitizeTags(patch.tags);3357 }33583359 if ("cardholderName" in patch) {3360 nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3361 }3362 if ("cardNumber" in patch) {3363 const n = patch.cardNumber ?? "";3364 nextPatch.cardNumber = n || undefined;3365 }3366 if ("expMonth" in patch) {3367 nextPatch.expMonth = patch.expMonth?.trim() || undefined;3368 }3369 if ("expYear" in patch) {3370 nextPatch.expYear = patch.expYear?.trim() || undefined;3371 }3372 if ("cvc" in patch) {3373 nextPatch.cvc = patch.cvc?.trim() || undefined;3374 }3375 if ("cardNickname" in patch) {3376 nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3377 }3378 if ("network" in patch) {3379 nextPatch.network = patch.network;3380 }3381 if ("last4" in patch) {3382 nextPatch.last4 = patch.last4?.trim() || undefined;3383 }33843385 return nextPatch;3386}33873388function normalizeEntry(entry: VaultEntry): VaultEntry {3389 const base: VaultEntry = {3390 id: entry.id,3391 type: entry.type,3392 title: entry.title,3393 username: entry.username,3394 email: entry.email,3395 password: entry.password,3396 url: entry.url,3397 additionalUrls:3398 "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3399 ? entry.additionalUrls3400 : undefined,3401 totp: entry.totp,3402 3403 totpAlgorithm: entry.totpAlgorithm,3404 totpDigits: entry.totpDigits,3405 totpPeriod: entry.totpPeriod,3406 notes: entry.notes,3407 breach: entry.breach,3408 3409 3410 3411 passwordChangedAt:3412 "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3413 3414 3415 3416 passwordHistory:3417 "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3418 ? entry.passwordHistory3419 : undefined,3420 canary: entry.canary,3421 passkey: entry.passkey,3422 createdAt: entry.createdAt,3423 modifiedAt: entry.modifiedAt,3424 deletedAt: entry.deletedAt,3425 tags: entry.tags,3426 cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3427 cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3428 expMonth: "expMonth" in entry ? entry.expMonth : undefined,3429 expYear: "expYear" in entry ? entry.expYear : undefined,3430 cvc: "cvc" in entry ? entry.cvc : undefined,3431 cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3432 network: "network" in entry ? entry.network : undefined,3433 last4: "last4" in entry ? entry.last4 : undefined,3434 };34353436 return base;3437}3438343934403441344234433444function entryDupeKey(e: VaultEntry): string {3445 if (e.type === "note") return `note|${e.title.toLowerCase()}`;3446 3447 3448 3449 3450 if (e.passkey) {3451 return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;3452 }3453 return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3454}345534563457export function countDuplicates(): number {3458 const best = new Map<string, VaultEntry>();3459 let dupeCount = 0;3460 for (const e of entries.filter((e) => !e.deletedAt)) {3461 const key = entryDupeKey(e);3462 const existing = best.get(key);3463 if (!existing) {3464 best.set(key, e);3465 } else {3466 dupeCount++;3467 3468 if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3469 best.set(key, e);3470 }3471 }3472 }3473 return dupeCount;3474}347534763477347834793480export async function deduplicateEntries(): Promise<number> {3481 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3482 3483 3484 if (vaultMode === "decoy") {3485 throw new Error("deduplicate disabled in decoy mode");3486 }34873488 const best = new Map<string, VaultEntry>();3489 for (const e of entries.filter((en) => !en.deletedAt)) {3490 const key = entryDupeKey(e);3491 const existing = best.get(key);3492 if (!existing) {3493 best.set(key, e);3494 } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3495 best.set(key, e);3496 }3497 }34983499 const keepIds = new Set(Array.from(best.values()).map((e) => e.id));3500 let removed = 0;3501 entries = entries.map((e) => {3502 if (!e.deletedAt && !keepIds.has(e.id)) {3503 removed++;3504 const deletedAt = monotonicEntryTimestamp(Math.max(3505 e.modifiedAt,3506 tombstones.get(e.id) ?? 0,3507 ));3508 tombstones.set(e.id, deletedAt);3509 return { ...e, deletedAt };3510 }3511 return e;3512 });35133514 if (removed > 0) await persistEntries();3515 return removed;3516}351735183519352035213522352335243525const HISTORY_KEY = "peach_vault_history";3526const HISTORY_MAX = 5;352735283529353035313532function bucketEntryCount(n: number): number {3533 if (n <= 0) return 0;3534 if (n <= 10) return 10;3535 if (n <= 25) return 25;3536 if (n <= 50) return 50;3537 if (n <= 100) return 100;3538 if (n <= 250) return 250;3539 if (n <= 500) return 500;3540 return Math.ceil(n / 500) * 500;3541}35423543354435453546354735483549export async function takeVaultSnapshot(3550 reason: VaultSnapshot["reason"],3551): Promise<void> {3552 if (recoveryInFlight || vaultCreatesInFlight) return;3553 3554 3555 3556 if (vaultMode === "decoy") return;3557 vaultWritesInFlight++;3558 try {3559 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);3560 const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];3561 const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];35623563 3564 3565 3566 if (!slotA) return;35673568 const vault_a = JSON.stringify(slotA);3569 const vault_b = JSON.stringify(slotB ?? slotA);35703571 3572 3573 3574 3575 3576 3577 let entryCount: number | null = null;3578 if (derivedKey && vaultMode === "real") {3579 try {3580 entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);3581 } catch {3582 entryCount = null;3583 }3584 }35853586 const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3587 const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)3588 ? existingRaw3589 : { snapshots: [] };35903591 3592 3593 3594 const latest = history.snapshots[0];3595 if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3596 return;3597 }35983599 const snapshot: VaultSnapshot = {3600 id: crypto.randomUUID(),3601 savedAt: Date.now(),3602 reason,3603 vault_a,3604 vault_b,3605 entryCount,3606 };36073608 history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3609 if (recoveryInFlight || vaultCreatesInFlight) return;3610 await chrome.storage.local.set({ [HISTORY_KEY]: history });3611 } catch (err) {3612 3613 3614 3615 3616 console.warn('[Peach] takeVaultSnapshot failed:', err);3617 if (String(err).includes('QUOTA') || String(err).includes('quota')) {3618 try {3619 await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3620 } catch {3621 3622 }3623 }3624 } finally { vaultWritesInFlight--; }3625}362636273628export async function clearVaultHistory(): Promise<void> {3629 if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");3630 vaultWritesInFlight++;3631 try {3632 await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3633 } catch {3634 3635 } finally { vaultWritesInFlight--; }3636}363736383639export async function getVaultHistory(): Promise<VaultSnapshot[]> {3640 if (vaultMode === "decoy") return [];3641 const raw = await chrome.storage.local.get(HISTORY_KEY);3642 const value = (raw as Record<string, unknown>)[HISTORY_KEY];3643 return sanitizeHistory(value);3644}364536463647364836493650export async function restoreVaultSnapshot(3651 snapshotId: string,3652): Promise<{ ok: true } | { ok: false; error: string }> {3653 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };3654 vaultReplacementInFlight = true;3655 try {3656 if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3657 const history = await getVaultHistory();3658 const snapshot = history.find((s) => s.id === snapshotId);3659 if (!snapshot) return { ok: false, error: "snapshot_not_found" };36603661 const restoredA = parseHistorySlot(snapshot.vault_a);3662 const restoredB = parseHistorySlot(snapshot.vault_b);3663 if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };36643665 await takeVaultSnapshot("restore");3666 const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3667 const previousA = (current as Record<string, unknown>)[SLOT_A];3668 const previousB = (current as Record<string, unknown>)[SLOT_B];3669 try {3670 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };3671 await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3672 await stampLocalVaultMutation();3673 } catch {3674 try {3675 await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3676 } catch {3677 3678 }3679 return { ok: false, error: "snapshot_corrupt" };3680 }36813682 await lock();3683 return { ok: true };3684 } finally {3685 vaultReplacementInFlight = false;3686 }3687}368836893690369136923693369436953696369736983699370037013702export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3703 if (vaultCreatesInFlight) throw new Error("vault_changed");3704 vaultWritesInFlight++;3705 try {3706 if (!derivedKey || vaultMode !== "real") {3707 return { ok: false, error: "vault_locked" };3708 }3709 const slotA = await loadSlot(SLOT_A);3710 if (!slotA) return { ok: false, error: "missing_slot_a" };37113712 3713 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3714 await generateAndWrapRootKey();37153716 3717 const newRootKey = unhex(rawRootKey);3718 const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");3719 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);37203721 3722 3723 3724 3725 await takeVaultSnapshot("local_save");3726 const nextSlotA: StoredVault = {3727 ...slotA,3728 recovery_vault_key: recoveryVaultKey,3729 recovery_salt: recoverySalt,3730 recovery_wrapped_root_key: wrappedRootKey,3731 recovery_nonce: wrappedNonce,3732 recovery_tag: wrappedTag,3733 ...pwRoot,3734 };3735 await writeSlot(SLOT_A, nextSlotA);37363737 3738 if (rootKey) zeroKey(rootKey);3739 rootKey = newRootKey;37403741 3742 3743 await notifyIdentityKeysRotated();37443745 3746 3747 3748 await clearPairedDevices();3749 await clearPairSecrets();37503751 3752 await setRecoveryConfirmPending(); 37533754 await stampLocalVaultMutation();3755 return { ok: true };3756 } finally { vaultWritesInFlight--; }3757}37583759376037613762376337643765export async function changePassword(3766 currentPassword: string,3767 newPassword: string3768): Promise<boolean> {3769 if (vaultCreatesInFlight) throw new Error("vault_changed");3770 vaultWritesInFlight++;3771 try {37723773 const epoch = vaultEpoch;3774 const stale = () => epoch !== vaultEpoch;3775 if (!derivedKey || vaultMode !== "real") return false;37763777 3778 const valid = await verifyMainPassword(currentPassword);3779 if (!valid) return false;37803781 const slotA = await loadSlot(SLOT_A);3782 if (!slotA) return false;3783 if (!rootKey) return false;37843785 3786 const newSalt = generateSalt();3787 const newKey = await deriveKey(newPassword, newSalt);3788 if (stale()) {3789 zeroKey(newKey);3790 return false;3791 }37923793 3794 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3795 const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");37963797 3798 3799 3800 const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);38013802 const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");3803 const finalSlotA: StoredVault = {3804 ...slotA,3805 recovery_vault_key: recoveryVaultKey,3806 salt: hex(newSalt),3807 nonce,3808 ciphertext,3809 tag,3810 ...pwRoot,3811 };38123813 3814 3815 3816 await takeVaultSnapshot("local_save");38173818 3819 3820 3821 3822 await writeSlot(SLOT_A, finalSlotA);3823 if (stale()) {3824 zeroKey(newKey);3825 return false;3826 }38273828 3829 3830 3831 zeroKey(derivedKey);3832 derivedKey = newKey;38333834 3835 3836 3837 3838 if (stale()) {3839 await lock();3840 return false;3841 }3842 await saveSessionKey(newKey, "real", epoch);3843 if (stale()) return false;38443845 3846 3847 3848 await notifyIdentityKeysRotated();3849 if (stale()) return false;38503851 3852 3853 3854 if (!duressConfigured) {3855 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3856 }3857 await clearPinUnlockStorage();3858 await stampLocalVaultMutation();38593860 return true;3861 } finally { vaultWritesInFlight--; }3862}