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, revokeRecoveryReveal } 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 vaultRemovalEpoch = 0;89let vaultWritesInFlight = 0;90let vaultCreatesInFlight = 0;91let creationSettled: Promise<void> = Promise.resolve();92let vaultUnlocksInFlight = 0;93let vaultReplacementInFlight = false;94let entries: VaultEntry[] = [];95969798let tombstones = new Map<string, number>();99let domainIndex: Map<string, VaultEntry[]> = new Map();100let vaultMode: "real" | "decoy" = "real";101102103104let duressConfigured = false;105106107108109110111112113114115let lastUnlockFailureReason: string | null = null;116117export function consumeLastUnlockFailureReason(): string | null {118 const r = lastUnlockFailureReason;119 lastUnlockFailureReason = null;120 return r;121}122123124125126127export type TextSize = "small" | "medium" | "large";128129export interface VaultSettings {130 accentColor?: AccentColorName;131 theme?: "dark" | "light";132 autoLockMinutes?: number;133 clipboardClearSeconds?: number;134 lockOnClose?: boolean;135 breachMonitoring?: boolean;136 passkeyProviderEnabled?: boolean;137 trashRetentionDays?: number;138 manualSummonDomains?: Record<string, ManualSummonRecord>;139 manualSummonSalt?: string;140 declinedCardFingerprints?: string[];141142 143 metadataVersion?: 1;144 145146147148149 textSize?: TextSize;150 151152153154155 reduceMotion?: boolean;156 157 lockedSyncRequiresUnlock?: boolean;158 159 pinEnabled?: boolean;160 161 pinPreferred?: boolean;162 163164165166167168169 shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;170}171172interface StoredPinWrap {173 version: 1;174 salt: string;175 nonce: string;176 ciphertext: string;177 tag: string;178}179180const PIN_WRAP_STORAGE = "peach_pin_wrap";181const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";182const PIN_MIN_LENGTH = 4;183const PIN_MAX_LENGTH = 12;184const PIN_MAX_ATTEMPTS = 3;185186let settings: VaultSettings = {};187const CARD_DECLINE_MAX = 256;188189const CARD_DECLINE_DIGEST_HEX = 32;190191async function metadataDigest(value: string, key: string): Promise<string> {192 const bytes = new TextEncoder().encode(`${key}:${value}`);193 const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));194 return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");195}196197let inMemoryPinWrap: StoredPinWrap | null = null;198let inMemoryPinFailedAttempts = 0;199let sessionPinStorageFailed = false;200201export function getSettings(): VaultSettings {202 return settings;203}204205export async function ensureSettingsLoaded(): Promise<VaultSettings> {206 await loadSettings();207 return settings;208}209210export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {211 await loadSettings();212 213 214 215 216 const safe = Object.fromEntries(217 Object.entries(patch).filter(218 ([k]) => !["__proto__", "constructor", "prototype"].includes(k),219 ),220 ) as Partial<VaultSettings>;221 settings = { ...settings, ...safe };222 await persistSettings();223}224225function isValidPin(pin: string): boolean {226 return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);227}228229230export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {231 if (vaultCreatesInFlight) return false;232 vaultWritesInFlight++;233 try {234 if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;235 if (!(await verifyMainPassword(currentPassword))) return false;236237 const salt = generateSalt();238 const pinKey = await deriveKey(pin, salt);239 try {240 const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");241 await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });242 await updateSettings({ pinEnabled: true });243 return true;244 } finally {245 zeroKey(pinKey);246 }247 } finally { vaultWritesInFlight--; }248}249250async function clearPinUnlockStorage(): Promise<void> {251 inMemoryPinWrap = null;252 inMemoryPinFailedAttempts = 0;253 sessionPinStorageFailed = false;254 if (chrome.storage.session) {255 await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);256 }257 await updateSettings({ pinEnabled: false });258}259260261export async function disablePinUnlock(currentPassword: string): Promise<boolean> {262 if (vaultCreatesInFlight) return false;263 vaultWritesInFlight++;264 try {265 if (!derivedKey || vaultMode !== "real") return false;266 if (!(await verifyMainPassword(currentPassword))) return false;267 await clearPinUnlockStorage();268 return true;269 } finally { vaultWritesInFlight--; }270}271272273export async function unlockWithPin(pin: string): Promise<boolean> {274 vaultUnlocksInFlight++;275 try {276 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;277 if (!isValidPin(pin)) return false;278 await loadSettings();279 if (!settings.pinEnabled) return false;280281 const { stored, failedAttempts } = await loadPinState();282 if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;283 if (284 !stored ||285 stored.version !== 1 ||286 !stored.salt ||287 !stored.nonce ||288 !stored.ciphertext ||289 !stored.tag290 ) return false;291292 const pinKey = await deriveKey(pin, unhex(stored.salt));293 let unwrappedKey: Uint8Array | null = null;294 try {295 const masterKeyHex = await decrypt(296 pinKey,297 stored.nonce,298 stored.ciphertext,299 stored.tag,300 "pin_wrap_v1",301 );302 if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;303 unwrappedKey = unhex(masterKeyHex);304 const result = await unlockWithKey(masterKeyHex);305 if (!result.ok) return false;306 await resetPinFailedAttempts();307 return true;308 } catch {309 await recordPinFailure(failedAttempts + 1);310 return false;311 } finally {312 zeroKey(pinKey);313 if (unwrappedKey) zeroKey(unwrappedKey);314 }315 } finally { vaultUnlocksInFlight--; }316}317318async function savePinWrap(stored: StoredPinWrap): Promise<void> {319 inMemoryPinWrap = stored;320 inMemoryPinFailedAttempts = 0;321 sessionPinStorageFailed = !chrome.storage.session;322 if (!chrome.storage.session) return;323 try {324 await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });325 sessionPinStorageFailed = false;326 } catch {327 328 sessionPinStorageFailed = true;329 }330}331332async function loadPinState(): Promise<{333 stored: StoredPinWrap | undefined;334 failedAttempts: number;335}> {336 if (!chrome.storage.session) {337 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };338 }339 try {340 const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);341 return {342 stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??343 (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),344 failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"345 ? result[PIN_ATTEMPTS_STORAGE]346 : 0,347 };348 } catch {349 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };350 }351}352353async function recordPinFailure(failedAttempts: number): Promise<void> {354 inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);355 if (!chrome.storage.session) return;356 try {357 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });358 } catch { }359}360361async function resetPinFailedAttempts(): Promise<void> {362 inMemoryPinFailedAttempts = 0;363 if (!chrome.storage.session) return;364 try {365 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });366 } catch { }367}368369export async function getPinUnlockStatus(): Promise<{370 configured: boolean;371 available: boolean;372 attemptsRemaining: number;373}> {374 await loadSettings();375 if (!settings.pinEnabled) {376 return { configured: false, available: false, attemptsRemaining: 0 };377 }378 const { stored, failedAttempts } = await loadPinState();379 const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;380 return {381 configured: true,382 available,383 attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,384 };385}386387async function persistSettings(): Promise<void> {388 try {389 await chrome.storage.local.set({390 peach_settings: {391 ...settings,392 manualSummonDomains: undefined,393 manualSummonSalt: undefined,394 cardFingerprintSalt: undefined,395 declinedCardFingerprints: settings.declinedCardFingerprints ?? [],396 metadataVersion: 1,397 },398 });399 } catch (err) {400 throw mapStorageError(err);401 }402}403404function mapStorageError(err: unknown): Error {405 const message = err instanceof Error ? err.message : String(err);406 if (/QUOTA_BYTES|quota/i.test(message)) {407 return new Error("STORAGE_QUOTA_EXCEEDED");408 }409 return err instanceof Error ? err : new Error(message);410}411412async function loadSettings(): Promise<void> {413 const result = await chrome.storage.local.get("peach_settings");414 settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};415}416417418419function fireSyncTrigger(reason: "vault_change"): void {420 void Promise.resolve()421 .then(() => triggerSyncIfReachable({ reason }))422 .catch(() => {423 424 });425}426export function lockedSyncRequiresUnlock(): boolean {427 return settings.lockedSyncRequiresUnlock === true;428}429430let lockedSyncRefreshHook: (() => Promise<void>) | null = null;431let lockedSyncUnlockHook: (() => Promise<void>) | null = null;432let decoySyncTeardownHook: (() => void) | null = null;433export type IdentityHooks = {434 435 onSessionEnded: () => Promise<void>;436 437 onKeysRotated: () => Promise<void>;438 439 onVaultCreated: (password: string) => Promise<void>;440};441442let identityHooks: IdentityHooks | null = null;443444export function setIdentityHooks(hooks: IdentityHooks): void {445 identityHooks = hooks;446}447448async function notifyIdentitySessionEnded(): Promise<void> {449 await identityHooks?.onSessionEnded().catch((error) => {450 console.warn("[Peach] local identity cache clear failed:", error);451 });452}453454async function notifyIdentityKeysRotated(): Promise<void> {455 await identityHooks?.onKeysRotated().catch((error) => {456 console.warn("[Peach] local identity re-wrap failed:", error);457 });458}459460export type SealedBox = { nonce: string; ciphertext: string; tag: string };461export type IdentityKeyEnvelope = {462 root?: SealedBox;463 local?: SealedBox;464 pending?: SealedBox;465 pendingSalt?: string;466};467468export function setLockedSyncHooks(hooks: {469 refresh: () => Promise<void>;470 afterUnlock: () => Promise<void>;471 onDecoy?: () => void;472}): void {473 lockedSyncRefreshHook = hooks.refresh;474 lockedSyncUnlockHook = hooks.afterUnlock;475 decoySyncTeardownHook = hooks.onDecoy ?? null;476}477478async function refreshLockedSyncState(): Promise<void> {479 if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;480 await lockedSyncRefreshHook().catch((error) => {481 console.warn("[Peach sync] locked spool refresh failed:", error);482 });483}484485486487488489export async function checkBreach(password: string): Promise<number> {490 491 492 const encoder = new TextEncoder();493 const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));494 const hashHex = Array.from(new Uint8Array(hashBuffer))495 .map((b) => b.toString(16).padStart(2, "0"))496 .join("")497 .toUpperCase();498499 const prefix = hashHex.slice(0, 5);500 const suffix = hashHex.slice(5);501502 try {503 504 505 const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {506 headers: { "Add-Padding": "true" },507 });508 if (!res.ok) return 0;509 const text = await res.text();510 const match = text.split("\r\n").find((l) => l.startsWith(suffix));511 return match ? parseInt(match.split(":")[1], 10) : 0;512 } catch {513 return 0; 514 }515}516517export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {518 519 const key = await cardDeclineKey();520 if (!key) return;521 const fingerprint = await cardFingerprint(last4, expMonth, expYear);522 await loadSettings();523 settings = {524 ...settings,525 declinedCardFingerprints: [526 527 528 ...(settings.declinedCardFingerprints ?? []).filter(529 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,530 ),531 await metadataDigest(fingerprint, key),532 ].slice(-CARD_DECLINE_MAX),533 };534 await persistSettings();535}536537export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {538 await loadSettings();539 const key = await cardDeclineKey();540 if (!key) return false;541 const fingerprint = await cardFingerprint(last4, expMonth, expYear);542 const candidate = await metadataDigest(fingerprint, key);543 return (settings.declinedCardFingerprints ?? []).some(544 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,545 );546}547548549550551552553554555556557558559async function cardDeclineKey(): Promise<string | null> {560 const root = getRootKeyHex();561 if (!root) return null;562 const digest = new Uint8Array(563 await crypto.subtle.digest(564 "SHA-256",565 new TextEncoder().encode(`peach-card-decline-v1:${root}`),566 ),567 );568 return hex(digest);569}570571async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {572 const encoder = new TextEncoder();573 const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));574 return Array.from(new Uint8Array(buf).slice(0, 8))575 .map((b) => b.toString(16).padStart(2, "0"))576 .join("");577}578579function hex(buf: Uint8Array): string {580 return Array.from(buf)581 .map((b) => b.toString(16).padStart(2, "0"))582 .join("");583}584585function unhex(s: string): Uint8Array {586 const out = new Uint8Array(s.length / 2);587 for (let i = 0; i < s.length; i += 2) {588 out[i / 2] = parseInt(s.slice(i, i + 2), 16);589 }590 return out;591}592593594595596597598599600601602603604605606607608609610611612async function generateAndWrapRootKey(): Promise<{613 rawRootKey: string; 614 recoverySalt: string;615 wrappedRootKey: string;616 wrappedNonce: string;617 wrappedTag: string;618}> {619 const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));620 try {621622 623 const words = await rootKeyToWords(rootKeyBytes);624 const wordMaterial = await wordsToRootKeyMaterial(words);625 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));626 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);627628 629 630 const nonce = crypto.getRandomValues(new Uint8Array(12));631 const encoded = new TextEncoder().encode(hex(rootKeyBytes));632 const raw = await crypto.subtle.encrypt(633 {634 name: "AES-GCM",635 iv: nonce,636 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,637 tagLength: 128,638 },639 recoveryKey,640 encoded641 );642 643 const rawU8 = new Uint8Array(raw);644 const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));645 const tag = hex(rawU8.slice(rawU8.length - 16));646647 return {648 rawRootKey: hex(rootKeyBytes),649 recoverySalt: hex(recoverySalt),650 wrappedRootKey: ciphertext,651 wrappedNonce: hex(nonce),652 wrappedTag: tag,653 };654 } finally { zeroKey(rootKeyBytes); }655}656657async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{658 recoverySalt: string;659 wrappedRootKey: string;660 wrappedNonce: string;661 wrappedTag: string;662}> {663 if (rootKeyBytes.length !== 32) {664 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");665 }666667 const words = await rootKeyToWords(rootKeyBytes);668 const wordMaterial = await wordsToRootKeyMaterial(words);669 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));670 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);671 const nonce = crypto.getRandomValues(new Uint8Array(12));672 const encoded = new TextEncoder().encode(hex(rootKeyBytes));673 const raw = await crypto.subtle.encrypt(674 {675 name: "AES-GCM",676 iv: nonce,677 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,678 tagLength: 128,679 },680 recoveryKey,681 encoded,682 );683 const rawU8 = new Uint8Array(raw);684 return {685 recoverySalt: hex(recoverySalt),686 wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),687 wrappedNonce: hex(nonce),688 wrappedTag: hex(rawU8.slice(rawU8.length - 16)),689 };690}691692693694695696async function unwrapRootKeyForRecovery(697 wrappedRootKey: string,698 wrappedNonce: string,699 wrappedTag: string,700 recoverySaltHex: string,701 words: string[]702): Promise<Uint8Array> {703 const wordMaterial = await wordsToRootKeyMaterial(words);704 const recoverySalt = unhex(recoverySaltHex);705 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);706707 708 709 710 711 712 const nonceRaw = unhex(wrappedNonce);713 const ciphertextRaw = unhex(wrappedRootKey);714 const tagRaw = unhex(wrappedTag);715 716 717 const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;718 const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);719 combined.set(ciphertextRaw, 0);720 combined.set(tagRaw, ciphertextRaw.length);721 const raw = await crypto.subtle.decrypt(722 { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },723 recoveryKey,724 combined725 );726 const decryptedHex = new TextDecoder().decode(raw);727 const recovered = unhex(decryptedHex);728 if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }729 return recovered;730}731732733export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {734 if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");735 if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");736 recoveryInFlight = true;737 let settle!: () => void;738 recoverySettled = new Promise<void>((resolve) => { settle = resolve; });739 const epoch = ++vaultEpoch;740 const check = () => {741 if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");742 };743 let recoveredRoot: Uint8Array | null = null;744 let oldKey: Uint8Array | null = null;745 let newKey: Uint8Array | null = null;746 let committed = false;747 try {748 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);749 check();750 const slot = raw[SLOT_A] as StoredVault | undefined;751 if (!slot) throw new Error("no_vault");752 if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");753 try {754 recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,755 slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);756 } catch {757 throw new Error("invalid_recovery_words");758 }759 check();760 if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");761 oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");762 check();763 if (!oldKey) throw new Error("recovery_data_unavailable");764 const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");765 check();766 if (result.status !== "ok") throw new Error("recovery_data_unavailable");767 const payload = result.payload;768 await loadSettings();769 check();770 const salt = generateSalt();771 newKey = await deriveKey(newPassword, salt);772 check();773 774 const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");775 const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");776 const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);777 const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");778 check();779 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);780 check();781 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");782 const history = raw[HISTORY_KEY] as VaultHistory | undefined;783 const snapshot: VaultSnapshot = {784 id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",785 vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,786 };787 const previousStamp = Number(raw.peach_last_modified_at);788 const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,789 salt: hex(salt), recovery_vault_key: recoveryVaultKey };790 791 await chrome.storage.local.set({792 [SLOT_A]: nextSlot,793 [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },794 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),795 });796 committed = true;797 check();798 derivedKey = newKey;799 rootKey = recoveredRoot;800 newKey = null;801 recoveredRoot = null;802 entries = payload.entries;803 tombstones = payload.tombstones;804 duressConfigured = payload.duressConfigured;805 vaultMode = "real";806 buildDomainIndexSync(entries);807 await saveSessionKey(derivedKey, "real", epoch);808 if (epoch !== vaultEpoch) throw new Error("vault_locked");809 await identityHooks?.onKeysRotated();810 if (epoch !== vaultEpoch) throw new Error("vault_locked");811 await reconcilePairSecrets(rootKey);812 if (epoch !== vaultEpoch) throw new Error("vault_locked");813 await clearPinUnlockStorage();814 if (epoch !== vaultEpoch) throw new Error("vault_locked");815 touchAutoLock();816 return { committed: true, unlocked: true };817 } catch (error) {818 if (committed) {819 console.warn("[Peach] recovery password saved; unlock required:", error);820 if (derivedKey && epoch === vaultEpoch) {821 try { await lock(); }822 catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }823 }824 return { committed: true, unlocked: false };825 }826 if (derivedKey && epoch === vaultEpoch) await lock();827 throw error;828 } finally {829 if (oldKey) zeroKey(oldKey);830 if (newKey) zeroKey(newKey);831 if (recoveredRoot) zeroKey(recoveredRoot);832 recoveryInFlight = false;833 settle();834 }835}836837838export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {839 vaultRemovalEpoch++;840 vaultRemovalsInFlight++;841 try {842 await lock();843 await recoverySettled;844 await creationSettled;845 return await remove();846 } finally {847 vaultRemovalsInFlight--;848 }849}850851852853854855856857858859860async function deriveRootKeyFromDerivedKey(861 derivedKeyBytes: Uint8Array,862 slotA: StoredVault,863): Promise<Uint8Array | null> {864 if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {865 return null;866 }867 try {868 const rootHex = await decrypt(869 derivedKeyBytes,870 slotA.pw_root_nonce,871 slotA.pw_root_ciphertext,872 slotA.pw_root_tag,873 "pw_root_v1",874 );875 return unhex(rootHex);876 } catch {877 return null;878 }879}880881export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {882 if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");883 884 885 const [root, local] = await Promise.all([886 encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),887 encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),888 ]);889 return { root, local };890}891892export async function sealIdentityKeyPreVault(893 password: string,894 ik: Uint8Array,895): Promise<IdentityKeyEnvelope> {896 const salt = generateSalt();897 const key = await deriveKey(password, salt);898 try {899 const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");900 return { pending, pendingSalt: hex(salt) };901 } finally {902 zeroKey(key);903 }904}905906907908909910911912913914export async function openIdentityKey(915 env: IdentityKeyEnvelope,916 password?: string,917): Promise<Uint8Array | null> {918 if (env.local && derivedKey) {919 const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");920 if (ik) return ik;921 }922 if (env.root && rootKey) {923 const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");924 if (ik) return ik;925 }926 if (!env.pending || !env.pendingSalt || password === undefined) return null;927 let key: Uint8Array;928 try {929 const salt = unhex(env.pendingSalt);930 key = await deriveKey(password, salt);931 salt.fill(0);932 } catch {933 return null;934 }935 try {936 return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");937 } finally {938 zeroKey(key);939 }940}941942943async function openSealedKey(944 key: Uint8Array,945 box: SealedBox,946 info: string,947): Promise<Uint8Array | null> {948 try {949 const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));950 if (value.length === 32) return value;951 value.fill(0);952 return null;953 } catch {954 return null;955 }956}957958959960async function wrapRootKeyForDerivedKey(961 derivedKeyBytes: Uint8Array,962 rootKeyBytes: Uint8Array,963): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {964 const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");965 return {966 pw_root_ciphertext: ciphertext,967 pw_root_nonce: nonce,968 pw_root_tag: tag,969 };970}971972973export async function getRecoveryWords(): Promise<string[]> {974 if (!rootKey) {975 throw new Error("recovery not set up");976 }977 return rootKeyToWords(rootKey);978}979980async function loadSlot(key: string): Promise<StoredVault | null> {981 const result = await chrome.storage.local.get(key);982 return (result as Record<string, StoredVault | undefined>)[key] ?? null;983}984985async function writeSlot(key: string, vault: StoredVault): Promise<void> {986 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");987 vaultWritesInFlight++;988 try {989 await chrome.storage.local.set({ [key]: vault });990 } catch (err) {991 throw mapStorageError(err);992 } finally {993 vaultWritesInFlight--;994 }995}9969979989991000100110021003100410051006export async function rollbackAdoptedVault(): Promise<void> {1007 await withVaultRemoval(async () => {1008 try {1009 await chrome.storage.local.remove([1010 SLOT_A,1011 SLOT_B,1012 "peach_last_modified_at",1013 ]);1014 } catch (err) {1015 throw mapStorageError(err);1016 }1017 });1018}10191020async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1021 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1022 vaultWritesInFlight++;1023 try {1024 const raw = await chrome.storage.local.get("peach_last_modified_at");1025 const previous = Number(1026 (raw as Record<string, unknown>).peach_last_modified_at,1027 );1028 const next = Math.max(1029 Date.now(),1030 Number.isFinite(previous) ? previous + 1 : 0,1031 );1032 try {1033 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1034 await chrome.storage.local.set({1035 [SLOT_A]: slotA,1036 [SLOT_B]: slotB,1037 peach_last_modified_at: String(next),1038 });1039 } catch (err) {1040 throw mapStorageError(err);1041 }1042 } finally {1043 vaultWritesInFlight--;1044 }1045}104610471048104910501051105210531054let lastEntryTimestamp = 0;1055function monotonicEntryTimestamp(currentModifiedAt?: number): number {1056 const base = Math.max(1057 Date.now(),1058 (currentModifiedAt ?? 0) + 1,1059 lastEntryTimestamp + 1,1060 );1061 lastEntryTimestamp = base;1062 return base;1063}10641065async function stampLocalVaultMutation(): Promise<void> {1066 if (vaultCreatesInFlight) throw new Error("vault_changed");1067 const raw = await chrome.storage.local.get("peach_last_modified_at");1068 const previous = Number(1069 (raw as Record<string, unknown>).peach_last_modified_at,1070 );1071 const next = Math.max(1072 Date.now(),1073 Number.isFinite(previous) ? previous + 1 : 0,1074 );1075 if (vaultCreatesInFlight) throw new Error("vault_changed");1076 await chrome.storage.local.set({1077 peach_last_modified_at: String(next),1078 });1079}108010811082108310841085108610871088108910901091function padPlaintext(json: string, minBytes = 0): string {1092 const encoded = new TextEncoder().encode(json);1093 const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1094 1095 const target = Math.max(bucket, minBytes);1096 const padLen = target - encoded.length;1097 return json + " ".repeat(padLen);1098}109911001101110211031104110511061107110811091110const CSPRNG_CHUNK = 65_536;11111112function fillRandom(buf: Uint8Array): Uint8Array {1113 for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1114 const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1115 const chunk = new Uint8Array(end - offset);1116 crypto.getRandomValues(chunk);1117 buf.set(chunk, offset);1118 }1119 return buf;1120}11211122function generateNoiseBlob(ciphertextBytes: number): StoredVault {1123 const salt = crypto.getRandomValues(new Uint8Array(16));1124 const nonce = crypto.getRandomValues(new Uint8Array(12));1125 const cipher = fillRandom(new Uint8Array(ciphertextBytes));1126 const tag = crypto.getRandomValues(new Uint8Array(16));1127 return {1128 version: 1,1129 salt: hex(salt),1130 nonce: hex(nonce),1131 ciphertext: hex(cipher),1132 tag: hex(tag),1133 };1134}113511361137113811391140type VaultPayload = {1141 entries: VaultEntry[];1142 tombstones?: Record<string, number>;1143 duressConfigured?: boolean;1144};11451146type DecryptedPayload = {1147 entries: VaultEntry[];1148 tombstones: Map<string, number>;1149 duressConfigured: boolean;1150};11511152function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1153 const envelope: VaultPayload = {1154 entries,1155 tombstones: Object.fromEntries(tombstones),1156 duressConfigured: duress,1157 };1158 return padPlaintext(JSON.stringify(envelope), minBytes);1159}11601161function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1162 const result = new Map<string, number>();1163 if (raw && typeof raw === "object" && !Array.isArray(raw)) {1164 for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1165 if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1166 result.set(id, timestamp);1167 }1168 }1169 }1170 1171 1172 for (const entry of allEntries) {1173 if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1174 continue;1175 }1176 if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1177 result.set(entry.id, entry.deletedAt);1178 }1179 }1180 return result;1181}11821183function reconcileTombstones(): void {1184 const byId = new Map(entries.map((entry) => [entry.id, entry]));1185 for (const [id] of tombstones) {1186 if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1187 }1188 for (const entry of entries) {1189 if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1190 if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1191 tombstones.set(entry.id, entry.deletedAt);1192 }1193 }1194 }1195}11961197function decodePayload(plain: string): DecryptedPayload {1198 const parsed = JSON.parse(plain) as VaultPayload;1199 if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1200 throw new Error("invalid vault payload");1201 }1202 const normalized = parsed.entries.map(normalizeEntry);1203 return {1204 entries: normalized,1205 tombstones: decodeTombstones(parsed.tombstones, normalized),1206 duressConfigured: parsed.duressConfigured === true,1207 };1208}120912101211function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1212 let merged = false;1213 const transferable = new Set(["id", "type", "title", "username", "url", "passkey", "createdAt", "modifiedAt", "totp", "totpAlgorithm", "totpDigits", "totpPeriod"]);1214 for (const source of entries.filter((entry) => !entry.deletedAt && entry.passkey)) {1215 const passkey = source.passkey!;1216 if (source.type !== "login" && source.type !== "passkey") continue;1217 if (!passkey.userName || (source.username && source.username !== passkey.userName)) continue;1218 if (Object.entries(source).some(([key, value]) => !transferable.has(key) && value !== undefined && value !== "")) continue;1219 const targets = entries.filter((entry) => {1220 if (entry.deletedAt || entry.passkey || entry.type !== "login" || entry.username !== passkey.userName) return false;1221 return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {1222 if (!url) return false;1223 try {1224 return new URL(url.includes("://") ? url : `https://${url}`).hostname === passkey.rpId;1225 } catch {1226 return false;1227 }1228 });1229 });1230 if (targets.length !== 1) continue;1231 const target = targets[0]!;1232 if (source.totp && target.totp && (source.totp !== target.totp || source.totpAlgorithm !== target.totpAlgorithm || source.totpDigits !== target.totpDigits || source.totpPeriod !== target.totpPeriod)) continue;1233 target.passkey = passkey;1234 if (source.totp && !target.totp) {1235 target.totp = source.totp;1236 target.totpAlgorithm = source.totpAlgorithm;1237 target.totpDigits = source.totpDigits;1238 target.totpPeriod = source.totpPeriod;1239 }1240 const stamp = monotonicEntryTimestamp(Math.max(source.modifiedAt, target.modifiedAt));1241 target.modifiedAt = stamp;1242 source.modifiedAt = stamp;1243 source.deletedAt = stamp;1244 merged = true;1245 }1246 return { merged };1247}12481249125012511252125312541255function hasValidVaultSchema(v: unknown): v is StoredVault {1256 if (typeof v !== "object" || v === null) return false;1257 const r = v as Record<string, unknown>;1258 return (1259 r.version === 1 &&1260 typeof r.salt === "string" &&1261 typeof r.nonce === "string" &&1262 typeof r.ciphertext === "string" &&1263 typeof r.tag === "string"1264 );1265}1266const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;12671268function hasValidHistorySlot(value: unknown): value is StoredVault {1269 if (!hasValidVaultSchema(value)) return false;1270 return /^[0-9a-f]{32}$/i.test(value.salt) &&1271 /^[0-9a-f]{24}$/i.test(value.nonce) &&1272 /^[0-9a-f]+$/i.test(value.ciphertext) &&1273 value.ciphertext.length % 2 === 0 &&1274 value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1275 /^[0-9a-f]{32}$/i.test(value.tag);1276}12771278function parseHistorySlot(value: string): StoredVault | null {1279 try {1280 const parsed: unknown = JSON.parse(value);1281 return hasValidHistorySlot(parsed) ? parsed : null;1282 } catch {1283 return null;1284 }1285}12861287function isHistoryRecord(value: unknown): value is VaultSnapshot {1288 if (typeof value !== "object" || value === null) return false;1289 const record = value as Record<string, unknown>;1290 return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1291 typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1292 typeof record.reason === "string" &&1293 typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1294 typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1295 (record.entryCount === null || typeof record.entryCount === "number");1296}12971298function sanitizeHistory(value: unknown): VaultSnapshot[] {1299 if (typeof value !== "object" || value === null) return [];1300 if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1301 return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1302}13031304export type TryDecryptResult =1305 | { status: "ok"; payload: DecryptedPayload }1306 | { status: "wrong_key" }1307 | { status: "corrupted"; reason: string };1308130913101311131213131314export async function tryDecryptSlot(1315 vault: StoredVault,1316 key: Uint8Array,1317 aadTag?: string,1318): Promise<DecryptedPayload | null> {1319 const res = await tryDecryptSlotResult(vault, key, aadTag);1320 return res.status === "ok" ? res.payload : null;1321}13221323export async function tryDecryptSlotResult(1324 vault: StoredVault,1325 key: Uint8Array,1326 aadTag?: string,1327): Promise<TryDecryptResult> {1328 if (!hasValidVaultSchema(vault)) {1329 return { status: "corrupted", reason: "invalid_slot_schema" };1330 }1331 let plain: string;1332 try {1333 plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1334 } catch {1335 return { status: "wrong_key" };1336 }1337 try {1338 const parsed = JSON.parse(plain) as unknown;1339 if (typeof parsed !== "object" || parsed === null) {1340 return { status: "corrupted", reason: "invalid_payload_shape" };1341 }1342 if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1343 return { status: "corrupted", reason: "invalid_payload_shape" };1344 }1345 return { status: "ok", payload: decodePayload(plain) };1346 } catch {1347 return { status: "corrupted", reason: "invalid_payload_json" };1348 }1349}135013511352135313541355function buildDomainIndexSync(all: VaultEntry[]): void {1356 domainIndex = new Map();13571358 for (const entry of all) {1359 if (entry.deletedAt) continue;1360 if (entry.type === "note" || entry.type === "card") continue;13611362 1363 1364 1365 1366 const domains = new Set<string>();1367 const primary = extractDomain(entry.url ?? "");1368 if (primary) domains.add(primary);1369 for (const extra of entry.additionalUrls ?? []) {1370 const d = extractDomain(extra);1371 if (d) domains.add(d);1372 }1373 if (domains.size === 0) continue;13741375 for (const domain of domains) {1376 const bucket = domainIndex.get(domain) ?? [];1377 bucket.push(entry);1378 domainIndex.set(domain, bucket);1379 }1380 }1381}13821383export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1384 if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1385 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1386 vaultCreatesInFlight++;1387 let settle!: () => void;1388 creationSettled = new Promise<void>((resolve) => { settle = resolve; });1389 let nextKey: Uint8Array | null = null;1390 let nextRoot: Uint8Array | null = null;1391 let committed = false;1392 let publishedEpoch: number | null = null;1393 const epoch = vaultEpoch;1394 const check = () => {1395 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1396 };1397 try {1398 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1399 check();1400 const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1401 if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1402 const salt = generateSalt();1403 nextKey = await deriveKey(password, salt);1404 check();1405 const recovery = await generateAndWrapRootKey();1406 nextRoot = unhex(recovery.rawRootKey);1407 check();1408 const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1409 const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1410 const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1411 check();1412 const slotA: StoredVault = {1413 ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1414 recovery_vault_key: recoveryVaultKey,1415 recovery_salt: recovery.recoverySalt,1416 recovery_wrapped_root_key: recovery.wrappedRootKey,1417 recovery_nonce: recovery.wrappedNonce,1418 recovery_tag: recovery.wrappedTag,1419 };1420 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1421 check();1422 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1423 const previous = Number(raw.peach_last_modified_at);1424 const update: Record<string, unknown> = {1425 [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1426 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1427 };1428 if (occupied) {1429 const history = raw[HISTORY_KEY] as VaultHistory | undefined;1430 const snapshot: VaultSnapshot = {1431 id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1432 vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1433 };1434 update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1435 }1436 try { await chrome.storage.local.set(update); }1437 catch (error) { throw mapStorageError(error); }1438 committed = true;1439 if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1440 const previousKey = derivedKey;1441 const previousRoot = rootKey;1442 publishedEpoch = ++vaultEpoch;1443 derivedKey = nextKey;1444 rootKey = nextRoot;1445 nextKey = null;1446 nextRoot = null;1447 entries = [];1448 tombstones = new Map();1449 vaultMode = "real";1450 duressConfigured = false;1451 buildDomainIndexSync(entries);1452 if (previousKey) zeroKey(previousKey);1453 if (previousRoot) zeroKey(previousRoot);1454 await clearSessionKey();1455 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1456 await identityHooks?.onVaultCreated(password).catch((error) => {1457 console.warn("[Peach] local identity promotion failed:", error);1458 });1459 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1460 touchAutoLock();1461 return { committed: true, unlocked: true };1462 } catch (error) {1463 if (!committed) throw error;1464 console.warn("[Peach] vault saved; unlock required:", error);1465 if (publishedEpoch === vaultEpoch) {1466 await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));1467 }1468 return { committed: true, unlocked: false };1469 } finally {1470 if (nextKey) zeroKey(nextKey);1471 if (nextRoot) zeroKey(nextRoot);1472 vaultCreatesInFlight--;1473 settle();1474 }1475}1476147714781479148014811482export async function createVaultFromRootKey(1483 password: string,1484 rootKeyHex: string,1485): Promise<{ vaultId: string }> {1486 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1487 if (typeof password !== "string" || password.length === 0) {1488 throw new Error("ADOPT_INVALID_PASSWORD");1489 }1490 if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1491 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1492 }14931494 if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1495 const rootKeyBytes = unhex(rootKeyHex);1496 if (rootKeyBytes.length !== 32) {1497 rootKeyBytes.fill(0);1498 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1499 }15001501 vaultCreatesInFlight++;1502 let settle!: () => void;1503 creationSettled = new Promise<void>((resolve) => { settle = resolve; });1504 const epoch = vaultEpoch;1505 let nextDerivedKey: Uint8Array | null = null;1506 let sessionRootKey: Uint8Array | null = null;1507 let committed = false;1508 try {1509 if (await hasVault()) {1510 throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1511 }15121513 const nextEntries: VaultEntry[] = [];1514 const nextDuressConfigured = false;1515 const vaultId = await computeVaultId(rootKeyBytes);1516 const salt = generateSalt();1517 nextDerivedKey = await deriveKey(password, salt);1518 const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);15191520 sessionRootKey = new Uint8Array(rootKeyBytes);1521 const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1522 const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1523 const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1524 const slotA: StoredVault = {1525 recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),1526 version: 1,1527 salt: hex(salt),1528 nonce,1529 ciphertext,1530 tag,1531 recovery_salt: recovery.recoverySalt,1532 recovery_wrapped_root_key: recovery.wrappedRootKey,1533 recovery_nonce: recovery.wrappedNonce,1534 recovery_tag: recovery.wrappedTag,1535 ...pwRoot,1536 };1537 const slotB = generateNoiseBlob(ciphertext.length / 2);1538 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1539 await commitCreatedVaultSlots(slotA, slotB);1540 committed = true;1541 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1542 vaultEpoch++;15431544 const previousDerivedKey = derivedKey;1545 const previousRootKey = rootKey;1546 derivedKey = nextDerivedKey;1547 rootKey = sessionRootKey;1548 nextDerivedKey = null;1549 sessionRootKey = null;1550 entries = nextEntries;1551 tombstones = new Map();1552 vaultMode = "real";1553 duressConfigured = nextDuressConfigured;1554 buildDomainIndexSync(entries);1555 if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1556 if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1557 touchAutoLock();15581559 1560 1561 await identityHooks?.onVaultCreated(password).catch((error) => {1562 console.warn("[Peach] local identity promotion failed:", error);1563 });15641565 return { vaultId };1566 } catch (error) {1567 if (committed) {1568 1569 try { await lock(); }1570 finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, "peach_last_modified_at"]); }1571 }1572 throw error;1573 } finally {1574 vaultCreatesInFlight--;1575 settle();1576 rootKeyBytes.fill(0);1577 if (nextDerivedKey) zeroKey(nextDerivedKey);1578 if (sessionRootKey) sessionRootKey.fill(0);1579 }1580}15811582export async function hasVault(): Promise<boolean> {1583 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);1584 return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1585}1586158715881589159015911592export async function isDuressEnabled(): Promise<boolean> {1593 return vaultMode === "real" && duressConfigured;1594}15951596export async function setupDuress(duressPassword: string): Promise<void> {1597 if (vaultCreatesInFlight) throw new Error("vault_changed");1598 vaultWritesInFlight++;1599 try {1600 if (!derivedKey || vaultMode !== "real") {1601 throw new Error("vault must be unlocked in real mode");1602 }1603 1604 1605 1606 const slotA = await loadSlot(SLOT_A);1607 if (!slotA) throw new Error("missing slot A");16081609 const decoySalt = generateSalt();1610 const decoyKey = await deriveKey(duressPassword, decoySalt);1611 try {1612 1613 1614 1615 1616 const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1617 const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1618 await writeSlot(SLOT_B, {1619 version: 1,1620 salt: hex(decoySalt),1621 nonce,1622 ciphertext,1623 tag,1624 });1625 } finally {1626 zeroKey(decoyKey);1627 }16281629 1630 1631 duressConfigured = true;1632 await persistSlotA();1633 } finally { vaultWritesInFlight--; }1634}16351636export async function disableDuress(): Promise<void> {1637 if (vaultCreatesInFlight) throw new Error("vault_changed");1638 vaultWritesInFlight++;1639 try {1640 if (!derivedKey || vaultMode !== "real") {1641 throw new Error("vault must be unlocked in real mode");1642 }1643 1644 1645 1646 const slotA = await loadSlot(SLOT_A);1647 if (slotA) {1648 await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1649 }16501651 duressConfigured = false;1652 await persistSlotA();1653 } finally { vaultWritesInFlight--; }1654}16551656165716581659166016611662export async function verifyMainPassword(password: string): Promise<boolean> {1663 const slotA = await loadSlot(SLOT_A);1664 if (!slotA) return false;1665 const key = await deriveKey(password, unhex(slotA.salt));1666 try {1667 return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1668 } finally {1669 zeroKey(key);1670 }1671}16721673export async function unlock(password: string): Promise<boolean> {1674 return attemptUnlockWithDerive(password, deriveKey);1675}16761677async function attemptUnlockWithDerive(1678 password: string,1679 derive: typeof deriveKey,1680): Promise<boolean> {1681 vaultUnlocksInFlight++;1682 try {1683 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1684 const epoch = vaultEpoch;1685 const stale = () => epoch !== vaultEpoch;1686 await revokeRecoveryReveal();1687 if (stale()) return false;1688 1689 1690 1691 1692 1693 1694 const [slotA, slotB] = await Promise.all([1695 loadSlot(SLOT_A),1696 loadSlot(SLOT_B),1697 ]);16981699 1700 const [keyA, keyB] = await Promise.all([1701 slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1702 slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1703 ]);17041705 1706 1707 1708 const [resultA, resultB] = await Promise.all([1709 keyA && slotA1710 ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1711 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1712 keyB && slotB1713 ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1714 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1715 ]);1716 const payloadA = resultA.status === "ok" ? resultA.payload : null;1717 const payloadB = resultB.status === "ok" ? resultB.payload : null;17181719 if (stale()) {1720 if (keyA) zeroKey(keyA);1721 if (keyB) zeroKey(keyB);1722 return false;1723 }17241725 if (payloadA && keyA) {1726 if (stale()) {1727 zeroKey(keyA);1728 if (keyB) zeroKey(keyB);1729 return false;1730 }1731 derivedKey = keyA;1732 vaultMode = "real";1733 entries = payloadA.entries;1734 tombstones = payloadA.tombstones;1735 duressConfigured = payloadA.duressConfigured;1736 buildDomainIndexSync(entries);1737 await loadSettings();1738 if (stale()) {1739 await lock();1740 return false;1741 }1742 touchAutoLock();1743 if (keyB) zeroKey(keyB);17441745 1746 1747 rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;1748 if (!rootKey) {1749 await lock();1750 return false;1751 }17521753 1754 if (slotA) {1755 const escrowed = slotA.recovery_vault_key1756 ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;1757 const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);1758 if (escrowed) zeroKey(escrowed);1759 if (stale()) { await lock(); return false; }1760 if (!matches) {1761 try {1762 const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");1763 if (stale()) { await lock(); return false; }1764 await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });1765 if (stale()) { await lock(); return false; }1766 } catch (error) {1767 await lock();1768 throw error;1769 }1770 }1771 }17721773 1774 1775 await reconcilePairSecrets(rootKey);1776 if (stale()) {1777 await lock();1778 return false;1779 }1780 await lockedSyncUnlockHook?.().catch((error) => {1781 console.warn("[Peach sync] locked inbox drain failed:", error);1782 });1783 if (stale()) {1784 await lock();1785 return false;1786 }1787 await resetPinFailedAttempts();1788 if (stale()) {1789 await lock();1790 return false;1791 }1792 await saveSessionKey(keyA, "real", epoch);1793 if (stale()) return false;1794 return true;1795 }17961797 if (payloadB && keyB) {1798 if (stale()) {1799 zeroKey(keyB);1800 if (keyA) zeroKey(keyA);1801 return false;1802 }1803 derivedKey = keyB;1804 vaultMode = "decoy";1805 decoySyncTeardownHook?.();1806 1807 1808 1809 if (rootKey) {1810 rootKey.fill(0);1811 rootKey = null;1812 }1813 entries = payloadB.entries;1814 tombstones = payloadB.tombstones;1815 duressConfigured = false;1816 buildDomainIndexSync(entries);1817 await loadSettings();1818 touchAutoLock();1819 if (keyA) zeroKey(keyA);1820 1821 await dropSessionCache();1822 1823 await notifyIdentitySessionEnded();1824 if (stale()) {1825 await lock();1826 return false;1827 }1828 await saveSessionKey(keyB, "decoy", epoch);1829 if (stale()) return false;1830 return true;1831 }18321833 if (keyA) zeroKey(keyA);1834 if (keyB) zeroKey(keyB);1835 1836 1837 if (resultA.status === "corrupted") {1838 lastUnlockFailureReason = resultA.reason;1839 } else if (resultB.status === "corrupted") {1840 lastUnlockFailureReason = resultB.reason;1841 }1842 return false;1843 } finally { vaultUnlocksInFlight--; }1844}18451846184718481849185018511852const SESSION_KEY_STORAGE = "peach_session_dk";1853185418551856let sessionKeyMutation = Promise.resolve();18571858function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {1859 const task = sessionKeyMutation.then(mutation, mutation);1860 sessionKeyMutation = task.catch(() => undefined);1861 return task;1862}186318641865186618671868let sessionEscrowAvailable = true;18691870187118721873187418751876export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {1877 setSessionAllowed(sessionEscrow);1878 if (sessionEscrow) return;1879 sessionEscrowAvailable = false;1880 await clearSessionKey();1881}18821883async function saveSessionKey(1884 key: Uint8Array,1885 mode: "real" | "decoy",1886 expectedEpoch = vaultEpoch,1887): Promise<void> {1888 const session = chrome.storage.session;1889 if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1890 const stored = { keyHex: hex(key), mode };1891 await mutateSessionKey(async () => {1892 if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1893 await session.set({ [SESSION_KEY_STORAGE]: stored });1894 });1895}18961897async function clearSessionKey(): Promise<void> {1898 const session = chrome.storage.session;1899 if (!session) return;1900 await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));1901}19021903190419051906190719081909let vaultEpoch = 0;1910191119121913let restoreInFlight: Promise<boolean> | null = null;191419151916191719181919192019211922export async function restoreFromSession(): Promise<boolean> {1923 vaultUnlocksInFlight++;1924 try {1925 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1926 if (derivedKey !== null) return true;1927 if (restoreInFlight) return restoreInFlight;1928 const task = restoreFromSessionInner();1929 restoreInFlight = task;1930 try {1931 return await task;1932 } finally {1933 restoreInFlight = null;1934 }1935 } finally { vaultUnlocksInFlight--; }1936}19371938async function restoreFromSessionInner(): Promise<boolean> {1939 const epoch = vaultEpoch;1940 const stale = () => epoch !== vaultEpoch;1941 if (derivedKey !== null) return true;1942 if (!sessionEscrowAvailable) return false;1943 if (!chrome.storage.session) return false;1944 const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1945 if (stale()) return false;1946 const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1947 if (!entry?.keyHex) return false;19481949 const key = unhex(entry.keyHex);1950 const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1951 const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1952 const slot = await loadSlot(slotKey);1953 if (stale()) { zeroKey(key); return false; }1954 if (!slot) { await clearSessionKey(); return false; }19551956 const result = await tryDecryptSlotResult(slot, key, aadTag);1957 if (stale()) { zeroKey(key); return false; }1958 if (result.status !== "ok") { await clearSessionKey(); return false; }19591960 1961 1962 const payload = result.payload;1963 await loadSettings();1964 if (stale()) { zeroKey(key); return false; }19651966 1967 1968 let freshRoot: Uint8Array | null = null;1969 if (entry.mode === "real") {1970 freshRoot = await deriveRootKeyFromDerivedKey(key, slot);1971 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1972 if (!freshRoot) {1973 await lock();1974 return false;1975 }1976 }19771978 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1979 if (freshRoot) {1980 1981 await reconcilePairSecrets(freshRoot);1982 if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }1983 } else {1984 1985 await dropSessionCache();1986 1987 await notifyIdentitySessionEnded();1988 if (stale()) { zeroKey(key); return false; }1989 }1990 derivedKey = key;1991 vaultMode = entry.mode;1992 if (entry.mode === "decoy") decoySyncTeardownHook?.();1993 entries = payload.entries;1994 tombstones = payload.tombstones;1995 duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;1996 if (freshRoot) rootKey = freshRoot;1997 buildDomainIndexSync(entries);1998 touchAutoLock();19992000 await lockedSyncUnlockHook?.().catch((error) => {2001 console.warn("[Peach sync] locked inbox drain failed:", error);2002 });2003 if (stale()) return false;20042005 return true;2006}20072008export async function lock(): Promise<void> {2009 const recoveryRevoked = revokeRecoveryReveal();2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 vaultEpoch++;2020 if (derivedKey) {2021 zeroKey(derivedKey);2022 derivedKey = null;2023 }2024 if (rootKey) {2025 rootKey.fill(0);2026 rootKey = null;2027 }20282029 entries = [];2030 tombstones = new Map();2031 domainIndex = new Map();2032 vaultMode = "real";2033 duressConfigured = false;2034 clearAutoLock();2035 try {2036 chrome.runtime?.sendMessage?.({ type: "VAULT_LOCKED" })?.catch?.(() => undefined);2037 } catch { }2038 await clearSessionKey();2039 await recoveryRevoked;2040 2041 2042 await notifyIdentitySessionEnded();2043}204420452046export function getVaultEpoch(): number {2047 return vaultEpoch;2048}20492050export function isUnlocked(): boolean {2051 return derivedKey !== null;2052}20532054export function isDecoyMode(): boolean {2055 return derivedKey !== null && vaultMode === "decoy";2056}20572058205920602061export async function unlockWithKey(2062 masterKeyHex: string,2063): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2064 vaultUnlocksInFlight++;2065 try {2066 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2067 const epoch = vaultEpoch;2068 const stale = () => epoch !== vaultEpoch;2069 await revokeRecoveryReveal();2070 if (stale()) return { ok: false, error: "vault_locked" };2071 let masterKeyBytes: Uint8Array | null = null;2072 try {2073 masterKeyBytes = unhex(masterKeyHex);2074 const stored = await loadSlot(SLOT_A);2075 if (!stored) return { ok: false, error: "invalid_key" };2076 const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2077 if (!payload || stale()) {2078 zeroKey(masterKeyBytes);2079 return { ok: false, error: "invalid_key" };2080 }20812082 derivedKey = masterKeyBytes;2083 vaultMode = "real";2084 entries = payload.entries;2085 tombstones = payload.tombstones;2086 duressConfigured = payload.duressConfigured;2087 buildDomainIndexSync(entries);2088 await loadSettings();2089 touchAutoLock();20902091 rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2092 if (!rootKey) {2093 await lock();2094 return { ok: false, error: "invalid_key" };2095 }2096 await reconcilePairSecrets(rootKey);2097 if (stale()) {2098 await lock();2099 return { ok: false, error: "invalid_key" };2100 }2101 await saveSessionKey(masterKeyBytes, "real", epoch);2102 if (stale()) return { ok: false, error: "invalid_key" };2103 return { ok: true, entries };2104 } catch {2105 if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2106 return { ok: false, error: "invalid_key" };2107 }2108 } finally { vaultUnlocksInFlight--; }2109}211021112112211321142115211621172118export async function exportDuressSlotForAdoption(): Promise<string | null> {2119 if (!(await isDuressEnabled())) return null;2120 const slotB = await loadSlot(SLOT_B);2121 if (!slotB) return null;2122 return JSON.stringify(slotB);2123}21242125212621272128212921302131export async function installAdoptedDuressSlot(json: string): Promise<void> {2132 if (vaultCreatesInFlight) throw new Error("vault_changed");2133 vaultWritesInFlight++;2134 try {2135 let parsed: StoredVault;2136 try {2137 const raw = JSON.parse(json) as unknown;2138 if (!hasValidVaultSchema(raw)) {2139 throw new Error("invalid_duress_slot_shape");2140 }2141 parsed = raw;2142 } catch (err) {2143 if (err instanceof SyntaxError) {2144 throw new Error("invalid_duress_slot_shape");2145 }2146 throw err;2147 }2148 await writeSlot(SLOT_B, parsed);2149 } finally { vaultWritesInFlight--; }2150}21512152215321542155215621572158215921602161216221632164216521662167216821692170export async function unlockFromCodex(params: {2171 slotA: string; 2172 slotB: string | null; 2173 timestamp: number;2174 masterPassphrase: string;2175}): Promise<2176 | { ok: true; entryCount: number }2177 | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2178> {2179 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2180 vaultReplacementInFlight = true;2181 try {2182 let parsedSlotA: StoredVault;2183 let parsedSlotB: StoredVault | null = null;2184 try {2185 const rawA = JSON.parse(params.slotA) as unknown;2186 if (!hasValidVaultSchema(rawA)) {2187 return { ok: false, reason: "invalid_slot_format" };2188 }2189 parsedSlotA = rawA;2190 if (params.slotB !== null) {2191 const rawB = JSON.parse(params.slotB) as unknown;2192 if (!hasValidVaultSchema(rawB)) {2193 return { ok: false, reason: "invalid_slot_format" };2194 }2195 parsedSlotB = rawB;2196 }2197 } catch {2198 return { ok: false, reason: "invalid_slot_format" };2199 }22002201 2202 2203 2204 const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2205 const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2206 if (!trialPayload) {2207 zeroKey(trialKey);2208 return { ok: false, reason: "wrong_passphrase" };2209 }2210 const hasEscrow =2211 !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2212 if (!hasEscrow) {2213 zeroKey(trialKey);2214 return { ok: false, reason: "missing_root_escrow" };2215 }2216 const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2217 if (!stagedRootKey) {2218 zeroKey(trialKey);2219 return { ok: false, reason: "wrong_passphrase" };2220 }2221 zeroKey(stagedRootKey);2222 zeroKey(trialKey);22232224 2225 const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);22262227 2228 22292230 2231 2232 await takeVaultSnapshot("restore");2233 const previousSlotA = await loadSlot(SLOT_A);2234 const previousSlotB = await loadSlot(SLOT_B);2235 let slotACommitted = false;2236 let slotBCommitted = false;2237 try {2238 await writeSlot(SLOT_A, parsedSlotA);2239 slotACommitted = true;2240 await writeSlot(SLOT_B, stagedSlotB);2241 slotBCommitted = true;2242 await chrome.storage.local.set({2243 peach_last_modified_at: String(params.timestamp),2244 });2245 } catch (err) {2246 if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2247 if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2248 throw err;2249 }22502251 2252 2253 const ok = await unlock(params.masterPassphrase);2254 if (!ok) {2255 2256 return { ok: false, reason: "wrong_passphrase" };2257 }2258 return { ok: true, entryCount: getEntries().length };2259 } finally {2260 vaultReplacementInFlight = false;2261 }2262}22632264226522662267export function getDerivedKeyHex(): string {2268 if (!derivedKey) throw new Error("vault_not_unlocked");2269 return hex(derivedKey);2270}22712272227322742275227622772278227922802281228222832284228522862287export function getRootKeyHex(): string | null {2288 return rootKey ? hex(rootKey) : null;2289}22902291export function getEntries(): VaultEntry[] {2292 if (!derivedKey) throw new Error("vault_locked");2293 return entries.filter((entry) => !entry.deletedAt);2294}22952296const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;22972298export function getIdentities(): SavedIdentity[] {2299 if (!derivedKey) throw new Error("vault_locked");2300 const active = entries.filter((e) => !e.deletedAt && e.type === "login");23012302 const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2303 const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();23042305 for (const entry of active) {2306 const domain = extractDomain(entry.url ?? "") ?? "";2307 const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;23082309 function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2310 const existing = map.get(v);2311 if (!existing || modifiedAt > existing.lastUsed) {2312 map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2313 } else {2314 map.set(v, { ...existing, count: existing.count + 1 });2315 }2316 }23172318 const uVal = entry.username?.trim();2319 if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);23202321 2322 2323 const eVal = entry.email?.trim();2324 if (eVal) tally(emailMap, eVal);2325 }23262327 const toIdentity = (type: "email" | "username") =>2328 ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2329 value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2330 });23312332 return [2333 ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2334 ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2335 ];2336}23372338export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2339 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");23402341 const now = Date.now();2342 const added: VaultEntry[] = [];2343 for (const draft of drafts) {2344 try {2345 const sanitized = sanitizeEntryDraft(draft);2346 const nextEntry: VaultEntry = {2347 ...sanitized,2348 id: crypto.randomUUID(),2349 createdAt: now,2350 modifiedAt: monotonicEntryTimestamp(),2351 };2352 entries.push(nextEntry);2353 added.push(nextEntry);2354 } catch {2355 2356 }2357 }23582359 if (added.length > 0) {2360 await persistEntries();2361 }23622363 return added;2364}236523662367236823692370237123722373export async function restoreEntries(2374 incoming: VaultEntry[],2375 mode: "replace" | "merge"2376): Promise<{ added: number; updated: number; skipped: number }> {2377 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");23782379 2380 2381 2382 if (mode === "replace" && incoming.length === 0) {2383 throw new Error("refuse to replace with empty entry set");2384 }23852386 let added = 0;2387 let updated = 0;2388 let skipped = 0;23892390 if (mode === "replace") {2391 entries = [];2392 for (const entry of incoming) {2393 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2394 if (!normalized) {2395 skipped += 1;2396 continue;2397 }2398 entries.push(normalized);2399 if (normalized.deletedAt) {2400 tombstones.set(2401 normalized.id,2402 Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2403 );2404 } else {2405 tombstones.delete(normalized.id);2406 }2407 added += 1;2408 }2409 } else {2410 const byId = new Map<string, VaultEntry>();2411 for (const e of entries) byId.set(e.id, e);24122413 for (const entry of incoming) {2414 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2415 if (!normalized) {2416 skipped += 1;2417 continue;2418 }2419 const existing = byId.get(normalized.id);2420 if (!existing) {2421 entries.push(normalized);2422 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2423 else tombstones.delete(normalized.id);2424 added += 1;2425 } else if (normalized.modifiedAt > existing.modifiedAt) {2426 const idx = entries.findIndex((e) => e.id === existing.id);2427 if (idx !== -1) {2428 entries[idx] = normalized;2429 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2430 else tombstones.delete(normalized.id);2431 updated += 1;2432 }2433 } else {2434 skipped += 1;2435 }2436 }2437 }24382439 await persistEntries("import");2440 return { added, updated, skipped };2441}244224432444244524462447244824492450245124522453245424552456245724582459const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;24602461function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {2462 if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;2463 return { ...entry, id: crypto.randomUUID() };2464}246524662467246824692470247124722473function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {2474 if (!entry || typeof entry !== "object") return null;2475 const title = typeof entry.title === "string" ? entry.title.trim() : "";2476 if (!title) return null;2477 const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();2478 const now = Date.now();2479 const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;2480 const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;24812482 2483 2484 const normalized = normalizeEntry({2485 ...entry,2486 id,2487 title,2488 type: entry.type ?? "login",2489 createdAt,2490 modifiedAt,2491 });24922493 if (normalized.passkey) {2494 normalized.passkey = sanitizePasskey(normalized.passkey);2495 }2496 if (normalized.canary) {2497 normalized.canary = sanitizeCanary(normalized.canary);2498 }2499 2500 normalized.tags = sanitizeTags(normalized.tags);25012502 2503 2504 if (2505 normalized.type === "login" &&2506 !normalized.passkey &&2507 typeof normalized.password !== "string"2508 ) {2509 return null;2510 }2511 if (entry.passkey && !normalized.passkey) {2512 2513 2514 return null;2515 }25162517 return normalized;2518}2519252025212522252325242525function sanitizePasskey(pk: unknown): PasskeyData | undefined {2526 if (!pk || typeof pk !== "object") return undefined;2527 const r = pk as Record<string, unknown>;2528 if (2529 typeof r.rpId !== "string" || !r.rpId ||2530 typeof r.credentialId !== "string" || !r.credentialId ||2531 typeof r.publicKeyCose !== "string" ||2532 typeof r.userHandle !== "string" ||2533 typeof r.userName !== "string"2534 ) {2535 return undefined;2536 }2537 return {2538 rpId: r.rpId,2539 rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2540 credentialId: r.credentialId,2541 publicKeyCose: r.publicKeyCose,2542 privateKeyJwk:2543 r.privateKeyJwk && typeof r.privateKeyJwk === "object"2544 ? (r.privateKeyJwk as JsonWebKey)2545 : undefined,2546 userHandle: r.userHandle,2547 userName: r.userName,2548 userDisplayName:2549 typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2550 algorithm: r.algorithm === -8 ? -8 : -7,2551 signCount: typeof r.signCount === "number" ? r.signCount : 0,2552 aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2553 backupEligible: r.backupEligible === true,2554 backupState: r.backupState === true,2555 lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2556 browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2557 transports: Array.isArray(r.transports)2558 ? r.transports.filter((t): t is string => typeof t === "string")2559 : undefined,2560 createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2561 };2562}25632564256525662567256825692570257125722573function sanitizeCanary(c: unknown): Canary | undefined {2574 if (!c || typeof c !== "object") return undefined;2575 const r = c as Record<string, unknown>;2576 if (typeof r.webhookUrl !== "string") return undefined;2577 let url: URL;2578 try {2579 url = new URL(r.webhookUrl);2580 } catch {2581 return undefined;2582 }2583 if (url.protocol !== "https:") return undefined;2584 return {2585 webhookUrl: url.toString(),2586 label: typeof r.label === "string" ? r.label : undefined,2587 lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2588 pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2589 };2590}25912592259325942595259625972598function sanitizeTags(tags: unknown): string[] | undefined {2599 if (!Array.isArray(tags)) return undefined;2600 const out: string[] = [];2601 for (const t of tags) {2602 if (typeof t !== "string") continue;2603 const trimmed = t.trim();2604 if (!trimmed) continue;2605 out.push(trimmed.slice(0, 256));2606 if (out.length >= 255) break;2607 }2608 return out.length > 0 ? out : undefined;2609}261026112612261326142615export async function clearVaultEntries(2616 confirmation: "REPLACE_ALL"2617): Promise<void> {2618 if (confirmation !== "REPLACE_ALL") {2619 throw new Error("clearVaultEntries requires explicit confirmation");2620 }2621 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2622 for (const entry of entries) {2623 if (!entry.deletedAt) {2624 const stamp = monotonicEntryTimestamp(Math.max(2625 entry.modifiedAt,2626 tombstones.get(entry.id) ?? 0,2627 ));2628 entry.deletedAt = stamp;2629 entry.modifiedAt = stamp;2630 tombstones.set(entry.id, stamp);2631 }2632 }2633 await persistEntries();2634}26352636export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2637 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");26382639 const sanitized = sanitizeEntryDraft(entry);2640 const now = Date.now();2641 const stamp = monotonicEntryTimestamp();2642 const nextEntry: VaultEntry = {2643 ...sanitized,2644 id: crypto.randomUUID(),2645 createdAt: now,2646 modifiedAt: stamp,2647 2648 2649 passwordChangedAt: sanitized.password ? stamp : undefined,2650 };26512652 2653 2654 2655 const rollback = entries;2656 entries = [...entries, nextEntry];2657 try {2658 await persistEntries();2659 } catch (err) {2660 entries = rollback;2661 throw err;2662 }26632664 2665 if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2666 const breachEpoch = vaultEpoch;2667 checkBreach(nextEntry.password).then(async (count) => {2668 if (count > 0 && breachEpoch === vaultEpoch && !vaultCreatesInFlight) {2669 const idx = entries.findIndex((e) => e.id === nextEntry.id);2670 if (idx !== -1) {2671 entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2672 await persistEntries();2673 }2674 }2675 });2676 }26772678 fireSyncTrigger("vault_change");26792680 return nextEntry;2681}268226832684export async function consolidatePasskeyEntries(): Promise<void> {2685 if (!derivedKey || vaultCreatesInFlight) return;2686 const epoch = vaultEpoch;2687 const rollback = entries;2688 const next = entries.map((entry) => ({ ...entry }));2689 if (!mergePasskeyOnlyIntoLogins(next).merged) return;2690 const unchanged = next.map((entry) => ({ entry, modifiedAt: entry.modifiedAt }));2691 entries = next;2692 try {2693 await persistEntries();2694 } catch (err) {2695 2696 if (epoch === vaultEpoch && entries === next && entries.length === unchanged.length &&2697 unchanged.every(({ entry, modifiedAt }, index) => entries[index] === entry && entry.modifiedAt === modifiedAt)) {2698 entries = rollback;2699 buildDomainIndexSync(entries);2700 }2701 throw err;2702 }2703}27042705export async function updateEntry(2706 id: string,2707 patch: Partial<VaultEntry>2708): Promise<void> {2709 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");27102711 const idx = entries.findIndex((entry) => entry.id === id);2712 if (idx === -1 || entries[idx].deletedAt) {2713 throw new Error("entry_not_found");2714 }27152716 const current = entries[idx];2717 const sanitizedPatch = sanitizeEntryPatch(patch);2718 2719 2720 2721 const passwordChanged =2722 "password" in patch &&2723 typeof sanitizedPatch.password === "string" &&2724 sanitizedPatch.password !== current.password;2725 const stamp = monotonicEntryTimestamp(current.modifiedAt);2726 2727 2728 2729 2730 2731 2732 2733 const priorPassword = current.password;2734 const shouldCapture =2735 passwordChanged &&2736 typeof priorPassword === "string" &&2737 priorPassword.length > 0 &&2738 current.passwordHistory?.[0]?.password !== priorPassword;2739 const nextHistory = shouldCapture2740 ? [2741 { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2742 ...(current.passwordHistory ?? []),2743 ].slice(0, PASSWORD_HISTORY_MAX)2744 : current.passwordHistory;2745 entries[idx] = {2746 ...current,2747 ...sanitizedPatch,2748 modifiedAt: stamp,2749 ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2750 };2751275227532754 2755 if (entries[idx].type === "card" && !entries[idx].cardNumber) {2756 entries[idx] = current;2757 throw new Error("card number is required for card entries");2758 }27592760 2761 2762 2763 2764 try {2765 await persistEntries();2766 } catch (err) {2767 entries[idx] = current;2768 throw err;2769 }27702771 2772 2773 if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2774 entries[idx] = { ...entries[idx], breach: undefined };2775 await persistEntries();2776 const password = entries[idx].password;2777 if (password) {2778 checkBreach(password).then(async (count) => {2779 const i = entries.findIndex((e) => e.id === id);2780 if (i !== -1 && count > 0) {2781 entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2782 await persistEntries();2783 }2784 });2785 }2786 }27872788 fireSyncTrigger("vault_change");2789}27902791export async function deleteEntry(id: string): Promise<void> {2792 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");27932794 const entry = entries.find((item) => item.id === id);2795 if (!entry || entry.deletedAt) {2796 throw new Error("entry_not_found");2797 }27982799 2800 2801 2802 const previousModifiedAt = entry.modifiedAt;2803 const previousTombstone = tombstones.get(id);2804 const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2805 entry.deletedAt = stamp;2806 entry.modifiedAt = stamp;2807 tombstones.set(id, stamp);2808 2809 2810 try {2811 await persistEntries();2812 } catch (err) {2813 delete entry.deletedAt;2814 entry.modifiedAt = previousModifiedAt;2815 if (previousTombstone === undefined) tombstones.delete(id);2816 else tombstones.set(id, previousTombstone);2817 throw err;2818 }2819 fireSyncTrigger("vault_change");2820}28212822export function getDeletedEntries(): VaultEntry[] {2823 if (!derivedKey) return [];2824 return entries.filter((e) => !!e.deletedAt);2825}282628272828export function getTombstoneManifest(): Record<string, number> {2829 if (!derivedKey) return {};2830 return Object.fromEntries(tombstones);2831}2832283328342835283628372838export async function getVaultVersion(): Promise<number> {2839 try {2840 const raw = await chrome.storage.local.get("peach_last_modified_at");2841 const v = (raw as Record<string, unknown>).peach_last_modified_at;2842 if (typeof v === "number") return v;2843 if (typeof v === "string" && v !== "") {2844 const n = Number.parseInt(v, 10);2845 return Number.isFinite(n) ? n : 0;2846 }2847 return 0;2848 } catch {2849 return 0;2850 }2851}2852285328542855285628572858285928602861286228632864export async function applyMergedRemoteEntries(2865 remoteEntries: VaultEntry[],2866 remoteTombstones: Record<string, number>,2867): Promise<{ received: number; applied: number; conflicts: number }> {2868 2869 2870 2871 2872 2873 2874 if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");28752876 const received = remoteEntries.length + Object.keys(remoteTombstones).length;2877 let applied = 0;2878 let conflicts = 0;28792880 const byId = new Map<string, VaultEntry>();2881 for (const e of entries) byId.set(e.id, e);28822883 const mergeNow = Date.now();2884 const remoteTombstoneTimes = new Map<string, number>();2885 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2886 if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {2887 remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));2888 }2889 }28902891 for (const remote of remoteEntries) {2892 const sanitized = sanitizeRestoredEntry(remote);2893 if (!sanitized) continue;2894 2895 2896 2897 sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2898 if (typeof sanitized.deletedAt === "number") {2899 sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2900 }2901 const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);2902 const localTombstoneTs = tombstones.get(sanitized.id);2903 const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);2904 if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {2905 continue;2906 }2907 const local = byId.get(sanitized.id);2908 if (!local) {2909 entries.push(sanitized);2910 byId.set(sanitized.id, sanitized);2911 tombstones.delete(sanitized.id);2912 applied += 1;2913 } else if (sanitized.modifiedAt > local.modifiedAt) {2914 const idx = entries.findIndex((e) => e.id === local.id);2915 if (idx !== -1) {2916 entries[idx] = sanitized;2917 byId.set(sanitized.id, sanitized);2918 tombstones.delete(sanitized.id);2919 applied += 1;2920 if (!local.deletedAt) conflicts += 1;2921 }2922 }2923 }29242925 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2926 if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;2927 2928 const deletedAt = remoteTombstoneTimes.get(id)!;2929 const knownTombstone = tombstones.get(id);2930 if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;2931 const local = byId.get(id);2932 if (!local) {2933 tombstones.set(id, deletedAt);2934 applied += 1;2935 continue;2936 }2937 if (local.deletedAt && local.deletedAt >= deletedAt) continue;2938 if (deletedAt < local.modifiedAt) continue;2939 const idx = entries.findIndex((e) => e.id === id);2940 if (idx !== -1) {2941 entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2942 tombstones.set(id, deletedAt);2943 applied += 1;2944 }2945 }29462947 if (applied > 0 && vaultMode === "real") {2948 await persistEntries("sync_received");2949 buildDomainIndexSync(entries);2950 2951 2952 2953 2954 try {2955 void chrome.runtime2956 .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })2957 .catch(() => undefined);2958 } catch {2959 2960 }2961 }2962 return { received, applied, conflicts };2963}29642965export async function restoreEntry(id: string): Promise<void> {2966 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2967 const entry = entries.find((e) => e.id === id && e.deletedAt);2968 if (!entry) throw new Error("deleted entry not found");2969 const previousDeletedAt = entry.deletedAt;2970 const previousModifiedAt = entry.modifiedAt;2971 const previousTombstone = tombstones.get(id);2972 delete entry.deletedAt;2973 entry.modifiedAt = monotonicEntryTimestamp(Math.max(2974 entry.modifiedAt,2975 previousTombstone ?? 0,2976 ));2977 tombstones.delete(id);2978 try {2979 await persistEntries();2980 } catch (err) {2981 entry.deletedAt = previousDeletedAt;2982 entry.modifiedAt = previousModifiedAt;2983 if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);2984 throw err;2985 }2986 buildDomainIndexSync(entries);2987}29882989export async function purgeEntry(id: string): Promise<void> {2990 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2991 const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2992 if (idx === -1) throw new Error("deleted entry not found");2993 const entry = entries[idx]!;2994 tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));2995 entries.splice(idx, 1);2996 await persistEntries();2997}299829993000export async function purgeExpiredTrash(retentionMs: number): Promise<number> {3001 if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;3002 const cutoff = Date.now() - retentionMs;3003 const before = entries.length;3004 for (const entry of entries) {3005 if (entry.deletedAt && entry.deletedAt < cutoff) {3006 tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));3007 }3008 }3009 entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));3010 const purged = before - entries.length;3011 if (purged > 0) await persistEntries();3012 return purged;3013}30143015export function queryDomain(domain: string): VaultEntry[] {3016 return domainIndex.get(domain) ?? [];3017}30183019export function getEntryById(id: string): VaultEntry | undefined {3020 return entries.find((entry) => entry.id === id && !entry.deletedAt);3021}30223023async function persistSlotA(3024 reason: VaultSnapshot["reason"] = "local_save",3025): Promise<StoredVault> {3026 if (!derivedKey) throw new Error("vault_locked");3027 const epoch = vaultEpoch;3028 const throwIfStale = () => {3029 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3030 };30313032 const slotA = await loadSlot(SLOT_A);3033 throwIfStale();3034 if (!slotA) throw new Error("missing slot A");30353036 3037 3038 await takeVaultSnapshot(reason);3039 throwIfStale();30403041 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3042 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3043 throwIfStale();30443045 3046 const nextSlotA: StoredVault = {3047 ...slotA,3048 nonce,3049 ciphertext,3050 tag,3051 3052 };30533054 3055 3056 3057 3058 3059 3060 let slotACommitted = false;3061 try {3062 throwIfStale();3063 await writeSlot(SLOT_A, nextSlotA);3064 slotACommitted = true;3065 throwIfStale();30663067 3068 3069 3070 if (!duressConfigured) {3071 throwIfStale();3072 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3073 throwIfStale();3074 }3075 3076 3077 3078 3079 3080 if (reason !== "sync_received") {3081 throwIfStale();3082 await stampLocalVaultMutation();3083 throwIfStale();3084 }3085 } catch (err) {3086 3087 3088 if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3089 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3090 throw err;3091 }30923093 return nextSlotA;3094}30953096async function persistSlotB(): Promise<void> {3097 if (!derivedKey) throw new Error("vault_locked");30983099 const slotB = await loadSlot(SLOT_B);3100 if (!slotB) throw new Error("missing slot B");31013102 3103 3104 3105 3106 const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3107 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");31083109 await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3110 3111 3112 3113 try {3114 await stampLocalVaultMutation();3115 } catch (err) {3116 await writeSlot(SLOT_B, slotB).catch(() => {});3117 throw err;3118 }3119}31203121async function persistEntries(3122 reason: VaultSnapshot["reason"] = "local_save",3123): Promise<void> {3124 if (vaultCreatesInFlight) throw new Error("vault_changed");3125 vaultWritesInFlight++;3126 try {3127 if (!derivedKey) throw new Error("vault_locked");31283129 3130 3131 const previousTombstones = tombstones;3132 const pendingTombstones = new Map(tombstones);3133 tombstones = pendingTombstones;3134 reconcileTombstones();3135 try {3136 if (vaultMode === "decoy") {3137 await persistSlotB();3138 } else {3139 await persistSlotA(reason);3140 }3141 } catch (err) {3142 if (tombstones === pendingTombstones) tombstones = previousTombstones;3143 throw err;3144 }3145 buildDomainIndexSync(entries);3146 await refreshLockedSyncState();3147 } finally { vaultWritesInFlight--; }3148}3149315031513152315331543155function allowHttpUrl(url: string | undefined): string {3156 const trimmed = url?.trim() ?? "";3157 if (!trimmed) return "";3158 try {3159 const parsed = new URL(trimmed);3160 if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3161 } catch {3162 3163 }3164 return trimmed;3165}31663167function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3168 if (!Array.isArray(values)) return undefined;3169 const seen = new Set<string>();3170 const cleaned: string[] = [];3171 for (const value of values) {3172 const trimmed = typeof value === "string" ? value.trim() : "";3173 if (!trimmed) continue;3174 if (!allowHttpUrl(trimmed)) continue;3175 const key = trimmed.toLowerCase();3176 if (seen.has(key)) continue;3177 seen.add(key);3178 cleaned.push(trimmed);3179 }3180 return cleaned.length > 0 ? cleaned : undefined;3181}31823183function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3184 const title = entry.title.trim();3185 const type: VaultEntry["type"] = entry.type ?? "login";31863187 if (!title) throw new Error("title is required");31883189 if (entry.passkey) {3190 const p = entry.passkey;3191 if (3192 !p.rpId ||3193 !p.credentialId ||3194 !p.publicKeyCose ||3195 !p.userHandle ||3196 !p.userName ||3197 (p.algorithm !== -7 && p.algorithm !== -8)3198 ) {3199 throw new Error("invalid passkey credential");3200 }3201 }3202 if (type === "card") {3203 if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3204 throw new Error("cardholder name and card number are required");3205 }3206 }32073208 return {3209 type,3210 title,3211 username: type === "login" ? entry.username?.trim() ?? "" : undefined,3212 email: type === "login" ? entry.email?.trim() || undefined : undefined,3213 password: type === "login" ? entry.password : undefined,3214 url: type === "login" ? allowHttpUrl(entry.url) : undefined,3215 additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3216 totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3217 3218 3219 totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3220 totpDigits: type === "login" ? entry.totpDigits : undefined,3221 totpPeriod: type === "login" ? entry.totpPeriod : undefined,3222 notes: entry.notes?.trim() || undefined,3223 breach: type === "login" ? entry.breach : undefined,3224 3225 3226 canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3227 tags: sanitizeTags(entry.tags),3228 passkey: entry.passkey,3229 cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3230 cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3231 expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3232 expYear: type === "card" ? entry.expYear?.trim() : undefined,3233 cvc: type === "card" ? entry.cvc?.trim() : undefined,3234 cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3235 network: type === "card" ? entry.network : undefined,3236 last4: type === "card" ? entry.last4?.trim() : undefined,3237 };3238}32393240function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3241 const nextPatch: Partial<VaultEntry> = {};32423243 if ("type" in patch) {3244 nextPatch.type = patch.type;3245 }32463247 if ("title" in patch) {3248 const title = patch.title?.trim() ?? "";3249 if (!title) throw new Error("title is required");3250 nextPatch.title = title;3251 }32523253 if ("url" in patch) {3254 nextPatch.url = allowHttpUrl(patch.url);3255 }32563257 if ("additionalUrls" in patch) {3258 const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3259 const seen = new Set<string>();3260 const cleaned: string[] = [];3261 for (const value of incoming) {3262 const trimmed = typeof value === "string" ? value.trim() : "";3263 if (!trimmed || !allowHttpUrl(trimmed)) continue;3264 const key = trimmed.toLowerCase();3265 if (seen.has(key)) continue;3266 seen.add(key);3267 cleaned.push(trimmed);3268 }3269 nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3270 }32713272 if ("username" in patch) {3273 nextPatch.username = patch.username?.trim() ?? "";3274 }32753276 if ("email" in patch) {3277 nextPatch.email = patch.email?.trim() || undefined;3278 }32793280 if ("password" in patch) {3281 const password = patch.password ?? "";3282 3283 nextPatch.password = password || undefined;3284 }32853286 if ("totp" in patch) {3287 nextPatch.totp = patch.totp?.trim() || undefined;3288 }32893290 if ("totpAlgorithm" in patch) {3291 nextPatch.totpAlgorithm = patch.totpAlgorithm;3292 }32933294 if ("totpDigits" in patch) {3295 nextPatch.totpDigits = patch.totpDigits;3296 }32973298 if ("totpPeriod" in patch) {3299 nextPatch.totpPeriod = patch.totpPeriod;3300 }33013302 if ("notes" in patch) {3303 nextPatch.notes = patch.notes?.trim() || undefined;3304 }33053306 if ("breach" in patch) {3307 nextPatch.breach = patch.breach;3308 }33093310 if ("canary" in patch) {3311 3312 3313 nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3314 }33153316 if ("passkey" in patch) {3317 3318 3319 if (patch.passkey === undefined || patch.passkey === null) {3320 nextPatch.passkey = undefined;3321 } else {3322 const sanitized = sanitizePasskey(patch.passkey);3323 if (!sanitized) throw new Error("invalid passkey credential");3324 nextPatch.passkey = sanitized;3325 }3326 }33273328 if ("tags" in patch) {3329 3330 nextPatch.tags = sanitizeTags(patch.tags);3331 }33323333 if ("cardholderName" in patch) {3334 nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3335 }3336 if ("cardNumber" in patch) {3337 const n = patch.cardNumber ?? "";3338 nextPatch.cardNumber = n || undefined;3339 }3340 if ("expMonth" in patch) {3341 nextPatch.expMonth = patch.expMonth?.trim() || undefined;3342 }3343 if ("expYear" in patch) {3344 nextPatch.expYear = patch.expYear?.trim() || undefined;3345 }3346 if ("cvc" in patch) {3347 nextPatch.cvc = patch.cvc?.trim() || undefined;3348 }3349 if ("cardNickname" in patch) {3350 nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3351 }3352 if ("network" in patch) {3353 nextPatch.network = patch.network;3354 }3355 if ("last4" in patch) {3356 nextPatch.last4 = patch.last4?.trim() || undefined;3357 }33583359 return nextPatch;3360}33613362function normalizeEntry(entry: VaultEntry): VaultEntry {3363 const base: VaultEntry = {3364 id: entry.id,3365 type: entry.type,3366 title: entry.title,3367 username: entry.username,3368 email: entry.email,3369 password: entry.password,3370 url: entry.url,3371 additionalUrls:3372 "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3373 ? entry.additionalUrls3374 : undefined,3375 totp: entry.totp,3376 3377 totpAlgorithm: entry.totpAlgorithm,3378 totpDigits: entry.totpDigits,3379 totpPeriod: entry.totpPeriod,3380 notes: entry.notes,3381 breach: entry.breach,3382 3383 3384 3385 passwordChangedAt:3386 "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3387 3388 3389 3390 passwordHistory:3391 "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3392 ? entry.passwordHistory3393 : undefined,3394 canary: entry.canary,3395 passkey: entry.passkey,3396 createdAt: entry.createdAt,3397 modifiedAt: entry.modifiedAt,3398 deletedAt: entry.deletedAt,3399 tags: entry.tags,3400 cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3401 cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3402 expMonth: "expMonth" in entry ? entry.expMonth : undefined,3403 expYear: "expYear" in entry ? entry.expYear : undefined,3404 cvc: "cvc" in entry ? entry.cvc : undefined,3405 cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3406 network: "network" in entry ? entry.network : undefined,3407 last4: "last4" in entry ? entry.last4 : undefined,3408 };34093410 return base;3411}3412341334143415341634173418function entryDupeKey(e: VaultEntry): string {3419 if (e.passkey) {3420 3421 const content = Object.fromEntries(Object.entries(e)3422 .filter(([key]) => key !== "id" && key !== "createdAt" && key !== "modifiedAt")3423 .sort(([a], [b]) => a.localeCompare(b)));3424 return `passkey|${e.passkey.rpId}|${e.passkey.credentialId}|${JSON.stringify(content)}`;3425 }3426 if (e.type === "note") return `note|${e.title.toLowerCase()}`;3427 return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3428}342934303431export function countDuplicates(): number {3432 const best = new Map<string, VaultEntry>();3433 let dupeCount = 0;3434 for (const e of entries.filter((e) => !e.deletedAt)) {3435 const key = entryDupeKey(e);3436 const existing = best.get(key);3437 if (!existing) {3438 best.set(key, e);3439 } else {3440 dupeCount++;3441 3442 if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3443 best.set(key, e);3444 }3445 }3446 }3447 return dupeCount;3448}344934503451345234533454export async function deduplicateEntries(): Promise<number> {3455 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3456 3457 3458 if (vaultMode === "decoy") {3459 throw new Error("deduplicate disabled in decoy mode");3460 }34613462 const best = new Map<string, VaultEntry>();3463 for (const e of entries.filter((en) => !en.deletedAt)) {3464 const key = entryDupeKey(e);3465 const existing = best.get(key);3466 if (!existing) {3467 best.set(key, e);3468 } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3469 best.set(key, e);3470 }3471 }34723473 const keepIds = new Set(Array.from(best.values()).map((e) => e.id));3474 let removed = 0;3475 entries = entries.map((e) => {3476 if (!e.deletedAt && !keepIds.has(e.id)) {3477 removed++;3478 const deletedAt = monotonicEntryTimestamp(Math.max(3479 e.modifiedAt,3480 tombstones.get(e.id) ?? 0,3481 ));3482 tombstones.set(e.id, deletedAt);3483 return { ...e, deletedAt };3484 }3485 return e;3486 });34873488 if (removed > 0) await persistEntries();3489 return removed;3490}349134923493349434953496349734983499const HISTORY_KEY = "peach_vault_history";3500const HISTORY_MAX = 5;350135023503350435053506function bucketEntryCount(n: number): number {3507 if (n <= 0) return 0;3508 if (n <= 10) return 10;3509 if (n <= 25) return 25;3510 if (n <= 50) return 50;3511 if (n <= 100) return 100;3512 if (n <= 250) return 250;3513 if (n <= 500) return 500;3514 return Math.ceil(n / 500) * 500;3515}35163517351835193520352135223523export async function takeVaultSnapshot(3524 reason: VaultSnapshot["reason"],3525): Promise<void> {3526 if (recoveryInFlight || vaultCreatesInFlight) return;3527 3528 3529 3530 if (vaultMode === "decoy") return;3531 vaultWritesInFlight++;3532 try {3533 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);3534 const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];3535 const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];35363537 3538 3539 3540 if (!slotA) return;35413542 const vault_a = JSON.stringify(slotA);3543 const vault_b = JSON.stringify(slotB ?? slotA);35443545 3546 3547 3548 3549 3550 3551 let entryCount: number | null = null;3552 if (derivedKey && vaultMode === "real") {3553 try {3554 entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);3555 } catch {3556 entryCount = null;3557 }3558 }35593560 const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3561 const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)3562 ? existingRaw3563 : { snapshots: [] };35643565 3566 3567 3568 const latest = history.snapshots[0];3569 if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3570 return;3571 }35723573 const snapshot: VaultSnapshot = {3574 id: crypto.randomUUID(),3575 savedAt: Date.now(),3576 reason,3577 vault_a,3578 vault_b,3579 entryCount,3580 };35813582 history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3583 if (recoveryInFlight || vaultCreatesInFlight) return;3584 await chrome.storage.local.set({ [HISTORY_KEY]: history });3585 } catch (err) {3586 3587 3588 3589 3590 console.warn('[Peach] takeVaultSnapshot failed:', err);3591 if (String(err).includes('QUOTA') || String(err).includes('quota')) {3592 try {3593 await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3594 } catch {3595 3596 }3597 }3598 } finally { vaultWritesInFlight--; }3599}360036013602export async function clearVaultHistory(): Promise<void> {3603 if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");3604 vaultWritesInFlight++;3605 try {3606 await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3607 } catch {3608 3609 } finally { vaultWritesInFlight--; }3610}361136123613export async function getVaultHistory(): Promise<VaultSnapshot[]> {3614 if (vaultMode === "decoy") return [];3615 const raw = await chrome.storage.local.get(HISTORY_KEY);3616 const value = (raw as Record<string, unknown>)[HISTORY_KEY];3617 return sanitizeHistory(value);3618}361936203621362236233624export async function restoreVaultSnapshot(3625 snapshotId: string,3626): Promise<{ ok: true } | { ok: false; error: string }> {3627 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };3628 vaultReplacementInFlight = true;3629 try {3630 if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3631 const history = await getVaultHistory();3632 const snapshot = history.find((s) => s.id === snapshotId);3633 if (!snapshot) return { ok: false, error: "snapshot_not_found" };36343635 const restoredA = parseHistorySlot(snapshot.vault_a);3636 const restoredB = parseHistorySlot(snapshot.vault_b);3637 if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };36383639 await takeVaultSnapshot("restore");3640 const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3641 const previousA = (current as Record<string, unknown>)[SLOT_A];3642 const previousB = (current as Record<string, unknown>)[SLOT_B];3643 try {3644 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };3645 await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3646 await stampLocalVaultMutation();3647 } catch {3648 try {3649 await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3650 } catch {3651 3652 }3653 return { ok: false, error: "snapshot_corrupt" };3654 }36553656 await lock();3657 return { ok: true };3658 } finally {3659 vaultReplacementInFlight = false;3660 }3661}366236633664366536663667366836693670367136723673367436753676export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3677 if (vaultCreatesInFlight) throw new Error("vault_changed");3678 const rotationEpoch = vaultEpoch;3679 const removalEpoch = vaultRemovalEpoch;3680 vaultWritesInFlight++;3681 try {3682 if (!derivedKey || vaultMode !== "real") {3683 return { ok: false, error: "vault_locked" };3684 }3685 const slotA = await loadSlot(SLOT_A);3686 if (!slotA) return { ok: false, error: "missing_slot_a" };36873688 3689 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3690 await generateAndWrapRootKey();36913692 3693 const newRootKey = unhex(rawRootKey);3694 const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");3695 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);36963697 3698 3699 3700 3701 await takeVaultSnapshot("local_save");3702 const nextSlotA: StoredVault = {3703 ...slotA,3704 recovery_vault_key: recoveryVaultKey,3705 recovery_salt: recoverySalt,3706 recovery_wrapped_root_key: wrappedRootKey,3707 recovery_nonce: wrappedNonce,3708 recovery_tag: wrappedTag,3709 ...pwRoot,3710 };3711 await writeSlot(SLOT_A, nextSlotA);37123713 3714 if (rotationEpoch === vaultEpoch && derivedKey) {3715 if (rootKey) zeroKey(rootKey);3716 rootKey = newRootKey;3717 } else {3718 zeroKey(newRootKey);3719 }37203721 3722 3723 await notifyIdentityKeysRotated();37243725 3726 3727 3728 await clearPairedDevices();3729 await clearPairSecrets();37303731 3732 if (removalEpoch === vaultRemovalEpoch) {3733 await setRecoveryConfirmPending(rotationEpoch === vaultEpoch && isUnlocked());3734 touchAutoLock();3735 }37363737 await stampLocalVaultMutation();3738 return { ok: true };3739 } finally { vaultWritesInFlight--; }3740}37413742374337443745374637473748export async function changePassword(3749 currentPassword: string,3750 newPassword: string3751): Promise<boolean> {3752 if (vaultCreatesInFlight) throw new Error("vault_changed");3753 vaultWritesInFlight++;3754 try {37553756 const epoch = vaultEpoch;3757 const stale = () => epoch !== vaultEpoch;3758 if (!derivedKey || vaultMode !== "real") return false;37593760 3761 const valid = await verifyMainPassword(currentPassword);3762 if (!valid) return false;37633764 const slotA = await loadSlot(SLOT_A);3765 if (!slotA) return false;3766 if (!rootKey) return false;37673768 3769 const newSalt = generateSalt();3770 const newKey = await deriveKey(newPassword, newSalt);3771 if (stale()) {3772 zeroKey(newKey);3773 return false;3774 }37753776 3777 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3778 const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");37793780 3781 3782 3783 const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);37843785 const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");3786 const finalSlotA: StoredVault = {3787 ...slotA,3788 recovery_vault_key: recoveryVaultKey,3789 salt: hex(newSalt),3790 nonce,3791 ciphertext,3792 tag,3793 ...pwRoot,3794 };37953796 3797 3798 3799 await takeVaultSnapshot("local_save");38003801 3802 3803 3804 3805 await writeSlot(SLOT_A, finalSlotA);3806 if (stale()) {3807 zeroKey(newKey);3808 return false;3809 }38103811 3812 3813 3814 zeroKey(derivedKey);3815 derivedKey = newKey;38163817 3818 3819 3820 3821 if (stale()) {3822 await lock();3823 return false;3824 }3825 await saveSessionKey(newKey, "real", epoch);3826 if (stale()) return false;38273828 3829 3830 3831 await notifyIdentityKeysRotated();3832 if (stale()) return false;38333834 3835 3836 3837 if (!duressConfigured) {3838 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3839 }3840 await clearPinUnlockStorage();3841 await stampLocalVaultMutation();38423843 return true;3844 } finally { vaultWritesInFlight--; }3845}