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 vaultReplacementInFlight = false;91let entries: VaultEntry[] = [];92939495let tombstones = new Map<string, number>();96let domainIndex: Map<string, VaultEntry[]> = new Map();97let vaultMode: "real" | "decoy" = "real";9899100101let duressConfigured = false;102103104105106107108109110111112let lastUnlockFailureReason: string | null = null;113114export function consumeLastUnlockFailureReason(): string | null {115 const r = lastUnlockFailureReason;116 lastUnlockFailureReason = null;117 return r;118}119120121122123124export type TextSize = "small" | "medium" | "large";125126export interface VaultSettings {127 accentColor?: AccentColorName;128 theme?: "dark" | "light";129 autoLockMinutes?: number;130 clipboardClearSeconds?: number;131 lockOnClose?: boolean;132 breachMonitoring?: boolean;133 passkeyProviderEnabled?: boolean;134 trashRetentionDays?: number;135 manualSummonDomains?: Record<string, ManualSummonRecord>;136 manualSummonSalt?: string;137 declinedCardFingerprints?: string[];138139 140 metadataVersion?: 1;141 142143144145146 textSize?: TextSize;147 148149150151152 reduceMotion?: boolean;153 154 lockedSyncRequiresUnlock?: boolean;155 156 pinEnabled?: boolean;157 158 pinPreferred?: boolean;159 160161162163164165166 shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;167}168169interface StoredPinWrap {170 version: 1;171 salt: string;172 nonce: string;173 ciphertext: string;174 tag: string;175}176177const PIN_WRAP_STORAGE = "peach_pin_wrap";178const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";179const PIN_MIN_LENGTH = 4;180const PIN_MAX_LENGTH = 12;181const PIN_MAX_ATTEMPTS = 3;182183let settings: VaultSettings = {};184const CARD_DECLINE_MAX = 256;185186const CARD_DECLINE_DIGEST_HEX = 32;187188async function metadataDigest(value: string, key: string): Promise<string> {189 const bytes = new TextEncoder().encode(`${key}:${value}`);190 const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));191 return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");192}193194let inMemoryPinWrap: StoredPinWrap | null = null;195let inMemoryPinFailedAttempts = 0;196let sessionPinStorageFailed = false;197198export function getSettings(): VaultSettings {199 return settings;200}201202export async function ensureSettingsLoaded(): Promise<VaultSettings> {203 await loadSettings();204 return settings;205}206207export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {208 await loadSettings();209 210 211 212 213 const safe = Object.fromEntries(214 Object.entries(patch).filter(215 ([k]) => !["__proto__", "constructor", "prototype"].includes(k),216 ),217 ) as Partial<VaultSettings>;218 settings = { ...settings, ...safe };219 await persistSettings();220}221222function isValidPin(pin: string): boolean {223 return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);224}225226227export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {228 if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;229 if (!(await verifyMainPassword(currentPassword))) return false;230231 const salt = generateSalt();232 const pinKey = await deriveKey(pin, salt);233 try {234 const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");235 await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });236 await updateSettings({ pinEnabled: true });237 return true;238 } finally {239 zeroKey(pinKey);240 }241}242243async function clearPinUnlockStorage(): Promise<void> {244 inMemoryPinWrap = null;245 inMemoryPinFailedAttempts = 0;246 sessionPinStorageFailed = false;247 if (chrome.storage.session) {248 await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);249 }250 await updateSettings({ pinEnabled: false });251}252253254export async function disablePinUnlock(currentPassword: string): Promise<boolean> {255 if (!derivedKey || vaultMode !== "real") return false;256 if (!(await verifyMainPassword(currentPassword))) return false;257 await clearPinUnlockStorage();258 return true;259}260261262export async function unlockWithPin(pin: string): Promise<boolean> {263 if (recoveryInFlight || vaultRemovalsInFlight) return false;264 if (!isValidPin(pin)) return false;265 await loadSettings();266 if (!settings.pinEnabled) return false;267268 const { stored, failedAttempts } = await loadPinState();269 if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;270 if (271 !stored ||272 stored.version !== 1 ||273 !stored.salt ||274 !stored.nonce ||275 !stored.ciphertext ||276 !stored.tag277 ) return false;278279 const pinKey = await deriveKey(pin, unhex(stored.salt));280 let unwrappedKey: Uint8Array | null = null;281 try {282 const masterKeyHex = await decrypt(283 pinKey,284 stored.nonce,285 stored.ciphertext,286 stored.tag,287 "pin_wrap_v1",288 );289 if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;290 unwrappedKey = unhex(masterKeyHex);291 const result = await unlockWithKey(masterKeyHex);292 if (!result.ok) return false;293 await resetPinFailedAttempts();294 return true;295 } catch {296 await recordPinFailure(failedAttempts + 1);297 return false;298 } finally {299 zeroKey(pinKey);300 if (unwrappedKey) zeroKey(unwrappedKey);301 }302}303304async function savePinWrap(stored: StoredPinWrap): Promise<void> {305 inMemoryPinWrap = stored;306 inMemoryPinFailedAttempts = 0;307 sessionPinStorageFailed = !chrome.storage.session;308 if (!chrome.storage.session) return;309 try {310 await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });311 sessionPinStorageFailed = false;312 } catch {313 314 sessionPinStorageFailed = true;315 }316}317318async function loadPinState(): Promise<{319 stored: StoredPinWrap | undefined;320 failedAttempts: number;321}> {322 if (!chrome.storage.session) {323 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };324 }325 try {326 const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);327 return {328 stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??329 (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),330 failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"331 ? result[PIN_ATTEMPTS_STORAGE]332 : 0,333 };334 } catch {335 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };336 }337}338339async function recordPinFailure(failedAttempts: number): Promise<void> {340 inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);341 if (!chrome.storage.session) return;342 try {343 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });344 } catch { }345}346347async function resetPinFailedAttempts(): Promise<void> {348 inMemoryPinFailedAttempts = 0;349 if (!chrome.storage.session) return;350 try {351 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });352 } catch { }353}354355export async function getPinUnlockStatus(): Promise<{356 configured: boolean;357 available: boolean;358 attemptsRemaining: number;359}> {360 await loadSettings();361 if (!settings.pinEnabled) {362 return { configured: false, available: false, attemptsRemaining: 0 };363 }364 const { stored, failedAttempts } = await loadPinState();365 const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;366 return {367 configured: true,368 available,369 attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,370 };371}372373async function persistSettings(): Promise<void> {374 try {375 await chrome.storage.local.set({376 peach_settings: {377 ...settings,378 manualSummonDomains: undefined,379 manualSummonSalt: undefined,380 cardFingerprintSalt: undefined,381 declinedCardFingerprints: settings.declinedCardFingerprints ?? [],382 metadataVersion: 1,383 },384 });385 } catch (err) {386 throw mapStorageError(err);387 }388}389390function mapStorageError(err: unknown): Error {391 const message = err instanceof Error ? err.message : String(err);392 if (/QUOTA_BYTES|quota/i.test(message)) {393 return new Error("STORAGE_QUOTA_EXCEEDED");394 }395 return err instanceof Error ? err : new Error(message);396}397398async function loadSettings(): Promise<void> {399 const result = await chrome.storage.local.get("peach_settings");400 settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};401}402403404405function fireSyncTrigger(reason: "vault_change"): void {406 void Promise.resolve()407 .then(() => triggerSyncIfReachable({ reason }))408 .catch(() => {409 410 });411}412export function lockedSyncRequiresUnlock(): boolean {413 return settings.lockedSyncRequiresUnlock === true;414}415416let lockedSyncRefreshHook: (() => Promise<void>) | null = null;417let lockedSyncUnlockHook: (() => Promise<void>) | null = null;418let decoySyncTeardownHook: (() => void) | null = null;419export type IdentityHooks = {420 421 onSessionEnded: () => Promise<void>;422 423 onKeysRotated: () => Promise<void>;424 425 onVaultCreated: (password: string) => Promise<void>;426};427428let identityHooks: IdentityHooks | null = null;429430export function setIdentityHooks(hooks: IdentityHooks): void {431 identityHooks = hooks;432}433434async function notifyIdentitySessionEnded(): Promise<void> {435 await identityHooks?.onSessionEnded().catch((error) => {436 console.warn("[Peach] local identity cache clear failed:", error);437 });438}439440async function notifyIdentityKeysRotated(): Promise<void> {441 await identityHooks?.onKeysRotated().catch((error) => {442 console.warn("[Peach] local identity re-wrap failed:", error);443 });444}445446export type SealedBox = { nonce: string; ciphertext: string; tag: string };447export type IdentityKeyEnvelope = {448 root?: SealedBox;449 local?: SealedBox;450 pending?: SealedBox;451 pendingSalt?: string;452};453454export function setLockedSyncHooks(hooks: {455 refresh: () => Promise<void>;456 afterUnlock: () => Promise<void>;457 onDecoy?: () => void;458}): void {459 lockedSyncRefreshHook = hooks.refresh;460 lockedSyncUnlockHook = hooks.afterUnlock;461 decoySyncTeardownHook = hooks.onDecoy ?? null;462}463464async function refreshLockedSyncState(): Promise<void> {465 if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;466 await lockedSyncRefreshHook().catch((error) => {467 console.warn("[Peach sync] locked spool refresh failed:", error);468 });469}470471472473474475export async function checkBreach(password: string): Promise<number> {476 477 478 const encoder = new TextEncoder();479 const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));480 const hashHex = Array.from(new Uint8Array(hashBuffer))481 .map((b) => b.toString(16).padStart(2, "0"))482 .join("")483 .toUpperCase();484485 const prefix = hashHex.slice(0, 5);486 const suffix = hashHex.slice(5);487488 try {489 490 491 const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {492 headers: { "Add-Padding": "true" },493 });494 if (!res.ok) return 0;495 const text = await res.text();496 const match = text.split("\r\n").find((l) => l.startsWith(suffix));497 return match ? parseInt(match.split(":")[1], 10) : 0;498 } catch {499 return 0; 500 }501}502503export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {504 505 const key = await cardDeclineKey();506 if (!key) return;507 const fingerprint = await cardFingerprint(last4, expMonth, expYear);508 await loadSettings();509 settings = {510 ...settings,511 declinedCardFingerprints: [512 513 514 ...(settings.declinedCardFingerprints ?? []).filter(515 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,516 ),517 await metadataDigest(fingerprint, key),518 ].slice(-CARD_DECLINE_MAX),519 };520 await persistSettings();521}522523export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {524 await loadSettings();525 const key = await cardDeclineKey();526 if (!key) return false;527 const fingerprint = await cardFingerprint(last4, expMonth, expYear);528 const candidate = await metadataDigest(fingerprint, key);529 return (settings.declinedCardFingerprints ?? []).some(530 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,531 );532}533534535536537538539540541542543544545async function cardDeclineKey(): Promise<string | null> {546 const root = getRootKeyHex();547 if (!root) return null;548 const digest = new Uint8Array(549 await crypto.subtle.digest(550 "SHA-256",551 new TextEncoder().encode(`peach-card-decline-v1:${root}`),552 ),553 );554 return hex(digest);555}556557async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {558 const encoder = new TextEncoder();559 const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));560 return Array.from(new Uint8Array(buf).slice(0, 8))561 .map((b) => b.toString(16).padStart(2, "0"))562 .join("");563}564565function hex(buf: Uint8Array): string {566 return Array.from(buf)567 .map((b) => b.toString(16).padStart(2, "0"))568 .join("");569}570571function unhex(s: string): Uint8Array {572 const out = new Uint8Array(s.length / 2);573 for (let i = 0; i < s.length; i += 2) {574 out[i / 2] = parseInt(s.slice(i, i + 2), 16);575 }576 return out;577}578579580581582583584585586587588589590591592593594595596597598async function generateAndWrapRootKey(): Promise<{599 rawRootKey: string; 600 recoverySalt: string;601 wrappedRootKey: string;602 wrappedNonce: string;603 wrappedTag: string;604}> {605 const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));606607 608 const words = await rootKeyToWords(rootKeyBytes);609 const wordMaterial = await wordsToRootKeyMaterial(words);610 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));611 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);612613 614 615 const nonce = crypto.getRandomValues(new Uint8Array(12));616 const encoded = new TextEncoder().encode(hex(rootKeyBytes));617 const raw = await crypto.subtle.encrypt(618 {619 name: "AES-GCM",620 iv: nonce,621 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,622 tagLength: 128,623 },624 recoveryKey,625 encoded626 );627 628 const rawU8 = new Uint8Array(raw);629 const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));630 const tag = hex(rawU8.slice(rawU8.length - 16));631632 return {633 rawRootKey: hex(rootKeyBytes),634 recoverySalt: hex(recoverySalt),635 wrappedRootKey: ciphertext,636 wrappedNonce: hex(nonce),637 wrappedTag: tag,638 };639}640641async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{642 recoverySalt: string;643 wrappedRootKey: string;644 wrappedNonce: string;645 wrappedTag: string;646}> {647 if (rootKeyBytes.length !== 32) {648 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");649 }650651 const words = await rootKeyToWords(rootKeyBytes);652 const wordMaterial = await wordsToRootKeyMaterial(words);653 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));654 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);655 const nonce = crypto.getRandomValues(new Uint8Array(12));656 const encoded = new TextEncoder().encode(hex(rootKeyBytes));657 const raw = await crypto.subtle.encrypt(658 {659 name: "AES-GCM",660 iv: nonce,661 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,662 tagLength: 128,663 },664 recoveryKey,665 encoded,666 );667 const rawU8 = new Uint8Array(raw);668 return {669 recoverySalt: hex(recoverySalt),670 wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),671 wrappedNonce: hex(nonce),672 wrappedTag: hex(rawU8.slice(rawU8.length - 16)),673 };674}675676677678679680async function unwrapRootKeyForRecovery(681 wrappedRootKey: string,682 wrappedNonce: string,683 wrappedTag: string,684 recoverySaltHex: string,685 words: string[]686): Promise<Uint8Array> {687 const wordMaterial = await wordsToRootKeyMaterial(words);688 const recoverySalt = unhex(recoverySaltHex);689 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);690691 692 693 694 695 696 const nonceRaw = unhex(wrappedNonce);697 const ciphertextRaw = unhex(wrappedRootKey);698 const tagRaw = unhex(wrappedTag);699 700 701 const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;702 const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);703 combined.set(ciphertextRaw, 0);704 combined.set(tagRaw, ciphertextRaw.length);705 const raw = await crypto.subtle.decrypt(706 { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },707 recoveryKey,708 combined709 );710 const decryptedHex = new TextDecoder().decode(raw);711 const recovered = unhex(decryptedHex);712 if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }713 return recovered;714}715716717export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {718 if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");719 if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");720 recoveryInFlight = true;721 let settle!: () => void;722 recoverySettled = new Promise<void>((resolve) => { settle = resolve; });723 const epoch = ++vaultEpoch;724 const check = () => {725 if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");726 };727 let recoveredRoot: Uint8Array | null = null;728 let oldKey: Uint8Array | null = null;729 let newKey: Uint8Array | null = null;730 let committed = false;731 try {732 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);733 check();734 const slot = raw[SLOT_A] as StoredVault | undefined;735 if (!slot) throw new Error("no_vault");736 if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");737 try {738 recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,739 slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);740 } catch {741 throw new Error("invalid_recovery_words");742 }743 check();744 if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");745 oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");746 check();747 if (!oldKey) throw new Error("recovery_data_unavailable");748 const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");749 check();750 if (result.status !== "ok") throw new Error("recovery_data_unavailable");751 const payload = result.payload;752 await loadSettings();753 check();754 const salt = generateSalt();755 newKey = await deriveKey(newPassword, salt);756 check();757 758 const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");759 const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");760 const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);761 const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");762 check();763 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);764 check();765 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");766 const history = raw[HISTORY_KEY] as VaultHistory | undefined;767 const snapshot: VaultSnapshot = {768 id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",769 vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,770 };771 const previousStamp = Number(raw.peach_last_modified_at);772 const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,773 salt: hex(salt), recovery_vault_key: recoveryVaultKey };774 775 await chrome.storage.local.set({776 [SLOT_A]: nextSlot,777 [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },778 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),779 });780 committed = true;781 check();782 derivedKey = newKey;783 rootKey = recoveredRoot;784 newKey = null;785 recoveredRoot = null;786 entries = payload.entries;787 tombstones = payload.tombstones;788 duressConfigured = payload.duressConfigured;789 vaultMode = "real";790 buildDomainIndexSync(entries);791 await saveSessionKey(derivedKey, "real", epoch);792 if (epoch !== vaultEpoch) throw new Error("vault_locked");793 await identityHooks?.onKeysRotated();794 if (epoch !== vaultEpoch) throw new Error("vault_locked");795 await reconcilePairSecrets(rootKey);796 if (epoch !== vaultEpoch) throw new Error("vault_locked");797 await clearPinUnlockStorage();798 if (epoch !== vaultEpoch) throw new Error("vault_locked");799 touchAutoLock();800 return { committed: true, unlocked: true };801 } catch (error) {802 if (committed) {803 console.warn("[Peach] recovery password saved; unlock required:", error);804 if (derivedKey && epoch === vaultEpoch) {805 try { await lock(); }806 catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }807 }808 return { committed: true, unlocked: false };809 }810 if (derivedKey && epoch === vaultEpoch) await lock();811 throw error;812 } finally {813 if (oldKey) zeroKey(oldKey);814 if (newKey) zeroKey(newKey);815 if (recoveredRoot) zeroKey(recoveredRoot);816 recoveryInFlight = false;817 settle();818 }819}820821822export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {823 vaultRemovalsInFlight++;824 try {825 await lock();826 await recoverySettled;827 return await remove();828 } finally {829 vaultRemovalsInFlight--;830 }831}832833834835836837838839840841842async function deriveRootKeyFromDerivedKey(843 derivedKeyBytes: Uint8Array,844 slotA: StoredVault,845): Promise<Uint8Array | null> {846 if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {847 return null;848 }849 try {850 const rootHex = await decrypt(851 derivedKeyBytes,852 slotA.pw_root_nonce,853 slotA.pw_root_ciphertext,854 slotA.pw_root_tag,855 "pw_root_v1",856 );857 return unhex(rootHex);858 } catch {859 return null;860 }861}862863export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {864 if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");865 866 867 const [root, local] = await Promise.all([868 encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),869 encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),870 ]);871 return { root, local };872}873874export async function sealIdentityKeyPreVault(875 password: string,876 ik: Uint8Array,877): Promise<IdentityKeyEnvelope> {878 const salt = generateSalt();879 const key = await deriveKey(password, salt);880 try {881 const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");882 return { pending, pendingSalt: hex(salt) };883 } finally {884 zeroKey(key);885 }886}887888889890891892893894895896export async function openIdentityKey(897 env: IdentityKeyEnvelope,898 password?: string,899): Promise<Uint8Array | null> {900 if (env.local && derivedKey) {901 const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");902 if (ik) return ik;903 }904 if (env.root && rootKey) {905 const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");906 if (ik) return ik;907 }908 if (!env.pending || !env.pendingSalt || password === undefined) return null;909 let key: Uint8Array;910 try {911 const salt = unhex(env.pendingSalt);912 key = await deriveKey(password, salt);913 salt.fill(0);914 } catch {915 return null;916 }917 try {918 return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");919 } finally {920 zeroKey(key);921 }922}923924925async function openSealedKey(926 key: Uint8Array,927 box: SealedBox,928 info: string,929): Promise<Uint8Array | null> {930 try {931 const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));932 if (value.length === 32) return value;933 value.fill(0);934 return null;935 } catch {936 return null;937 }938}939940941942async function wrapRootKeyForDerivedKey(943 derivedKeyBytes: Uint8Array,944 rootKeyBytes: Uint8Array,945): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {946 const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");947 return {948 pw_root_ciphertext: ciphertext,949 pw_root_nonce: nonce,950 pw_root_tag: tag,951 };952}953954955export async function getRecoveryWords(): Promise<string[]> {956 if (!rootKey) {957 throw new Error("recovery not set up");958 }959 return rootKeyToWords(rootKey);960}961962async function loadSlot(key: string): Promise<StoredVault | null> {963 const result = await chrome.storage.local.get(key);964 return (result as Record<string, StoredVault | undefined>)[key] ?? null;965}966967async function writeSlot(key: string, vault: StoredVault): Promise<void> {968 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");969 vaultWritesInFlight++;970 try {971 await chrome.storage.local.set({ [key]: vault });972 } catch (err) {973 throw mapStorageError(err);974 } finally {975 vaultWritesInFlight--;976 }977}978979980981982983984985986987988export async function rollbackAdoptedVault(): Promise<void> {989 await withVaultRemoval(async () => {990 try {991 await chrome.storage.local.remove([992 SLOT_A,993 SLOT_B,994 "peach_last_modified_at",995 ]);996 } catch (err) {997 throw mapStorageError(err);998 }999 });1000}10011002async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1003 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1004 vaultWritesInFlight++;1005 try {1006 const raw = await chrome.storage.local.get("peach_last_modified_at");1007 const previous = Number(1008 (raw as Record<string, unknown>).peach_last_modified_at,1009 );1010 const next = Math.max(1011 Date.now(),1012 Number.isFinite(previous) ? previous + 1 : 0,1013 );1014 try {1015 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1016 await chrome.storage.local.set({1017 [SLOT_A]: slotA,1018 [SLOT_B]: slotB,1019 peach_last_modified_at: String(next),1020 });1021 } catch (err) {1022 throw mapStorageError(err);1023 }1024 } finally {1025 vaultWritesInFlight--;1026 }1027}102810291030103110321033103410351036let lastEntryTimestamp = 0;1037function monotonicEntryTimestamp(currentModifiedAt?: number): number {1038 const base = Math.max(1039 Date.now(),1040 (currentModifiedAt ?? 0) + 1,1041 lastEntryTimestamp + 1,1042 );1043 lastEntryTimestamp = base;1044 return base;1045}10461047async function stampLocalVaultMutation(): Promise<void> {1048 const raw = await chrome.storage.local.get("peach_last_modified_at");1049 const previous = Number(1050 (raw as Record<string, unknown>).peach_last_modified_at,1051 );1052 const next = Math.max(1053 Date.now(),1054 Number.isFinite(previous) ? previous + 1 : 0,1055 );1056 await chrome.storage.local.set({1057 peach_last_modified_at: String(next),1058 });1059}106010611062106310641065106610671068106910701071function padPlaintext(json: string, minBytes = 0): string {1072 const encoded = new TextEncoder().encode(json);1073 const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1074 1075 const target = Math.max(bucket, minBytes);1076 const padLen = target - encoded.length;1077 return json + " ".repeat(padLen);1078}107910801081108210831084108510861087108810891090const CSPRNG_CHUNK = 65_536;10911092function fillRandom(buf: Uint8Array): Uint8Array {1093 for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1094 const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1095 const chunk = new Uint8Array(end - offset);1096 crypto.getRandomValues(chunk);1097 buf.set(chunk, offset);1098 }1099 return buf;1100}11011102function generateNoiseBlob(ciphertextBytes: number): StoredVault {1103 const salt = crypto.getRandomValues(new Uint8Array(16));1104 const nonce = crypto.getRandomValues(new Uint8Array(12));1105 const cipher = fillRandom(new Uint8Array(ciphertextBytes));1106 const tag = crypto.getRandomValues(new Uint8Array(16));1107 return {1108 version: 1,1109 salt: hex(salt),1110 nonce: hex(nonce),1111 ciphertext: hex(cipher),1112 tag: hex(tag),1113 };1114}111511161117111811191120type VaultPayload = {1121 entries: VaultEntry[];1122 tombstones?: Record<string, number>;1123 duressConfigured?: boolean;1124};11251126type DecryptedPayload = {1127 entries: VaultEntry[];1128 tombstones: Map<string, number>;1129 duressConfigured: boolean;1130};11311132function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1133 const envelope: VaultPayload = {1134 entries,1135 tombstones: Object.fromEntries(tombstones),1136 duressConfigured: duress,1137 };1138 return padPlaintext(JSON.stringify(envelope), minBytes);1139}11401141function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1142 const result = new Map<string, number>();1143 if (raw && typeof raw === "object" && !Array.isArray(raw)) {1144 for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1145 if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1146 result.set(id, timestamp);1147 }1148 }1149 }1150 1151 1152 for (const entry of allEntries) {1153 if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1154 continue;1155 }1156 if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1157 result.set(entry.id, entry.deletedAt);1158 }1159 }1160 return result;1161}11621163function reconcileTombstones(): void {1164 const byId = new Map(entries.map((entry) => [entry.id, entry]));1165 for (const [id] of tombstones) {1166 if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1167 }1168 for (const entry of entries) {1169 if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1170 if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1171 tombstones.set(entry.id, entry.deletedAt);1172 }1173 }1174 }1175}11761177function decodePayload(plain: string): DecryptedPayload {1178 const parsed = JSON.parse(plain) as VaultPayload;1179 if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1180 throw new Error("invalid vault payload");1181 }1182 const normalized = parsed.entries.map(normalizeEntry);1183 return {1184 entries: normalized,1185 tombstones: decodeTombstones(parsed.tombstones, normalized),1186 duressConfigured: parsed.duressConfigured === true,1187 };1188}1189119011911192119311941195119611971198119912001201120212031204120512061207120812091210function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1211 let merged = false;1212 const now = Date.now();12131214 const candidates = entries.filter((e) => !e.deletedAt && e.passkey);1215 const byRpId = new Map<string, VaultEntry[]>();1216 for (const e of candidates) {1217 const rpId = e.passkey!.rpId;1218 const list = byRpId.get(rpId);1219 if (list) list.push(e);1220 else byRpId.set(rpId, [e]);1221 }12221223 for (const [rpId, group] of byRpId) {1224 if (group.length === 0) continue;1225 group.sort((a, b) => {1226 const aT =1227 a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;1228 const bT =1229 b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;1230 return bT - aT;1231 });1232 const winner = group[0]!;12331234 1235 1236 1237 const loginTarget = entries.find((e) => {1238 if (e.deletedAt || e.passkey || e.type !== "login") return false;1239 if (e.url && extractDomain(e.url) === rpId) return true;1240 for (const extra of e.additionalUrls ?? []) {1241 if (extractDomain(extra) === rpId) return true;1242 }1243 return false;1244 });12451246 if (loginTarget) {1247 loginTarget.passkey = winner.passkey;1248 1249 1250 1251 if (!loginTarget.totp && winner.totp) {1252 loginTarget.totp = winner.totp;1253 loginTarget.totpAlgorithm = winner.totpAlgorithm;1254 loginTarget.totpDigits = winner.totpDigits;1255 loginTarget.totpPeriod = winner.totpPeriod;1256 }1257 loginTarget.modifiedAt = now;1258 for (const dup of group) {1259 if (!dup.deletedAt) {1260 dup.deletedAt = now;1261 dup.modifiedAt = now;1262 }1263 }1264 merged = true;1265 } else if (group.length > 1) {1266 for (let i = 1; i < group.length; i += 1) {1267 const dup = group[i]!;1268 if (!dup.deletedAt) {1269 dup.deletedAt = now;1270 dup.modifiedAt = now;1271 }1272 }1273 merged = true;1274 }1275 }12761277 return { merged };1278}12791280128112821283128412851286function hasValidVaultSchema(v: unknown): v is StoredVault {1287 if (typeof v !== "object" || v === null) return false;1288 const r = v as Record<string, unknown>;1289 return (1290 r.version === 1 &&1291 typeof r.salt === "string" &&1292 typeof r.nonce === "string" &&1293 typeof r.ciphertext === "string" &&1294 typeof r.tag === "string"1295 );1296}1297const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;12981299function hasValidHistorySlot(value: unknown): value is StoredVault {1300 if (!hasValidVaultSchema(value)) return false;1301 return /^[0-9a-f]{32}$/i.test(value.salt) &&1302 /^[0-9a-f]{24}$/i.test(value.nonce) &&1303 /^[0-9a-f]+$/i.test(value.ciphertext) &&1304 value.ciphertext.length % 2 === 0 &&1305 value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1306 /^[0-9a-f]{32}$/i.test(value.tag);1307}13081309function parseHistorySlot(value: string): StoredVault | null {1310 try {1311 const parsed: unknown = JSON.parse(value);1312 return hasValidHistorySlot(parsed) ? parsed : null;1313 } catch {1314 return null;1315 }1316}13171318function isHistoryRecord(value: unknown): value is VaultSnapshot {1319 if (typeof value !== "object" || value === null) return false;1320 const record = value as Record<string, unknown>;1321 return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1322 typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1323 typeof record.reason === "string" &&1324 typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1325 typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1326 (record.entryCount === null || typeof record.entryCount === "number");1327}13281329function sanitizeHistory(value: unknown): VaultSnapshot[] {1330 if (typeof value !== "object" || value === null) return [];1331 if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1332 return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1333}13341335export type TryDecryptResult =1336 | { status: "ok"; payload: DecryptedPayload }1337 | { status: "wrong_key" }1338 | { status: "corrupted"; reason: string };1339134013411342134313441345export async function tryDecryptSlot(1346 vault: StoredVault,1347 key: Uint8Array,1348 aadTag?: string,1349): Promise<DecryptedPayload | null> {1350 const res = await tryDecryptSlotResult(vault, key, aadTag);1351 return res.status === "ok" ? res.payload : null;1352}13531354export async function tryDecryptSlotResult(1355 vault: StoredVault,1356 key: Uint8Array,1357 aadTag?: string,1358): Promise<TryDecryptResult> {1359 if (!hasValidVaultSchema(vault)) {1360 return { status: "corrupted", reason: "invalid_slot_schema" };1361 }1362 let plain: string;1363 try {1364 plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1365 } catch {1366 return { status: "wrong_key" };1367 }1368 try {1369 const parsed = JSON.parse(plain) as unknown;1370 if (typeof parsed !== "object" || parsed === null) {1371 return { status: "corrupted", reason: "invalid_payload_shape" };1372 }1373 if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1374 return { status: "corrupted", reason: "invalid_payload_shape" };1375 }1376 return { status: "ok", payload: decodePayload(plain) };1377 } catch {1378 return { status: "corrupted", reason: "invalid_payload_json" };1379 }1380}138113821383138413851386function buildDomainIndexSync(all: VaultEntry[]): void {1387 domainIndex = new Map();13881389 for (const entry of all) {1390 if (entry.deletedAt) continue;1391 if (entry.type === "note" || entry.type === "card") continue;13921393 1394 1395 1396 1397 const domains = new Set<string>();1398 const primary = extractDomain(entry.url ?? "");1399 if (primary) domains.add(primary);1400 for (const extra of entry.additionalUrls ?? []) {1401 const d = extractDomain(extra);1402 if (d) domains.add(d);1403 }1404 if (domains.size === 0) continue;14051406 for (const domain of domains) {1407 const bucket = domainIndex.get(domain) ?? [];1408 bucket.push(entry);1409 domainIndex.set(domain, bucket);1410 }1411 }1412}14131414export async function createVault(password: string): Promise<void> {1415 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1416 vaultCreatesInFlight++;1417 try {1418 const epoch = vaultEpoch;1419 const salt = generateSalt();1420 const key = await deriveKey(password, salt);1421 if (epoch !== vaultEpoch) { zeroKey(key); throw new Error("vault_changed"); }1422 if (recoveryInFlight || vaultRemovalsInFlight) { zeroKey(key); throw new Error("recovery_in_progress"); }1423 derivedKey = key;1424 entries = [];1425 tombstones = new Map();1426 vaultMode = "real";1427 duressConfigured = false;1428 buildDomainIndexSync(entries);14291430 1431 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =1432 await generateAndWrapRootKey();1433 if (epoch !== vaultEpoch) throw new Error("vault_changed");1434 rootKey = unhex(rawRootKey);14351436 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1437 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");14381439 1440 1441 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);14421443 const slotA: StoredVault = {1444 recovery_vault_key: await encrypt(rootKey, hex(derivedKey), "recovery_vault_key_v1"),1445 version: 1,1446 salt: hex(salt),1447 nonce,1448 ciphertext,1449 tag,1450 recovery_salt: recoverySalt,1451 recovery_wrapped_root_key: wrappedRootKey,1452 recovery_nonce: wrappedNonce,1453 recovery_tag: wrappedTag,1454 ...pwRoot,1455 };1456 if (epoch !== vaultEpoch) throw new Error("vault_changed");1457 await writeSlot(SLOT_A, slotA);14581459 1460 1461 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1462 await stampLocalVaultMutation();14631464 1465 1466 await identityHooks?.onVaultCreated(password).catch((error) => {1467 console.warn("[Peach] local identity promotion failed:", error);1468 });14691470 touchAutoLock();1471 } finally {1472 vaultCreatesInFlight--;1473 }1474}1475147614771478147914801481export async function createVaultFromRootKey(1482 password: string,1483 rootKeyHex: string,1484): Promise<{ vaultId: string }> {1485 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1486 if (typeof password !== "string" || password.length === 0) {1487 throw new Error("ADOPT_INVALID_PASSWORD");1488 }1489 if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1490 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1491 }14921493 const rootKeyBytes = unhex(rootKeyHex);1494 if (rootKeyBytes.length !== 32) {1495 rootKeyBytes.fill(0);1496 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1497 }14981499 let nextDerivedKey: Uint8Array | null = null;1500 let sessionRootKey: Uint8Array | null = null;1501 try {1502 if ((await loadSlot(SLOT_A)) !== null) {1503 throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1504 }15051506 const nextEntries: VaultEntry[] = [];1507 const nextDuressConfigured = false;1508 const vaultId = await computeVaultId(rootKeyBytes);1509 const salt = generateSalt();1510 nextDerivedKey = await deriveKey(password, salt);1511 const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);15121513 sessionRootKey = new Uint8Array(rootKeyBytes);1514 const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1515 const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1516 const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1517 const slotA: StoredVault = {1518 recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),1519 version: 1,1520 salt: hex(salt),1521 nonce,1522 ciphertext,1523 tag,1524 recovery_salt: recovery.recoverySalt,1525 recovery_wrapped_root_key: recovery.wrappedRootKey,1526 recovery_nonce: recovery.wrappedNonce,1527 recovery_tag: recovery.wrappedTag,1528 ...pwRoot,1529 };1530 const slotB = generateNoiseBlob(ciphertext.length / 2);1531 await commitCreatedVaultSlots(slotA, slotB);15321533 const previousDerivedKey = derivedKey;1534 const previousRootKey = rootKey;1535 derivedKey = nextDerivedKey;1536 rootKey = sessionRootKey;1537 nextDerivedKey = null;1538 sessionRootKey = null;1539 entries = nextEntries;1540 tombstones = new Map();1541 vaultMode = "real";1542 duressConfigured = nextDuressConfigured;1543 buildDomainIndexSync(entries);1544 if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1545 if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1546 touchAutoLock();15471548 1549 1550 await identityHooks?.onVaultCreated(password).catch((error) => {1551 console.warn("[Peach] local identity promotion failed:", error);1552 });15531554 return { vaultId };1555 } finally {1556 rootKeyBytes.fill(0);1557 if (nextDerivedKey) zeroKey(nextDerivedKey);1558 if (sessionRootKey) sessionRootKey.fill(0);1559 }1560}15611562export async function hasVault(): Promise<boolean> {1563 return (await loadSlot(SLOT_A)) !== null;1564}1565156615671568156915701571export async function isDuressEnabled(): Promise<boolean> {1572 return vaultMode === "real" && duressConfigured;1573}15741575export async function setupDuress(duressPassword: string): Promise<void> {1576 if (!derivedKey || vaultMode !== "real") {1577 throw new Error("vault must be unlocked in real mode");1578 }1579 1580 1581 1582 const slotA = await loadSlot(SLOT_A);1583 if (!slotA) throw new Error("missing slot A");15841585 const decoySalt = generateSalt();1586 const decoyKey = await deriveKey(duressPassword, decoySalt);1587 try {1588 1589 1590 1591 1592 const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1593 const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1594 await writeSlot(SLOT_B, {1595 version: 1,1596 salt: hex(decoySalt),1597 nonce,1598 ciphertext,1599 tag,1600 });1601 } finally {1602 zeroKey(decoyKey);1603 }16041605 1606 1607 duressConfigured = true;1608 await persistSlotA();1609}16101611export async function disableDuress(): Promise<void> {1612 if (!derivedKey || vaultMode !== "real") {1613 throw new Error("vault must be unlocked in real mode");1614 }1615 1616 1617 1618 const slotA = await loadSlot(SLOT_A);1619 if (slotA) {1620 await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1621 }16221623 duressConfigured = false;1624 await persistSlotA();1625}16261627162816291630163116321633export async function verifyMainPassword(password: string): Promise<boolean> {1634 const slotA = await loadSlot(SLOT_A);1635 if (!slotA) return false;1636 const key = await deriveKey(password, unhex(slotA.salt));1637 try {1638 return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1639 } finally {1640 zeroKey(key);1641 }1642}16431644export async function unlock(password: string): Promise<boolean> {1645 return attemptUnlockWithDerive(password, deriveKey);1646}16471648async function attemptUnlockWithDerive(1649 password: string,1650 derive: typeof deriveKey,1651): Promise<boolean> {1652 if (recoveryInFlight || vaultRemovalsInFlight) return false;1653 const epoch = vaultEpoch;1654 const stale = () => epoch !== vaultEpoch;1655 1656 1657 1658 1659 1660 1661 const [slotA, slotB] = await Promise.all([1662 loadSlot(SLOT_A),1663 loadSlot(SLOT_B),1664 ]);16651666 1667 const [keyA, keyB] = await Promise.all([1668 slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1669 slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1670 ]);16711672 1673 1674 1675 const [resultA, resultB] = await Promise.all([1676 keyA && slotA1677 ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1678 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1679 keyB && slotB1680 ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1681 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1682 ]);1683 const payloadA = resultA.status === "ok" ? resultA.payload : null;1684 const payloadB = resultB.status === "ok" ? resultB.payload : null;16851686 if (stale()) {1687 if (keyA) zeroKey(keyA);1688 if (keyB) zeroKey(keyB);1689 return false;1690 }16911692 if (payloadA && keyA) {1693 if (stale()) {1694 zeroKey(keyA);1695 if (keyB) zeroKey(keyB);1696 return false;1697 }1698 derivedKey = keyA;1699 vaultMode = "real";1700 entries = payloadA.entries;1701 tombstones = payloadA.tombstones;1702 duressConfigured = payloadA.duressConfigured;1703 buildDomainIndexSync(entries);1704 await loadSettings();1705 if (stale()) {1706 await lock();1707 return false;1708 }1709 touchAutoLock();1710 if (keyB) zeroKey(keyB);17111712 1713 1714 rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;1715 if (!rootKey) {1716 await lock();1717 return false;1718 }17191720 1721 if (slotA) {1722 const escrowed = slotA.recovery_vault_key1723 ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;1724 const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);1725 if (escrowed) zeroKey(escrowed);1726 if (stale()) { await lock(); return false; }1727 if (!matches) {1728 try {1729 const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");1730 if (stale()) { await lock(); return false; }1731 await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });1732 if (stale()) { await lock(); return false; }1733 } catch (error) {1734 await lock();1735 throw error;1736 }1737 }1738 }17391740 1741 1742 await reconcilePairSecrets(rootKey);1743 if (stale()) {1744 await lock();1745 return false;1746 }1747 await lockedSyncUnlockHook?.().catch((error) => {1748 console.warn("[Peach sync] locked inbox drain failed:", error);1749 });1750 if (stale()) {1751 await lock();1752 return false;1753 }1754 await resetPinFailedAttempts();1755 if (stale()) {1756 await lock();1757 return false;1758 }1759 await saveSessionKey(keyA, "real", epoch);1760 if (stale()) return false;1761 return true;1762 }17631764 if (payloadB && keyB) {1765 if (stale()) {1766 zeroKey(keyB);1767 if (keyA) zeroKey(keyA);1768 return false;1769 }1770 derivedKey = keyB;1771 vaultMode = "decoy";1772 decoySyncTeardownHook?.();1773 1774 1775 1776 if (rootKey) {1777 rootKey.fill(0);1778 rootKey = null;1779 }1780 entries = payloadB.entries;1781 tombstones = payloadB.tombstones;1782 duressConfigured = false;1783 buildDomainIndexSync(entries);1784 await loadSettings();1785 touchAutoLock();1786 if (keyA) zeroKey(keyA);1787 1788 await dropSessionCache();1789 1790 await notifyIdentitySessionEnded();1791 if (stale()) {1792 await lock();1793 return false;1794 }1795 await saveSessionKey(keyB, "decoy", epoch);1796 if (stale()) return false;1797 return true;1798 }17991800 if (keyA) zeroKey(keyA);1801 if (keyB) zeroKey(keyB);1802 1803 1804 if (resultA.status === "corrupted") {1805 lastUnlockFailureReason = resultA.reason;1806 } else if (resultB.status === "corrupted") {1807 lastUnlockFailureReason = resultB.reason;1808 }1809 return false;1810}18111812181318141815181618171818const SESSION_KEY_STORAGE = "peach_session_dk";1819182018211822let sessionKeyMutation = Promise.resolve();18231824function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {1825 const task = sessionKeyMutation.then(mutation, mutation);1826 sessionKeyMutation = task.catch(() => undefined);1827 return task;1828}182918301831183218331834let sessionEscrowAvailable = true;18351836183718381839184018411842export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {1843 setSessionAllowed(sessionEscrow);1844 if (sessionEscrow) return;1845 sessionEscrowAvailable = false;1846 await clearSessionKey();1847}18481849async function saveSessionKey(1850 key: Uint8Array,1851 mode: "real" | "decoy",1852 expectedEpoch = vaultEpoch,1853): Promise<void> {1854 const session = chrome.storage.session;1855 if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1856 const stored = { keyHex: hex(key), mode };1857 await mutateSessionKey(async () => {1858 if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1859 await session.set({ [SESSION_KEY_STORAGE]: stored });1860 });1861}18621863async function clearSessionKey(): Promise<void> {1864 const session = chrome.storage.session;1865 if (!session) return;1866 await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));1867}18681869187018711872187318741875let vaultEpoch = 0;1876187718781879let restoreInFlight: Promise<boolean> | null = null;188018811882188318841885188618871888export async function restoreFromSession(): Promise<boolean> {1889 if (recoveryInFlight || vaultRemovalsInFlight) return false;1890 if (derivedKey !== null) return true;1891 if (restoreInFlight) return restoreInFlight;1892 const task = restoreFromSessionInner();1893 restoreInFlight = task;1894 try {1895 return await task;1896 } finally {1897 restoreInFlight = null;1898 }1899}19001901async function restoreFromSessionInner(): Promise<boolean> {1902 const epoch = vaultEpoch;1903 const stale = () => epoch !== vaultEpoch;1904 if (derivedKey !== null) return true;1905 if (!sessionEscrowAvailable) return false;1906 if (!chrome.storage.session) return false;1907 const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1908 if (stale()) return false;1909 const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1910 if (!entry?.keyHex) return false;19111912 const key = unhex(entry.keyHex);1913 const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1914 const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1915 const slot = await loadSlot(slotKey);1916 if (stale()) { zeroKey(key); return false; }1917 if (!slot) { await clearSessionKey(); return false; }19181919 const result = await tryDecryptSlotResult(slot, key, aadTag);1920 if (stale()) { zeroKey(key); return false; }1921 if (result.status !== "ok") { await clearSessionKey(); return false; }19221923 1924 1925 const payload = result.payload;1926 await loadSettings();1927 if (stale()) { zeroKey(key); return false; }19281929 1930 1931 let freshRoot: Uint8Array | null = null;1932 if (entry.mode === "real") {1933 freshRoot = await deriveRootKeyFromDerivedKey(key, slot);1934 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1935 if (!freshRoot) {1936 await lock();1937 return false;1938 }1939 }19401941 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1942 if (freshRoot) {1943 1944 await reconcilePairSecrets(freshRoot);1945 if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }1946 } else {1947 1948 await dropSessionCache();1949 1950 await notifyIdentitySessionEnded();1951 if (stale()) { zeroKey(key); return false; }1952 }1953 derivedKey = key;1954 vaultMode = entry.mode;1955 if (entry.mode === "decoy") decoySyncTeardownHook?.();1956 entries = payload.entries;1957 tombstones = payload.tombstones;1958 duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;1959 if (freshRoot) rootKey = freshRoot;1960 buildDomainIndexSync(entries);1961 touchAutoLock();19621963 await lockedSyncUnlockHook?.().catch((error) => {1964 console.warn("[Peach sync] locked inbox drain failed:", error);1965 });1966 if (stale()) return false;19671968 return true;1969}19701971export async function lock(): Promise<void> {1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 vaultEpoch++;1982 if (derivedKey) {1983 zeroKey(derivedKey);1984 derivedKey = null;1985 }1986 if (rootKey) {1987 rootKey.fill(0);1988 rootKey = null;1989 }19901991 entries = [];1992 tombstones = new Map();1993 domainIndex = new Map();1994 vaultMode = "real";1995 duressConfigured = false;1996 clearAutoLock();1997 await clearSessionKey();1998 1999 2000 await notifyIdentitySessionEnded();2001}20022003export function isUnlocked(): boolean {2004 return derivedKey !== null;2005}20062007export function isDecoyMode(): boolean {2008 return derivedKey !== null && vaultMode === "decoy";2009}20102011201220132014export async function unlockWithKey(2015 masterKeyHex: string,2016): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2017 if (recoveryInFlight || vaultRemovalsInFlight) return { ok: false, error: "recovery_in_progress" };2018 const epoch = vaultEpoch;2019 const stale = () => epoch !== vaultEpoch;2020 let masterKeyBytes: Uint8Array | null = null;2021 try {2022 masterKeyBytes = unhex(masterKeyHex);2023 const stored = await loadSlot(SLOT_A);2024 if (!stored) return { ok: false, error: "invalid_key" };2025 const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2026 if (!payload || stale()) {2027 zeroKey(masterKeyBytes);2028 return { ok: false, error: "invalid_key" };2029 }20302031 derivedKey = masterKeyBytes;2032 vaultMode = "real";2033 entries = payload.entries;2034 tombstones = payload.tombstones;2035 duressConfigured = payload.duressConfigured;2036 buildDomainIndexSync(entries);2037 await loadSettings();2038 touchAutoLock();20392040 rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2041 if (!rootKey) {2042 await lock();2043 return { ok: false, error: "invalid_key" };2044 }2045 await reconcilePairSecrets(rootKey);2046 if (stale()) {2047 await lock();2048 return { ok: false, error: "invalid_key" };2049 }2050 await saveSessionKey(masterKeyBytes, "real", epoch);2051 if (stale()) return { ok: false, error: "invalid_key" };2052 return { ok: true, entries };2053 } catch {2054 if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2055 return { ok: false, error: "invalid_key" };2056 }2057}205820592060206120622063206420652066export async function exportDuressSlotForAdoption(): Promise<string | null> {2067 if (!(await isDuressEnabled())) return null;2068 const slotB = await loadSlot(SLOT_B);2069 if (!slotB) return null;2070 return JSON.stringify(slotB);2071}20722073207420752076207720782079export async function installAdoptedDuressSlot(json: string): Promise<void> {2080 let parsed: StoredVault;2081 try {2082 const raw = JSON.parse(json) as unknown;2083 if (!hasValidVaultSchema(raw)) {2084 throw new Error("invalid_duress_slot_shape");2085 }2086 parsed = raw;2087 } catch (err) {2088 if (err instanceof SyntaxError) {2089 throw new Error("invalid_duress_slot_shape");2090 }2091 throw err;2092 }2093 await writeSlot(SLOT_B, parsed);2094}20952096209720982099210021012102210321042105210621072108210921102111211221132114export async function unlockFromCodex(params: {2115 slotA: string; 2116 slotB: string | null; 2117 timestamp: number;2118 masterPassphrase: string;2119}): Promise<2120 | { ok: true; entryCount: number }2121 | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2122> {2123 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight) throw new Error("vault_changed");2124 vaultReplacementInFlight = true;2125 try {2126 let parsedSlotA: StoredVault;2127 let parsedSlotB: StoredVault | null = null;2128 try {2129 const rawA = JSON.parse(params.slotA) as unknown;2130 if (!hasValidVaultSchema(rawA)) {2131 return { ok: false, reason: "invalid_slot_format" };2132 }2133 parsedSlotA = rawA;2134 if (params.slotB !== null) {2135 const rawB = JSON.parse(params.slotB) as unknown;2136 if (!hasValidVaultSchema(rawB)) {2137 return { ok: false, reason: "invalid_slot_format" };2138 }2139 parsedSlotB = rawB;2140 }2141 } catch {2142 return { ok: false, reason: "invalid_slot_format" };2143 }21442145 2146 2147 2148 const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2149 const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2150 if (!trialPayload) {2151 zeroKey(trialKey);2152 return { ok: false, reason: "wrong_passphrase" };2153 }2154 const hasEscrow =2155 !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2156 if (!hasEscrow) {2157 zeroKey(trialKey);2158 return { ok: false, reason: "missing_root_escrow" };2159 }2160 const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2161 if (!stagedRootKey) {2162 zeroKey(trialKey);2163 return { ok: false, reason: "wrong_passphrase" };2164 }2165 zeroKey(stagedRootKey);2166 zeroKey(trialKey);21672168 2169 const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);21702171 2172 21732174 2175 2176 await takeVaultSnapshot("restore");2177 const previousSlotA = await loadSlot(SLOT_A);2178 const previousSlotB = await loadSlot(SLOT_B);2179 let slotACommitted = false;2180 let slotBCommitted = false;2181 try {2182 await writeSlot(SLOT_A, parsedSlotA);2183 slotACommitted = true;2184 await writeSlot(SLOT_B, stagedSlotB);2185 slotBCommitted = true;2186 await chrome.storage.local.set({2187 peach_last_modified_at: String(params.timestamp),2188 });2189 } catch (err) {2190 if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2191 if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2192 throw err;2193 }21942195 2196 2197 const ok = await unlock(params.masterPassphrase);2198 if (!ok) {2199 2200 return { ok: false, reason: "wrong_passphrase" };2201 }2202 return { ok: true, entryCount: getEntries().length };2203 } finally {2204 vaultReplacementInFlight = false;2205 }2206}22072208220922102211export function getDerivedKeyHex(): string {2212 if (!derivedKey) throw new Error("vault_not_unlocked");2213 return hex(derivedKey);2214}22152216221722182219222022212222222322242225222622272228222922302231export function getRootKeyHex(): string | null {2232 return rootKey ? hex(rootKey) : null;2233}22342235export function getEntries(): VaultEntry[] {2236 if (!derivedKey) throw new Error("vault_locked");2237 return entries.filter((entry) => !entry.deletedAt);2238}22392240const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;22412242export function getIdentities(): SavedIdentity[] {2243 if (!derivedKey) throw new Error("vault_locked");2244 const active = entries.filter((e) => !e.deletedAt && e.type === "login");22452246 const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2247 const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();22482249 for (const entry of active) {2250 const domain = extractDomain(entry.url ?? "") ?? "";2251 const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;22522253 function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2254 const existing = map.get(v);2255 if (!existing || modifiedAt > existing.lastUsed) {2256 map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2257 } else {2258 map.set(v, { ...existing, count: existing.count + 1 });2259 }2260 }22612262 const uVal = entry.username?.trim();2263 if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);22642265 2266 2267 const eVal = entry.email?.trim();2268 if (eVal) tally(emailMap, eVal);2269 }22702271 const toIdentity = (type: "email" | "username") =>2272 ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2273 value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2274 });22752276 return [2277 ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2278 ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2279 ];2280}22812282export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2283 if (!derivedKey) throw new Error("vault_locked");22842285 const now = Date.now();2286 const added: VaultEntry[] = [];2287 for (const draft of drafts) {2288 try {2289 const sanitized = sanitizeEntryDraft(draft);2290 const nextEntry: VaultEntry = {2291 ...sanitized,2292 id: crypto.randomUUID(),2293 createdAt: now,2294 modifiedAt: monotonicEntryTimestamp(),2295 };2296 entries.push(nextEntry);2297 added.push(nextEntry);2298 } catch {2299 2300 }2301 }23022303 if (added.length > 0) {2304 await persistEntries();2305 }23062307 return added;2308}230923102311231223132314231523162317export async function restoreEntries(2318 incoming: VaultEntry[],2319 mode: "replace" | "merge"2320): Promise<{ added: number; updated: number; skipped: number }> {2321 if (!derivedKey) throw new Error("vault_locked");23222323 2324 2325 2326 if (mode === "replace" && incoming.length === 0) {2327 throw new Error("refuse to replace with empty entry set");2328 }23292330 let added = 0;2331 let updated = 0;2332 let skipped = 0;23332334 if (mode === "replace") {2335 entries = [];2336 for (const entry of incoming) {2337 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2338 if (!normalized) {2339 skipped += 1;2340 continue;2341 }2342 entries.push(normalized);2343 if (normalized.deletedAt) {2344 tombstones.set(2345 normalized.id,2346 Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2347 );2348 } else {2349 tombstones.delete(normalized.id);2350 }2351 added += 1;2352 }2353 } else {2354 const byId = new Map<string, VaultEntry>();2355 for (const e of entries) byId.set(e.id, e);23562357 for (const entry of incoming) {2358 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2359 if (!normalized) {2360 skipped += 1;2361 continue;2362 }2363 const existing = byId.get(normalized.id);2364 if (!existing) {2365 entries.push(normalized);2366 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2367 else tombstones.delete(normalized.id);2368 added += 1;2369 } else if (normalized.modifiedAt > existing.modifiedAt) {2370 const idx = entries.findIndex((e) => e.id === existing.id);2371 if (idx !== -1) {2372 entries[idx] = normalized;2373 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2374 else tombstones.delete(normalized.id);2375 updated += 1;2376 }2377 } else {2378 skipped += 1;2379 }2380 }2381 }23822383 await persistEntries("import");2384 return { added, updated, skipped };2385}238623872388238923902391239223932394239523962397239823992400240124022403const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;24042405function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {2406 if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;2407 return { ...entry, id: crypto.randomUUID() };2408}240924102411241224132414241524162417function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {2418 if (!entry || typeof entry !== "object") return null;2419 const title = typeof entry.title === "string" ? entry.title.trim() : "";2420 if (!title) return null;2421 const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();2422 const now = Date.now();2423 const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;2424 const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;24252426 2427 2428 const normalized = normalizeEntry({2429 ...entry,2430 id,2431 title,2432 type: entry.type ?? "login",2433 createdAt,2434 modifiedAt,2435 });24362437 if (normalized.passkey) {2438 normalized.passkey = sanitizePasskey(normalized.passkey);2439 }2440 if (normalized.canary) {2441 normalized.canary = sanitizeCanary(normalized.canary);2442 }2443 2444 normalized.tags = sanitizeTags(normalized.tags);24452446 2447 2448 if (2449 normalized.type === "login" &&2450 !normalized.passkey &&2451 typeof normalized.password !== "string"2452 ) {2453 return null;2454 }2455 if (entry.passkey && !normalized.passkey) {2456 2457 2458 return null;2459 }24602461 return normalized;2462}2463246424652466246724682469function sanitizePasskey(pk: unknown): PasskeyData | undefined {2470 if (!pk || typeof pk !== "object") return undefined;2471 const r = pk as Record<string, unknown>;2472 if (2473 typeof r.rpId !== "string" || !r.rpId ||2474 typeof r.credentialId !== "string" || !r.credentialId ||2475 typeof r.publicKeyCose !== "string" ||2476 typeof r.userHandle !== "string" ||2477 typeof r.userName !== "string"2478 ) {2479 return undefined;2480 }2481 return {2482 rpId: r.rpId,2483 rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2484 credentialId: r.credentialId,2485 publicKeyCose: r.publicKeyCose,2486 privateKeyJwk:2487 r.privateKeyJwk && typeof r.privateKeyJwk === "object"2488 ? (r.privateKeyJwk as JsonWebKey)2489 : undefined,2490 userHandle: r.userHandle,2491 userName: r.userName,2492 userDisplayName:2493 typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2494 algorithm: r.algorithm === -8 ? -8 : -7,2495 signCount: typeof r.signCount === "number" ? r.signCount : 0,2496 aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2497 backupEligible: r.backupEligible === true,2498 backupState: r.backupState === true,2499 lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2500 browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2501 transports: Array.isArray(r.transports)2502 ? r.transports.filter((t): t is string => typeof t === "string")2503 : undefined,2504 createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2505 };2506}25072508250925102511251225132514251525162517function sanitizeCanary(c: unknown): Canary | undefined {2518 if (!c || typeof c !== "object") return undefined;2519 const r = c as Record<string, unknown>;2520 if (typeof r.webhookUrl !== "string") return undefined;2521 let url: URL;2522 try {2523 url = new URL(r.webhookUrl);2524 } catch {2525 return undefined;2526 }2527 if (url.protocol !== "https:") return undefined;2528 return {2529 webhookUrl: url.toString(),2530 label: typeof r.label === "string" ? r.label : undefined,2531 lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2532 pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2533 };2534}25352536253725382539254025412542function sanitizeTags(tags: unknown): string[] | undefined {2543 if (!Array.isArray(tags)) return undefined;2544 const out: string[] = [];2545 for (const t of tags) {2546 if (typeof t !== "string") continue;2547 const trimmed = t.trim();2548 if (!trimmed) continue;2549 out.push(trimmed.slice(0, 256));2550 if (out.length >= 255) break;2551 }2552 return out.length > 0 ? out : undefined;2553}255425552556255725582559export async function clearVaultEntries(2560 confirmation: "REPLACE_ALL"2561): Promise<void> {2562 if (confirmation !== "REPLACE_ALL") {2563 throw new Error("clearVaultEntries requires explicit confirmation");2564 }2565 if (!derivedKey) throw new Error("vault_locked");2566 for (const entry of entries) {2567 if (!entry.deletedAt) {2568 const stamp = monotonicEntryTimestamp(Math.max(2569 entry.modifiedAt,2570 tombstones.get(entry.id) ?? 0,2571 ));2572 entry.deletedAt = stamp;2573 entry.modifiedAt = stamp;2574 tombstones.set(entry.id, stamp);2575 }2576 }2577 await persistEntries();2578}25792580export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2581 if (!derivedKey) throw new Error("vault_locked");25822583 const sanitized = sanitizeEntryDraft(entry);2584 const now = Date.now();2585 const stamp = monotonicEntryTimestamp();2586 const nextEntry: VaultEntry = {2587 ...sanitized,2588 id: crypto.randomUUID(),2589 createdAt: now,2590 modifiedAt: stamp,2591 2592 2593 passwordChangedAt: sanitized.password ? stamp : undefined,2594 };25952596 2597 2598 2599 const rollback = entries;2600 entries = [...entries, nextEntry];2601 try {2602 await persistEntries();2603 } catch (err) {2604 entries = rollback;2605 throw err;2606 }26072608 2609 if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2610 checkBreach(nextEntry.password).then(async (count) => {2611 if (count > 0) {2612 const idx = entries.findIndex((e) => e.id === nextEntry.id);2613 if (idx !== -1) {2614 entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2615 await persistEntries();2616 }2617 }2618 });2619 }26202621 fireSyncTrigger("vault_change");26222623 return nextEntry;2624}26252626262726282629263026312632export async function consolidatePasskeyEntries(): Promise<void> {2633 if (!derivedKey) return;2634 const { merged } = mergePasskeyOnlyIntoLogins(entries);2635 if (merged) {2636 await persistEntries();2637 }2638}26392640export async function updateEntry(2641 id: string,2642 patch: Partial<VaultEntry>2643): Promise<void> {2644 if (!derivedKey) throw new Error("vault_locked");26452646 const idx = entries.findIndex((entry) => entry.id === id);2647 if (idx === -1 || entries[idx].deletedAt) {2648 throw new Error("entry_not_found");2649 }26502651 const current = entries[idx];2652 const sanitizedPatch = sanitizeEntryPatch(patch);2653 2654 2655 2656 const passwordChanged =2657 "password" in patch &&2658 typeof sanitizedPatch.password === "string" &&2659 sanitizedPatch.password !== current.password;2660 const stamp = monotonicEntryTimestamp(current.modifiedAt);2661 2662 2663 2664 2665 2666 2667 2668 const priorPassword = current.password;2669 const shouldCapture =2670 passwordChanged &&2671 typeof priorPassword === "string" &&2672 priorPassword.length > 0 &&2673 current.passwordHistory?.[0]?.password !== priorPassword;2674 const nextHistory = shouldCapture2675 ? [2676 { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2677 ...(current.passwordHistory ?? []),2678 ].slice(0, PASSWORD_HISTORY_MAX)2679 : current.passwordHistory;2680 entries[idx] = {2681 ...current,2682 ...sanitizedPatch,2683 modifiedAt: stamp,2684 ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2685 };2686268726882689 2690 if (entries[idx].type === "card" && !entries[idx].cardNumber) {2691 entries[idx] = current;2692 throw new Error("card number is required for card entries");2693 }26942695 2696 2697 2698 2699 try {2700 await persistEntries();2701 } catch (err) {2702 entries[idx] = current;2703 throw err;2704 }27052706 2707 2708 if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2709 entries[idx] = { ...entries[idx], breach: undefined };2710 await persistEntries();2711 const password = entries[idx].password;2712 if (password) {2713 checkBreach(password).then(async (count) => {2714 const i = entries.findIndex((e) => e.id === id);2715 if (i !== -1 && count > 0) {2716 entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2717 await persistEntries();2718 }2719 });2720 }2721 }27222723 fireSyncTrigger("vault_change");2724}27252726export async function deleteEntry(id: string): Promise<void> {2727 if (!derivedKey) throw new Error("vault_locked");27282729 const entry = entries.find((item) => item.id === id);2730 if (!entry || entry.deletedAt) {2731 throw new Error("entry_not_found");2732 }27332734 2735 2736 2737 const previousModifiedAt = entry.modifiedAt;2738 const previousTombstone = tombstones.get(id);2739 const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2740 entry.deletedAt = stamp;2741 entry.modifiedAt = stamp;2742 tombstones.set(id, stamp);2743 2744 2745 try {2746 await persistEntries();2747 } catch (err) {2748 delete entry.deletedAt;2749 entry.modifiedAt = previousModifiedAt;2750 if (previousTombstone === undefined) tombstones.delete(id);2751 else tombstones.set(id, previousTombstone);2752 throw err;2753 }2754 fireSyncTrigger("vault_change");2755}27562757export function getDeletedEntries(): VaultEntry[] {2758 if (!derivedKey) return [];2759 return entries.filter((e) => !!e.deletedAt);2760}276127622763export function getTombstoneManifest(): Record<string, number> {2764 if (!derivedKey) return {};2765 return Object.fromEntries(tombstones);2766}2767276827692770277127722773export async function getVaultVersion(): Promise<number> {2774 try {2775 const raw = await chrome.storage.local.get("peach_last_modified_at");2776 const v = (raw as Record<string, unknown>).peach_last_modified_at;2777 if (typeof v === "number") return v;2778 if (typeof v === "string" && v !== "") {2779 const n = Number.parseInt(v, 10);2780 return Number.isFinite(n) ? n : 0;2781 }2782 return 0;2783 } catch {2784 return 0;2785 }2786}2787278827892790279127922793279427952796279727982799export async function applyMergedRemoteEntries(2800 remoteEntries: VaultEntry[],2801 remoteTombstones: Record<string, number>,2802): Promise<{ received: number; applied: number; conflicts: number }> {2803 2804 2805 2806 2807 2808 2809 if (!derivedKey || vaultMode === "decoy") throw new Error("vault_locked");28102811 const received = remoteEntries.length + Object.keys(remoteTombstones).length;2812 let applied = 0;2813 let conflicts = 0;28142815 const byId = new Map<string, VaultEntry>();2816 for (const e of entries) byId.set(e.id, e);28172818 const mergeNow = Date.now();2819 const remoteTombstoneTimes = new Map<string, number>();2820 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2821 if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {2822 remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));2823 }2824 }28252826 for (const remote of remoteEntries) {2827 const sanitized = sanitizeRestoredEntry(remote);2828 if (!sanitized) continue;2829 2830 2831 2832 sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2833 if (typeof sanitized.deletedAt === "number") {2834 sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2835 }2836 const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);2837 const localTombstoneTs = tombstones.get(sanitized.id);2838 const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);2839 if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {2840 continue;2841 }2842 const local = byId.get(sanitized.id);2843 if (!local) {2844 entries.push(sanitized);2845 byId.set(sanitized.id, sanitized);2846 tombstones.delete(sanitized.id);2847 applied += 1;2848 } else if (sanitized.modifiedAt > local.modifiedAt) {2849 const idx = entries.findIndex((e) => e.id === local.id);2850 if (idx !== -1) {2851 entries[idx] = sanitized;2852 byId.set(sanitized.id, sanitized);2853 tombstones.delete(sanitized.id);2854 applied += 1;2855 if (!local.deletedAt) conflicts += 1;2856 }2857 }2858 }28592860 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2861 if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;2862 2863 const deletedAt = remoteTombstoneTimes.get(id)!;2864 const knownTombstone = tombstones.get(id);2865 if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;2866 const local = byId.get(id);2867 if (!local) {2868 tombstones.set(id, deletedAt);2869 applied += 1;2870 continue;2871 }2872 if (local.deletedAt && local.deletedAt >= deletedAt) continue;2873 if (deletedAt < local.modifiedAt) continue;2874 const idx = entries.findIndex((e) => e.id === id);2875 if (idx !== -1) {2876 entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2877 tombstones.set(id, deletedAt);2878 applied += 1;2879 }2880 }28812882 if (applied > 0 && vaultMode === "real") {2883 await persistEntries("sync_received");2884 buildDomainIndexSync(entries);2885 2886 2887 2888 2889 try {2890 void chrome.runtime2891 .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })2892 .catch(() => undefined);2893 } catch {2894 2895 }2896 }2897 return { received, applied, conflicts };2898}28992900export async function restoreEntry(id: string): Promise<void> {2901 if (!derivedKey) throw new Error("vault_locked");2902 const entry = entries.find((e) => e.id === id && e.deletedAt);2903 if (!entry) throw new Error("deleted entry not found");2904 const previousDeletedAt = entry.deletedAt;2905 const previousModifiedAt = entry.modifiedAt;2906 const previousTombstone = tombstones.get(id);2907 delete entry.deletedAt;2908 entry.modifiedAt = monotonicEntryTimestamp(Math.max(2909 entry.modifiedAt,2910 previousTombstone ?? 0,2911 ));2912 tombstones.delete(id);2913 try {2914 await persistEntries();2915 } catch (err) {2916 entry.deletedAt = previousDeletedAt;2917 entry.modifiedAt = previousModifiedAt;2918 if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);2919 throw err;2920 }2921 buildDomainIndexSync(entries);2922}29232924export async function purgeEntry(id: string): Promise<void> {2925 if (!derivedKey) throw new Error("vault_locked");2926 const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2927 if (idx === -1) throw new Error("deleted entry not found");2928 const entry = entries[idx]!;2929 tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));2930 entries.splice(idx, 1);2931 await persistEntries();2932}293329342935export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2936 if (!derivedKey || retentionMs === 0) return 0;2937 const cutoff = Date.now() - retentionMs;2938 const before = entries.length;2939 for (const entry of entries) {2940 if (entry.deletedAt && entry.deletedAt < cutoff) {2941 tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));2942 }2943 }2944 entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2945 const purged = before - entries.length;2946 if (purged > 0) await persistEntries();2947 return purged;2948}29492950export function queryDomain(domain: string): VaultEntry[] {2951 return domainIndex.get(domain) ?? [];2952}29532954export function getEntryById(id: string): VaultEntry | undefined {2955 return entries.find((entry) => entry.id === id && !entry.deletedAt);2956}29572958async function persistSlotA(2959 reason: VaultSnapshot["reason"] = "local_save",2960): Promise<StoredVault> {2961 if (!derivedKey) throw new Error("vault_locked");2962 const epoch = vaultEpoch;2963 const throwIfStale = () => {2964 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");2965 };29662967 const slotA = await loadSlot(SLOT_A);2968 throwIfStale();2969 if (!slotA) throw new Error("missing slot A");29702971 2972 2973 await takeVaultSnapshot(reason);2974 throwIfStale();29752976 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2977 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");2978 throwIfStale();29792980 2981 const nextSlotA: StoredVault = {2982 ...slotA,2983 nonce,2984 ciphertext,2985 tag,2986 2987 };29882989 2990 2991 2992 2993 2994 2995 let slotACommitted = false;2996 try {2997 throwIfStale();2998 await writeSlot(SLOT_A, nextSlotA);2999 slotACommitted = true;3000 throwIfStale();30013002 3003 3004 3005 if (!duressConfigured) {3006 throwIfStale();3007 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3008 throwIfStale();3009 }3010 3011 3012 3013 3014 3015 if (reason !== "sync_received") {3016 throwIfStale();3017 await stampLocalVaultMutation();3018 throwIfStale();3019 }3020 } catch (err) {3021 3022 3023 if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3024 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3025 throw err;3026 }30273028 return nextSlotA;3029}30303031async function persistSlotB(): Promise<void> {3032 if (!derivedKey) throw new Error("vault_locked");30333034 const slotB = await loadSlot(SLOT_B);3035 if (!slotB) throw new Error("missing slot B");30363037 3038 3039 3040 3041 const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3042 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");30433044 await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3045 3046 3047 3048 try {3049 await stampLocalVaultMutation();3050 } catch (err) {3051 await writeSlot(SLOT_B, slotB).catch(() => {});3052 throw err;3053 }3054}30553056async function persistEntries(3057 reason: VaultSnapshot["reason"] = "local_save",3058): Promise<void> {3059 if (!derivedKey) throw new Error("vault_locked");30603061 3062 3063 const previousTombstones = tombstones;3064 tombstones = new Map(tombstones);3065 reconcileTombstones();3066 try {3067 if (vaultMode === "decoy") {3068 await persistSlotB();3069 } else {3070 await persistSlotA(reason);3071 }3072 } catch (err) {3073 tombstones = previousTombstones;3074 throw err;3075 }3076 buildDomainIndexSync(entries);3077 await refreshLockedSyncState();3078}3079308030813082308330843085function allowHttpUrl(url: string | undefined): string {3086 const trimmed = url?.trim() ?? "";3087 if (!trimmed) return "";3088 try {3089 const parsed = new URL(trimmed);3090 if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3091 } catch {3092 3093 }3094 return trimmed;3095}30963097function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3098 if (!Array.isArray(values)) return undefined;3099 const seen = new Set<string>();3100 const cleaned: string[] = [];3101 for (const value of values) {3102 const trimmed = typeof value === "string" ? value.trim() : "";3103 if (!trimmed) continue;3104 if (!allowHttpUrl(trimmed)) continue;3105 const key = trimmed.toLowerCase();3106 if (seen.has(key)) continue;3107 seen.add(key);3108 cleaned.push(trimmed);3109 }3110 return cleaned.length > 0 ? cleaned : undefined;3111}31123113function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3114 const title = entry.title.trim();3115 const type: VaultEntry["type"] = entry.type ?? "login";31163117 if (!title) throw new Error("title is required");31183119 if (entry.passkey) {3120 const p = entry.passkey;3121 if (3122 !p.rpId ||3123 !p.credentialId ||3124 !p.publicKeyCose ||3125 !p.userHandle ||3126 !p.userName ||3127 (p.algorithm !== -7 && p.algorithm !== -8)3128 ) {3129 throw new Error("invalid passkey credential");3130 }3131 }3132 if (type === "card") {3133 if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3134 throw new Error("cardholder name and card number are required");3135 }3136 }31373138 return {3139 type,3140 title,3141 username: type === "login" ? entry.username?.trim() ?? "" : undefined,3142 email: type === "login" ? entry.email?.trim() || undefined : undefined,3143 password: type === "login" ? entry.password : undefined,3144 url: type === "login" ? allowHttpUrl(entry.url) : undefined,3145 additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3146 totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3147 3148 3149 totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3150 totpDigits: type === "login" ? entry.totpDigits : undefined,3151 totpPeriod: type === "login" ? entry.totpPeriod : undefined,3152 notes: entry.notes?.trim() || undefined,3153 breach: type === "login" ? entry.breach : undefined,3154 3155 3156 canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3157 tags: sanitizeTags(entry.tags),3158 passkey: entry.passkey,3159 cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3160 cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3161 expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3162 expYear: type === "card" ? entry.expYear?.trim() : undefined,3163 cvc: type === "card" ? entry.cvc?.trim() : undefined,3164 cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3165 network: type === "card" ? entry.network : undefined,3166 last4: type === "card" ? entry.last4?.trim() : undefined,3167 };3168}31693170function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3171 const nextPatch: Partial<VaultEntry> = {};31723173 if ("type" in patch) {3174 nextPatch.type = patch.type;3175 }31763177 if ("title" in patch) {3178 const title = patch.title?.trim() ?? "";3179 if (!title) throw new Error("title is required");3180 nextPatch.title = title;3181 }31823183 if ("url" in patch) {3184 nextPatch.url = allowHttpUrl(patch.url);3185 }31863187 if ("additionalUrls" in patch) {3188 const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3189 const seen = new Set<string>();3190 const cleaned: string[] = [];3191 for (const value of incoming) {3192 const trimmed = typeof value === "string" ? value.trim() : "";3193 if (!trimmed || !allowHttpUrl(trimmed)) continue;3194 const key = trimmed.toLowerCase();3195 if (seen.has(key)) continue;3196 seen.add(key);3197 cleaned.push(trimmed);3198 }3199 nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3200 }32013202 if ("username" in patch) {3203 nextPatch.username = patch.username?.trim() ?? "";3204 }32053206 if ("email" in patch) {3207 nextPatch.email = patch.email?.trim() || undefined;3208 }32093210 if ("password" in patch) {3211 const password = patch.password ?? "";3212 3213 nextPatch.password = password || undefined;3214 }32153216 if ("totp" in patch) {3217 nextPatch.totp = patch.totp?.trim() || undefined;3218 }32193220 if ("totpAlgorithm" in patch) {3221 nextPatch.totpAlgorithm = patch.totpAlgorithm;3222 }32233224 if ("totpDigits" in patch) {3225 nextPatch.totpDigits = patch.totpDigits;3226 }32273228 if ("totpPeriod" in patch) {3229 nextPatch.totpPeriod = patch.totpPeriod;3230 }32313232 if ("notes" in patch) {3233 nextPatch.notes = patch.notes?.trim() || undefined;3234 }32353236 if ("breach" in patch) {3237 nextPatch.breach = patch.breach;3238 }32393240 if ("canary" in patch) {3241 3242 3243 nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3244 }32453246 if ("passkey" in patch) {3247 3248 3249 if (patch.passkey === undefined || patch.passkey === null) {3250 nextPatch.passkey = undefined;3251 } else {3252 const sanitized = sanitizePasskey(patch.passkey);3253 if (!sanitized) throw new Error("invalid passkey credential");3254 nextPatch.passkey = sanitized;3255 }3256 }32573258 if ("tags" in patch) {3259 3260 nextPatch.tags = sanitizeTags(patch.tags);3261 }32623263 if ("cardholderName" in patch) {3264 nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3265 }3266 if ("cardNumber" in patch) {3267 const n = patch.cardNumber ?? "";3268 nextPatch.cardNumber = n || undefined;3269 }3270 if ("expMonth" in patch) {3271 nextPatch.expMonth = patch.expMonth?.trim() || undefined;3272 }3273 if ("expYear" in patch) {3274 nextPatch.expYear = patch.expYear?.trim() || undefined;3275 }3276 if ("cvc" in patch) {3277 nextPatch.cvc = patch.cvc?.trim() || undefined;3278 }3279 if ("cardNickname" in patch) {3280 nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3281 }3282 if ("network" in patch) {3283 nextPatch.network = patch.network;3284 }3285 if ("last4" in patch) {3286 nextPatch.last4 = patch.last4?.trim() || undefined;3287 }32883289 return nextPatch;3290}32913292function normalizeEntry(entry: VaultEntry): VaultEntry {3293 const base: VaultEntry = {3294 id: entry.id,3295 type: entry.type,3296 title: entry.title,3297 username: entry.username,3298 email: entry.email,3299 password: entry.password,3300 url: entry.url,3301 additionalUrls:3302 "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3303 ? entry.additionalUrls3304 : undefined,3305 totp: entry.totp,3306 3307 totpAlgorithm: entry.totpAlgorithm,3308 totpDigits: entry.totpDigits,3309 totpPeriod: entry.totpPeriod,3310 notes: entry.notes,3311 breach: entry.breach,3312 3313 3314 3315 passwordChangedAt:3316 "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3317 3318 3319 3320 passwordHistory:3321 "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3322 ? entry.passwordHistory3323 : undefined,3324 canary: entry.canary,3325 passkey: entry.passkey,3326 createdAt: entry.createdAt,3327 modifiedAt: entry.modifiedAt,3328 deletedAt: entry.deletedAt,3329 tags: entry.tags,3330 cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3331 cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3332 expMonth: "expMonth" in entry ? entry.expMonth : undefined,3333 expYear: "expYear" in entry ? entry.expYear : undefined,3334 cvc: "cvc" in entry ? entry.cvc : undefined,3335 cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3336 network: "network" in entry ? entry.network : undefined,3337 last4: "last4" in entry ? entry.last4 : undefined,3338 };33393340 return base;3341}3342334333443345334633473348function entryDupeKey(e: VaultEntry): string {3349 if (e.type === "note") return `note|${e.title.toLowerCase()}`;3350 3351 3352 3353 3354 if (e.passkey) {3355 return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;3356 }3357 return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3358}335933603361export function countDuplicates(): number {3362 const best = new Map<string, VaultEntry>();3363 let dupeCount = 0;3364 for (const e of entries.filter((e) => !e.deletedAt)) {3365 const key = entryDupeKey(e);3366 const existing = best.get(key);3367 if (!existing) {3368 best.set(key, e);3369 } else {3370 dupeCount++;3371 3372 if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3373 best.set(key, e);3374 }3375 }3376 }3377 return dupeCount;3378}337933803381338233833384export async function deduplicateEntries(): Promise<number> {3385 if (!derivedKey) throw new Error("vault_locked");3386 3387 3388 if (vaultMode === "decoy") {3389 throw new Error("deduplicate disabled in decoy mode");3390 }33913392 const best = new Map<string, VaultEntry>();3393 for (const e of entries.filter((en) => !en.deletedAt)) {3394 const key = entryDupeKey(e);3395 const existing = best.get(key);3396 if (!existing) {3397 best.set(key, e);3398 } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3399 best.set(key, e);3400 }3401 }34023403 const keepIds = new Set(Array.from(best.values()).map((e) => e.id));3404 let removed = 0;3405 entries = entries.map((e) => {3406 if (!e.deletedAt && !keepIds.has(e.id)) {3407 removed++;3408 const deletedAt = monotonicEntryTimestamp(Math.max(3409 e.modifiedAt,3410 tombstones.get(e.id) ?? 0,3411 ));3412 tombstones.set(e.id, deletedAt);3413 return { ...e, deletedAt };3414 }3415 return e;3416 });34173418 if (removed > 0) await persistEntries();3419 return removed;3420}342134223423342434253426342734283429const HISTORY_KEY = "peach_vault_history";3430const HISTORY_MAX = 5;343134323433343434353436function bucketEntryCount(n: number): number {3437 if (n <= 0) return 0;3438 if (n <= 10) return 10;3439 if (n <= 25) return 25;3440 if (n <= 50) return 50;3441 if (n <= 100) return 100;3442 if (n <= 250) return 250;3443 if (n <= 500) return 500;3444 return Math.ceil(n / 500) * 500;3445}34463447344834493450345134523453export async function takeVaultSnapshot(3454 reason: VaultSnapshot["reason"],3455): Promise<void> {3456 if (recoveryInFlight) return;3457 3458 3459 3460 if (vaultMode === "decoy") return;3461 try {3462 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);3463 const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];3464 const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];34653466 3467 3468 3469 if (!slotA) return;34703471 const vault_a = JSON.stringify(slotA);3472 const vault_b = JSON.stringify(slotB ?? slotA);34733474 3475 3476 3477 3478 3479 3480 let entryCount: number | null = null;3481 if (derivedKey && vaultMode === "real") {3482 try {3483 entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);3484 } catch {3485 entryCount = null;3486 }3487 }34883489 const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3490 const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)3491 ? existingRaw3492 : { snapshots: [] };34933494 3495 3496 3497 const latest = history.snapshots[0];3498 if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3499 return;3500 }35013502 const snapshot: VaultSnapshot = {3503 id: crypto.randomUUID(),3504 savedAt: Date.now(),3505 reason,3506 vault_a,3507 vault_b,3508 entryCount,3509 };35103511 history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3512 if (recoveryInFlight) return;3513 await chrome.storage.local.set({ [HISTORY_KEY]: history });3514 } catch (err) {3515 3516 3517 3518 3519 console.warn('[Peach] takeVaultSnapshot failed:', err);3520 if (String(err).includes('QUOTA') || String(err).includes('quota')) {3521 try {3522 await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3523 } catch {3524 3525 }3526 }3527 }3528}352935303531export async function clearVaultHistory(): Promise<void> {3532 if (recoveryInFlight) throw new Error("recovery_in_progress");3533 try {3534 await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3535 } catch {3536 3537 }3538}353935403541export async function getVaultHistory(): Promise<VaultSnapshot[]> {3542 if (vaultMode === "decoy") return [];3543 const raw = await chrome.storage.local.get(HISTORY_KEY);3544 const value = (raw as Record<string, unknown>)[HISTORY_KEY];3545 return sanitizeHistory(value);3546}354735483549355035513552export async function restoreVaultSnapshot(3553 snapshotId: string,3554): Promise<{ ok: true } | { ok: false; error: string }> {3555 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight) return { ok: false, error: "vault_changed" };3556 vaultReplacementInFlight = true;3557 try {3558 if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3559 const history = await getVaultHistory();3560 const snapshot = history.find((s) => s.id === snapshotId);3561 if (!snapshot) return { ok: false, error: "snapshot_not_found" };35623563 const restoredA = parseHistorySlot(snapshot.vault_a);3564 const restoredB = parseHistorySlot(snapshot.vault_b);3565 if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };35663567 await takeVaultSnapshot("restore");3568 const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3569 const previousA = (current as Record<string, unknown>)[SLOT_A];3570 const previousB = (current as Record<string, unknown>)[SLOT_B];3571 try {3572 if (recoveryInFlight || vaultRemovalsInFlight) return { ok: false, error: "recovery_in_progress" };3573 await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3574 await stampLocalVaultMutation();3575 } catch {3576 try {3577 await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3578 } catch {3579 3580 }3581 return { ok: false, error: "snapshot_corrupt" };3582 }35833584 await lock();3585 return { ok: true };3586 } finally {3587 vaultReplacementInFlight = false;3588 }3589}359035913592359335943595359635973598359936003601360236033604export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3605 if (!derivedKey || vaultMode !== "real") {3606 return { ok: false, error: "vault_locked" };3607 }3608 const slotA = await loadSlot(SLOT_A);3609 if (!slotA) return { ok: false, error: "missing_slot_a" };36103611 3612 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3613 await generateAndWrapRootKey();36143615 3616 const newRootKey = unhex(rawRootKey);3617 const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");3618 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);36193620 3621 3622 3623 3624 await takeVaultSnapshot("local_save");3625 const nextSlotA: StoredVault = {3626 ...slotA,3627 recovery_vault_key: recoveryVaultKey,3628 recovery_salt: recoverySalt,3629 recovery_wrapped_root_key: wrappedRootKey,3630 recovery_nonce: wrappedNonce,3631 recovery_tag: wrappedTag,3632 ...pwRoot,3633 };3634 await writeSlot(SLOT_A, nextSlotA);36353636 3637 if (rootKey) zeroKey(rootKey);3638 rootKey = newRootKey;36393640 3641 3642 await notifyIdentityKeysRotated();36433644 3645 3646 3647 await clearPairedDevices();3648 await clearPairSecrets();36493650 3651 await setRecoveryConfirmPending(); 36523653 await stampLocalVaultMutation();3654 return { ok: true };3655}36563657365836593660366136623663export async function changePassword(3664 currentPassword: string,3665 newPassword: string3666): Promise<boolean> {3667 const epoch = vaultEpoch;3668 const stale = () => epoch !== vaultEpoch;3669 if (!derivedKey || vaultMode !== "real") return false;36703671 3672 const valid = await verifyMainPassword(currentPassword);3673 if (!valid) return false;36743675 const slotA = await loadSlot(SLOT_A);3676 if (!slotA) return false;3677 if (!rootKey) return false;36783679 3680 const newSalt = generateSalt();3681 const newKey = await deriveKey(newPassword, newSalt);3682 if (stale()) {3683 zeroKey(newKey);3684 return false;3685 }36863687 3688 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3689 const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");36903691 3692 3693 3694 const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);36953696 const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");3697 const finalSlotA: StoredVault = {3698 ...slotA,3699 recovery_vault_key: recoveryVaultKey,3700 salt: hex(newSalt),3701 nonce,3702 ciphertext,3703 tag,3704 ...pwRoot,3705 };37063707 3708 3709 3710 await takeVaultSnapshot("local_save");37113712 3713 3714 3715 3716 await writeSlot(SLOT_A, finalSlotA);3717 if (stale()) {3718 zeroKey(newKey);3719 return false;3720 }37213722 3723 3724 3725 zeroKey(derivedKey);3726 derivedKey = newKey;37273728 3729 3730 3731 3732 if (stale()) {3733 await lock();3734 return false;3735 }3736 await saveSessionKey(newKey, "real", epoch);3737 if (stale()) return false;37383739 3740 3741 3742 await notifyIdentityKeysRotated();3743 if (stale()) return false;37443745 3746 3747 3748 if (!duressConfigured) {3749 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3750 }3751 await clearPinUnlockStorage();3752 await stampLocalVaultMutation();37533754 return true;3755}