123456789101112import { deriveKey, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import { clampSyncTimestamp } from "../shared/sync-limits";15import { computeVaultId } from "../shared/sync-identity";161718import { triggerSyncIfReachable } from "./sync-trigger";19import { clearPairedDevices } from "./paired-devices";20import {21 rootKeyToWords,22 wordsToRootKeyMaterial,23 deriveRecoveryKey,24} from "../shared/recovery-words";25import type {26 AccentColorName,27 BreachScanStatus,28 Canary,29 ManualSummonRecord,30 PasskeyData,31 RecoveryResult,32 SavedIdentity,33 StoredVault,34 VaultEntry,35 VaultHistory,36 VaultSnapshot,37} from "../shared/types";38import { decrypt, encrypt, zeroKey } from "./aes";39import { clearAutoLock, touchAutoLock } from "./alarms";40import { setRecoveryConfirmPending, revokeRecoveryReveal } from "./recovery-pending";41import {42 clearPairSecrets,43 dropSessionCache,44 reconcilePairSecrets,45 setSessionAllowed,46} from "./pair-secrets";4748type EntryDraft = Omit<49 VaultEntry,50 "id" | "createdAt" | "modifiedAt" | "deletedAt"51>;525354555657const SLOT_A = "peach_vault_a";58const SLOT_B = "peach_vault_b";59606162const PAD_BLOCK = 1024;6364656667const PASSWORD_HISTORY_MAX = 50;6869707172737475767778const DURESS_SLOT_SIZE = 262_144;7980let derivedKey: Uint8Array | null = null;8182838485let rootKey: Uint8Array | null = null;86let recoveryInFlight = false;87let recoverySettled: Promise<void> = Promise.resolve();88let vaultRemovalsInFlight = 0;89let vaultRemovalEpoch = 0;90let vaultWritesInFlight = 0;91let vaultCreatesInFlight = 0;92let creationSettled: Promise<void> = Promise.resolve();93let vaultUnlocksInFlight = 0;94let vaultReplacementInFlight = false;95let entries: VaultEntry[] = [];96979899let tombstones = new Map<string, number>();100let domainIndex: Map<string, VaultEntry[]> = new Map();101let vaultMode: "real" | "decoy" = "real";102103104105let duressConfigured = false;106107108109110111112113114115116let lastUnlockFailureReason: string | null = null;117118export function consumeLastUnlockFailureReason(): string | null {119 const r = lastUnlockFailureReason;120 lastUnlockFailureReason = null;121 return r;122}123124125126127128export type TextSize = "small" | "medium" | "large";129130export interface VaultSettings {131 accentColor?: AccentColorName;132 theme?: "dark" | "light";133 autoLockMinutes?: number;134 clipboardClearSeconds?: number;135 lockOnClose?: boolean;136 breachMonitoring?: boolean;137 passkeyProviderEnabled?: boolean;138 trashRetentionDays?: number;139 manualSummonDomains?: Record<string, ManualSummonRecord>;140 manualSummonSalt?: string;141 declinedCardFingerprints?: string[];142143 144 metadataVersion?: 1;145 146147148149150 textSize?: TextSize;151 152153154155156 reduceMotion?: boolean;157 158 lockedSyncRequiresUnlock?: boolean;159 160 pinEnabled?: boolean;161 162 pinPreferred?: boolean;163 164165166167168169170 shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;171}172173interface StoredPinWrap {174 version: 1;175 salt: string;176 nonce: string;177 ciphertext: string;178 tag: string;179}180181const PIN_WRAP_STORAGE = "peach_pin_wrap";182const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";183const PIN_MIN_LENGTH = 4;184const PIN_MAX_LENGTH = 12;185const PIN_MAX_ATTEMPTS = 3;186187let settings: VaultSettings = {};188const CARD_DECLINE_MAX = 256;189190const CARD_DECLINE_DIGEST_HEX = 32;191192async function metadataDigest(value: string, key: string): Promise<string> {193 const bytes = new TextEncoder().encode(`${key}:${value}`);194 const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));195 return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");196}197198let inMemoryPinWrap: StoredPinWrap | null = null;199let inMemoryPinFailedAttempts = 0;200let sessionPinStorageFailed = false;201202export function getSettings(): VaultSettings {203 return settings;204}205206export async function ensureSettingsLoaded(): Promise<VaultSettings> {207 await loadSettings();208 return settings;209}210211export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {212 await loadSettings();213 214 215 216 217 const safe = Object.fromEntries(218 Object.entries(patch).filter(219 ([k]) => !["__proto__", "constructor", "prototype"].includes(k),220 ),221 ) as Partial<VaultSettings>;222 settings = { ...settings, ...safe };223 await persistSettings();224}225226function isValidPin(pin: string): boolean {227 return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);228}229230231export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {232 if (vaultCreatesInFlight) return false;233 vaultWritesInFlight++;234 try {235 if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;236 if (!(await verifyMainPassword(currentPassword))) return false;237238 const salt = generateSalt();239 const pinKey = await deriveKey(pin, salt);240 try {241 const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");242 await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });243 await updateSettings({ pinEnabled: true });244 return true;245 } finally {246 zeroKey(pinKey);247 }248 } finally { vaultWritesInFlight--; }249}250251async function clearPinUnlockStorage(): Promise<void> {252 inMemoryPinWrap = null;253 inMemoryPinFailedAttempts = 0;254 sessionPinStorageFailed = false;255 if (chrome.storage.session) {256 await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);257 }258 await updateSettings({ pinEnabled: false });259}260261262export async function disablePinUnlock(currentPassword: string): Promise<boolean> {263 if (vaultCreatesInFlight) return false;264 vaultWritesInFlight++;265 try {266 if (!derivedKey || vaultMode !== "real") return false;267 if (!(await verifyMainPassword(currentPassword))) return false;268 await clearPinUnlockStorage();269 return true;270 } finally { vaultWritesInFlight--; }271}272273274export async function unlockWithPin(pin: string): Promise<boolean> {275 vaultUnlocksInFlight++;276 try {277 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;278 if (!isValidPin(pin)) return false;279 await loadSettings();280 if (!settings.pinEnabled) return false;281282 const { stored, failedAttempts } = await loadPinState();283 if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;284 if (285 !stored ||286 stored.version !== 1 ||287 !stored.salt ||288 !stored.nonce ||289 !stored.ciphertext ||290 !stored.tag291 ) return false;292293 const pinKey = await deriveKey(pin, unhex(stored.salt));294 let unwrappedKey: Uint8Array | null = null;295 try {296 const masterKeyHex = await decrypt(297 pinKey,298 stored.nonce,299 stored.ciphertext,300 stored.tag,301 "pin_wrap_v1",302 );303 if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;304 unwrappedKey = unhex(masterKeyHex);305 const result = await unlockWithKey(masterKeyHex);306 if (!result.ok) return false;307 await resetPinFailedAttempts();308 return true;309 } catch {310 await recordPinFailure(failedAttempts + 1);311 return false;312 } finally {313 zeroKey(pinKey);314 if (unwrappedKey) zeroKey(unwrappedKey);315 }316 } finally { vaultUnlocksInFlight--; }317}318319async function savePinWrap(stored: StoredPinWrap): Promise<void> {320 inMemoryPinWrap = stored;321 inMemoryPinFailedAttempts = 0;322 sessionPinStorageFailed = !chrome.storage.session;323 if (!chrome.storage.session) return;324 try {325 await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });326 sessionPinStorageFailed = false;327 } catch {328 329 sessionPinStorageFailed = true;330 }331}332333async function loadPinState(): Promise<{334 stored: StoredPinWrap | undefined;335 failedAttempts: number;336}> {337 if (!chrome.storage.session) {338 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };339 }340 try {341 const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);342 return {343 stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??344 (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),345 failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"346 ? result[PIN_ATTEMPTS_STORAGE]347 : 0,348 };349 } catch {350 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };351 }352}353354async function recordPinFailure(failedAttempts: number): Promise<void> {355 inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);356 if (!chrome.storage.session) return;357 try {358 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });359 } catch { }360}361362async function resetPinFailedAttempts(): Promise<void> {363 inMemoryPinFailedAttempts = 0;364 if (!chrome.storage.session) return;365 try {366 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });367 } catch { }368}369370export async function getPinUnlockStatus(): Promise<{371 configured: boolean;372 available: boolean;373 attemptsRemaining: number;374}> {375 await loadSettings();376 if (!settings.pinEnabled) {377 return { configured: false, available: false, attemptsRemaining: 0 };378 }379 const { stored, failedAttempts } = await loadPinState();380 const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;381 return {382 configured: true,383 available,384 attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,385 };386}387388async function persistSettings(): Promise<void> {389 try {390 await chrome.storage.local.set({391 peach_settings: {392 ...settings,393 manualSummonDomains: undefined,394 manualSummonSalt: undefined,395 cardFingerprintSalt: undefined,396 declinedCardFingerprints: settings.declinedCardFingerprints ?? [],397 metadataVersion: 1,398 },399 });400 } catch (err) {401 throw mapStorageError(err);402 }403}404405function mapStorageError(err: unknown): Error {406 const message = err instanceof Error ? err.message : String(err);407 if (/QUOTA_BYTES|quota/i.test(message)) {408 return new Error("STORAGE_QUOTA_EXCEEDED");409 }410 return err instanceof Error ? err : new Error(message);411}412413async function loadSettings(): Promise<void> {414 const result = await chrome.storage.local.get("peach_settings");415 settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};416}417418419420function fireSyncTrigger(reason: "vault_change"): void {421 void Promise.resolve()422 .then(() => triggerSyncIfReachable({ reason }))423 .catch(() => {424 425 });426}427export function lockedSyncRequiresUnlock(): boolean {428 return settings.lockedSyncRequiresUnlock === true;429}430431let lockedSyncRefreshHook: (() => Promise<void>) | null = null;432let lockedSyncUnlockHook: (() => Promise<void>) | null = null;433let decoySyncTeardownHook: (() => void) | null = null;434export type IdentityHooks = {435 436 onSessionEnded: () => Promise<void>;437 438 onKeysRotated: () => Promise<void>;439 440 onVaultCreated: (password: string) => Promise<void>;441};442443let identityHooks: IdentityHooks | null = null;444445export function setIdentityHooks(hooks: IdentityHooks): void {446 identityHooks = hooks;447}448449async function notifyIdentitySessionEnded(): Promise<void> {450 await identityHooks?.onSessionEnded().catch((error) => {451 console.warn("[Peach] local identity cache clear failed:", error);452 });453}454455async function notifyIdentityKeysRotated(): Promise<void> {456 await identityHooks?.onKeysRotated().catch((error) => {457 console.warn("[Peach] local identity re-wrap failed:", error);458 });459}460461export type SealedBox = { nonce: string; ciphertext: string; tag: string };462export type IdentityKeyEnvelope = {463 root?: SealedBox;464 local?: SealedBox;465 pending?: SealedBox;466 pendingSalt?: string;467};468469export function setLockedSyncHooks(hooks: {470 refresh: () => Promise<void>;471 afterUnlock: () => Promise<void>;472 onDecoy?: () => void;473}): void {474 lockedSyncRefreshHook = hooks.refresh;475 lockedSyncUnlockHook = hooks.afterUnlock;476 decoySyncTeardownHook = hooks.onDecoy ?? null;477}478479async function refreshLockedSyncState(): Promise<void> {480 if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;481 await lockedSyncRefreshHook().catch((error) => {482 console.warn("[Peach sync] locked spool refresh failed:", error);483 });484}485486487488489490export async function checkBreach(password: string, signal?: AbortSignal): Promise<number | null> {491 const controller = new AbortController();492 let timeout: ReturnType<typeof setTimeout> | undefined;493 let onAbort: (() => void) | undefined;494 try {495 const unavailable = new Promise<null>((resolve) => {496 onAbort = () => { controller.abort(); resolve(null); };497 signal?.addEventListener("abort", onAbort, { once: true });498 timeout = setTimeout(onAbort, 8_000);499 if (signal?.aborted) onAbort();500 });501 const lookup = async (): Promise<number | null> => {502 503 const hash = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(password));504 if (controller.signal.aborted) return null;505 const hex = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();506 const res = await fetch(`https://api.pwnedpasswords.com/range/${hex.slice(0, 5)}`, {507 headers: { "Add-Padding": "true" },508 signal: controller.signal,509 });510 if (!res.ok) return null;511 const text = await res.text();512 const lines = text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");513 let count = 0;514 const seen = new Set<string>();515 for (const line of lines) {516 const match = /^([A-Fa-f0-9]{35}):([0-9]+)$/.exec(line);517 if (!match) return null;518 const suffix = match[1].toUpperCase();519 const value = Number(match[2]);520 if (!Number.isSafeInteger(value) || seen.has(suffix)) return null;521 seen.add(suffix);522 if (suffix === hex.slice(5)) count = value;523 }524 return count;525 };526 return await Promise.race([lookup(), unavailable]);527 } catch {528 return null;529 } finally {530 clearTimeout(timeout);531 if (onAbort) signal?.removeEventListener("abort", onAbort);532 }533}534535type BreachCredential = { id: string; password: string; epoch: number; key: Uint8Array };536const breachChecks = new Map<string, symbol>();537538async function checkEntryBreach(credential: BreachCredential, signal?: AbortSignal): Promise<"unknown" | "unapplied" | number> {539 const { id, password, epoch } = credential;540 const isCurrent = () => {541 const entry = entries.find((entry) => entry.id === id);542 return !signal?.aborted && epoch === vaultEpoch && credential.key === derivedKey && !vaultCreatesInFlight &&543 entry?.type === "login" && !entry.deletedAt && entry.password === password;544 };545 if (!isCurrent()) return "unapplied";546 const token = Symbol();547 breachChecks.set(id, token);548 try {549 const count = await checkBreach(password, signal);550 const idx = entries.findIndex((entry) => entry.id === id);551 const current = entries[idx];552 if (signal?.aborted || epoch !== vaultEpoch || credential.key !== derivedKey || vaultCreatesInFlight ||553 breachChecks.get(id) !== token || !current || current.deletedAt || current.type !== "login" || current.password !== password) return "unapplied";554 if (count === null) return "unknown";555 if ((current.breach ?? 0) === count) return count;556 const owner = entries;557 const next = { ...current, breach: count, modifiedAt: monotonicEntryTimestamp(current.modifiedAt) };558 entries[idx] = next;559 try {560 await persistEntries();561 } catch (error) {562 if (epoch === vaultEpoch && entries === owner && entries[idx] === next && !next.deletedAt) entries[idx] = current;563 throw error;564 }565 if (!isCurrent() || breachChecks.get(id) !== token) return "unapplied";566 fireSyncTrigger("vault_change");567 return count;568 } finally {569 if (breachChecks.get(id) === token) breachChecks.delete(id);570 }571}572573function checkEntryBreachDetached(credential: BreachCredential): void {574 void checkEntryBreach(credential).catch(() => {575 console.warn("[Peach] Could not save a breach check result");576 });577}578579function emptyBreachScan(state: BreachScanStatus["state"] = "idle"): BreachScanStatus {580 return { id: null, state, total: 0, scanned: 0, unknown: 0, unapplied: 0, breached: 0, cancelled: 0 };581}582583type BreachScan = {584 epoch: number;585 key: Uint8Array | null;586 status: BreachScanStatus;587 credentials: BreachCredential[];588 controller: AbortController;589};590let breachScan: BreachScan | null = null;591592function cancelBreachScan(): void {593 breachChecks.clear();594 const scan = breachScan;595 if (!scan) return;596 scan.controller.abort();597 scan.credentials.length = 0;598 scan.key = null;599 if (scan.status.state === "running") {600 scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;601 scan.status.state = "cancelled";602 }603}604605606export function getBreachScanStatus(): BreachScanStatus {607 if (!derivedKey) return emptyBreachScan(breachScan ? "cancelled" : "idle");608 if (!breachScan || breachScan.epoch !== vaultEpoch || breachScan.key !== derivedKey) return emptyBreachScan();609 return { ...breachScan.status };610}611612613export function startBreachScan(): BreachScanStatus {614 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");615 if (breachScan?.status.state === "running" && breachScan.epoch === vaultEpoch && breachScan.key === derivedKey) return getBreachScanStatus();616 cancelBreachScan();617 const key = derivedKey;618 const credentials = entries.filter((entry) => !entry.deletedAt && entry.type === "login" && entry.password)619 .map((entry) => ({ id: entry.id, password: entry.password!, epoch: vaultEpoch, key }));620 const scan: BreachScan = {621 epoch: vaultEpoch, key, credentials, controller: new AbortController(),622 status: { ...emptyBreachScan(credentials.length ? "running" : "complete"), id: crypto.randomUUID(), total: credentials.length },623 };624 breachScan = scan;625 void runBreachScan(scan);626 return { ...scan.status };627}628629async function runBreachScan(scan: BreachScan): Promise<void> {630 try {631 while (scan.credentials.length) {632 if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;633 const credential = scan.credentials.shift()!;634 let result: "unknown" | "unapplied" | number;635 try { result = await checkEntryBreach(credential, scan.controller.signal); }636 catch { result = "unknown"; console.warn("[Peach] Could not save a breach scan result"); }637 if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;638 if (result === "unknown") scan.status.unknown++;639 else if (result === "unapplied") scan.status.unapplied++;640 else { scan.status.scanned++; if (result > 0) scan.status.breached++; }641 if (scan.credentials.length) {642 await new Promise<void>((resolve) => {643 const done = () => { clearTimeout(timer); scan.controller.signal.removeEventListener("abort", done); resolve(); };644 const timer = setTimeout(done, 200);645 scan.controller.signal.addEventListener("abort", done, { once: true });646 if (scan.controller.signal.aborted) done();647 });648 }649 }650 } finally {651 scan.credentials.length = 0;652 if (scan.status.state === "running") {653 if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) {654 scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;655 scan.status.state = "cancelled";656 } else scan.status.state = "complete";657 }658 }659}660661export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {662 663 const key = await cardDeclineKey();664 if (!key) return;665 const fingerprint = await cardFingerprint(last4, expMonth, expYear);666 await loadSettings();667 settings = {668 ...settings,669 declinedCardFingerprints: [670 671 672 ...(settings.declinedCardFingerprints ?? []).filter(673 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,674 ),675 await metadataDigest(fingerprint, key),676 ].slice(-CARD_DECLINE_MAX),677 };678 await persistSettings();679}680681export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {682 await loadSettings();683 const key = await cardDeclineKey();684 if (!key) return false;685 const fingerprint = await cardFingerprint(last4, expMonth, expYear);686 const candidate = await metadataDigest(fingerprint, key);687 return (settings.declinedCardFingerprints ?? []).some(688 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,689 );690}691692693694695696697698699700701702703async function cardDeclineKey(): Promise<string | null> {704 const root = getRootKeyHex();705 if (!root) return null;706 const digest = new Uint8Array(707 await crypto.subtle.digest(708 "SHA-256",709 new TextEncoder().encode(`peach-card-decline-v1:${root}`),710 ),711 );712 return hex(digest);713}714715async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {716 const encoder = new TextEncoder();717 const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));718 return Array.from(new Uint8Array(buf).slice(0, 8))719 .map((b) => b.toString(16).padStart(2, "0"))720 .join("");721}722723function hex(buf: Uint8Array): string {724 return Array.from(buf)725 .map((b) => b.toString(16).padStart(2, "0"))726 .join("");727}728729function unhex(s: string): Uint8Array {730 const out = new Uint8Array(s.length / 2);731 for (let i = 0; i < s.length; i += 2) {732 out[i / 2] = parseInt(s.slice(i, i + 2), 16);733 }734 return out;735}736737738739740741742743744745746747748749750751752753754755756async function generateAndWrapRootKey(): Promise<{757 rawRootKey: string; 758 recoverySalt: string;759 wrappedRootKey: string;760 wrappedNonce: string;761 wrappedTag: string;762}> {763 const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));764 try {765766 767 const words = await rootKeyToWords(rootKeyBytes);768 const wordMaterial = await wordsToRootKeyMaterial(words);769 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));770 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);771772 773 774 const nonce = crypto.getRandomValues(new Uint8Array(12));775 const encoded = new TextEncoder().encode(hex(rootKeyBytes));776 const raw = await crypto.subtle.encrypt(777 {778 name: "AES-GCM",779 iv: nonce,780 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,781 tagLength: 128,782 },783 recoveryKey,784 encoded785 );786 787 const rawU8 = new Uint8Array(raw);788 const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));789 const tag = hex(rawU8.slice(rawU8.length - 16));790791 return {792 rawRootKey: hex(rootKeyBytes),793 recoverySalt: hex(recoverySalt),794 wrappedRootKey: ciphertext,795 wrappedNonce: hex(nonce),796 wrappedTag: tag,797 };798 } finally { zeroKey(rootKeyBytes); }799}800801async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{802 recoverySalt: string;803 wrappedRootKey: string;804 wrappedNonce: string;805 wrappedTag: string;806}> {807 if (rootKeyBytes.length !== 32) {808 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");809 }810811 const words = await rootKeyToWords(rootKeyBytes);812 const wordMaterial = await wordsToRootKeyMaterial(words);813 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));814 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);815 const nonce = crypto.getRandomValues(new Uint8Array(12));816 const encoded = new TextEncoder().encode(hex(rootKeyBytes));817 const raw = await crypto.subtle.encrypt(818 {819 name: "AES-GCM",820 iv: nonce,821 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,822 tagLength: 128,823 },824 recoveryKey,825 encoded,826 );827 const rawU8 = new Uint8Array(raw);828 return {829 recoverySalt: hex(recoverySalt),830 wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),831 wrappedNonce: hex(nonce),832 wrappedTag: hex(rawU8.slice(rawU8.length - 16)),833 };834}835836837838839840async function unwrapRootKeyForRecovery(841 wrappedRootKey: string,842 wrappedNonce: string,843 wrappedTag: string,844 recoverySaltHex: string,845 words: string[]846): Promise<Uint8Array> {847 const wordMaterial = await wordsToRootKeyMaterial(words);848 const recoverySalt = unhex(recoverySaltHex);849 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);850851 852 853 854 855 856 const nonceRaw = unhex(wrappedNonce);857 const ciphertextRaw = unhex(wrappedRootKey);858 const tagRaw = unhex(wrappedTag);859 860 861 const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;862 const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);863 combined.set(ciphertextRaw, 0);864 combined.set(tagRaw, ciphertextRaw.length);865 const raw = await crypto.subtle.decrypt(866 { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },867 recoveryKey,868 combined869 );870 const decryptedHex = new TextDecoder().decode(raw);871 const recovered = unhex(decryptedHex);872 if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }873 return recovered;874}875876877export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {878 if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");879 if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");880 recoveryInFlight = true;881 let settle!: () => void;882 recoverySettled = new Promise<void>((resolve) => { settle = resolve; });883 cancelBreachScan();884 const epoch = ++vaultEpoch;885 const check = () => {886 if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");887 };888 let recoveredRoot: Uint8Array | null = null;889 let oldKey: Uint8Array | null = null;890 let newKey: Uint8Array | null = null;891 let committed = false;892 try {893 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);894 check();895 const slot = raw[SLOT_A] as StoredVault | undefined;896 if (!slot) throw new Error("no_vault");897 if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");898 try {899 recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,900 slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);901 } catch {902 throw new Error("invalid_recovery_words");903 }904 check();905 if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");906 oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");907 check();908 if (!oldKey) throw new Error("recovery_data_unavailable");909 const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");910 check();911 if (result.status !== "ok") throw new Error("recovery_data_unavailable");912 const payload = result.payload;913 await loadSettings();914 check();915 const salt = generateSalt();916 newKey = await deriveKey(newPassword, salt);917 check();918 919 const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");920 const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");921 const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);922 const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");923 check();924 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);925 check();926 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");927 const history = raw[HISTORY_KEY] as VaultHistory | undefined;928 const snapshot: VaultSnapshot = {929 id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",930 vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,931 };932 const previousStamp = Number(raw.peach_last_modified_at);933 const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,934 salt: hex(salt), recovery_vault_key: recoveryVaultKey };935 936 await chrome.storage.local.set({937 [SLOT_A]: nextSlot,938 [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },939 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),940 });941 committed = true;942 check();943 cancelBreachScan();944 derivedKey = newKey;945 rootKey = recoveredRoot;946 newKey = null;947 recoveredRoot = null;948 entries = payload.entries;949 tombstones = payload.tombstones;950 duressConfigured = payload.duressConfigured;951 vaultMode = "real";952 buildDomainIndexSync(entries);953 await saveSessionKey(derivedKey, "real", epoch);954 if (epoch !== vaultEpoch) throw new Error("vault_locked");955 await identityHooks?.onKeysRotated();956 if (epoch !== vaultEpoch) throw new Error("vault_locked");957 await reconcilePairSecrets(rootKey);958 if (epoch !== vaultEpoch) throw new Error("vault_locked");959 await clearPinUnlockStorage();960 if (epoch !== vaultEpoch) throw new Error("vault_locked");961 touchAutoLock();962 return { committed: true, unlocked: true };963 } catch (error) {964 if (committed) {965 console.warn("[Peach] recovery password saved; unlock required:", error);966 if (derivedKey && epoch === vaultEpoch) {967 try { await lock(); }968 catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }969 }970 return { committed: true, unlocked: false };971 }972 if (derivedKey && epoch === vaultEpoch) await lock();973 throw error;974 } finally {975 if (oldKey) zeroKey(oldKey);976 if (newKey) zeroKey(newKey);977 if (recoveredRoot) zeroKey(recoveredRoot);978 recoveryInFlight = false;979 settle();980 }981}982983984export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {985 vaultRemovalEpoch++;986 vaultRemovalsInFlight++;987 try {988 await lock();989 await recoverySettled;990 await creationSettled;991 return await remove();992 } finally {993 vaultRemovalsInFlight--;994 }995}9969979989991000100110021003100410051006async function deriveRootKeyFromDerivedKey(1007 derivedKeyBytes: Uint8Array,1008 slotA: StoredVault,1009): Promise<Uint8Array | null> {1010 if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {1011 return null;1012 }1013 try {1014 const rootHex = await decrypt(1015 derivedKeyBytes,1016 slotA.pw_root_nonce,1017 slotA.pw_root_ciphertext,1018 slotA.pw_root_tag,1019 "pw_root_v1",1020 );1021 return unhex(rootHex);1022 } catch {1023 return null;1024 }1025}10261027export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {1028 if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");1029 1030 1031 const [root, local] = await Promise.all([1032 encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),1033 encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),1034 ]);1035 return { root, local };1036}10371038export async function sealIdentityKeyPreVault(1039 password: string,1040 ik: Uint8Array,1041): Promise<IdentityKeyEnvelope> {1042 const salt = generateSalt();1043 const key = await deriveKey(password, salt);1044 try {1045 const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");1046 return { pending, pendingSalt: hex(salt) };1047 } finally {1048 zeroKey(key);1049 }1050}1051105210531054105510561057105810591060export async function openIdentityKey(1061 env: IdentityKeyEnvelope,1062 password?: string,1063): Promise<Uint8Array | null> {1064 if (env.local && derivedKey) {1065 const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");1066 if (ik) return ik;1067 }1068 if (env.root && rootKey) {1069 const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");1070 if (ik) return ik;1071 }1072 if (!env.pending || !env.pendingSalt || password === undefined) return null;1073 let key: Uint8Array;1074 try {1075 const salt = unhex(env.pendingSalt);1076 key = await deriveKey(password, salt);1077 salt.fill(0);1078 } catch {1079 return null;1080 }1081 try {1082 return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");1083 } finally {1084 zeroKey(key);1085 }1086}108710881089async function openSealedKey(1090 key: Uint8Array,1091 box: SealedBox,1092 info: string,1093): Promise<Uint8Array | null> {1094 try {1095 const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));1096 if (value.length === 32) return value;1097 value.fill(0);1098 return null;1099 } catch {1100 return null;1101 }1102}1103110411051106async function wrapRootKeyForDerivedKey(1107 derivedKeyBytes: Uint8Array,1108 rootKeyBytes: Uint8Array,1109): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {1110 const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");1111 return {1112 pw_root_ciphertext: ciphertext,1113 pw_root_nonce: nonce,1114 pw_root_tag: tag,1115 };1116}111711181119export async function getRecoveryWords(): Promise<string[]> {1120 if (!rootKey) {1121 throw new Error("recovery not set up");1122 }1123 return rootKeyToWords(rootKey);1124}11251126async function loadSlot(key: string): Promise<StoredVault | null> {1127 const result = await chrome.storage.local.get(key);1128 return (result as Record<string, StoredVault | undefined>)[key] ?? null;1129}11301131async function writeSlot(key: string, vault: StoredVault): Promise<void> {1132 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1133 vaultWritesInFlight++;1134 try {1135 await chrome.storage.local.set({ [key]: vault });1136 } catch (err) {1137 throw mapStorageError(err);1138 } finally {1139 vaultWritesInFlight--;1140 }1141}11421143114411451146114711481149115011511152export async function rollbackAdoptedVault(): Promise<void> {1153 await withVaultRemoval(async () => {1154 try {1155 await chrome.storage.local.remove([1156 SLOT_A,1157 SLOT_B,1158 "peach_last_modified_at",1159 ]);1160 } catch (err) {1161 throw mapStorageError(err);1162 }1163 });1164}11651166async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1167 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1168 vaultWritesInFlight++;1169 try {1170 const raw = await chrome.storage.local.get("peach_last_modified_at");1171 const previous = Number(1172 (raw as Record<string, unknown>).peach_last_modified_at,1173 );1174 const next = Math.max(1175 Date.now(),1176 Number.isFinite(previous) ? previous + 1 : 0,1177 );1178 try {1179 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1180 await chrome.storage.local.set({1181 [SLOT_A]: slotA,1182 [SLOT_B]: slotB,1183 peach_last_modified_at: String(next),1184 });1185 } catch (err) {1186 throw mapStorageError(err);1187 }1188 } finally {1189 vaultWritesInFlight--;1190 }1191}119211931194119511961197119811991200let lastEntryTimestamp = 0;1201function monotonicEntryTimestamp(currentModifiedAt?: number): number {1202 const base = Math.max(1203 Date.now(),1204 (currentModifiedAt ?? 0) + 1,1205 lastEntryTimestamp + 1,1206 );1207 lastEntryTimestamp = base;1208 return base;1209}12101211async function stampLocalVaultMutation(): Promise<void> {1212 if (vaultCreatesInFlight) throw new Error("vault_changed");1213 const raw = await chrome.storage.local.get("peach_last_modified_at");1214 const previous = Number(1215 (raw as Record<string, unknown>).peach_last_modified_at,1216 );1217 const next = Math.max(1218 Date.now(),1219 Number.isFinite(previous) ? previous + 1 : 0,1220 );1221 if (vaultCreatesInFlight) throw new Error("vault_changed");1222 await chrome.storage.local.set({1223 peach_last_modified_at: String(next),1224 });1225}122612271228122912301231123212331234123512361237function padPlaintext(json: string, minBytes = 0): string {1238 const encoded = new TextEncoder().encode(json);1239 const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1240 1241 const target = Math.max(bucket, minBytes);1242 const padLen = target - encoded.length;1243 return json + " ".repeat(padLen);1244}124512461247124812491250125112521253125412551256const CSPRNG_CHUNK = 65_536;12571258function fillRandom(buf: Uint8Array): Uint8Array {1259 for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1260 const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1261 const chunk = new Uint8Array(end - offset);1262 crypto.getRandomValues(chunk);1263 buf.set(chunk, offset);1264 }1265 return buf;1266}12671268function generateNoiseBlob(ciphertextBytes: number): StoredVault {1269 const salt = crypto.getRandomValues(new Uint8Array(16));1270 const nonce = crypto.getRandomValues(new Uint8Array(12));1271 const cipher = fillRandom(new Uint8Array(ciphertextBytes));1272 const tag = crypto.getRandomValues(new Uint8Array(16));1273 return {1274 version: 1,1275 salt: hex(salt),1276 nonce: hex(nonce),1277 ciphertext: hex(cipher),1278 tag: hex(tag),1279 };1280}128112821283128412851286type VaultPayload = {1287 entries: VaultEntry[];1288 tombstones?: Record<string, number>;1289 duressConfigured?: boolean;1290};12911292type DecryptedPayload = {1293 entries: VaultEntry[];1294 tombstones: Map<string, number>;1295 duressConfigured: boolean;1296};12971298function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1299 const envelope: VaultPayload = {1300 entries,1301 tombstones: Object.fromEntries(tombstones),1302 duressConfigured: duress,1303 };1304 return padPlaintext(JSON.stringify(envelope), minBytes);1305}13061307function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1308 const result = new Map<string, number>();1309 if (raw && typeof raw === "object" && !Array.isArray(raw)) {1310 for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1311 if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1312 result.set(id, timestamp);1313 }1314 }1315 }1316 1317 1318 for (const entry of allEntries) {1319 if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1320 continue;1321 }1322 if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1323 result.set(entry.id, entry.deletedAt);1324 }1325 }1326 return result;1327}13281329function reconcileTombstones(): void {1330 const byId = new Map(entries.map((entry) => [entry.id, entry]));1331 for (const [id] of tombstones) {1332 if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1333 }1334 for (const entry of entries) {1335 if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1336 if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1337 tombstones.set(entry.id, entry.deletedAt);1338 }1339 }1340 }1341}13421343function decodePayload(plain: string): DecryptedPayload {1344 const parsed = JSON.parse(plain) as VaultPayload;1345 if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1346 throw new Error("invalid vault payload");1347 }1348 const normalized = parsed.entries.map(normalizeEntry);1349 return {1350 entries: normalized,1351 tombstones: decodeTombstones(parsed.tombstones, normalized),1352 duressConfigured: parsed.duressConfigured === true,1353 };1354}135513561357function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1358 let merged = false;1359 const transferable = new Set(["id", "type", "title", "username", "url", "passkey", "createdAt", "modifiedAt", "totp", "totpAlgorithm", "totpDigits", "totpPeriod"]);1360 for (const source of entries.filter((entry) => !entry.deletedAt && entry.passkey)) {1361 const passkey = source.passkey!;1362 if (source.type !== "login" && source.type !== "passkey") continue;1363 if (!passkey.userName || (source.username && source.username !== passkey.userName)) continue;1364 if (Object.entries(source).some(([key, value]) => !transferable.has(key) && value !== undefined && value !== "")) continue;1365 const targets = entries.filter((entry) => {1366 if (entry.deletedAt || entry.passkey || entry.type !== "login" || entry.username !== passkey.userName) return false;1367 return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {1368 if (!url) return false;1369 try {1370 return new URL(url.includes("://") ? url : `https://${url}`).hostname === passkey.rpId;1371 } catch {1372 return false;1373 }1374 });1375 });1376 if (targets.length !== 1) continue;1377 const target = targets[0]!;1378 if (source.totp && target.totp && (source.totp !== target.totp || source.totpAlgorithm !== target.totpAlgorithm || source.totpDigits !== target.totpDigits || source.totpPeriod !== target.totpPeriod)) continue;1379 target.passkey = passkey;1380 if (source.totp && !target.totp) {1381 target.totp = source.totp;1382 target.totpAlgorithm = source.totpAlgorithm;1383 target.totpDigits = source.totpDigits;1384 target.totpPeriod = source.totpPeriod;1385 }1386 const stamp = monotonicEntryTimestamp(Math.max(source.modifiedAt, target.modifiedAt));1387 target.modifiedAt = stamp;1388 source.modifiedAt = stamp;1389 source.deletedAt = stamp;1390 merged = true;1391 }1392 return { merged };1393}13941395139613971398139914001401function hasValidVaultSchema(v: unknown): v is StoredVault {1402 if (typeof v !== "object" || v === null) return false;1403 const r = v as Record<string, unknown>;1404 return (1405 r.version === 1 &&1406 typeof r.salt === "string" &&1407 typeof r.nonce === "string" &&1408 typeof r.ciphertext === "string" &&1409 typeof r.tag === "string"1410 );1411}1412const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;14131414function hasValidHistorySlot(value: unknown): value is StoredVault {1415 if (!hasValidVaultSchema(value)) return false;1416 return /^[0-9a-f]{32}$/i.test(value.salt) &&1417 /^[0-9a-f]{24}$/i.test(value.nonce) &&1418 /^[0-9a-f]+$/i.test(value.ciphertext) &&1419 value.ciphertext.length % 2 === 0 &&1420 value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1421 /^[0-9a-f]{32}$/i.test(value.tag);1422}14231424function parseHistorySlot(value: string): StoredVault | null {1425 try {1426 const parsed: unknown = JSON.parse(value);1427 return hasValidHistorySlot(parsed) ? parsed : null;1428 } catch {1429 return null;1430 }1431}14321433function isHistoryRecord(value: unknown): value is VaultSnapshot {1434 if (typeof value !== "object" || value === null) return false;1435 const record = value as Record<string, unknown>;1436 return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1437 typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1438 typeof record.reason === "string" &&1439 typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1440 typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1441 (record.entryCount === null || typeof record.entryCount === "number");1442}14431444function sanitizeHistory(value: unknown): VaultSnapshot[] {1445 if (typeof value !== "object" || value === null) return [];1446 if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1447 return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1448}14491450export type TryDecryptResult =1451 | { status: "ok"; payload: DecryptedPayload }1452 | { status: "wrong_key" }1453 | { status: "corrupted"; reason: string };1454145514561457145814591460export async function tryDecryptSlot(1461 vault: StoredVault,1462 key: Uint8Array,1463 aadTag?: string,1464): Promise<DecryptedPayload | null> {1465 const res = await tryDecryptSlotResult(vault, key, aadTag);1466 return res.status === "ok" ? res.payload : null;1467}14681469export async function tryDecryptSlotResult(1470 vault: StoredVault,1471 key: Uint8Array,1472 aadTag?: string,1473): Promise<TryDecryptResult> {1474 if (!hasValidVaultSchema(vault)) {1475 return { status: "corrupted", reason: "invalid_slot_schema" };1476 }1477 let plain: string;1478 try {1479 plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1480 } catch {1481 return { status: "wrong_key" };1482 }1483 try {1484 const parsed = JSON.parse(plain) as unknown;1485 if (typeof parsed !== "object" || parsed === null) {1486 return { status: "corrupted", reason: "invalid_payload_shape" };1487 }1488 if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1489 return { status: "corrupted", reason: "invalid_payload_shape" };1490 }1491 return { status: "ok", payload: decodePayload(plain) };1492 } catch {1493 return { status: "corrupted", reason: "invalid_payload_json" };1494 }1495}149614971498149915001501function buildDomainIndexSync(all: VaultEntry[]): void {1502 domainIndex = new Map();15031504 for (const entry of all) {1505 if (entry.deletedAt) continue;1506 if (entry.type === "note" || entry.type === "card") continue;15071508 1509 1510 1511 1512 const domains = new Set<string>();1513 const primary = extractDomain(entry.url ?? "");1514 if (primary) domains.add(primary);1515 for (const extra of entry.additionalUrls ?? []) {1516 const d = extractDomain(extra);1517 if (d) domains.add(d);1518 }1519 if (domains.size === 0) continue;15201521 for (const domain of domains) {1522 const bucket = domainIndex.get(domain) ?? [];1523 bucket.push(entry);1524 domainIndex.set(domain, bucket);1525 }1526 }1527}15281529export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1530 if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1531 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1532 vaultCreatesInFlight++;1533 let settle!: () => void;1534 creationSettled = new Promise<void>((resolve) => { settle = resolve; });1535 let nextKey: Uint8Array | null = null;1536 let nextRoot: Uint8Array | null = null;1537 let committed = false;1538 let publishedEpoch: number | null = null;1539 const epoch = vaultEpoch;1540 const check = () => {1541 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1542 };1543 try {1544 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1545 check();1546 const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1547 if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1548 const salt = generateSalt();1549 nextKey = await deriveKey(password, salt);1550 check();1551 const recovery = await generateAndWrapRootKey();1552 nextRoot = unhex(recovery.rawRootKey);1553 check();1554 const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1555 const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1556 const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1557 check();1558 const slotA: StoredVault = {1559 ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1560 recovery_vault_key: recoveryVaultKey,1561 recovery_salt: recovery.recoverySalt,1562 recovery_wrapped_root_key: recovery.wrappedRootKey,1563 recovery_nonce: recovery.wrappedNonce,1564 recovery_tag: recovery.wrappedTag,1565 };1566 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1567 check();1568 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1569 const previous = Number(raw.peach_last_modified_at);1570 const update: Record<string, unknown> = {1571 [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1572 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1573 };1574 if (occupied) {1575 const history = raw[HISTORY_KEY] as VaultHistory | undefined;1576 const snapshot: VaultSnapshot = {1577 id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1578 vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1579 };1580 update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1581 }1582 try { await chrome.storage.local.set(update); }1583 catch (error) { throw mapStorageError(error); }1584 committed = true;1585 if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1586 const previousKey = derivedKey;1587 const previousRoot = rootKey;1588 cancelBreachScan();1589 publishedEpoch = ++vaultEpoch;1590 derivedKey = nextKey;1591 rootKey = nextRoot;1592 nextKey = null;1593 nextRoot = null;1594 entries = [];1595 tombstones = new Map();1596 vaultMode = "real";1597 duressConfigured = false;1598 buildDomainIndexSync(entries);1599 if (previousKey) zeroKey(previousKey);1600 if (previousRoot) zeroKey(previousRoot);1601 await clearSessionKey();1602 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1603 await identityHooks?.onVaultCreated(password).catch((error) => {1604 console.warn("[Peach] local identity promotion failed:", error);1605 });1606 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1607 touchAutoLock();1608 return { committed: true, unlocked: true };1609 } catch (error) {1610 if (!committed) throw error;1611 console.warn("[Peach] vault saved; unlock required:", error);1612 if (publishedEpoch === vaultEpoch) {1613 await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));1614 }1615 return { committed: true, unlocked: false };1616 } finally {1617 if (nextKey) zeroKey(nextKey);1618 if (nextRoot) zeroKey(nextRoot);1619 vaultCreatesInFlight--;1620 settle();1621 }1622}1623162416251626162716281629export async function createVaultFromRootKey(1630 password: string,1631 rootKeyHex: string,1632): Promise<{ vaultId: string }> {1633 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1634 if (typeof password !== "string" || password.length === 0) {1635 throw new Error("ADOPT_INVALID_PASSWORD");1636 }1637 if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1638 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1639 }16401641 if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1642 const rootKeyBytes = unhex(rootKeyHex);1643 if (rootKeyBytes.length !== 32) {1644 rootKeyBytes.fill(0);1645 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1646 }16471648 vaultCreatesInFlight++;1649 let settle!: () => void;1650 creationSettled = new Promise<void>((resolve) => { settle = resolve; });1651 const epoch = vaultEpoch;1652 let nextDerivedKey: Uint8Array | null = null;1653 let sessionRootKey: Uint8Array | null = null;1654 let committed = false;1655 try {1656 if (await hasVault()) {1657 throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1658 }16591660 const nextEntries: VaultEntry[] = [];1661 const nextDuressConfigured = false;1662 const vaultId = await computeVaultId(rootKeyBytes);1663 const salt = generateSalt();1664 nextDerivedKey = await deriveKey(password, salt);1665 const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);16661667 sessionRootKey = new Uint8Array(rootKeyBytes);1668 const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1669 const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1670 const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1671 const slotA: StoredVault = {1672 recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),1673 version: 1,1674 salt: hex(salt),1675 nonce,1676 ciphertext,1677 tag,1678 recovery_salt: recovery.recoverySalt,1679 recovery_wrapped_root_key: recovery.wrappedRootKey,1680 recovery_nonce: recovery.wrappedNonce,1681 recovery_tag: recovery.wrappedTag,1682 ...pwRoot,1683 };1684 const slotB = generateNoiseBlob(ciphertext.length / 2);1685 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1686 await commitCreatedVaultSlots(slotA, slotB);1687 committed = true;1688 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1689 cancelBreachScan();1690 vaultEpoch++;16911692 const previousDerivedKey = derivedKey;1693 const previousRootKey = rootKey;1694 derivedKey = nextDerivedKey;1695 rootKey = sessionRootKey;1696 nextDerivedKey = null;1697 sessionRootKey = null;1698 entries = nextEntries;1699 tombstones = new Map();1700 vaultMode = "real";1701 duressConfigured = nextDuressConfigured;1702 buildDomainIndexSync(entries);1703 if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1704 if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1705 touchAutoLock();17061707 1708 1709 await identityHooks?.onVaultCreated(password).catch((error) => {1710 console.warn("[Peach] local identity promotion failed:", error);1711 });17121713 return { vaultId };1714 } catch (error) {1715 if (committed) {1716 1717 try { await lock(); }1718 finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, "peach_last_modified_at"]); }1719 }1720 throw error;1721 } finally {1722 vaultCreatesInFlight--;1723 settle();1724 rootKeyBytes.fill(0);1725 if (nextDerivedKey) zeroKey(nextDerivedKey);1726 if (sessionRootKey) sessionRootKey.fill(0);1727 }1728}17291730export async function hasVault(): Promise<boolean> {1731 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);1732 return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1733}1734173517361737173817391740export async function isDuressEnabled(): Promise<boolean> {1741 return vaultMode === "real" && duressConfigured;1742}17431744export async function setupDuress(duressPassword: string): Promise<void> {1745 if (vaultCreatesInFlight) throw new Error("vault_changed");1746 vaultWritesInFlight++;1747 try {1748 if (!derivedKey || vaultMode !== "real") {1749 throw new Error("vault must be unlocked in real mode");1750 }1751 1752 1753 1754 const slotA = await loadSlot(SLOT_A);1755 if (!slotA) throw new Error("missing slot A");17561757 const decoySalt = generateSalt();1758 const decoyKey = await deriveKey(duressPassword, decoySalt);1759 try {1760 1761 1762 1763 1764 const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1765 const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1766 await writeSlot(SLOT_B, {1767 version: 1,1768 salt: hex(decoySalt),1769 nonce,1770 ciphertext,1771 tag,1772 });1773 } finally {1774 zeroKey(decoyKey);1775 }17761777 1778 1779 duressConfigured = true;1780 await persistSlotA();1781 } finally { vaultWritesInFlight--; }1782}17831784export async function disableDuress(): Promise<void> {1785 if (vaultCreatesInFlight) throw new Error("vault_changed");1786 vaultWritesInFlight++;1787 try {1788 if (!derivedKey || vaultMode !== "real") {1789 throw new Error("vault must be unlocked in real mode");1790 }1791 1792 1793 1794 const slotA = await loadSlot(SLOT_A);1795 if (slotA) {1796 await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1797 }17981799 duressConfigured = false;1800 await persistSlotA();1801 } finally { vaultWritesInFlight--; }1802}18031804180518061807180818091810export async function verifyMainPassword(password: string): Promise<boolean> {1811 const slotA = await loadSlot(SLOT_A);1812 if (!slotA) return false;1813 const key = await deriveKey(password, unhex(slotA.salt));1814 try {1815 return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1816 } finally {1817 zeroKey(key);1818 }1819}18201821export async function unlock(password: string): Promise<boolean> {1822 return attemptUnlockWithDerive(password, deriveKey);1823}18241825async function attemptUnlockWithDerive(1826 password: string,1827 derive: typeof deriveKey,1828): Promise<boolean> {1829 vaultUnlocksInFlight++;1830 try {1831 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1832 const epoch = vaultEpoch;1833 const stale = () => epoch !== vaultEpoch;1834 await revokeRecoveryReveal();1835 if (stale()) return false;1836 1837 1838 1839 1840 1841 1842 const [slotA, slotB] = await Promise.all([1843 loadSlot(SLOT_A),1844 loadSlot(SLOT_B),1845 ]);18461847 1848 const [keyA, keyB] = await Promise.all([1849 slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1850 slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1851 ]);18521853 1854 1855 1856 const [resultA, resultB] = await Promise.all([1857 keyA && slotA1858 ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1859 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1860 keyB && slotB1861 ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1862 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1863 ]);1864 const payloadA = resultA.status === "ok" ? resultA.payload : null;1865 const payloadB = resultB.status === "ok" ? resultB.payload : null;18661867 if (stale()) {1868 if (keyA) zeroKey(keyA);1869 if (keyB) zeroKey(keyB);1870 return false;1871 }18721873 if (payloadA && keyA) {1874 if (stale()) {1875 zeroKey(keyA);1876 if (keyB) zeroKey(keyB);1877 return false;1878 }1879 cancelBreachScan();1880 derivedKey = keyA;1881 vaultMode = "real";1882 entries = payloadA.entries;1883 tombstones = payloadA.tombstones;1884 duressConfigured = payloadA.duressConfigured;1885 buildDomainIndexSync(entries);1886 await loadSettings();1887 if (stale()) {1888 await lock();1889 return false;1890 }1891 touchAutoLock();1892 if (keyB) zeroKey(keyB);18931894 1895 1896 rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;1897 if (!rootKey) {1898 await lock();1899 return false;1900 }19011902 1903 if (slotA) {1904 const escrowed = slotA.recovery_vault_key1905 ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;1906 const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);1907 if (escrowed) zeroKey(escrowed);1908 if (stale()) { await lock(); return false; }1909 if (!matches) {1910 try {1911 const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");1912 if (stale()) { await lock(); return false; }1913 await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });1914 if (stale()) { await lock(); return false; }1915 } catch (error) {1916 await lock();1917 throw error;1918 }1919 }1920 }19211922 1923 1924 await reconcilePairSecrets(rootKey);1925 if (stale()) {1926 await lock();1927 return false;1928 }1929 await lockedSyncUnlockHook?.().catch((error) => {1930 console.warn("[Peach sync] locked inbox drain failed:", error);1931 });1932 if (stale()) {1933 await lock();1934 return false;1935 }1936 await resetPinFailedAttempts();1937 if (stale()) {1938 await lock();1939 return false;1940 }1941 await saveSessionKey(keyA, "real", epoch);1942 if (stale()) return false;1943 return true;1944 }19451946 if (payloadB && keyB) {1947 if (stale()) {1948 zeroKey(keyB);1949 if (keyA) zeroKey(keyA);1950 return false;1951 }1952 cancelBreachScan();1953 derivedKey = keyB;1954 vaultMode = "decoy";1955 decoySyncTeardownHook?.();1956 1957 1958 1959 if (rootKey) {1960 rootKey.fill(0);1961 rootKey = null;1962 }1963 entries = payloadB.entries;1964 tombstones = payloadB.tombstones;1965 duressConfigured = false;1966 buildDomainIndexSync(entries);1967 await loadSettings();1968 touchAutoLock();1969 if (keyA) zeroKey(keyA);1970 1971 await dropSessionCache();1972 1973 await notifyIdentitySessionEnded();1974 if (stale()) {1975 await lock();1976 return false;1977 }1978 await saveSessionKey(keyB, "decoy", epoch);1979 if (stale()) return false;1980 return true;1981 }19821983 if (keyA) zeroKey(keyA);1984 if (keyB) zeroKey(keyB);1985 1986 1987 if (resultA.status === "corrupted") {1988 lastUnlockFailureReason = resultA.reason;1989 } else if (resultB.status === "corrupted") {1990 lastUnlockFailureReason = resultB.reason;1991 }1992 return false;1993 } finally { vaultUnlocksInFlight--; }1994}19951996199719981999200020012002const SESSION_KEY_STORAGE = "peach_session_dk";2003200420052006let sessionKeyMutation = Promise.resolve();20072008function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {2009 const task = sessionKeyMutation.then(mutation, mutation);2010 sessionKeyMutation = task.catch(() => undefined);2011 return task;2012}201320142015201620172018let sessionEscrowAvailable = true;20192020202120222023202420252026export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {2027 setSessionAllowed(sessionEscrow);2028 if (sessionEscrow) return;2029 sessionEscrowAvailable = false;2030 await clearSessionKey();2031}20322033async function saveSessionKey(2034 key: Uint8Array,2035 mode: "real" | "decoy",2036 expectedEpoch = vaultEpoch,2037): Promise<void> {2038 const session = chrome.storage.session;2039 if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2040 const stored = { keyHex: hex(key), mode };2041 await mutateSessionKey(async () => {2042 if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2043 await session.set({ [SESSION_KEY_STORAGE]: stored });2044 });2045}20462047async function clearSessionKey(): Promise<void> {2048 const session = chrome.storage.session;2049 if (!session) return;2050 await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));2051}20522053205420552056205720582059let vaultEpoch = 0;2060206120622063let restoreInFlight: Promise<boolean> | null = null;206420652066206720682069207020712072export async function restoreFromSession(): Promise<boolean> {2073 vaultUnlocksInFlight++;2074 try {2075 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;2076 if (derivedKey !== null) return true;2077 if (restoreInFlight) return restoreInFlight;2078 const task = restoreFromSessionInner();2079 restoreInFlight = task;2080 try {2081 return await task;2082 } finally {2083 restoreInFlight = null;2084 }2085 } finally { vaultUnlocksInFlight--; }2086}20872088async function restoreFromSessionInner(): Promise<boolean> {2089 const epoch = vaultEpoch;2090 const stale = () => epoch !== vaultEpoch;2091 if (derivedKey !== null) return true;2092 if (!sessionEscrowAvailable) return false;2093 if (!chrome.storage.session) return false;2094 const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);2095 if (stale()) return false;2096 const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;2097 if (!entry?.keyHex) return false;20982099 const key = unhex(entry.keyHex);2100 const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;2101 const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";2102 const slot = await loadSlot(slotKey);2103 if (stale()) { zeroKey(key); return false; }2104 if (!slot) { await clearSessionKey(); return false; }21052106 const result = await tryDecryptSlotResult(slot, key, aadTag);2107 if (stale()) { zeroKey(key); return false; }2108 if (result.status !== "ok") { await clearSessionKey(); return false; }21092110 2111 2112 const payload = result.payload;2113 await loadSettings();2114 if (stale()) { zeroKey(key); return false; }21152116 2117 2118 let freshRoot: Uint8Array | null = null;2119 if (entry.mode === "real") {2120 freshRoot = await deriveRootKeyFromDerivedKey(key, slot);2121 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2122 if (!freshRoot) {2123 await lock();2124 return false;2125 }2126 }21272128 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2129 if (freshRoot) {2130 2131 await reconcilePairSecrets(freshRoot);2132 if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }2133 } else {2134 2135 await dropSessionCache();2136 2137 await notifyIdentitySessionEnded();2138 if (stale()) { zeroKey(key); return false; }2139 }2140 cancelBreachScan();2141 derivedKey = key;2142 vaultMode = entry.mode;2143 if (entry.mode === "decoy") decoySyncTeardownHook?.();2144 entries = payload.entries;2145 tombstones = payload.tombstones;2146 duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;2147 if (freshRoot) rootKey = freshRoot;2148 buildDomainIndexSync(entries);2149 touchAutoLock();21502151 await lockedSyncUnlockHook?.().catch((error) => {2152 console.warn("[Peach sync] locked inbox drain failed:", error);2153 });2154 if (stale()) return false;21552156 return true;2157}21582159export async function lock(): Promise<void> {2160 const recoveryRevoked = revokeRecoveryReveal();2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 cancelBreachScan();2171 vaultEpoch++;2172 if (derivedKey) {2173 zeroKey(derivedKey);2174 derivedKey = null;2175 }2176 if (rootKey) {2177 rootKey.fill(0);2178 rootKey = null;2179 }21802181 entries = [];2182 tombstones = new Map();2183 domainIndex = new Map();2184 vaultMode = "real";2185 duressConfigured = false;2186 clearAutoLock();2187 try {2188 chrome.runtime?.sendMessage?.({ type: "VAULT_LOCKED" })?.catch?.(() => undefined);2189 } catch { }2190 await clearSessionKey();2191 await recoveryRevoked;2192 2193 2194 await notifyIdentitySessionEnded();2195}219621972198export function getVaultEpoch(): number {2199 return vaultEpoch;2200}22012202export function isUnlocked(): boolean {2203 return derivedKey !== null;2204}22052206export function isDecoyMode(): boolean {2207 return derivedKey !== null && vaultMode === "decoy";2208}22092210221122122213export async function unlockWithKey(2214 masterKeyHex: string,2215): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2216 vaultUnlocksInFlight++;2217 try {2218 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2219 const epoch = vaultEpoch;2220 const stale = () => epoch !== vaultEpoch;2221 await revokeRecoveryReveal();2222 if (stale()) return { ok: false, error: "vault_locked" };2223 let masterKeyBytes: Uint8Array | null = null;2224 try {2225 masterKeyBytes = unhex(masterKeyHex);2226 const stored = await loadSlot(SLOT_A);2227 if (!stored) return { ok: false, error: "invalid_key" };2228 const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2229 if (!payload || stale()) {2230 zeroKey(masterKeyBytes);2231 return { ok: false, error: "invalid_key" };2232 }22332234 cancelBreachScan();2235 derivedKey = masterKeyBytes;2236 vaultMode = "real";2237 entries = payload.entries;2238 tombstones = payload.tombstones;2239 duressConfigured = payload.duressConfigured;2240 buildDomainIndexSync(entries);2241 await loadSettings();2242 touchAutoLock();22432244 rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2245 if (!rootKey) {2246 await lock();2247 return { ok: false, error: "invalid_key" };2248 }2249 await reconcilePairSecrets(rootKey);2250 if (stale()) {2251 await lock();2252 return { ok: false, error: "invalid_key" };2253 }2254 await saveSessionKey(masterKeyBytes, "real", epoch);2255 if (stale()) return { ok: false, error: "invalid_key" };2256 return { ok: true, entries };2257 } catch {2258 if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2259 return { ok: false, error: "invalid_key" };2260 }2261 } finally { vaultUnlocksInFlight--; }2262}226322642265226622672268226922702271export async function exportDuressSlotForAdoption(): Promise<string | null> {2272 if (!(await isDuressEnabled())) return null;2273 const slotB = await loadSlot(SLOT_B);2274 if (!slotB) return null;2275 return JSON.stringify(slotB);2276}22772278227922802281228222832284export async function installAdoptedDuressSlot(json: string): Promise<void> {2285 if (vaultCreatesInFlight) throw new Error("vault_changed");2286 vaultWritesInFlight++;2287 try {2288 let parsed: StoredVault;2289 try {2290 const raw = JSON.parse(json) as unknown;2291 if (!hasValidVaultSchema(raw)) {2292 throw new Error("invalid_duress_slot_shape");2293 }2294 parsed = raw;2295 } catch (err) {2296 if (err instanceof SyntaxError) {2297 throw new Error("invalid_duress_slot_shape");2298 }2299 throw err;2300 }2301 await writeSlot(SLOT_B, parsed);2302 } finally { vaultWritesInFlight--; }2303}23042305230623072308230923102311231223132314231523162317231823192320232123222323export async function unlockFromCodex(params: {2324 slotA: string; 2325 slotB: string | null; 2326 timestamp: number;2327 masterPassphrase: string;2328}): Promise<2329 | { ok: true; entryCount: number }2330 | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2331> {2332 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2333 vaultReplacementInFlight = true;2334 try {2335 let parsedSlotA: StoredVault;2336 let parsedSlotB: StoredVault | null = null;2337 try {2338 const rawA = JSON.parse(params.slotA) as unknown;2339 if (!hasValidVaultSchema(rawA)) {2340 return { ok: false, reason: "invalid_slot_format" };2341 }2342 parsedSlotA = rawA;2343 if (params.slotB !== null) {2344 const rawB = JSON.parse(params.slotB) as unknown;2345 if (!hasValidVaultSchema(rawB)) {2346 return { ok: false, reason: "invalid_slot_format" };2347 }2348 parsedSlotB = rawB;2349 }2350 } catch {2351 return { ok: false, reason: "invalid_slot_format" };2352 }23532354 2355 2356 2357 const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2358 const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2359 if (!trialPayload) {2360 zeroKey(trialKey);2361 return { ok: false, reason: "wrong_passphrase" };2362 }2363 const hasEscrow =2364 !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2365 if (!hasEscrow) {2366 zeroKey(trialKey);2367 return { ok: false, reason: "missing_root_escrow" };2368 }2369 const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2370 if (!stagedRootKey) {2371 zeroKey(trialKey);2372 return { ok: false, reason: "wrong_passphrase" };2373 }2374 zeroKey(stagedRootKey);2375 zeroKey(trialKey);23762377 2378 const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);23792380 2381 23822383 2384 2385 await takeVaultSnapshot("restore");2386 const previousSlotA = await loadSlot(SLOT_A);2387 const previousSlotB = await loadSlot(SLOT_B);2388 let slotACommitted = false;2389 let slotBCommitted = false;2390 try {2391 await writeSlot(SLOT_A, parsedSlotA);2392 slotACommitted = true;2393 await writeSlot(SLOT_B, stagedSlotB);2394 slotBCommitted = true;2395 await chrome.storage.local.set({2396 peach_last_modified_at: String(params.timestamp),2397 });2398 } catch (err) {2399 if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2400 if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2401 throw err;2402 }24032404 2405 2406 const ok = await unlock(params.masterPassphrase);2407 if (!ok) {2408 2409 return { ok: false, reason: "wrong_passphrase" };2410 }2411 return { ok: true, entryCount: getEntries().length };2412 } finally {2413 vaultReplacementInFlight = false;2414 }2415}24162417241824192420export function getDerivedKeyHex(): string {2421 if (!derivedKey) throw new Error("vault_not_unlocked");2422 return hex(derivedKey);2423}24242425242624272428242924302431243224332434243524362437243824392440export function getRootKeyHex(): string | null {2441 return rootKey ? hex(rootKey) : null;2442}24432444export function getEntries(): VaultEntry[] {2445 if (!derivedKey) throw new Error("vault_locked");2446 return entries.filter((entry) => !entry.deletedAt);2447}24482449const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;24502451export function getIdentities(): SavedIdentity[] {2452 if (!derivedKey) throw new Error("vault_locked");2453 const active = entries.filter((e) => !e.deletedAt && e.type === "login");24542455 const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2456 const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();24572458 for (const entry of active) {2459 const domain = extractDomain(entry.url ?? "") ?? "";2460 const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;24612462 function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2463 const existing = map.get(v);2464 if (!existing || modifiedAt > existing.lastUsed) {2465 map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2466 } else {2467 map.set(v, { ...existing, count: existing.count + 1 });2468 }2469 }24702471 const uVal = entry.username?.trim();2472 if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);24732474 2475 2476 const eVal = entry.email?.trim();2477 if (eVal) tally(emailMap, eVal);2478 }24792480 const toIdentity = (type: "email" | "username") =>2481 ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2482 value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2483 });24842485 return [2486 ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2487 ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2488 ];2489}24902491export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2492 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");24932494 const now = Date.now();2495 const added: VaultEntry[] = [];2496 for (const draft of drafts) {2497 try {2498 const sanitized = sanitizeEntryDraft(draft);2499 const nextEntry: VaultEntry = {2500 ...sanitized,2501 id: crypto.randomUUID(),2502 createdAt: now,2503 modifiedAt: monotonicEntryTimestamp(),2504 };2505 entries.push(nextEntry);2506 added.push(nextEntry);2507 } catch {2508 2509 }2510 }25112512 if (added.length > 0) {2513 await persistEntries();2514 }25152516 return added;2517}251825192520252125222523252425252526export async function restoreEntries(2527 incoming: VaultEntry[],2528 mode: "replace" | "merge"2529): Promise<{ added: number; updated: number; skipped: number }> {2530 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");25312532 2533 2534 2535 if (mode === "replace" && incoming.length === 0) {2536 throw new Error("refuse to replace with empty entry set");2537 }25382539 let added = 0;2540 let updated = 0;2541 let skipped = 0;25422543 if (mode === "replace") {2544 entries = [];2545 for (const entry of incoming) {2546 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2547 if (!normalized) {2548 skipped += 1;2549 continue;2550 }2551 entries.push(normalized);2552 if (normalized.deletedAt) {2553 tombstones.set(2554 normalized.id,2555 Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2556 );2557 } else {2558 tombstones.delete(normalized.id);2559 }2560 added += 1;2561 }2562 } else {2563 const byId = new Map<string, VaultEntry>();2564 for (const e of entries) byId.set(e.id, e);25652566 for (const entry of incoming) {2567 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2568 if (!normalized) {2569 skipped += 1;2570 continue;2571 }2572 const existing = byId.get(normalized.id);2573 if (!existing) {2574 entries.push(normalized);2575 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2576 else tombstones.delete(normalized.id);2577 added += 1;2578 } else if (normalized.modifiedAt > existing.modifiedAt) {2579 const idx = entries.findIndex((e) => e.id === existing.id);2580 if (idx !== -1) {2581 entries[idx] = normalized;2582 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2583 else tombstones.delete(normalized.id);2584 updated += 1;2585 }2586 } else {2587 skipped += 1;2588 }2589 }2590 }25912592 await persistEntries("import");2593 return { added, updated, skipped };2594}259525962597259825992600260126022603260426052606260726082609261026112612const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;26132614function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {2615 if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;2616 return { ...entry, id: crypto.randomUUID() };2617}261826192620262126222623262426252626function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {2627 if (!entry || typeof entry !== "object") return null;2628 const title = typeof entry.title === "string" ? entry.title.trim() : "";2629 if (!title) return null;2630 const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();2631 const now = Date.now();2632 const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;2633 const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;26342635 2636 2637 const normalized = normalizeEntry({2638 ...entry,2639 id,2640 title,2641 type: entry.type ?? "login",2642 createdAt,2643 modifiedAt,2644 });26452646 if (normalized.passkey) {2647 normalized.passkey = sanitizePasskey(normalized.passkey);2648 }2649 if (normalized.canary) {2650 normalized.canary = sanitizeCanary(normalized.canary);2651 }2652 2653 normalized.tags = sanitizeTags(normalized.tags);26542655 2656 2657 if (2658 normalized.type === "login" &&2659 !normalized.passkey &&2660 typeof normalized.password !== "string"2661 ) {2662 return null;2663 }2664 if (entry.passkey && !normalized.passkey) {2665 2666 2667 return null;2668 }26692670 return normalized;2671}2672267326742675267626772678function sanitizePasskey(pk: unknown): PasskeyData | undefined {2679 if (!pk || typeof pk !== "object") return undefined;2680 const r = pk as Record<string, unknown>;2681 if (2682 typeof r.rpId !== "string" || !r.rpId ||2683 typeof r.credentialId !== "string" || !r.credentialId ||2684 typeof r.publicKeyCose !== "string" ||2685 typeof r.userHandle !== "string" ||2686 typeof r.userName !== "string"2687 ) {2688 return undefined;2689 }2690 return {2691 rpId: r.rpId,2692 rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2693 credentialId: r.credentialId,2694 publicKeyCose: r.publicKeyCose,2695 privateKeyJwk:2696 r.privateKeyJwk && typeof r.privateKeyJwk === "object"2697 ? (r.privateKeyJwk as JsonWebKey)2698 : undefined,2699 userHandle: r.userHandle,2700 userName: r.userName,2701 userDisplayName:2702 typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2703 algorithm: r.algorithm === -8 ? -8 : -7,2704 signCount: typeof r.signCount === "number" ? r.signCount : 0,2705 aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2706 backupEligible: r.backupEligible === true,2707 backupState: r.backupState === true,2708 lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2709 browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2710 transports: Array.isArray(r.transports)2711 ? r.transports.filter((t): t is string => typeof t === "string")2712 : undefined,2713 createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2714 };2715}27162717271827192720272127222723272427252726function sanitizeCanary(c: unknown): Canary | undefined {2727 if (!c || typeof c !== "object") return undefined;2728 const r = c as Record<string, unknown>;2729 if (typeof r.webhookUrl !== "string") return undefined;2730 let url: URL;2731 try {2732 url = new URL(r.webhookUrl);2733 } catch {2734 return undefined;2735 }2736 if (url.protocol !== "https:") return undefined;2737 return {2738 webhookUrl: url.toString(),2739 label: typeof r.label === "string" ? r.label : undefined,2740 lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2741 pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2742 };2743}27442745274627472748274927502751function sanitizeTags(tags: unknown): string[] | undefined {2752 if (!Array.isArray(tags)) return undefined;2753 const out: string[] = [];2754 for (const t of tags) {2755 if (typeof t !== "string") continue;2756 const trimmed = t.trim();2757 if (!trimmed) continue;2758 out.push(trimmed.slice(0, 256));2759 if (out.length >= 255) break;2760 }2761 return out.length > 0 ? out : undefined;2762}276327642765276627672768export async function clearVaultEntries(2769 confirmation: "REPLACE_ALL"2770): Promise<void> {2771 if (confirmation !== "REPLACE_ALL") {2772 throw new Error("clearVaultEntries requires explicit confirmation");2773 }2774 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2775 for (const entry of entries) {2776 if (!entry.deletedAt) {2777 const stamp = monotonicEntryTimestamp(Math.max(2778 entry.modifiedAt,2779 tombstones.get(entry.id) ?? 0,2780 ));2781 entry.deletedAt = stamp;2782 entry.modifiedAt = stamp;2783 tombstones.set(entry.id, stamp);2784 }2785 }2786 await persistEntries();2787}27882789export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2790 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2791 const epoch = vaultEpoch;2792 const key = derivedKey;27932794 const sanitized = sanitizeEntryDraft(entry);2795 const now = Date.now();2796 const stamp = monotonicEntryTimestamp();2797 const nextEntry: VaultEntry = {2798 ...sanitized,2799 id: crypto.randomUUID(),2800 createdAt: now,2801 modifiedAt: stamp,2802 2803 2804 passwordChangedAt: sanitized.password ? stamp : undefined,2805 };28062807 2808 2809 2810 const rollback = entries;2811 entries = [...entries, nextEntry];2812 try {2813 await persistEntries();2814 } catch (err) {2815 entries = rollback;2816 throw err;2817 }28182819 if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password && epoch === vaultEpoch) {2820 checkEntryBreachDetached({ id: nextEntry.id, password: nextEntry.password, epoch, key });2821 }28222823 fireSyncTrigger("vault_change");28242825 return nextEntry;2826}282728282829export async function consolidatePasskeyEntries(): Promise<void> {2830 if (!derivedKey || vaultCreatesInFlight) return;2831 const epoch = vaultEpoch;2832 const rollback = entries;2833 const next = entries.map((entry) => ({ ...entry }));2834 if (!mergePasskeyOnlyIntoLogins(next).merged) return;2835 const unchanged = next.map((entry) => ({ entry, modifiedAt: entry.modifiedAt }));2836 entries = next;2837 try {2838 await persistEntries();2839 } catch (err) {2840 2841 if (epoch === vaultEpoch && entries === next && entries.length === unchanged.length &&2842 unchanged.every(({ entry, modifiedAt }, index) => entries[index] === entry && entry.modifiedAt === modifiedAt)) {2843 entries = rollback;2844 buildDomainIndexSync(entries);2845 }2846 throw err;2847 }2848}28492850export async function updateEntry(2851 id: string,2852 patch: Partial<VaultEntry>2853): Promise<void> {2854 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");28552856 const idx = entries.findIndex((entry) => entry.id === id);2857 if (idx === -1 || entries[idx].deletedAt) {2858 throw new Error("entry_not_found");2859 }28602861 const current = entries[idx];2862 const owner = entries;2863 const epoch = vaultEpoch;2864 const key = derivedKey;2865 const sanitizedPatch = sanitizeEntryPatch(patch);2866 2867 2868 2869 const passwordChanged =2870 "password" in patch &&2871 typeof sanitizedPatch.password === "string" &&2872 sanitizedPatch.password !== current.password;2873 const stamp = monotonicEntryTimestamp(current.modifiedAt);2874 2875 2876 2877 2878 2879 2880 2881 const priorPassword = current.password;2882 const shouldCapture =2883 passwordChanged &&2884 typeof priorPassword === "string" &&2885 priorPassword.length > 0 &&2886 current.passwordHistory?.[0]?.password !== priorPassword;2887 const nextHistory = shouldCapture2888 ? [2889 { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2890 ...(current.passwordHistory ?? []),2891 ].slice(0, PASSWORD_HISTORY_MAX)2892 : current.passwordHistory;2893 const next = {2894 ...current,2895 ...sanitizedPatch,2896 modifiedAt: stamp,2897 ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2898 };2899 entries[idx] = next;29002901 2902 if (entries[idx].type === "card" && !entries[idx].cardNumber) {2903 entries[idx] = current;2904 throw new Error("card number is required for card entries");2905 }29062907 2908 2909 2910 2911 try {2912 await persistEntries();2913 } catch (err) {2914 if (epoch === vaultEpoch && entries === owner && entries[idx] === next && next.modifiedAt === stamp && !next.deletedAt) entries[idx] = current;2915 throw err;2916 }29172918 if (passwordChanged && settings.breachMonitoring !== false && next.type === "login" && next.password && epoch === vaultEpoch) {2919 checkEntryBreachDetached({ id, password: next.password, epoch, key });2920 }29212922 fireSyncTrigger("vault_change");2923}29242925export async function deleteEntry(id: string): Promise<void> {2926 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29272928 const entry = entries.find((item) => item.id === id);2929 if (!entry || entry.deletedAt) {2930 throw new Error("entry_not_found");2931 }29322933 2934 2935 2936 const previousModifiedAt = entry.modifiedAt;2937 const previousTombstone = tombstones.get(id);2938 const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2939 entry.deletedAt = stamp;2940 entry.modifiedAt = stamp;2941 tombstones.set(id, stamp);2942 2943 2944 try {2945 await persistEntries();2946 } catch (err) {2947 delete entry.deletedAt;2948 entry.modifiedAt = previousModifiedAt;2949 if (previousTombstone === undefined) tombstones.delete(id);2950 else tombstones.set(id, previousTombstone);2951 throw err;2952 }2953 fireSyncTrigger("vault_change");2954}29552956export function getDeletedEntries(): VaultEntry[] {2957 if (!derivedKey) return [];2958 return entries.filter((e) => !!e.deletedAt);2959}296029612962export function getTombstoneManifest(): Record<string, number> {2963 if (!derivedKey) return {};2964 return Object.fromEntries(tombstones);2965}2966296729682969297029712972export async function getVaultVersion(): Promise<number> {2973 try {2974 const raw = await chrome.storage.local.get("peach_last_modified_at");2975 const v = (raw as Record<string, unknown>).peach_last_modified_at;2976 if (typeof v === "number") return v;2977 if (typeof v === "string" && v !== "") {2978 const n = Number.parseInt(v, 10);2979 return Number.isFinite(n) ? n : 0;2980 }2981 return 0;2982 } catch {2983 return 0;2984 }2985}2986298729882989299029912992299329942995299629972998export async function applyMergedRemoteEntries(2999 remoteEntries: VaultEntry[],3000 remoteTombstones: Record<string, number>,3001): Promise<{ received: number; applied: number; conflicts: number }> {3002 3003 3004 3005 3006 3007 3008 if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");30093010 const received = remoteEntries.length + Object.keys(remoteTombstones).length;3011 let applied = 0;3012 let conflicts = 0;30133014 const byId = new Map<string, VaultEntry>();3015 for (const e of entries) byId.set(e.id, e);30163017 const mergeNow = Date.now();3018 const remoteTombstoneTimes = new Map<string, number>();3019 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3020 if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {3021 remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));3022 }3023 }30243025 for (const remote of remoteEntries) {3026 const sanitized = sanitizeRestoredEntry(remote);3027 if (!sanitized) continue;3028 3029 3030 3031 sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);3032 if (typeof sanitized.deletedAt === "number") {3033 sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);3034 }3035 const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);3036 const localTombstoneTs = tombstones.get(sanitized.id);3037 const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);3038 if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {3039 continue;3040 }3041 const local = byId.get(sanitized.id);3042 if (!local) {3043 entries.push(sanitized);3044 byId.set(sanitized.id, sanitized);3045 tombstones.delete(sanitized.id);3046 applied += 1;3047 } else if (sanitized.modifiedAt > local.modifiedAt) {3048 const idx = entries.findIndex((e) => e.id === local.id);3049 if (idx !== -1) {3050 entries[idx] = sanitized;3051 byId.set(sanitized.id, sanitized);3052 tombstones.delete(sanitized.id);3053 applied += 1;3054 if (!local.deletedAt) conflicts += 1;3055 }3056 }3057 }30583059 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3060 if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;3061 3062 const deletedAt = remoteTombstoneTimes.get(id)!;3063 const knownTombstone = tombstones.get(id);3064 if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;3065 const local = byId.get(id);3066 if (!local) {3067 tombstones.set(id, deletedAt);3068 applied += 1;3069 continue;3070 }3071 if (local.deletedAt && local.deletedAt >= deletedAt) continue;3072 if (deletedAt < local.modifiedAt) continue;3073 const idx = entries.findIndex((e) => e.id === id);3074 if (idx !== -1) {3075 entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };3076 tombstones.set(id, deletedAt);3077 applied += 1;3078 }3079 }30803081 if (applied > 0 && vaultMode === "real") {3082 await persistEntries("sync_received");3083 buildDomainIndexSync(entries);3084 3085 3086 3087 3088 try {3089 void chrome.runtime3090 .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })3091 .catch(() => undefined);3092 } catch {3093 3094 }3095 }3096 return { received, applied, conflicts };3097}30983099export async function restoreEntry(id: string): Promise<void> {3100 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3101 const entry = entries.find((e) => e.id === id && e.deletedAt);3102 if (!entry) throw new Error("deleted entry not found");3103 const previousDeletedAt = entry.deletedAt;3104 const previousModifiedAt = entry.modifiedAt;3105 const previousTombstone = tombstones.get(id);3106 delete entry.deletedAt;3107 entry.modifiedAt = monotonicEntryTimestamp(Math.max(3108 entry.modifiedAt,3109 previousTombstone ?? 0,3110 ));3111 tombstones.delete(id);3112 try {3113 await persistEntries();3114 } catch (err) {3115 entry.deletedAt = previousDeletedAt;3116 entry.modifiedAt = previousModifiedAt;3117 if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);3118 throw err;3119 }3120 buildDomainIndexSync(entries);3121}31223123export async function purgeEntry(id: string): Promise<void> {3124 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3125 const idx = entries.findIndex((e) => e.id === id && e.deletedAt);3126 if (idx === -1) throw new Error("deleted entry not found");3127 const entry = entries[idx]!;3128 tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));3129 entries.splice(idx, 1);3130 await persistEntries();3131}313231333134export async function purgeExpiredTrash(retentionMs: number): Promise<number> {3135 if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;3136 const cutoff = Date.now() - retentionMs;3137 const before = entries.length;3138 for (const entry of entries) {3139 if (entry.deletedAt && entry.deletedAt < cutoff) {3140 tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));3141 }3142 }3143 entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));3144 const purged = before - entries.length;3145 if (purged > 0) await persistEntries();3146 return purged;3147}31483149export function queryDomain(domain: string): VaultEntry[] {3150 return domainIndex.get(domain) ?? [];3151}31523153export function getEntryById(id: string): VaultEntry | undefined {3154 return entries.find((entry) => entry.id === id && !entry.deletedAt);3155}31563157async function persistSlotA(3158 reason: VaultSnapshot["reason"] = "local_save",3159): Promise<StoredVault> {3160 if (!derivedKey) throw new Error("vault_locked");3161 const epoch = vaultEpoch;3162 const throwIfStale = () => {3163 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3164 };31653166 const slotA = await loadSlot(SLOT_A);3167 throwIfStale();3168 if (!slotA) throw new Error("missing slot A");31693170 3171 3172 await takeVaultSnapshot(reason);3173 throwIfStale();31743175 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3176 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3177 throwIfStale();31783179 3180 const nextSlotA: StoredVault = {3181 ...slotA,3182 nonce,3183 ciphertext,3184 tag,3185 3186 };31873188 3189 3190 3191 3192 3193 3194 let slotACommitted = false;3195 try {3196 throwIfStale();3197 await writeSlot(SLOT_A, nextSlotA);3198 slotACommitted = true;3199 throwIfStale();32003201 3202 3203 3204 if (!duressConfigured) {3205 throwIfStale();3206 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3207 throwIfStale();3208 }3209 3210 3211 3212 3213 3214 if (reason !== "sync_received") {3215 throwIfStale();3216 await stampLocalVaultMutation();3217 throwIfStale();3218 }3219 } catch (err) {3220 3221 3222 if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3223 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3224 throw err;3225 }32263227 return nextSlotA;3228}32293230async function persistSlotB(): Promise<void> {3231 if (!derivedKey) throw new Error("vault_locked");32323233 const slotB = await loadSlot(SLOT_B);3234 if (!slotB) throw new Error("missing slot B");32353236 3237 3238 3239 3240 const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3241 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");32423243 await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3244 3245 3246 3247 try {3248 await stampLocalVaultMutation();3249 } catch (err) {3250 await writeSlot(SLOT_B, slotB).catch(() => {});3251 throw err;3252 }3253}32543255async function persistEntries(3256 reason: VaultSnapshot["reason"] = "local_save",3257): Promise<void> {3258 if (vaultCreatesInFlight) throw new Error("vault_changed");3259 vaultWritesInFlight++;3260 try {3261 if (!derivedKey) throw new Error("vault_locked");32623263 3264 3265 const previousTombstones = tombstones;3266 const pendingTombstones = new Map(tombstones);3267 tombstones = pendingTombstones;3268 reconcileTombstones();3269 try {3270 if (vaultMode === "decoy") {3271 await persistSlotB();3272 } else {3273 await persistSlotA(reason);3274 }3275 } catch (err) {3276 if (tombstones === pendingTombstones) tombstones = previousTombstones;3277 throw err;3278 }3279 buildDomainIndexSync(entries);3280 await refreshLockedSyncState();3281 } finally { vaultWritesInFlight--; }3282}3283328432853286328732883289function allowHttpUrl(url: string | undefined): string {3290 const trimmed = url?.trim() ?? "";3291 if (!trimmed) return "";3292 try {3293 const parsed = new URL(trimmed);3294 if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3295 } catch {3296 3297 }3298 return trimmed;3299}33003301function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3302 if (!Array.isArray(values)) return undefined;3303 const seen = new Set<string>();3304 const cleaned: string[] = [];3305 for (const value of values) {3306 const trimmed = typeof value === "string" ? value.trim() : "";3307 if (!trimmed) continue;3308 if (!allowHttpUrl(trimmed)) continue;3309 const key = trimmed.toLowerCase();3310 if (seen.has(key)) continue;3311 seen.add(key);3312 cleaned.push(trimmed);3313 }3314 return cleaned.length > 0 ? cleaned : undefined;3315}33163317function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3318 const title = entry.title.trim();3319 const type: VaultEntry["type"] = entry.type ?? "login";33203321 if (!title) throw new Error("title is required");33223323 if (entry.passkey) {3324 const p = entry.passkey;3325 if (3326 !p.rpId ||3327 !p.credentialId ||3328 !p.publicKeyCose ||3329 !p.userHandle ||3330 !p.userName ||3331 (p.algorithm !== -7 && p.algorithm !== -8)3332 ) {3333 throw new Error("invalid passkey credential");3334 }3335 }3336 if (type === "card") {3337 if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3338 throw new Error("cardholder name and card number are required");3339 }3340 }33413342 return {3343 type,3344 title,3345 username: type === "login" ? entry.username?.trim() ?? "" : undefined,3346 email: type === "login" ? entry.email?.trim() || undefined : undefined,3347 password: type === "login" ? entry.password : undefined,3348 url: type === "login" ? allowHttpUrl(entry.url) : undefined,3349 additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3350 totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3351 3352 3353 totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3354 totpDigits: type === "login" ? entry.totpDigits : undefined,3355 totpPeriod: type === "login" ? entry.totpPeriod : undefined,3356 notes: entry.notes?.trim() || undefined,3357 breach: type === "login" ? entry.breach : undefined,3358 3359 3360 canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3361 tags: sanitizeTags(entry.tags),3362 passkey: entry.passkey,3363 cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3364 cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3365 expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3366 expYear: type === "card" ? entry.expYear?.trim() : undefined,3367 cvc: type === "card" ? entry.cvc?.trim() : undefined,3368 cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3369 network: type === "card" ? entry.network : undefined,3370 last4: type === "card" ? entry.last4?.trim() : undefined,3371 };3372}33733374function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3375 const nextPatch: Partial<VaultEntry> = {};33763377 if ("type" in patch) {3378 nextPatch.type = patch.type;3379 }33803381 if ("title" in patch) {3382 const title = patch.title?.trim() ?? "";3383 if (!title) throw new Error("title is required");3384 nextPatch.title = title;3385 }33863387 if ("url" in patch) {3388 nextPatch.url = allowHttpUrl(patch.url);3389 }33903391 if ("additionalUrls" in patch) {3392 const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3393 const seen = new Set<string>();3394 const cleaned: string[] = [];3395 for (const value of incoming) {3396 const trimmed = typeof value === "string" ? value.trim() : "";3397 if (!trimmed || !allowHttpUrl(trimmed)) continue;3398 const key = trimmed.toLowerCase();3399 if (seen.has(key)) continue;3400 seen.add(key);3401 cleaned.push(trimmed);3402 }3403 nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3404 }34053406 if ("username" in patch) {3407 nextPatch.username = patch.username?.trim() ?? "";3408 }34093410 if ("email" in patch) {3411 nextPatch.email = patch.email?.trim() || undefined;3412 }34133414 if ("password" in patch) {3415 const password = patch.password ?? "";3416 3417 nextPatch.password = password || undefined;3418 }34193420 if ("totp" in patch) {3421 nextPatch.totp = patch.totp?.trim() || undefined;3422 }34233424 if ("totpAlgorithm" in patch) {3425 nextPatch.totpAlgorithm = patch.totpAlgorithm;3426 }34273428 if ("totpDigits" in patch) {3429 nextPatch.totpDigits = patch.totpDigits;3430 }34313432 if ("totpPeriod" in patch) {3433 nextPatch.totpPeriod = patch.totpPeriod;3434 }34353436 if ("notes" in patch) {3437 nextPatch.notes = patch.notes?.trim() || undefined;3438 }34393440 if ("breach" in patch) {3441 nextPatch.breach = patch.breach;3442 }34433444 if ("canary" in patch) {3445 3446 3447 nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3448 }34493450 if ("passkey" in patch) {3451 3452 3453 if (patch.passkey === undefined || patch.passkey === null) {3454 nextPatch.passkey = undefined;3455 } else {3456 const sanitized = sanitizePasskey(patch.passkey);3457 if (!sanitized) throw new Error("invalid passkey credential");3458 nextPatch.passkey = sanitized;3459 }3460 }34613462 if ("tags" in patch) {3463 3464 nextPatch.tags = sanitizeTags(patch.tags);3465 }34663467 if ("cardholderName" in patch) {3468 nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3469 }3470 if ("cardNumber" in patch) {3471 const n = patch.cardNumber ?? "";3472 nextPatch.cardNumber = n || undefined;3473 }3474 if ("expMonth" in patch) {3475 nextPatch.expMonth = patch.expMonth?.trim() || undefined;3476 }3477 if ("expYear" in patch) {3478 nextPatch.expYear = patch.expYear?.trim() || undefined;3479 }3480 if ("cvc" in patch) {3481 nextPatch.cvc = patch.cvc?.trim() || undefined;3482 }3483 if ("cardNickname" in patch) {3484 nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3485 }3486 if ("network" in patch) {3487 nextPatch.network = patch.network;3488 }3489 if ("last4" in patch) {3490 nextPatch.last4 = patch.last4?.trim() || undefined;3491 }34923493 return nextPatch;3494}34953496function normalizeEntry(entry: VaultEntry): VaultEntry {3497 const base: VaultEntry = {3498 id: entry.id,3499 type: entry.type,3500 title: entry.title,3501 username: entry.username,3502 email: entry.email,3503 password: entry.password,3504 url: entry.url,3505 additionalUrls:3506 "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3507 ? entry.additionalUrls3508 : undefined,3509 totp: entry.totp,3510 3511 totpAlgorithm: entry.totpAlgorithm,3512 totpDigits: entry.totpDigits,3513 totpPeriod: entry.totpPeriod,3514 notes: entry.notes,3515 breach: entry.breach,3516 3517 3518 3519 passwordChangedAt:3520 "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3521 3522 3523 3524 passwordHistory:3525 "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3526 ? entry.passwordHistory3527 : undefined,3528 canary: entry.canary,3529 passkey: entry.passkey,3530 createdAt: entry.createdAt,3531 modifiedAt: entry.modifiedAt,3532 deletedAt: entry.deletedAt,3533 tags: entry.tags,3534 cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3535 cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3536 expMonth: "expMonth" in entry ? entry.expMonth : undefined,3537 expYear: "expYear" in entry ? entry.expYear : undefined,3538 cvc: "cvc" in entry ? entry.cvc : undefined,3539 cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3540 network: "network" in entry ? entry.network : undefined,3541 last4: "last4" in entry ? entry.last4 : undefined,3542 };35433544 return base;3545}3546354735483549355035513552function entryDupeKey(e: VaultEntry): string {3553 if (e.passkey) {3554 3555 const content = Object.fromEntries(Object.entries(e)3556 .filter(([key]) => key !== "id" && key !== "createdAt" && key !== "modifiedAt")3557 .sort(([a], [b]) => a.localeCompare(b)));3558 return `passkey|${e.passkey.rpId}|${e.passkey.credentialId}|${JSON.stringify(content)}`;3559 }3560 if (e.type === "note") return `note|${e.title.toLowerCase()}`;3561 return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3562}356335643565export function countDuplicates(): number {3566 const best = new Map<string, VaultEntry>();3567 let dupeCount = 0;3568 for (const e of entries.filter((e) => !e.deletedAt)) {3569 const key = entryDupeKey(e);3570 const existing = best.get(key);3571 if (!existing) {3572 best.set(key, e);3573 } else {3574 dupeCount++;3575 3576 if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3577 best.set(key, e);3578 }3579 }3580 }3581 return dupeCount;3582}358335843585358635873588export async function deduplicateEntries(): Promise<number> {3589 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3590 3591 3592 if (vaultMode === "decoy") {3593 throw new Error("deduplicate disabled in decoy mode");3594 }35953596 const best = new Map<string, VaultEntry>();3597 for (const e of entries.filter((en) => !en.deletedAt)) {3598 const key = entryDupeKey(e);3599 const existing = best.get(key);3600 if (!existing) {3601 best.set(key, e);3602 } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3603 best.set(key, e);3604 }3605 }36063607 const keepIds = new Set(Array.from(best.values()).map((e) => e.id));3608 let removed = 0;3609 entries = entries.map((e) => {3610 if (!e.deletedAt && !keepIds.has(e.id)) {3611 removed++;3612 const deletedAt = monotonicEntryTimestamp(Math.max(3613 e.modifiedAt,3614 tombstones.get(e.id) ?? 0,3615 ));3616 tombstones.set(e.id, deletedAt);3617 return { ...e, deletedAt };3618 }3619 return e;3620 });36213622 if (removed > 0) await persistEntries();3623 return removed;3624}362536263627362836293630363136323633const HISTORY_KEY = "peach_vault_history";3634const HISTORY_MAX = 5;363536363637363836393640function bucketEntryCount(n: number): number {3641 if (n <= 0) return 0;3642 if (n <= 10) return 10;3643 if (n <= 25) return 25;3644 if (n <= 50) return 50;3645 if (n <= 100) return 100;3646 if (n <= 250) return 250;3647 if (n <= 500) return 500;3648 return Math.ceil(n / 500) * 500;3649}36503651365236533654365536563657export async function takeVaultSnapshot(3658 reason: VaultSnapshot["reason"],3659): Promise<void> {3660 if (recoveryInFlight || vaultCreatesInFlight) return;3661 3662 3663 3664 if (vaultMode === "decoy") return;3665 vaultWritesInFlight++;3666 try {3667 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);3668 const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];3669 const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];36703671 3672 3673 3674 if (!slotA) return;36753676 const vault_a = JSON.stringify(slotA);3677 const vault_b = JSON.stringify(slotB ?? slotA);36783679 3680 3681 3682 3683 3684 3685 let entryCount: number | null = null;3686 if (derivedKey && vaultMode === "real") {3687 try {3688 entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);3689 } catch {3690 entryCount = null;3691 }3692 }36933694 const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3695 const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)3696 ? existingRaw3697 : { snapshots: [] };36983699 3700 3701 3702 const latest = history.snapshots[0];3703 if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3704 return;3705 }37063707 const snapshot: VaultSnapshot = {3708 id: crypto.randomUUID(),3709 savedAt: Date.now(),3710 reason,3711 vault_a,3712 vault_b,3713 entryCount,3714 };37153716 history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3717 if (recoveryInFlight || vaultCreatesInFlight) return;3718 await chrome.storage.local.set({ [HISTORY_KEY]: history });3719 } catch (err) {3720 3721 3722 3723 3724 console.warn('[Peach] takeVaultSnapshot failed:', err);3725 if (String(err).includes('QUOTA') || String(err).includes('quota')) {3726 try {3727 await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3728 } catch {3729 3730 }3731 }3732 } finally { vaultWritesInFlight--; }3733}373437353736export async function clearVaultHistory(): Promise<void> {3737 if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");3738 vaultWritesInFlight++;3739 try {3740 await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3741 } catch {3742 3743 } finally { vaultWritesInFlight--; }3744}374537463747export async function getVaultHistory(): Promise<VaultSnapshot[]> {3748 if (vaultMode === "decoy") return [];3749 const raw = await chrome.storage.local.get(HISTORY_KEY);3750 const value = (raw as Record<string, unknown>)[HISTORY_KEY];3751 return sanitizeHistory(value);3752}375337543755375637573758export async function restoreVaultSnapshot(3759 snapshotId: string,3760): Promise<{ ok: true } | { ok: false; error: string }> {3761 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };3762 vaultReplacementInFlight = true;3763 try {3764 if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3765 const history = await getVaultHistory();3766 const snapshot = history.find((s) => s.id === snapshotId);3767 if (!snapshot) return { ok: false, error: "snapshot_not_found" };37683769 const restoredA = parseHistorySlot(snapshot.vault_a);3770 const restoredB = parseHistorySlot(snapshot.vault_b);3771 if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };37723773 await takeVaultSnapshot("restore");3774 const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3775 const previousA = (current as Record<string, unknown>)[SLOT_A];3776 const previousB = (current as Record<string, unknown>)[SLOT_B];3777 try {3778 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };3779 await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3780 await stampLocalVaultMutation();3781 } catch {3782 try {3783 await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3784 } catch {3785 3786 }3787 return { ok: false, error: "snapshot_corrupt" };3788 }37893790 await lock();3791 return { ok: true };3792 } finally {3793 vaultReplacementInFlight = false;3794 }3795}379637973798379938003801380238033804380538063807380838093810export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3811 if (vaultCreatesInFlight) throw new Error("vault_changed");3812 const rotationEpoch = vaultEpoch;3813 const removalEpoch = vaultRemovalEpoch;3814 vaultWritesInFlight++;3815 try {3816 if (!derivedKey || vaultMode !== "real") {3817 return { ok: false, error: "vault_locked" };3818 }3819 const slotA = await loadSlot(SLOT_A);3820 if (!slotA) return { ok: false, error: "missing_slot_a" };38213822 3823 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3824 await generateAndWrapRootKey();38253826 3827 const newRootKey = unhex(rawRootKey);3828 const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");3829 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);38303831 3832 3833 3834 3835 await takeVaultSnapshot("local_save");3836 const nextSlotA: StoredVault = {3837 ...slotA,3838 recovery_vault_key: recoveryVaultKey,3839 recovery_salt: recoverySalt,3840 recovery_wrapped_root_key: wrappedRootKey,3841 recovery_nonce: wrappedNonce,3842 recovery_tag: wrappedTag,3843 ...pwRoot,3844 };3845 await writeSlot(SLOT_A, nextSlotA);38463847 3848 if (rotationEpoch === vaultEpoch && derivedKey) {3849 if (rootKey) zeroKey(rootKey);3850 rootKey = newRootKey;3851 } else {3852 zeroKey(newRootKey);3853 }38543855 3856 3857 await notifyIdentityKeysRotated();38583859 3860 3861 3862 await clearPairedDevices();3863 await clearPairSecrets();38643865 3866 if (removalEpoch === vaultRemovalEpoch) {3867 await setRecoveryConfirmPending(rotationEpoch === vaultEpoch && isUnlocked());3868 touchAutoLock();3869 }38703871 await stampLocalVaultMutation();3872 return { ok: true };3873 } finally { vaultWritesInFlight--; }3874}38753876387738783879388038813882export async function changePassword(3883 currentPassword: string,3884 newPassword: string3885): Promise<boolean> {3886 if (vaultCreatesInFlight) throw new Error("vault_changed");3887 vaultWritesInFlight++;3888 try {38893890 const epoch = vaultEpoch;3891 const stale = () => epoch !== vaultEpoch;3892 if (!derivedKey || vaultMode !== "real") return false;38933894 3895 const valid = await verifyMainPassword(currentPassword);3896 if (!valid) return false;38973898 const slotA = await loadSlot(SLOT_A);3899 if (!slotA) return false;3900 if (!rootKey) return false;39013902 3903 const newSalt = generateSalt();3904 const newKey = await deriveKey(newPassword, newSalt);3905 if (stale()) {3906 zeroKey(newKey);3907 return false;3908 }39093910 3911 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3912 const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");39133914 3915 3916 3917 const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);39183919 const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");3920 const finalSlotA: StoredVault = {3921 ...slotA,3922 recovery_vault_key: recoveryVaultKey,3923 salt: hex(newSalt),3924 nonce,3925 ciphertext,3926 tag,3927 ...pwRoot,3928 };39293930 3931 3932 3933 await takeVaultSnapshot("local_save");39343935 3936 3937 3938 3939 await writeSlot(SLOT_A, finalSlotA);3940 if (stale()) {3941 zeroKey(newKey);3942 return false;3943 }39443945 3946 3947 3948 zeroKey(derivedKey);3949 cancelBreachScan();3950 derivedKey = newKey;39513952 3953 3954 3955 3956 if (stale()) {3957 await lock();3958 return false;3959 }3960 await saveSessionKey(newKey, "real", epoch);3961 if (stale()) return false;39623963 3964 3965 3966 await notifyIdentityKeysRotated();3967 if (stale()) return false;39683969 3970 3971 3972 if (!duressConfigured) {3973 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3974 }3975 await clearPinUnlockStorage();3976 await stampLocalVaultMutation();39773978 return true;3979 } finally { vaultWritesInFlight--; }3980}