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";59export const SETTINGS_STORAGE_KEY = "peach_settings";60616263const PAD_BLOCK = 1024;6465666768const PASSWORD_HISTORY_MAX = 50;6970717273747576777879const DURESS_SLOT_SIZE = 262_144;8081let derivedKey: Uint8Array | null = null;8283848586let rootKey: Uint8Array | null = null;87let recoveryInFlight = false;88let recoverySettled: Promise<void> = Promise.resolve();89let vaultRemovalsInFlight = 0;90let vaultRemovalEpoch = 0;91let vaultWritesInFlight = 0;92let vaultCreatesInFlight = 0;93let creationSettled: Promise<void> = Promise.resolve();94let vaultUnlocksInFlight = 0;95let vaultReplacementInFlight = false;96let entries: VaultEntry[] = [];979899100let tombstones = new Map<string, number>();101let domainIndex: Map<string, VaultEntry[]> = new Map();102let vaultMode: "real" | "decoy" = "real";103104105106let duressConfigured = false;107108109110111112113114115116117let lastUnlockFailureReason: string | null = null;118119export function consumeLastUnlockFailureReason(): string | null {120 const r = lastUnlockFailureReason;121 lastUnlockFailureReason = null;122 return r;123}124125126127128129export type TextSize = "small" | "medium" | "large";130131export interface VaultSettings {132 accentColor?: AccentColorName;133 theme?: "dark" | "light";134 autoLockMinutes?: number;135 clipboardClearSeconds?: number;136 lockOnClose?: boolean;137 breachMonitoring?: boolean;138 passkeyProviderEnabled?: boolean;139 trashRetentionDays?: number;140 manualSummonDomains?: Record<string, ManualSummonRecord>;141 manualSummonSalt?: string;142 declinedCardFingerprints?: string[];143144 145 metadataVersion?: 1;146 147148149150151 textSize?: TextSize;152 153154155156157 reduceMotion?: boolean;158 159 lockedSyncRequiresUnlock?: boolean;160 161 pinEnabled?: boolean;162 163 pinPreferred?: boolean;164 165166167168169170171 shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;172}173174interface StoredPinWrap {175 version: 1;176 salt: string;177 nonce: string;178 ciphertext: string;179 tag: string;180}181182const PIN_WRAP_STORAGE = "peach_pin_wrap";183const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";184const PIN_MIN_LENGTH = 4;185const PIN_MAX_LENGTH = 12;186const PIN_MAX_ATTEMPTS = 3;187188let settings: VaultSettings = {};189const CARD_DECLINE_MAX = 256;190191const CARD_DECLINE_DIGEST_HEX = 32;192193async function metadataDigest(value: string, key: string): Promise<string> {194 const bytes = new TextEncoder().encode(`${key}:${value}`);195 const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));196 return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");197}198199let inMemoryPinWrap: StoredPinWrap | null = null;200let inMemoryPinFailedAttempts = 0;201let sessionPinStorageFailed = false;202203export function getSettings(): VaultSettings {204 return settings;205}206207export async function ensureSettingsLoaded(): Promise<VaultSettings> {208 await loadSettings();209 return settings;210}211212export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {213 await loadSettings();214 215 216 217 218 219 220 const safe = Object.fromEntries(221 Object.entries(patch).filter(222 ([k]) => ![223 "__proto__", "constructor", "prototype",224 "manualSummonDomains", "manualSummonSalt",225 ].includes(k),226 ),227 ) as Partial<VaultSettings>;228 settings = { ...settings, ...safe };229 await persistSettings();230}231232function isValidPin(pin: string): boolean {233 return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);234}235236237export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {238 if (vaultCreatesInFlight) return false;239 vaultWritesInFlight++;240 try {241 if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;242 if (!(await verifyMainPassword(currentPassword))) return false;243244 const salt = generateSalt();245 const pinKey = await deriveKey(pin, salt);246 try {247 const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");248 await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });249 await updateSettings({ pinEnabled: true });250 return true;251 } finally {252 zeroKey(pinKey);253 }254 } finally { vaultWritesInFlight--; }255}256257async function clearPinUnlockStorage(): Promise<void> {258 inMemoryPinWrap = null;259 inMemoryPinFailedAttempts = 0;260 sessionPinStorageFailed = false;261 if (chrome.storage.session) {262 await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);263 }264 await updateSettings({ pinEnabled: false });265}266267268export async function disablePinUnlock(currentPassword: string): Promise<boolean> {269 if (vaultCreatesInFlight) return false;270 vaultWritesInFlight++;271 try {272 if (!derivedKey || vaultMode !== "real") return false;273 if (!(await verifyMainPassword(currentPassword))) return false;274 await clearPinUnlockStorage();275 return true;276 } finally { vaultWritesInFlight--; }277}278279280export async function unlockWithPin(pin: string): Promise<boolean> {281 vaultUnlocksInFlight++;282 try {283 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;284 if (!isValidPin(pin)) return false;285 await loadSettings();286 if (!settings.pinEnabled) return false;287288 const { stored, failedAttempts } = await loadPinState();289 if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;290 if (291 !stored ||292 stored.version !== 1 ||293 !stored.salt ||294 !stored.nonce ||295 !stored.ciphertext ||296 !stored.tag297 ) return false;298299 const pinKey = await deriveKey(pin, unhex(stored.salt));300 let unwrappedKey: Uint8Array | null = null;301 try {302 const masterKeyHex = await decrypt(303 pinKey,304 stored.nonce,305 stored.ciphertext,306 stored.tag,307 "pin_wrap_v1",308 );309 if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;310 unwrappedKey = unhex(masterKeyHex);311 const result = await unlockWithKey(masterKeyHex);312 if (!result.ok) return false;313 await resetPinFailedAttempts();314 return true;315 } catch {316 await recordPinFailure(failedAttempts + 1);317 return false;318 } finally {319 zeroKey(pinKey);320 if (unwrappedKey) zeroKey(unwrappedKey);321 }322 } finally { vaultUnlocksInFlight--; }323}324325async function savePinWrap(stored: StoredPinWrap): Promise<void> {326 inMemoryPinWrap = stored;327 inMemoryPinFailedAttempts = 0;328 sessionPinStorageFailed = !chrome.storage.session;329 if (!chrome.storage.session) return;330 try {331 await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });332 sessionPinStorageFailed = false;333 } catch {334 335 sessionPinStorageFailed = true;336 }337}338339async function loadPinState(): Promise<{340 stored: StoredPinWrap | undefined;341 failedAttempts: number;342}> {343 if (!chrome.storage.session) {344 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };345 }346 try {347 const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);348 return {349 stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??350 (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),351 failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"352 ? result[PIN_ATTEMPTS_STORAGE]353 : 0,354 };355 } catch {356 return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };357 }358}359360async function recordPinFailure(failedAttempts: number): Promise<void> {361 inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);362 if (!chrome.storage.session) return;363 try {364 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });365 } catch { }366}367368async function resetPinFailedAttempts(): Promise<void> {369 inMemoryPinFailedAttempts = 0;370 if (!chrome.storage.session) return;371 try {372 await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });373 } catch { }374}375376export async function getPinUnlockStatus(): Promise<{377 configured: boolean;378 available: boolean;379 attemptsRemaining: number;380}> {381 await loadSettings();382 if (!settings.pinEnabled) {383 return { configured: false, available: false, attemptsRemaining: 0 };384 }385 const { stored, failedAttempts } = await loadPinState();386 const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;387 return {388 configured: true,389 available,390 attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,391 };392}393394async function persistSettings(): Promise<void> {395 try {396 await chrome.storage.local.set({397 [SETTINGS_STORAGE_KEY]: {398 399 400 ...settings,401 cardFingerprintSalt: undefined,402 declinedCardFingerprints: settings.declinedCardFingerprints ?? [],403 metadataVersion: 1,404 },405 });406 } catch (err) {407 throw mapStorageError(err);408 }409}410411function mapStorageError(err: unknown): Error {412 const message = err instanceof Error ? err.message : String(err);413 if (/QUOTA_BYTES|quota/i.test(message)) {414 return new Error("STORAGE_QUOTA_EXCEEDED");415 }416 return err instanceof Error ? err : new Error(message);417}418419async function loadSettings(): Promise<void> {420 const result = await chrome.storage.local.get(SETTINGS_STORAGE_KEY);421 settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};422}423424425async function clearLegacyManualSummonPlaintext(): Promise<void> {426 settings = { ...settings, manualSummonDomains: undefined, manualSummonSalt: undefined };427 await persistSettings();428}429430431432433434435436437438const RECALL_STORAGE = "peach_manual_summon_recall_v1";439const RECALL_REAL_AAD = "manual_summon_recall_v1";440const RECALL_DECOY_AAD = "manual_summon_recall_decoy_v1";441const RECALL_MAX_RECORDS = 256;442const RECALL_DOMAIN_MAX_BYTES = 253;443444445const RECALL_MAX_CLOCK_SKEW_MS = 5 * 60_000;446447interface SealedRecall {448 nonce: string;449 ciphertext: string;450 tag: string;451}452453interface StoredRecall {454 v: 1;455 real?: SealedRecall;456 decoy?: SealedRecall;457}458459let manualSummonRecall = new Map<string, ManualSummonRecord>();460let recallMutation: Promise<void> = Promise.resolve();461462function isValidRecallDomain(domain: unknown): domain is string {463 return typeof domain === "string" && domain.length > 0 &&464 new TextEncoder().encode(domain).length <= RECALL_DOMAIN_MAX_BYTES;465}466467function sanitizeSummonRecord(value: unknown, now: number): ManualSummonRecord | null {468 if (!value || typeof value !== "object") return null;469 const record = value as Record<string, unknown>;470 const firstSummonedAt = record.firstSummonedAt;471 const lastSummonedAt = record.lastSummonedAt;472 const latestAllowed = now + RECALL_MAX_CLOCK_SKEW_MS;473 for (const timestamp of [firstSummonedAt, lastSummonedAt]) {474 if (475 typeof timestamp !== "number" ||476 !Number.isSafeInteger(timestamp) ||477 timestamp < 0 ||478 timestamp > latestAllowed479 ) {480 return null;481 }482 }483 if (typeof record.summonCount !== "number" || !Number.isFinite(record.summonCount)) {484 return null;485 }486 return {487 firstSummonedAt: firstSummonedAt as number,488 lastSummonedAt: lastSummonedAt as number,489 490 summonCount: Math.min(2, Math.max(1, Math.trunc(record.summonCount))),491 };492}493494function capManualSummonRecall(495 records: Map<string, ManualSummonRecord>,496): Map<string, ManualSummonRecord> {497 if (records.size <= RECALL_MAX_RECORDS) return records;498 const kept = new Map(records);499 while (kept.size > RECALL_MAX_RECORDS) {500 let oldestDomain: string | null = null;501 let oldestAt = Number.POSITIVE_INFINITY;502 for (const [domain, record] of kept) {503 if (record.lastSummonedAt < oldestAt) {504 oldestAt = record.lastSummonedAt;505 oldestDomain = domain;506 }507 }508 if (oldestDomain === null) break;509 kept.delete(oldestDomain);510 }511 return kept;512}513514function sanitizeManualSummonRecall(value: unknown): Map<string, ManualSummonRecord> {515 const records = new Map<string, ManualSummonRecord>();516 if (!value || typeof value !== "object" || Array.isArray(value)) return records;517 const now = Date.now();518 for (const [domain, raw] of Object.entries(value as Record<string, unknown>)) {519 if (!isValidRecallDomain(domain)) continue;520 const record = sanitizeSummonRecord(raw, now);521 if (record) records.set(domain, record);522 }523 return capManualSummonRecall(records);524}525526function readStoredRecall(value: unknown): StoredRecall {527 const stored: StoredRecall = { v: 1 };528 if (!value || typeof value !== "object" || Array.isArray(value)) return stored;529 for (const mode of ["real", "decoy"] as const) {530 const member = (value as Record<string, unknown>)[mode];531 if (!member || typeof member !== "object") continue;532 const sealed = member as Record<string, unknown>;533 if (534 typeof sealed.nonce === "string" &&535 typeof sealed.ciphertext === "string" &&536 typeof sealed.tag === "string"537 ) {538 stored[mode] = { nonce: sealed.nonce, ciphertext: sealed.ciphertext, tag: sealed.tag };539 }540 }541 return stored;542}543544function recallSealContext(): { key: Uint8Array; aad: string } | null {545 if (vaultMode === "decoy") {546 return derivedKey ? { key: derivedKey, aad: RECALL_DECOY_AAD } : null;547 }548 return rootKey ? { key: rootKey, aad: RECALL_REAL_AAD } : null;549}550551function serializeRecallMutation(run: () => Promise<void>): Promise<void> {552 const task = recallMutation.then(run, run);553 recallMutation = task.then(() => undefined, () => undefined);554 return task;555}556557async function readStoredRecallFromDisk(): Promise<StoredRecall> {558 const raw = await chrome.storage.local.get(RECALL_STORAGE);559 return readStoredRecall((raw as Record<string, unknown>)[RECALL_STORAGE]);560}561562563564565function recallSealIsCurrent(566 epoch: number,567 mode: "real" | "decoy",568 sealKey: Uint8Array,569): boolean {570 return epoch === vaultEpoch && mode === vaultMode && recallSealContext()?.key === sealKey;571}572573async function loadManualSummonRecall(): Promise<void> {574 const epoch = vaultEpoch;575 const mode = vaultMode;576 const context = recallSealContext();577 manualSummonRecall = new Map();578 if (!context) return;579 let stored: StoredRecall;580 try {581 stored = await readStoredRecallFromDisk();582 } catch (error) {583 console.warn("[Peach] manual-summon recall read failed:", error);584 return;585 }586 if (epoch !== vaultEpoch || mode !== vaultMode) return;587 const member = stored[mode];588 if (!member) return;589 try {590 const plain = await decrypt(context.key, member.nonce, member.ciphertext, member.tag, context.aad);591 if (epoch !== vaultEpoch || mode !== vaultMode) return;592 manualSummonRecall = sanitizeManualSummonRecall(JSON.parse(plain));593 } catch {594 595 596 manualSummonRecall = new Map();597 }598}599600async function persistManualSummonRecall(): Promise<void> {601 const epoch = vaultEpoch;602 const mode = vaultMode;603 const context = recallSealContext();604 if (!derivedKey || !context) throw new Error("vault_locked");605 const sealKey = context.key;606 let stored: StoredRecall;607 try {608 stored = await readStoredRecallFromDisk();609 } catch (error) {610 throw mapStorageError(error);611 }612 613 614 615 let records = manualSummonRecall;616 const existing = stored[mode];617 if (existing) {618 try {619 const plain = await decrypt(sealKey, existing.nonce, existing.ciphertext, existing.tag, context.aad);620 const merged = sanitizeManualSummonRecall(JSON.parse(plain));621 for (const [domain, record] of records) merged.set(domain, record);622 records = capManualSummonRecall(merged);623 } catch {624 625 }626 }627 if (!recallSealIsCurrent(epoch, mode, sealKey)) throw new Error("vault_locked");628 const sealed = await encrypt(629 sealKey,630 JSON.stringify(Object.fromEntries(records)),631 context.aad,632 );633 if (!recallSealIsCurrent(epoch, mode, sealKey)) throw new Error("vault_locked");634 635 stored[mode] = sealed;636 try {637 await chrome.storage.local.set({ [RECALL_STORAGE]: stored });638 } catch (error) {639 throw mapStorageError(error);640 }641 642 643 if (recallSealIsCurrent(epoch, mode, sealKey)) manualSummonRecall = records;644}645646647648649650651async function rekeyManualSummonRecall(652 oldRootKey: Uint8Array,653 newRootKey: Uint8Array,654): Promise<void> {655 const epoch = vaultEpoch;656 const sealIsCurrent = (): boolean =>657 epoch === vaultEpoch && vaultMode === "real" && rootKey === oldRootKey;658 if (!sealIsCurrent()) throw new Error("vault_locked");659 const stored = await readStoredRecallFromDisk();660 let records = manualSummonRecall;661 const existing = stored.real;662 if (existing) {663 try {664 const plain = await decrypt(oldRootKey, existing.nonce, existing.ciphertext, existing.tag, RECALL_REAL_AAD);665 const merged = sanitizeManualSummonRecall(JSON.parse(plain));666 for (const [domain, record] of records) merged.set(domain, record);667 records = capManualSummonRecall(merged);668 } catch {669 670 }671 }672 if (!existing && records.size === 0) return;673 if (!sealIsCurrent()) throw new Error("vault_locked");674 stored.real = await encrypt(675 newRootKey,676 JSON.stringify(Object.fromEntries(records)),677 RECALL_REAL_AAD,678 );679 if (!sealIsCurrent()) return;680 await chrome.storage.local.set({ [RECALL_STORAGE]: stored });681 if (sealIsCurrent()) manualSummonRecall = records;682}683684685686687688async function adoptLegacyManualSummonRecall(): Promise<void> {689 if (vaultMode !== "real" || !rootKey) return;690 const legacy = sanitizeManualSummonRecall(settings.manualSummonDomains);691 if (legacy.size === 0) return;692 const epoch = vaultEpoch;693 const previous = manualSummonRecall;694 const merged = new Map(legacy);695 for (const [domain, record] of previous) merged.set(domain, record);696 manualSummonRecall = capManualSummonRecall(merged);697 try {698 await persistManualSummonRecall();699 } catch (error) {700 if (epoch === vaultEpoch && vaultMode === "real") manualSummonRecall = previous;701 throw error;702 }703 await clearLegacyManualSummonPlaintext();704}705706async function restoreManualSummonRecall(): Promise<void> {707 try {708 await loadSettings();709 } catch (error) {710 console.warn("[Peach] manual-summon recall settings read failed:", error);711 return;712 }713 try {714 await serializeRecallMutation(async () => {715 await loadManualSummonRecall();716 await adoptLegacyManualSummonRecall();717 });718 } catch (error) {719 720 console.warn("[Peach] manual-summon recall migration deferred:", error);721 }722}723724async function clearStoredManualSummonRecall(mode?: "real" | "decoy"): Promise<void> {725 if (mode === undefined) {726 manualSummonRecall = new Map();727 try {728 await chrome.storage.local.remove(RECALL_STORAGE);729 } catch (error) {730 console.warn("[Peach] manual-summon recall cleanup failed:", error);731 }732 return;733 }734 try {735 736 737 await serializeRecallMutation(async () => {738 const stored = await readStoredRecallFromDisk();739 if (!stored[mode]) return;740 delete stored[mode];741 if (stored.real || stored.decoy) {742 await chrome.storage.local.set({ [RECALL_STORAGE]: stored });743 } else {744 await chrome.storage.local.remove(RECALL_STORAGE);745 }746 });747 } catch (error) {748 console.warn("[Peach] manual-summon recall cleanup failed:", error);749 }750}751752753export function getManualSummonRecord(domain: string): ManualSummonRecord | undefined {754 const recalled = manualSummonRecall.get(domain);755 if (recalled) return recalled;756 757 if (vaultMode !== "real" || !isValidRecallDomain(domain)) return undefined;758 return sanitizeSummonRecord(settings.manualSummonDomains?.[domain], Date.now()) ?? undefined;759}760761762export async function recordManualSummon(domain: string): Promise<void> {763 if (!isValidRecallDomain(domain)) throw new Error("invalid_domain");764 vaultWritesInFlight++;765 try {766 const run = async (): Promise<void> => {767 if (!derivedKey || !recallSealContext()) throw new Error("vault_locked");768 const epoch = vaultEpoch;769 const mode = vaultMode;770 const previous = manualSummonRecall;771 const now = Date.now();772 const existing = previous.get(domain);773 const next = new Map(previous);774 next.set(domain, {775 firstSummonedAt: existing?.firstSummonedAt ?? now,776 summonCount: Math.min(2, (existing?.summonCount ?? 0) + 1),777 lastSummonedAt: now,778 });779 manualSummonRecall = capManualSummonRecall(next);780 try {781 await persistManualSummonRecall();782 } catch (error) {783 if (epoch === vaultEpoch && mode === vaultMode) manualSummonRecall = previous;784 throw error;785 }786 };787 788 await serializeRecallMutation(run);789 } finally {790 vaultWritesInFlight--;791 }792}793794795796function fireSyncTrigger(reason: "vault_change"): void {797 void Promise.resolve()798 .then(() => triggerSyncIfReachable({ reason }))799 .catch(() => {800 801 });802}803export function lockedSyncRequiresUnlock(): boolean {804 return settings.lockedSyncRequiresUnlock === true;805}806807let lockedSyncRefreshHook: (() => Promise<void>) | null = null;808let lockedSyncUnlockHook: (() => Promise<void>) | null = null;809let vaultLockHook: (() => void) | null = null;810let decoySyncTeardownHook: (() => void) | null = null;811export type IdentityHooks = {812 813 onSessionEnded: () => Promise<void>;814 815 onKeysRotated: () => Promise<void>;816 817 onVaultCreated: (password: string) => Promise<void>;818};819820let identityHooks: IdentityHooks | null = null;821822export function setIdentityHooks(hooks: IdentityHooks): void {823 identityHooks = hooks;824}825826async function notifyIdentitySessionEnded(): Promise<void> {827 await identityHooks?.onSessionEnded().catch((error) => {828 console.warn("[Peach] local identity cache clear failed:", error);829 });830}831832async function notifyIdentityKeysRotated(): Promise<void> {833 await identityHooks?.onKeysRotated().catch((error) => {834 console.warn("[Peach] local identity re-wrap failed:", error);835 });836}837838export type SealedBox = { nonce: string; ciphertext: string; tag: string };839export type IdentityKeyEnvelope = {840 root?: SealedBox;841 local?: SealedBox;842 pending?: SealedBox;843 pendingSalt?: string;844};845846export function setLockedSyncHooks(hooks: {847 refresh: () => Promise<void>;848 afterUnlock: () => Promise<void>;849 onLock?: () => void;850 onDecoy?: () => void;851}): void {852 lockedSyncRefreshHook = hooks.refresh;853 lockedSyncUnlockHook = hooks.afterUnlock;854 vaultLockHook = hooks.onLock ?? null;855 decoySyncTeardownHook = hooks.onDecoy ?? null;856}857858async function refreshLockedSyncState(): Promise<void> {859 if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;860 await lockedSyncRefreshHook().catch((error) => {861 console.warn("[Peach sync] locked spool refresh failed:", error);862 });863}864865866867868869export async function checkBreach(password: string, signal?: AbortSignal): Promise<number | null> {870 const controller = new AbortController();871 let timeout: ReturnType<typeof setTimeout> | undefined;872 let onAbort: (() => void) | undefined;873 try {874 const unavailable = new Promise<null>((resolve) => {875 onAbort = () => { controller.abort(); resolve(null); };876 signal?.addEventListener("abort", onAbort, { once: true });877 timeout = setTimeout(onAbort, 8_000);878 if (signal?.aborted) onAbort();879 });880 const lookup = async (): Promise<number | null> => {881 882 const hash = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(password));883 if (controller.signal.aborted) return null;884 const hex = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();885 const res = await fetch(`https://api.pwnedpasswords.com/range/${hex.slice(0, 5)}`, {886 headers: { "Add-Padding": "true" },887 signal: controller.signal,888 });889 if (!res.ok) return null;890 const text = await res.text();891 const lines = text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");892 let count = 0;893 const seen = new Set<string>();894 for (const line of lines) {895 const match = /^([A-Fa-f0-9]{35}):([0-9]+)$/.exec(line);896 if (!match) return null;897 const suffix = match[1].toUpperCase();898 const value = Number(match[2]);899 if (!Number.isSafeInteger(value) || seen.has(suffix)) return null;900 seen.add(suffix);901 if (suffix === hex.slice(5)) count = value;902 }903 return count;904 };905 return await Promise.race([lookup(), unavailable]);906 } catch {907 return null;908 } finally {909 clearTimeout(timeout);910 if (onAbort) signal?.removeEventListener("abort", onAbort);911 }912}913914type BreachCredential = { id: string; password: string; epoch: number; key: Uint8Array };915const breachChecks = new Map<string, symbol>();916917async function checkEntryBreach(credential: BreachCredential, signal?: AbortSignal): Promise<"unknown" | "unapplied" | number> {918 const { id, password, epoch } = credential;919 const isCurrent = () => {920 const entry = entries.find((entry) => entry.id === id);921 return !signal?.aborted && epoch === vaultEpoch && credential.key === derivedKey && !vaultCreatesInFlight &&922 entry?.type === "login" && !entry.deletedAt && entry.password === password;923 };924 if (!isCurrent()) return "unapplied";925 const token = Symbol();926 breachChecks.set(id, token);927 try {928 const count = await checkBreach(password, signal);929 const idx = entries.findIndex((entry) => entry.id === id);930 const current = entries[idx];931 if (signal?.aborted || epoch !== vaultEpoch || credential.key !== derivedKey || vaultCreatesInFlight ||932 breachChecks.get(id) !== token || !current || current.deletedAt || current.type !== "login" || current.password !== password) return "unapplied";933 if (count === null) return "unknown";934 if ((current.breach ?? 0) === count) return count;935 const owner = entries;936 const next = { ...current, breach: count, modifiedAt: monotonicEntryTimestamp(current.modifiedAt) };937 entries[idx] = next;938 try {939 await persistEntries();940 } catch (error) {941 if (epoch === vaultEpoch && entries === owner && entries[idx] === next && !next.deletedAt) entries[idx] = current;942 throw error;943 }944 if (!isCurrent() || breachChecks.get(id) !== token) return "unapplied";945 fireSyncTrigger("vault_change");946 return count;947 } finally {948 if (breachChecks.get(id) === token) breachChecks.delete(id);949 }950}951952function checkEntryBreachDetached(credential: BreachCredential): void {953 void checkEntryBreach(credential).catch(() => {954 console.warn("[Peach] Could not save a breach check result");955 });956}957958function emptyBreachScan(state: BreachScanStatus["state"] = "idle"): BreachScanStatus {959 return { id: null, state, total: 0, scanned: 0, unknown: 0, unapplied: 0, breached: 0, cancelled: 0 };960}961962type BreachScan = {963 epoch: number;964 key: Uint8Array | null;965 status: BreachScanStatus;966 credentials: BreachCredential[];967 controller: AbortController;968};969let breachScan: BreachScan | null = null;970971function cancelBreachScan(): void {972 breachChecks.clear();973 const scan = breachScan;974 if (!scan) return;975 scan.controller.abort();976 scan.credentials.length = 0;977 scan.key = null;978 if (scan.status.state === "running") {979 scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;980 scan.status.state = "cancelled";981 }982}983984985export function getBreachScanStatus(): BreachScanStatus {986 if (!derivedKey) return emptyBreachScan(breachScan ? "cancelled" : "idle");987 if (!breachScan || breachScan.epoch !== vaultEpoch || breachScan.key !== derivedKey) return emptyBreachScan();988 return { ...breachScan.status };989}990991992export function startBreachScan(): BreachScanStatus {993 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");994 if (breachScan?.status.state === "running" && breachScan.epoch === vaultEpoch && breachScan.key === derivedKey) return getBreachScanStatus();995 cancelBreachScan();996 const key = derivedKey;997 const credentials = entries.filter((entry) => !entry.deletedAt && entry.type === "login" && entry.password)998 .map((entry) => ({ id: entry.id, password: entry.password!, epoch: vaultEpoch, key }));999 const scan: BreachScan = {1000 epoch: vaultEpoch, key, credentials, controller: new AbortController(),1001 status: { ...emptyBreachScan(credentials.length ? "running" : "complete"), id: crypto.randomUUID(), total: credentials.length },1002 };1003 breachScan = scan;1004 void runBreachScan(scan);1005 return { ...scan.status };1006}10071008async function runBreachScan(scan: BreachScan): Promise<void> {1009 try {1010 while (scan.credentials.length) {1011 if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;1012 const credential = scan.credentials.shift()!;1013 let result: "unknown" | "unapplied" | number;1014 try { result = await checkEntryBreach(credential, scan.controller.signal); }1015 catch { result = "unknown"; console.warn("[Peach] Could not save a breach scan result"); }1016 if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;1017 if (result === "unknown") scan.status.unknown++;1018 else if (result === "unapplied") scan.status.unapplied++;1019 else { scan.status.scanned++; if (result > 0) scan.status.breached++; }1020 if (scan.credentials.length) {1021 await new Promise<void>((resolve) => {1022 const done = () => { clearTimeout(timer); scan.controller.signal.removeEventListener("abort", done); resolve(); };1023 const timer = setTimeout(done, 200);1024 scan.controller.signal.addEventListener("abort", done, { once: true });1025 if (scan.controller.signal.aborted) done();1026 });1027 }1028 }1029 } finally {1030 scan.credentials.length = 0;1031 if (scan.status.state === "running") {1032 if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) {1033 scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;1034 scan.status.state = "cancelled";1035 } else scan.status.state = "complete";1036 }1037 }1038}10391040export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {1041 1042 const key = await cardDeclineKey();1043 if (!key) return;1044 const fingerprint = await cardFingerprint(last4, expMonth, expYear);1045 await loadSettings();1046 settings = {1047 ...settings,1048 declinedCardFingerprints: [1049 1050 1051 ...(settings.declinedCardFingerprints ?? []).filter(1052 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,1053 ),1054 await metadataDigest(fingerprint, key),1055 ].slice(-CARD_DECLINE_MAX),1056 };1057 await persistSettings();1058}10591060export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {1061 await loadSettings();1062 const key = await cardDeclineKey();1063 if (!key) return false;1064 const fingerprint = await cardFingerprint(last4, expMonth, expYear);1065 const candidate = await metadataDigest(fingerprint, key);1066 return (settings.declinedCardFingerprints ?? []).some(1067 (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,1068 );1069}1070107110721073107410751076107710781079108010811082async function cardDeclineKey(): Promise<string | null> {1083 const root = getRootKeyHex();1084 if (!root) return null;1085 const digest = new Uint8Array(1086 await crypto.subtle.digest(1087 "SHA-256",1088 new TextEncoder().encode(`peach-card-decline-v1:${root}`),1089 ),1090 );1091 return hex(digest);1092}10931094async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {1095 const encoder = new TextEncoder();1096 const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));1097 return Array.from(new Uint8Array(buf).slice(0, 8))1098 .map((b) => b.toString(16).padStart(2, "0"))1099 .join("");1100}11011102function hex(buf: Uint8Array): string {1103 return Array.from(buf)1104 .map((b) => b.toString(16).padStart(2, "0"))1105 .join("");1106}11071108function unhex(s: string): Uint8Array {1109 const out = new Uint8Array(s.length / 2);1110 for (let i = 0; i < s.length; i += 2) {1111 out[i / 2] = parseInt(s.slice(i, i + 2), 16);1112 }1113 return out;1114}111511161117111811191120112111221123112411251126112711281129113011311132113311341135async function generateAndWrapRootKey(): Promise<{1136 rawRootKey: string; 1137 recoverySalt: string;1138 wrappedRootKey: string;1139 wrappedNonce: string;1140 wrappedTag: string;1141}> {1142 const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));1143 try {11441145 1146 const words = await rootKeyToWords(rootKeyBytes);1147 const wordMaterial = await wordsToRootKeyMaterial(words);1148 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));1149 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);11501151 1152 1153 const nonce = crypto.getRandomValues(new Uint8Array(12));1154 const encoded = new TextEncoder().encode(hex(rootKeyBytes));1155 const raw = await crypto.subtle.encrypt(1156 {1157 name: "AES-GCM",1158 iv: nonce,1159 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,1160 tagLength: 128,1161 },1162 recoveryKey,1163 encoded1164 );1165 1166 const rawU8 = new Uint8Array(raw);1167 const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));1168 const tag = hex(rawU8.slice(rawU8.length - 16));11691170 return {1171 rawRootKey: hex(rootKeyBytes),1172 recoverySalt: hex(recoverySalt),1173 wrappedRootKey: ciphertext,1174 wrappedNonce: hex(nonce),1175 wrappedTag: tag,1176 };1177 } finally { zeroKey(rootKeyBytes); }1178}11791180async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{1181 recoverySalt: string;1182 wrappedRootKey: string;1183 wrappedNonce: string;1184 wrappedTag: string;1185}> {1186 if (rootKeyBytes.length !== 32) {1187 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1188 }11891190 const words = await rootKeyToWords(rootKeyBytes);1191 const wordMaterial = await wordsToRootKeyMaterial(words);1192 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));1193 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);1194 const nonce = crypto.getRandomValues(new Uint8Array(12));1195 const encoded = new TextEncoder().encode(hex(rootKeyBytes));1196 const raw = await crypto.subtle.encrypt(1197 {1198 name: "AES-GCM",1199 iv: nonce,1200 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,1201 tagLength: 128,1202 },1203 recoveryKey,1204 encoded,1205 );1206 const rawU8 = new Uint8Array(raw);1207 return {1208 recoverySalt: hex(recoverySalt),1209 wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),1210 wrappedNonce: hex(nonce),1211 wrappedTag: hex(rawU8.slice(rawU8.length - 16)),1212 };1213}121412151216121712181219async function unwrapRootKeyForRecovery(1220 wrappedRootKey: string,1221 wrappedNonce: string,1222 wrappedTag: string,1223 recoverySaltHex: string,1224 words: string[]1225): Promise<Uint8Array> {1226 const wordMaterial = await wordsToRootKeyMaterial(words);1227 const recoverySalt = unhex(recoverySaltHex);1228 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);12291230 1231 1232 1233 1234 1235 const nonceRaw = unhex(wrappedNonce);1236 const ciphertextRaw = unhex(wrappedRootKey);1237 const tagRaw = unhex(wrappedTag);1238 1239 1240 const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;1241 const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);1242 combined.set(ciphertextRaw, 0);1243 combined.set(tagRaw, ciphertextRaw.length);1244 const raw = await crypto.subtle.decrypt(1245 { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },1246 recoveryKey,1247 combined1248 );1249 const decryptedHex = new TextDecoder().decode(raw);1250 const recovered = unhex(decryptedHex);1251 if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }1252 return recovered;1253}125412551256export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {1257 if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");1258 if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");1259 recoveryInFlight = true;1260 let settle!: () => void;1261 recoverySettled = new Promise<void>((resolve) => { settle = resolve; });1262 cancelBreachScan();1263 const epoch = ++vaultEpoch;1264 const check = () => {1265 if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");1266 };1267 let recoveredRoot: Uint8Array | null = null;1268 let oldKey: Uint8Array | null = null;1269 let newKey: Uint8Array | null = null;1270 let committed = false;1271 try {1272 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1273 check();1274 const slot = raw[SLOT_A] as StoredVault | undefined;1275 if (!slot) throw new Error("no_vault");1276 if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");1277 try {1278 recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,1279 slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);1280 } catch {1281 throw new Error("invalid_recovery_words");1282 }1283 check();1284 if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");1285 oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");1286 check();1287 if (!oldKey) throw new Error("recovery_data_unavailable");1288 const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");1289 check();1290 if (result.status !== "ok") throw new Error("recovery_data_unavailable");1291 const payload = result.payload;1292 await loadSettings();1293 check();1294 const salt = generateSalt();1295 newKey = await deriveKey(newPassword, salt);1296 check();1297 1298 const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");1299 const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");1300 const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);1301 const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");1302 check();1303 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1304 check();1305 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1306 const history = raw[HISTORY_KEY] as VaultHistory | undefined;1307 const snapshot: VaultSnapshot = {1308 id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",1309 vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,1310 };1311 const previousStamp = Number(raw.peach_last_modified_at);1312 const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,1313 salt: hex(salt), recovery_vault_key: recoveryVaultKey };1314 1315 await chrome.storage.local.set({1316 [SLOT_A]: nextSlot,1317 [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },1318 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),1319 });1320 committed = true;1321 check();1322 cancelBreachScan();1323 derivedKey = newKey;1324 rootKey = recoveredRoot;1325 newKey = null;1326 recoveredRoot = null;1327 entries = payload.entries;1328 tombstones = payload.tombstones;1329 duressConfigured = payload.duressConfigured;1330 vaultMode = "real";1331 manualSummonRecall = new Map();1332 buildDomainIndexSync(entries);1333 await saveSessionKey(derivedKey, "real", epoch);1334 if (epoch !== vaultEpoch) throw new Error("vault_locked");1335 await identityHooks?.onKeysRotated();1336 if (epoch !== vaultEpoch) throw new Error("vault_locked");1337 await reconcilePairSecrets(rootKey);1338 if (epoch !== vaultEpoch) throw new Error("vault_locked");1339 await clearPinUnlockStorage();1340 if (epoch !== vaultEpoch) throw new Error("vault_locked");1341 await restoreManualSummonRecall();1342 if (epoch !== vaultEpoch) throw new Error("vault_locked");1343 touchAutoLock();1344 return { committed: true, unlocked: true };1345 } catch (error) {1346 if (committed) {1347 console.warn("[Peach] recovery password saved; unlock required:", error);1348 if (derivedKey && epoch === vaultEpoch) {1349 try { await lock(); }1350 catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }1351 }1352 return { committed: true, unlocked: false };1353 }1354 if (derivedKey && epoch === vaultEpoch) await lock();1355 throw error;1356 } finally {1357 if (oldKey) zeroKey(oldKey);1358 if (newKey) zeroKey(newKey);1359 if (recoveredRoot) zeroKey(recoveredRoot);1360 recoveryInFlight = false;1361 settle();1362 }1363}136413651366export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {1367 vaultRemovalEpoch++;1368 vaultRemovalsInFlight++;1369 try {1370 await lock();1371 await recoverySettled;1372 await creationSettled;1373 return await remove();1374 } finally {1375 vaultRemovalsInFlight--;1376 }1377}13781379138013811382138313841385138613871388async function deriveRootKeyFromDerivedKey(1389 derivedKeyBytes: Uint8Array,1390 slotA: StoredVault,1391): Promise<Uint8Array | null> {1392 if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {1393 return null;1394 }1395 try {1396 const rootHex = await decrypt(1397 derivedKeyBytes,1398 slotA.pw_root_nonce,1399 slotA.pw_root_ciphertext,1400 slotA.pw_root_tag,1401 "pw_root_v1",1402 );1403 return unhex(rootHex);1404 } catch {1405 return null;1406 }1407}14081409export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {1410 if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");1411 1412 1413 const [root, local] = await Promise.all([1414 encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),1415 encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),1416 ]);1417 return { root, local };1418}14191420export async function sealIdentityKeyPreVault(1421 password: string,1422 ik: Uint8Array,1423): Promise<IdentityKeyEnvelope> {1424 const salt = generateSalt();1425 const key = await deriveKey(password, salt);1426 try {1427 const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");1428 return { pending, pendingSalt: hex(salt) };1429 } finally {1430 zeroKey(key);1431 }1432}1433143414351436143714381439144014411442export async function openIdentityKey(1443 env: IdentityKeyEnvelope,1444 password?: string,1445): Promise<Uint8Array | null> {1446 if (env.local && derivedKey) {1447 const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");1448 if (ik) return ik;1449 }1450 if (env.root && rootKey) {1451 const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");1452 if (ik) return ik;1453 }1454 if (!env.pending || !env.pendingSalt || password === undefined) return null;1455 let key: Uint8Array;1456 try {1457 const salt = unhex(env.pendingSalt);1458 key = await deriveKey(password, salt);1459 salt.fill(0);1460 } catch {1461 return null;1462 }1463 try {1464 return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");1465 } finally {1466 zeroKey(key);1467 }1468}146914701471async function openSealedKey(1472 key: Uint8Array,1473 box: SealedBox,1474 info: string,1475): Promise<Uint8Array | null> {1476 try {1477 const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));1478 if (value.length === 32) return value;1479 value.fill(0);1480 return null;1481 } catch {1482 return null;1483 }1484}1485148614871488async function wrapRootKeyForDerivedKey(1489 derivedKeyBytes: Uint8Array,1490 rootKeyBytes: Uint8Array,1491): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {1492 const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");1493 return {1494 pw_root_ciphertext: ciphertext,1495 pw_root_nonce: nonce,1496 pw_root_tag: tag,1497 };1498}149915001501export async function getRecoveryWords(): Promise<string[]> {1502 if (!rootKey) {1503 throw new Error("recovery not set up");1504 }1505 return rootKeyToWords(rootKey);1506}15071508async function loadSlot(key: string): Promise<StoredVault | null> {1509 const result = await chrome.storage.local.get(key);1510 return (result as Record<string, StoredVault | undefined>)[key] ?? null;1511}15121513async function writeSlot(key: string, vault: StoredVault): Promise<void> {1514 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1515 vaultWritesInFlight++;1516 try {1517 await chrome.storage.local.set({ [key]: vault });1518 } catch (err) {1519 throw mapStorageError(err);1520 } finally {1521 vaultWritesInFlight--;1522 }1523}15241525152615271528152915301531153215331534export async function rollbackAdoptedVault(): Promise<void> {1535 await withVaultRemoval(async () => {1536 try {1537 await chrome.storage.local.remove([1538 SLOT_A,1539 SLOT_B,1540 "peach_last_modified_at",1541 RECALL_STORAGE,1542 ]);1543 } catch (err) {1544 throw mapStorageError(err);1545 }1546 });1547}15481549async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1550 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1551 vaultWritesInFlight++;1552 try {1553 const raw = await chrome.storage.local.get("peach_last_modified_at");1554 const previous = Number(1555 (raw as Record<string, unknown>).peach_last_modified_at,1556 );1557 const next = Math.max(1558 Date.now(),1559 Number.isFinite(previous) ? previous + 1 : 0,1560 );1561 try {1562 if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1563 await chrome.storage.local.set({1564 [SLOT_A]: slotA,1565 [SLOT_B]: slotB,1566 peach_last_modified_at: String(next),1567 });1568 } catch (err) {1569 throw mapStorageError(err);1570 }1571 } finally {1572 vaultWritesInFlight--;1573 }1574}157515761577157815791580158115821583let lastEntryTimestamp = 0;1584function monotonicEntryTimestamp(currentModifiedAt?: number): number {1585 const base = Math.max(1586 Date.now(),1587 (currentModifiedAt ?? 0) + 1,1588 lastEntryTimestamp + 1,1589 );1590 lastEntryTimestamp = base;1591 return base;1592}15931594async function stampLocalVaultMutation(): Promise<void> {1595 if (vaultCreatesInFlight) throw new Error("vault_changed");1596 const raw = await chrome.storage.local.get("peach_last_modified_at");1597 const previous = Number(1598 (raw as Record<string, unknown>).peach_last_modified_at,1599 );1600 const next = Math.max(1601 Date.now(),1602 Number.isFinite(previous) ? previous + 1 : 0,1603 );1604 if (vaultCreatesInFlight) throw new Error("vault_changed");1605 await chrome.storage.local.set({1606 peach_last_modified_at: String(next),1607 });1608}160916101611161216131614161516161617161816191620function padPlaintext(json: string, minBytes = 0): string {1621 const encoded = new TextEncoder().encode(json);1622 const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1623 1624 const target = Math.max(bucket, minBytes);1625 const padLen = target - encoded.length;1626 return json + " ".repeat(padLen);1627}162816291630163116321633163416351636163716381639const CSPRNG_CHUNK = 65_536;16401641function fillRandom(buf: Uint8Array): Uint8Array {1642 for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1643 const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1644 const chunk = new Uint8Array(end - offset);1645 crypto.getRandomValues(chunk);1646 buf.set(chunk, offset);1647 }1648 return buf;1649}16501651function generateNoiseBlob(ciphertextBytes: number): StoredVault {1652 const salt = crypto.getRandomValues(new Uint8Array(16));1653 const nonce = crypto.getRandomValues(new Uint8Array(12));1654 const cipher = fillRandom(new Uint8Array(ciphertextBytes));1655 const tag = crypto.getRandomValues(new Uint8Array(16));1656 return {1657 version: 1,1658 salt: hex(salt),1659 nonce: hex(nonce),1660 ciphertext: hex(cipher),1661 tag: hex(tag),1662 };1663}166416651666166716681669type VaultPayload = {1670 entries: VaultEntry[];1671 tombstones?: Record<string, number>;1672 duressConfigured?: boolean;1673};16741675type DecryptedPayload = {1676 entries: VaultEntry[];1677 tombstones: Map<string, number>;1678 duressConfigured: boolean;1679};16801681function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1682 const envelope: VaultPayload = {1683 entries,1684 tombstones: Object.fromEntries(tombstones),1685 duressConfigured: duress,1686 };1687 return padPlaintext(JSON.stringify(envelope), minBytes);1688}16891690function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1691 const result = new Map<string, number>();1692 if (raw && typeof raw === "object" && !Array.isArray(raw)) {1693 for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1694 if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1695 result.set(id, timestamp);1696 }1697 }1698 }1699 1700 1701 for (const entry of allEntries) {1702 if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1703 continue;1704 }1705 if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1706 result.set(entry.id, entry.deletedAt);1707 }1708 }1709 return result;1710}17111712function reconcileTombstones(): void {1713 const byId = new Map(entries.map((entry) => [entry.id, entry]));1714 for (const [id] of tombstones) {1715 if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1716 }1717 for (const entry of entries) {1718 if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1719 if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1720 tombstones.set(entry.id, entry.deletedAt);1721 }1722 }1723 }1724}17251726function decodePayload(plain: string): DecryptedPayload {1727 const parsed = JSON.parse(plain) as VaultPayload;1728 if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1729 throw new Error("invalid vault payload");1730 }1731 const normalized = parsed.entries.map(normalizeEntry);1732 return {1733 entries: normalized,1734 tombstones: decodeTombstones(parsed.tombstones, normalized),1735 duressConfigured: parsed.duressConfigured === true,1736 };1737}173817391740function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1741 let merged = false;1742 const transferable = new Set(["id", "type", "title", "username", "url", "passkey", "createdAt", "modifiedAt", "totp", "totpAlgorithm", "totpDigits", "totpPeriod"]);1743 for (const source of entries.filter((entry) => !entry.deletedAt && entry.passkey)) {1744 const passkey = source.passkey!;1745 if (source.type !== "login" && source.type !== "passkey") continue;1746 if (!passkey.userName || (source.username && source.username !== passkey.userName)) continue;1747 if (Object.entries(source).some(([key, value]) => !transferable.has(key) && value !== undefined && value !== "")) continue;1748 const targets = entries.filter((entry) => {1749 if (entry.deletedAt || entry.passkey || entry.type !== "login" || entry.username !== passkey.userName) return false;1750 return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {1751 if (!url) return false;1752 try {1753 return new URL(url.includes("://") ? url : `https://${url}`).hostname === passkey.rpId;1754 } catch {1755 return false;1756 }1757 });1758 });1759 if (targets.length !== 1) continue;1760 const target = targets[0]!;1761 if (source.totp && target.totp && (source.totp !== target.totp || source.totpAlgorithm !== target.totpAlgorithm || source.totpDigits !== target.totpDigits || source.totpPeriod !== target.totpPeriod)) continue;1762 target.passkey = passkey;1763 if (source.totp && !target.totp) {1764 target.totp = source.totp;1765 target.totpAlgorithm = source.totpAlgorithm;1766 target.totpDigits = source.totpDigits;1767 target.totpPeriod = source.totpPeriod;1768 }1769 const stamp = monotonicEntryTimestamp(Math.max(source.modifiedAt, target.modifiedAt));1770 target.modifiedAt = stamp;1771 source.modifiedAt = stamp;1772 source.deletedAt = stamp;1773 merged = true;1774 }1775 return { merged };1776}17771778177917801781178217831784function hasValidVaultSchema(v: unknown): v is StoredVault {1785 if (typeof v !== "object" || v === null) return false;1786 const r = v as Record<string, unknown>;1787 return (1788 r.version === 1 &&1789 typeof r.salt === "string" &&1790 typeof r.nonce === "string" &&1791 typeof r.ciphertext === "string" &&1792 typeof r.tag === "string"1793 );1794}1795const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;17961797function hasValidHistorySlot(value: unknown): value is StoredVault {1798 if (!hasValidVaultSchema(value)) return false;1799 return /^[0-9a-f]{32}$/i.test(value.salt) &&1800 /^[0-9a-f]{24}$/i.test(value.nonce) &&1801 /^[0-9a-f]+$/i.test(value.ciphertext) &&1802 value.ciphertext.length % 2 === 0 &&1803 value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1804 /^[0-9a-f]{32}$/i.test(value.tag);1805}18061807function parseHistorySlot(value: string): StoredVault | null {1808 try {1809 const parsed: unknown = JSON.parse(value);1810 return hasValidHistorySlot(parsed) ? parsed : null;1811 } catch {1812 return null;1813 }1814}18151816function isHistoryRecord(value: unknown): value is VaultSnapshot {1817 if (typeof value !== "object" || value === null) return false;1818 const record = value as Record<string, unknown>;1819 return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1820 typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1821 typeof record.reason === "string" &&1822 typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1823 typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1824 (record.entryCount === null || typeof record.entryCount === "number");1825}18261827function sanitizeHistory(value: unknown): VaultSnapshot[] {1828 if (typeof value !== "object" || value === null) return [];1829 if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1830 return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1831}18321833export type TryDecryptResult =1834 | { status: "ok"; payload: DecryptedPayload }1835 | { status: "wrong_key" }1836 | { status: "corrupted"; reason: string };1837183818391840184118421843export async function tryDecryptSlot(1844 vault: StoredVault,1845 key: Uint8Array,1846 aadTag?: string,1847): Promise<DecryptedPayload | null> {1848 const res = await tryDecryptSlotResult(vault, key, aadTag);1849 return res.status === "ok" ? res.payload : null;1850}18511852export async function tryDecryptSlotResult(1853 vault: StoredVault,1854 key: Uint8Array,1855 aadTag?: string,1856): Promise<TryDecryptResult> {1857 if (!hasValidVaultSchema(vault)) {1858 return { status: "corrupted", reason: "invalid_slot_schema" };1859 }1860 let plain: string;1861 try {1862 plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1863 } catch {1864 return { status: "wrong_key" };1865 }1866 try {1867 const parsed = JSON.parse(plain) as unknown;1868 if (typeof parsed !== "object" || parsed === null) {1869 return { status: "corrupted", reason: "invalid_payload_shape" };1870 }1871 if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1872 return { status: "corrupted", reason: "invalid_payload_shape" };1873 }1874 return { status: "ok", payload: decodePayload(plain) };1875 } catch {1876 return { status: "corrupted", reason: "invalid_payload_json" };1877 }1878}187918801881188218831884function buildDomainIndexSync(all: VaultEntry[]): void {1885 domainIndex = new Map();18861887 for (const entry of all) {1888 if (entry.deletedAt) continue;1889 if (entry.type === "note" || entry.type === "card") continue;18901891 1892 1893 1894 1895 const domains = new Set<string>();1896 const primary = extractDomain(entry.url ?? "");1897 if (primary) domains.add(primary);1898 for (const extra of entry.additionalUrls ?? []) {1899 const d = extractDomain(extra);1900 if (d) domains.add(d);1901 }1902 if (domains.size === 0) continue;19031904 for (const domain of domains) {1905 const bucket = domainIndex.get(domain) ?? [];1906 bucket.push(entry);1907 domainIndex.set(domain, bucket);1908 }1909 }1910}19111912export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1913 if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1914 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1915 vaultCreatesInFlight++;1916 let settle!: () => void;1917 creationSettled = new Promise<void>((resolve) => { settle = resolve; });1918 let nextKey: Uint8Array | null = null;1919 let nextRoot: Uint8Array | null = null;1920 let committed = false;1921 let publishedEpoch: number | null = null;1922 const epoch = vaultEpoch;1923 const check = () => {1924 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1925 };1926 try {1927 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1928 check();1929 const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1930 if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1931 const salt = generateSalt();1932 nextKey = await deriveKey(password, salt);1933 check();1934 const recovery = await generateAndWrapRootKey();1935 nextRoot = unhex(recovery.rawRootKey);1936 check();1937 const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1938 const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1939 const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1940 check();1941 const slotA: StoredVault = {1942 ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1943 recovery_vault_key: recoveryVaultKey,1944 recovery_salt: recovery.recoverySalt,1945 recovery_wrapped_root_key: recovery.wrappedRootKey,1946 recovery_nonce: recovery.wrappedNonce,1947 recovery_tag: recovery.wrappedTag,1948 };1949 const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1950 check();1951 if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1952 const previous = Number(raw.peach_last_modified_at);1953 const update: Record<string, unknown> = {1954 [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1955 peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1956 };1957 if (occupied) {1958 const history = raw[HISTORY_KEY] as VaultHistory | undefined;1959 const snapshot: VaultSnapshot = {1960 id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1961 vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1962 };1963 update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1964 }1965 try { await chrome.storage.local.set(update); }1966 catch (error) { throw mapStorageError(error); }1967 committed = true;1968 if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1969 const previousKey = derivedKey;1970 const previousRoot = rootKey;1971 cancelBreachScan();1972 publishedEpoch = ++vaultEpoch;1973 derivedKey = nextKey;1974 rootKey = nextRoot;1975 nextKey = null;1976 nextRoot = null;1977 entries = [];1978 tombstones = new Map();1979 vaultMode = "real";1980 manualSummonRecall = new Map();1981 duressConfigured = false;1982 buildDomainIndexSync(entries);1983 if (previousKey) zeroKey(previousKey);1984 if (previousRoot) zeroKey(previousRoot);1985 await clearSessionKey();1986 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1987 await identityHooks?.onVaultCreated(password).catch((error) => {1988 console.warn("[Peach] local identity promotion failed:", error);1989 });1990 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1991 1992 1993 await clearStoredManualSummonRecall();1994 await restoreManualSummonRecall();1995 if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1996 touchAutoLock();1997 return { committed: true, unlocked: true };1998 } catch (error) {1999 if (!committed) throw error;2000 console.warn("[Peach] vault saved; unlock required:", error);2001 if (publishedEpoch === vaultEpoch) {2002 await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));2003 }2004 return { committed: true, unlocked: false };2005 } finally {2006 if (nextKey) zeroKey(nextKey);2007 if (nextRoot) zeroKey(nextRoot);2008 vaultCreatesInFlight--;2009 settle();2010 }2011}2012201320142015201620172018export async function createVaultFromRootKey(2019 password: string,2020 rootKeyHex: string,2021): Promise<{ vaultId: string }> {2022 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");2023 if (typeof password !== "string" || password.length === 0) {2024 throw new Error("ADOPT_INVALID_PASSWORD");2025 }2026 if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {2027 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");2028 }20292030 if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");2031 const rootKeyBytes = unhex(rootKeyHex);2032 if (rootKeyBytes.length !== 32) {2033 rootKeyBytes.fill(0);2034 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");2035 }20362037 vaultCreatesInFlight++;2038 let settle!: () => void;2039 creationSettled = new Promise<void>((resolve) => { settle = resolve; });2040 const epoch = vaultEpoch;2041 let nextDerivedKey: Uint8Array | null = null;2042 let sessionRootKey: Uint8Array | null = null;2043 let committed = false;2044 try {2045 if (await hasVault()) {2046 throw new Error("ADOPT_VAULT_ALREADY_EXISTS");2047 }20482049 const nextEntries: VaultEntry[] = [];2050 const nextDuressConfigured = false;2051 const vaultId = await computeVaultId(rootKeyBytes);2052 const salt = generateSalt();2053 nextDerivedKey = await deriveKey(password, salt);2054 const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);20552056 sessionRootKey = new Uint8Array(rootKeyBytes);2057 const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);2058 const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");2059 const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);2060 const slotA: StoredVault = {2061 recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),2062 version: 1,2063 salt: hex(salt),2064 nonce,2065 ciphertext,2066 tag,2067 recovery_salt: recovery.recoverySalt,2068 recovery_wrapped_root_key: recovery.wrappedRootKey,2069 recovery_nonce: recovery.wrappedNonce,2070 recovery_tag: recovery.wrappedTag,2071 ...pwRoot,2072 };2073 const slotB = generateNoiseBlob(ciphertext.length / 2);2074 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");2075 await commitCreatedVaultSlots(slotA, slotB);2076 committed = true;2077 if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");2078 cancelBreachScan();2079 vaultEpoch++;20802081 const previousDerivedKey = derivedKey;2082 const previousRootKey = rootKey;2083 derivedKey = nextDerivedKey;2084 rootKey = sessionRootKey;2085 nextDerivedKey = null;2086 sessionRootKey = null;2087 entries = nextEntries;2088 tombstones = new Map();2089 vaultMode = "real";2090 manualSummonRecall = new Map();2091 duressConfigured = nextDuressConfigured;2092 buildDomainIndexSync(entries);2093 if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);2094 if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);2095 touchAutoLock();20962097 2098 2099 await identityHooks?.onVaultCreated(password).catch((error) => {2100 console.warn("[Peach] local identity promotion failed:", error);2101 });2102 await clearStoredManualSummonRecall();2103 await restoreManualSummonRecall();21042105 return { vaultId };2106 } catch (error) {2107 if (committed) {2108 2109 try { await lock(); }2110 finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, RECALL_STORAGE, "peach_last_modified_at"]); }2111 }2112 throw error;2113 } finally {2114 vaultCreatesInFlight--;2115 settle();2116 rootKeyBytes.fill(0);2117 if (nextDerivedKey) zeroKey(nextDerivedKey);2118 if (sessionRootKey) sessionRootKey.fill(0);2119 }2120}21212122export async function hasVault(): Promise<boolean> {2123 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);2124 return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;2125}2126212721282129213021312132export async function isDuressEnabled(): Promise<boolean> {2133 return vaultMode === "real" && duressConfigured;2134}21352136export async function setupDuress(duressPassword: string): Promise<void> {2137 if (vaultCreatesInFlight) throw new Error("vault_changed");2138 vaultWritesInFlight++;2139 try {2140 if (!derivedKey || vaultMode !== "real") {2141 throw new Error("vault must be unlocked in real mode");2142 }2143 2144 2145 2146 const slotA = await loadSlot(SLOT_A);2147 if (!slotA) throw new Error("missing slot A");21482149 const decoySalt = generateSalt();2150 const decoyKey = await deriveKey(duressPassword, decoySalt);2151 try {2152 2153 2154 2155 2156 const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);2157 const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");2158 await writeSlot(SLOT_B, {2159 version: 1,2160 salt: hex(decoySalt),2161 nonce,2162 ciphertext,2163 tag,2164 });2165 2166 await clearStoredManualSummonRecall("decoy");2167 } finally {2168 zeroKey(decoyKey);2169 }21702171 2172 2173 duressConfigured = true;2174 await persistSlotA();2175 } finally { vaultWritesInFlight--; }2176}21772178export async function disableDuress(): Promise<void> {2179 if (vaultCreatesInFlight) throw new Error("vault_changed");2180 vaultWritesInFlight++;2181 try {2182 if (!derivedKey || vaultMode !== "real") {2183 throw new Error("vault must be unlocked in real mode");2184 }2185 2186 2187 2188 const slotA = await loadSlot(SLOT_A);2189 if (slotA) {2190 await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));2191 await clearStoredManualSummonRecall("decoy");2192 }21932194 duressConfigured = false;2195 await persistSlotA();2196 } finally { vaultWritesInFlight--; }2197}21982199220022012202220322042205export async function verifyMainPassword(password: string): Promise<boolean> {2206 const slotA = await loadSlot(SLOT_A);2207 if (!slotA) return false;2208 const key = await deriveKey(password, unhex(slotA.salt));2209 try {2210 return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;2211 } finally {2212 zeroKey(key);2213 }2214}22152216export async function unlock(password: string): Promise<boolean> {2217 return attemptUnlockWithDerive(password, deriveKey);2218}22192220async function attemptUnlockWithDerive(2221 password: string,2222 derive: typeof deriveKey,2223): Promise<boolean> {2224 vaultUnlocksInFlight++;2225 try {2226 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;2227 const epoch = vaultEpoch;2228 const stale = () => epoch !== vaultEpoch;2229 await revokeRecoveryReveal();2230 if (stale()) return false;2231 2232 2233 2234 2235 2236 2237 const [slotA, slotB] = await Promise.all([2238 loadSlot(SLOT_A),2239 loadSlot(SLOT_B),2240 ]);22412242 2243 const [keyA, keyB] = await Promise.all([2244 slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),2245 slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),2246 ]);22472248 2249 2250 2251 const [resultA, resultB] = await Promise.all([2252 keyA && slotA2253 ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")2254 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),2255 keyB && slotB2256 ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")2257 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),2258 ]);2259 const payloadA = resultA.status === "ok" ? resultA.payload : null;2260 const payloadB = resultB.status === "ok" ? resultB.payload : null;22612262 if (stale()) {2263 if (keyA) zeroKey(keyA);2264 if (keyB) zeroKey(keyB);2265 return false;2266 }22672268 if (payloadA && keyA) {2269 if (stale()) {2270 zeroKey(keyA);2271 if (keyB) zeroKey(keyB);2272 return false;2273 }2274 cancelBreachScan();2275 derivedKey = keyA;2276 vaultMode = "real";2277 manualSummonRecall = new Map();2278 entries = payloadA.entries;2279 tombstones = payloadA.tombstones;2280 duressConfigured = payloadA.duressConfigured;2281 buildDomainIndexSync(entries);2282 await loadSettings();2283 if (stale()) {2284 await lock();2285 return false;2286 }2287 touchAutoLock();2288 if (keyB) zeroKey(keyB);22892290 2291 2292 rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;2293 if (!rootKey) {2294 await lock();2295 return false;2296 }22972298 2299 if (slotA) {2300 const escrowed = slotA.recovery_vault_key2301 ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;2302 const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);2303 if (escrowed) zeroKey(escrowed);2304 if (stale()) { await lock(); return false; }2305 if (!matches) {2306 try {2307 const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");2308 if (stale()) { await lock(); return false; }2309 await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });2310 if (stale()) { await lock(); return false; }2311 } catch (error) {2312 await lock();2313 throw error;2314 }2315 }2316 }23172318 2319 2320 await reconcilePairSecrets(rootKey);2321 if (stale()) {2322 await lock();2323 return false;2324 }2325 await lockedSyncUnlockHook?.().catch((error) => {2326 console.warn("[Peach sync] locked inbox drain failed:", error);2327 });2328 if (stale()) {2329 await lock();2330 return false;2331 }2332 await resetPinFailedAttempts();2333 if (stale()) {2334 await lock();2335 return false;2336 }2337 await saveSessionKey(keyA, "real", epoch);2338 if (stale()) return false;2339 await restoreManualSummonRecall();2340 if (stale()) return false;2341 return true;2342 }23432344 if (payloadB && keyB) {2345 if (stale()) {2346 zeroKey(keyB);2347 if (keyA) zeroKey(keyA);2348 return false;2349 }2350 cancelBreachScan();2351 derivedKey = keyB;2352 vaultMode = "decoy";2353 manualSummonRecall = new Map();2354 decoySyncTeardownHook?.();2355 2356 2357 2358 if (rootKey) {2359 rootKey.fill(0);2360 rootKey = null;2361 }2362 entries = payloadB.entries;2363 tombstones = payloadB.tombstones;2364 duressConfigured = false;2365 buildDomainIndexSync(entries);2366 await loadSettings();2367 touchAutoLock();2368 if (keyA) zeroKey(keyA);2369 2370 await dropSessionCache();2371 2372 await notifyIdentitySessionEnded();2373 if (stale()) {2374 await lock();2375 return false;2376 }2377 await saveSessionKey(keyB, "decoy", epoch);2378 if (stale()) return false;2379 await restoreManualSummonRecall();2380 if (stale()) return false;2381 return true;2382 }23832384 if (keyA) zeroKey(keyA);2385 if (keyB) zeroKey(keyB);2386 2387 2388 if (resultA.status === "corrupted") {2389 lastUnlockFailureReason = resultA.reason;2390 } else if (resultB.status === "corrupted") {2391 lastUnlockFailureReason = resultB.reason;2392 }2393 return false;2394 } finally { vaultUnlocksInFlight--; }2395}23962397239823992400240124022403const SESSION_KEY_STORAGE = "peach_session_dk";2404240524062407let sessionKeyMutation = Promise.resolve();24082409function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {2410 const task = sessionKeyMutation.then(mutation, mutation);2411 sessionKeyMutation = task.catch(() => undefined);2412 return task;2413}241424152416241724182419let sessionEscrowAvailable = true;24202421242224232424242524262427export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {2428 setSessionAllowed(sessionEscrow);2429 if (sessionEscrow) return;2430 sessionEscrowAvailable = false;2431 await clearSessionKey();2432}24332434async function saveSessionKey(2435 key: Uint8Array,2436 mode: "real" | "decoy",2437 expectedEpoch = vaultEpoch,2438): Promise<void> {2439 const session = chrome.storage.session;2440 if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2441 const stored = { keyHex: hex(key), mode };2442 await mutateSessionKey(async () => {2443 if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2444 await session.set({ [SESSION_KEY_STORAGE]: stored });2445 });2446}24472448async function clearSessionKey(): Promise<void> {2449 const session = chrome.storage.session;2450 if (!session) return;2451 await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));2452}24532454245524562457245824592460let vaultEpoch = 0;2461246224632464let restoreInFlight: Promise<boolean> | null = null;246524662467246824692470247124722473export async function restoreFromSession(): Promise<boolean> {2474 vaultUnlocksInFlight++;2475 try {2476 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;2477 if (derivedKey !== null) return true;2478 if (restoreInFlight) return restoreInFlight;2479 const task = restoreFromSessionInner();2480 restoreInFlight = task;2481 try {2482 return await task;2483 } finally {2484 restoreInFlight = null;2485 }2486 } finally { vaultUnlocksInFlight--; }2487}24882489async function restoreFromSessionInner(): Promise<boolean> {2490 const epoch = vaultEpoch;2491 const stale = () => epoch !== vaultEpoch;2492 if (derivedKey !== null) return true;2493 if (!sessionEscrowAvailable) return false;2494 if (!chrome.storage.session) return false;2495 const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);2496 if (stale()) return false;2497 const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;2498 if (!entry?.keyHex) return false;24992500 const key = unhex(entry.keyHex);2501 const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;2502 const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";2503 const slot = await loadSlot(slotKey);2504 if (stale()) { zeroKey(key); return false; }2505 if (!slot) { await clearSessionKey(); return false; }25062507 const result = await tryDecryptSlotResult(slot, key, aadTag);2508 if (stale()) { zeroKey(key); return false; }2509 if (result.status !== "ok") { await clearSessionKey(); return false; }25102511 2512 2513 const payload = result.payload;2514 await loadSettings();2515 if (stale()) { zeroKey(key); return false; }25162517 2518 2519 let freshRoot: Uint8Array | null = null;2520 if (entry.mode === "real") {2521 freshRoot = await deriveRootKeyFromDerivedKey(key, slot);2522 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2523 if (!freshRoot) {2524 await lock();2525 return false;2526 }2527 }25282529 if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2530 if (freshRoot) {2531 2532 await reconcilePairSecrets(freshRoot);2533 if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }2534 } else {2535 2536 await dropSessionCache();2537 2538 await notifyIdentitySessionEnded();2539 if (stale()) { zeroKey(key); return false; }2540 }2541 cancelBreachScan();2542 derivedKey = key;2543 vaultMode = entry.mode;2544 manualSummonRecall = new Map();2545 if (entry.mode === "decoy") decoySyncTeardownHook?.();2546 entries = payload.entries;2547 tombstones = payload.tombstones;2548 duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;2549 if (freshRoot) rootKey = freshRoot;2550 buildDomainIndexSync(entries);2551 touchAutoLock();25522553 await lockedSyncUnlockHook?.().catch((error) => {2554 console.warn("[Peach sync] locked inbox drain failed:", error);2555 });2556 if (stale()) return false;2557 await restoreManualSummonRecall();2558 if (stale()) return false;25592560 return true;2561}25622563export async function lock(): Promise<void> {2564 const recoveryRevoked = revokeRecoveryReveal();2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 cancelBreachScan();2575 vaultEpoch++;2576 if (derivedKey) {2577 zeroKey(derivedKey);2578 derivedKey = null;2579 }2580 if (rootKey) {2581 rootKey.fill(0);2582 rootKey = null;2583 }25842585 entries = [];2586 manualSummonRecall = new Map();2587 tombstones = new Map();2588 domainIndex = new Map();2589 vaultMode = "real";2590 duressConfigured = false;2591 clearAutoLock();2592 try {2593 chrome.runtime?.sendMessage?.({ type: "VAULT_LOCKED" })?.catch?.(() => undefined);2594 } catch { }2595 await clearSessionKey();2596 await recoveryRevoked;2597 2598 2599 await notifyIdentitySessionEnded();2600 vaultLockHook?.();2601}260226032604export function getVaultEpoch(): number {2605 return vaultEpoch;2606}26072608export function isUnlocked(): boolean {2609 return derivedKey !== null;2610}26112612export function isDecoyMode(): boolean {2613 return derivedKey !== null && vaultMode === "decoy";2614}26152616261726182619export async function unlockWithKey(2620 masterKeyHex: string,2621): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2622 vaultUnlocksInFlight++;2623 try {2624 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2625 const epoch = vaultEpoch;2626 const stale = () => epoch !== vaultEpoch;2627 await revokeRecoveryReveal();2628 if (stale()) return { ok: false, error: "vault_locked" };2629 let masterKeyBytes: Uint8Array | null = null;2630 try {2631 masterKeyBytes = unhex(masterKeyHex);2632 const stored = await loadSlot(SLOT_A);2633 if (!stored) return { ok: false, error: "invalid_key" };2634 const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2635 if (!payload || stale()) {2636 zeroKey(masterKeyBytes);2637 return { ok: false, error: "invalid_key" };2638 }26392640 cancelBreachScan();2641 derivedKey = masterKeyBytes;2642 vaultMode = "real";2643 manualSummonRecall = new Map();2644 entries = payload.entries;2645 tombstones = payload.tombstones;2646 duressConfigured = payload.duressConfigured;2647 buildDomainIndexSync(entries);2648 await loadSettings();2649 touchAutoLock();26502651 rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2652 if (!rootKey) {2653 await lock();2654 return { ok: false, error: "invalid_key" };2655 }2656 await reconcilePairSecrets(rootKey);2657 if (stale()) {2658 await lock();2659 return { ok: false, error: "invalid_key" };2660 }2661 await saveSessionKey(masterKeyBytes, "real", epoch);2662 if (stale()) return { ok: false, error: "invalid_key" };2663 await restoreManualSummonRecall();2664 if (stale()) return { ok: false, error: "invalid_key" };2665 2666 2667 await lockedSyncUnlockHook?.().catch((error) => {2668 console.warn("[Peach sync] locked inbox drain failed:", error);2669 });2670 if (stale()) return { ok: false, error: "invalid_key" };2671 return { ok: true, entries };2672 } catch {2673 if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2674 return { ok: false, error: "invalid_key" };2675 }2676 } finally { vaultUnlocksInFlight--; }2677}267826792680268126822683268426852686export async function exportDuressSlotForAdoption(): Promise<string | null> {2687 if (!(await isDuressEnabled())) return null;2688 const slotB = await loadSlot(SLOT_B);2689 if (!slotB) return null;2690 return JSON.stringify(slotB);2691}26922693269426952696269726982699export async function installAdoptedDuressSlot(json: string): Promise<void> {2700 if (vaultCreatesInFlight) throw new Error("vault_changed");2701 vaultWritesInFlight++;2702 try {2703 let parsed: StoredVault;2704 try {2705 const raw = JSON.parse(json) as unknown;2706 if (!hasValidVaultSchema(raw)) {2707 throw new Error("invalid_duress_slot_shape");2708 }2709 parsed = raw;2710 } catch (err) {2711 if (err instanceof SyntaxError) {2712 throw new Error("invalid_duress_slot_shape");2713 }2714 throw err;2715 }2716 await writeSlot(SLOT_B, parsed);2717 2718 await clearStoredManualSummonRecall("decoy");2719 manualSummonRecall = new Map();2720 await restoreManualSummonRecall();2721 } finally { vaultWritesInFlight--; }2722}27232724272527262727272827292730273127322733273427352736273727382739274027412742export async function unlockFromCodex(params: {2743 slotA: string; 2744 slotB: string | null; 2745 timestamp: number;2746 masterPassphrase: string;2747}): Promise<2748 | { ok: true; entryCount: number }2749 | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2750> {2751 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2752 vaultReplacementInFlight = true;2753 try {2754 let parsedSlotA: StoredVault;2755 let parsedSlotB: StoredVault | null = null;2756 try {2757 const rawA = JSON.parse(params.slotA) as unknown;2758 if (!hasValidVaultSchema(rawA)) {2759 return { ok: false, reason: "invalid_slot_format" };2760 }2761 parsedSlotA = rawA;2762 if (params.slotB !== null) {2763 const rawB = JSON.parse(params.slotB) as unknown;2764 if (!hasValidVaultSchema(rawB)) {2765 return { ok: false, reason: "invalid_slot_format" };2766 }2767 parsedSlotB = rawB;2768 }2769 } catch {2770 return { ok: false, reason: "invalid_slot_format" };2771 }27722773 2774 2775 2776 const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2777 const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2778 if (!trialPayload) {2779 zeroKey(trialKey);2780 return { ok: false, reason: "wrong_passphrase" };2781 }2782 const hasEscrow =2783 !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2784 if (!hasEscrow) {2785 zeroKey(trialKey);2786 return { ok: false, reason: "missing_root_escrow" };2787 }2788 const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2789 if (!stagedRootKey) {2790 zeroKey(trialKey);2791 return { ok: false, reason: "wrong_passphrase" };2792 }2793 zeroKey(stagedRootKey);2794 zeroKey(trialKey);27952796 2797 const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);27982799 2800 28012802 2803 2804 await takeVaultSnapshot("restore");2805 const previousSlotA = await loadSlot(SLOT_A);2806 const previousSlotB = await loadSlot(SLOT_B);2807 let slotACommitted = false;2808 let slotBCommitted = false;2809 try {2810 await writeSlot(SLOT_A, parsedSlotA);2811 slotACommitted = true;2812 await writeSlot(SLOT_B, stagedSlotB);2813 slotBCommitted = true;2814 await chrome.storage.local.set({2815 peach_last_modified_at: String(params.timestamp),2816 });2817 } catch (err) {2818 if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2819 if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2820 throw err;2821 }28222823 2824 2825 const ok = await unlock(params.masterPassphrase);2826 if (!ok) {2827 2828 return { ok: false, reason: "wrong_passphrase" };2829 }2830 return { ok: true, entryCount: getEntries().length };2831 } finally {2832 vaultReplacementInFlight = false;2833 }2834}28352836283728382839export function getDerivedKeyHex(): string {2840 if (!derivedKey) throw new Error("vault_not_unlocked");2841 return hex(derivedKey);2842}28432844284528462847284828492850285128522853285428552856285728582859export function getRootKeyHex(): string | null {2860 return rootKey ? hex(rootKey) : null;2861}28622863export function getEntries(): VaultEntry[] {2864 if (!derivedKey) throw new Error("vault_locked");2865 return entries.filter((entry) => !entry.deletedAt);2866}28672868const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;28692870export function getIdentities(): SavedIdentity[] {2871 if (!derivedKey) throw new Error("vault_locked");2872 const active = entries.filter((e) => !e.deletedAt && e.type === "login");28732874 const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2875 const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();28762877 for (const entry of active) {2878 const domain = extractDomain(entry.url ?? "") ?? "";2879 const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;28802881 function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2882 const existing = map.get(v);2883 if (!existing || modifiedAt > existing.lastUsed) {2884 map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2885 } else {2886 map.set(v, { ...existing, count: existing.count + 1 });2887 }2888 }28892890 const uVal = entry.username?.trim();2891 if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);28922893 2894 2895 const eVal = entry.email?.trim();2896 if (eVal) tally(emailMap, eVal);2897 }28982899 const toIdentity = (type: "email" | "username") =>2900 ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2901 value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2902 });29032904 return [2905 ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2906 ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2907 ];2908}29092910export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2911 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29122913 const now = Date.now();2914 const added: VaultEntry[] = [];2915 for (const draft of drafts) {2916 try {2917 const sanitized = sanitizeEntryDraft(draft);2918 const nextEntry: VaultEntry = {2919 ...sanitized,2920 id: crypto.randomUUID(),2921 createdAt: now,2922 modifiedAt: monotonicEntryTimestamp(),2923 };2924 entries.push(nextEntry);2925 added.push(nextEntry);2926 } catch {2927 2928 }2929 }29302931 if (added.length > 0) {2932 await persistEntries();2933 }29342935 return added;2936}293729382939294029412942294329442945export async function restoreEntries(2946 incoming: VaultEntry[],2947 mode: "replace" | "merge"2948): Promise<{ added: number; updated: number; skipped: number }> {2949 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29502951 2952 2953 2954 if (mode === "replace" && incoming.length === 0) {2955 throw new Error("refuse to replace with empty entry set");2956 }29572958 let added = 0;2959 let updated = 0;2960 let skipped = 0;29612962 if (mode === "replace") {2963 entries = [];2964 for (const entry of incoming) {2965 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2966 if (!normalized) {2967 skipped += 1;2968 continue;2969 }2970 entries.push(normalized);2971 if (normalized.deletedAt) {2972 tombstones.set(2973 normalized.id,2974 Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2975 );2976 } else {2977 tombstones.delete(normalized.id);2978 }2979 added += 1;2980 }2981 } else {2982 const byId = new Map<string, VaultEntry>();2983 for (const e of entries) byId.set(e.id, e);29842985 for (const entry of incoming) {2986 const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2987 if (!normalized) {2988 skipped += 1;2989 continue;2990 }2991 const existing = byId.get(normalized.id);2992 if (!existing) {2993 entries.push(normalized);2994 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2995 else tombstones.delete(normalized.id);2996 added += 1;2997 } else if (normalized.modifiedAt > existing.modifiedAt) {2998 const idx = entries.findIndex((e) => e.id === existing.id);2999 if (idx !== -1) {3000 entries[idx] = normalized;3001 if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);3002 else tombstones.delete(normalized.id);3003 updated += 1;3004 }3005 } else {3006 skipped += 1;3007 }3008 }3009 }30103011 await persistEntries("import");3012 return { added, updated, skipped };3013}301430153016301730183019302030213022302330243025302630273028302930303031const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;30323033function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {3034 if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;3035 return { ...entry, id: crypto.randomUUID() };3036}303730383039304030413042304330443045function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {3046 if (!entry || typeof entry !== "object") return null;3047 const title = typeof entry.title === "string" ? entry.title.trim() : "";3048 if (!title) return null;3049 const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();3050 const now = Date.now();3051 const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;3052 const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;30533054 3055 3056 const normalized = normalizeEntry({3057 ...entry,3058 id,3059 title,3060 type: entry.type ?? "login",3061 createdAt,3062 modifiedAt,3063 });30643065 if (normalized.passkey) {3066 normalized.passkey = sanitizePasskey(normalized.passkey);3067 }3068 if (normalized.canary) {3069 normalized.canary = sanitizeCanary(normalized.canary);3070 }3071 3072 normalized.tags = sanitizeTags(normalized.tags);30733074 3075 3076 if (3077 normalized.type === "login" &&3078 !normalized.passkey &&3079 typeof normalized.password !== "string"3080 ) {3081 return null;3082 }3083 if (entry.passkey && !normalized.passkey) {3084 3085 3086 return null;3087 }30883089 return normalized;3090}3091309230933094309530963097function sanitizePasskey(pk: unknown): PasskeyData | undefined {3098 if (!pk || typeof pk !== "object") return undefined;3099 const r = pk as Record<string, unknown>;3100 if (3101 typeof r.rpId !== "string" || !r.rpId ||3102 typeof r.credentialId !== "string" || !r.credentialId ||3103 typeof r.publicKeyCose !== "string" ||3104 typeof r.userHandle !== "string" ||3105 typeof r.userName !== "string"3106 ) {3107 return undefined;3108 }3109 return {3110 rpId: r.rpId,3111 rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,3112 credentialId: r.credentialId,3113 publicKeyCose: r.publicKeyCose,3114 privateKeyJwk:3115 r.privateKeyJwk && typeof r.privateKeyJwk === "object"3116 ? (r.privateKeyJwk as JsonWebKey)3117 : undefined,3118 userHandle: r.userHandle,3119 userName: r.userName,3120 userDisplayName:3121 typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,3122 algorithm: r.algorithm === -8 ? -8 : -7,3123 signCount: typeof r.signCount === "number" ? r.signCount : 0,3124 aaguid: typeof r.aaguid === "string" ? r.aaguid : "",3125 backupEligible: r.backupEligible === true,3126 backupState: r.backupState === true,3127 lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,3128 browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,3129 transports: Array.isArray(r.transports)3130 ? r.transports.filter((t): t is string => typeof t === "string")3131 : undefined,3132 createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),3133 };3134}31353136313731383139314031413142314331443145function sanitizeCanary(c: unknown): Canary | undefined {3146 if (!c || typeof c !== "object") return undefined;3147 const r = c as Record<string, unknown>;3148 if (typeof r.webhookUrl !== "string") return undefined;3149 let url: URL;3150 try {3151 url = new URL(r.webhookUrl);3152 } catch {3153 return undefined;3154 }3155 if (url.protocol !== "https:") return undefined;3156 return {3157 webhookUrl: url.toString(),3158 label: typeof r.label === "string" ? r.label : undefined,3159 lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,3160 pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,3161 };3162}31633164316531663167316831693170function sanitizeTags(tags: unknown): string[] | undefined {3171 if (!Array.isArray(tags)) return undefined;3172 const out: string[] = [];3173 for (const t of tags) {3174 if (typeof t !== "string") continue;3175 const trimmed = t.trim();3176 if (!trimmed) continue;3177 out.push(trimmed.slice(0, 256));3178 if (out.length >= 255) break;3179 }3180 return out.length > 0 ? out : undefined;3181}318231833184318531863187export async function clearVaultEntries(3188 confirmation: "REPLACE_ALL"3189): Promise<void> {3190 if (confirmation !== "REPLACE_ALL") {3191 throw new Error("clearVaultEntries requires explicit confirmation");3192 }3193 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3194 for (const entry of entries) {3195 if (!entry.deletedAt) {3196 const stamp = monotonicEntryTimestamp(Math.max(3197 entry.modifiedAt,3198 tombstones.get(entry.id) ?? 0,3199 ));3200 entry.deletedAt = stamp;3201 entry.modifiedAt = stamp;3202 tombstones.set(entry.id, stamp);3203 }3204 }3205 await persistEntries();3206}32073208export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {3209 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3210 const epoch = vaultEpoch;3211 const key = derivedKey;32123213 const sanitized = sanitizeEntryDraft(entry);3214 const now = Date.now();3215 const stamp = monotonicEntryTimestamp();3216 const nextEntry: VaultEntry = {3217 ...sanitized,3218 id: crypto.randomUUID(),3219 createdAt: now,3220 modifiedAt: stamp,3221 3222 3223 passwordChangedAt: sanitized.password ? stamp : undefined,3224 };32253226 3227 3228 3229 const rollback = entries;3230 entries = [...entries, nextEntry];3231 try {3232 await persistEntries();3233 } catch (err) {3234 entries = rollback;3235 throw err;3236 }32373238 if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password && epoch === vaultEpoch) {3239 checkEntryBreachDetached({ id: nextEntry.id, password: nextEntry.password, epoch, key });3240 }32413242 fireSyncTrigger("vault_change");32433244 return nextEntry;3245}324632473248export async function consolidatePasskeyEntries(): Promise<void> {3249 if (!derivedKey || vaultCreatesInFlight) return;3250 const epoch = vaultEpoch;3251 const rollback = entries;3252 const next = entries.map((entry) => ({ ...entry }));3253 if (!mergePasskeyOnlyIntoLogins(next).merged) return;3254 const unchanged = next.map((entry) => ({ entry, modifiedAt: entry.modifiedAt }));3255 entries = next;3256 try {3257 await persistEntries();3258 } catch (err) {3259 3260 if (epoch === vaultEpoch && entries === next && entries.length === unchanged.length &&3261 unchanged.every(({ entry, modifiedAt }, index) => entries[index] === entry && entry.modifiedAt === modifiedAt)) {3262 entries = rollback;3263 buildDomainIndexSync(entries);3264 }3265 throw err;3266 }3267}32683269export async function updateEntry(3270 id: string,3271 patch: Partial<VaultEntry>3272): Promise<void> {3273 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");32743275 const idx = entries.findIndex((entry) => entry.id === id);3276 if (idx === -1 || entries[idx].deletedAt) {3277 throw new Error("entry_not_found");3278 }32793280 const current = entries[idx];3281 const owner = entries;3282 const epoch = vaultEpoch;3283 const key = derivedKey;3284 const sanitizedPatch = sanitizeEntryPatch(patch);3285 3286 3287 3288 const passwordChanged =3289 "password" in patch &&3290 typeof sanitizedPatch.password === "string" &&3291 sanitizedPatch.password !== current.password;3292 const stamp = monotonicEntryTimestamp(current.modifiedAt);3293 3294 3295 3296 3297 3298 3299 3300 const priorPassword = current.password;3301 const shouldCapture =3302 passwordChanged &&3303 typeof priorPassword === "string" &&3304 priorPassword.length > 0 &&3305 current.passwordHistory?.[0]?.password !== priorPassword;3306 const nextHistory = shouldCapture3307 ? [3308 { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },3309 ...(current.passwordHistory ?? []),3310 ].slice(0, PASSWORD_HISTORY_MAX)3311 : current.passwordHistory;3312 const next = {3313 ...current,3314 ...sanitizedPatch,3315 modifiedAt: stamp,3316 ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),3317 };3318 entries[idx] = next;33193320 3321 if (entries[idx].type === "card" && !entries[idx].cardNumber) {3322 entries[idx] = current;3323 throw new Error("card number is required for card entries");3324 }33253326 3327 3328 3329 3330 try {3331 await persistEntries();3332 } catch (err) {3333 if (epoch === vaultEpoch && entries === owner && entries[idx] === next && next.modifiedAt === stamp && !next.deletedAt) entries[idx] = current;3334 throw err;3335 }33363337 if (passwordChanged && settings.breachMonitoring !== false && next.type === "login" && next.password && epoch === vaultEpoch) {3338 checkEntryBreachDetached({ id, password: next.password, epoch, key });3339 }33403341 fireSyncTrigger("vault_change");3342}33433344export async function deleteEntry(id: string): Promise<void> {3345 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");33463347 const entry = entries.find((item) => item.id === id);3348 if (!entry || entry.deletedAt) {3349 throw new Error("entry_not_found");3350 }33513352 3353 3354 3355 const previousModifiedAt = entry.modifiedAt;3356 const previousTombstone = tombstones.get(id);3357 const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));3358 entry.deletedAt = stamp;3359 entry.modifiedAt = stamp;3360 tombstones.set(id, stamp);3361 3362 3363 try {3364 await persistEntries();3365 } catch (err) {3366 delete entry.deletedAt;3367 entry.modifiedAt = previousModifiedAt;3368 if (previousTombstone === undefined) tombstones.delete(id);3369 else tombstones.set(id, previousTombstone);3370 throw err;3371 }3372 fireSyncTrigger("vault_change");3373}33743375export function getDeletedEntries(): VaultEntry[] {3376 if (!derivedKey) return [];3377 return entries.filter((e) => !!e.deletedAt);3378}337933803381export function getTombstoneManifest(): Record<string, number> {3382 if (!derivedKey) return {};3383 return Object.fromEntries(tombstones);3384}3385338633873388338933903391export async function getVaultVersion(): Promise<number> {3392 try {3393 const raw = await chrome.storage.local.get("peach_last_modified_at");3394 const v = (raw as Record<string, unknown>).peach_last_modified_at;3395 if (typeof v === "number") return v;3396 if (typeof v === "string" && v !== "") {3397 const n = Number.parseInt(v, 10);3398 return Number.isFinite(n) ? n : 0;3399 }3400 return 0;3401 } catch {3402 return 0;3403 }3404}3405340634073408340934103411341234133414341534163417export async function applyMergedRemoteEntries(3418 remoteEntries: VaultEntry[],3419 remoteTombstones: Record<string, number>,3420): Promise<{ received: number; applied: number; conflicts: number }> {3421 3422 3423 3424 3425 3426 3427 if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");34283429 const received = remoteEntries.length + Object.keys(remoteTombstones).length;3430 let applied = 0;3431 let conflicts = 0;34323433 const byId = new Map<string, VaultEntry>();3434 for (const e of entries) byId.set(e.id, e);34353436 const mergeNow = Date.now();3437 const remoteTombstoneTimes = new Map<string, number>();3438 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3439 if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {3440 remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));3441 }3442 }34433444 for (const remote of remoteEntries) {3445 const sanitized = sanitizeRestoredEntry(remote);3446 if (!sanitized) continue;3447 3448 3449 3450 sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);3451 if (typeof sanitized.deletedAt === "number") {3452 sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);3453 }3454 const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);3455 const localTombstoneTs = tombstones.get(sanitized.id);3456 const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);3457 if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {3458 continue;3459 }3460 const local = byId.get(sanitized.id);3461 if (!local) {3462 entries.push(sanitized);3463 byId.set(sanitized.id, sanitized);3464 tombstones.delete(sanitized.id);3465 applied += 1;3466 } else if (sanitized.modifiedAt > local.modifiedAt) {3467 const idx = entries.findIndex((e) => e.id === local.id);3468 if (idx !== -1) {3469 entries[idx] = sanitized;3470 byId.set(sanitized.id, sanitized);3471 tombstones.delete(sanitized.id);3472 applied += 1;3473 if (!local.deletedAt) conflicts += 1;3474 }3475 }3476 }34773478 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3479 if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;3480 3481 const deletedAt = remoteTombstoneTimes.get(id)!;3482 const knownTombstone = tombstones.get(id);3483 if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;3484 const local = byId.get(id);3485 if (!local) {3486 tombstones.set(id, deletedAt);3487 applied += 1;3488 continue;3489 }3490 if (local.deletedAt && local.deletedAt >= deletedAt) continue;3491 if (deletedAt < local.modifiedAt) continue;3492 const idx = entries.findIndex((e) => e.id === id);3493 if (idx !== -1) {3494 entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };3495 tombstones.set(id, deletedAt);3496 applied += 1;3497 }3498 }34993500 if (applied > 0 && vaultMode === "real") {3501 await persistEntries("sync_received");3502 buildDomainIndexSync(entries);3503 3504 3505 3506 3507 try {3508 void chrome.runtime3509 .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })3510 .catch(() => undefined);3511 } catch {3512 3513 }3514 }3515 return { received, applied, conflicts };3516}35173518export async function restoreEntry(id: string): Promise<void> {3519 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3520 const entry = entries.find((e) => e.id === id && e.deletedAt);3521 if (!entry) throw new Error("deleted entry not found");3522 const previousDeletedAt = entry.deletedAt;3523 const previousModifiedAt = entry.modifiedAt;3524 const previousTombstone = tombstones.get(id);3525 delete entry.deletedAt;3526 entry.modifiedAt = monotonicEntryTimestamp(Math.max(3527 entry.modifiedAt,3528 previousTombstone ?? 0,3529 ));3530 tombstones.delete(id);3531 try {3532 await persistEntries();3533 } catch (err) {3534 entry.deletedAt = previousDeletedAt;3535 entry.modifiedAt = previousModifiedAt;3536 if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);3537 throw err;3538 }3539 buildDomainIndexSync(entries);3540}35413542export async function purgeEntry(id: string): Promise<void> {3543 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3544 const idx = entries.findIndex((e) => e.id === id && e.deletedAt);3545 if (idx === -1) throw new Error("deleted entry not found");3546 const entry = entries[idx]!;3547 tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));3548 entries.splice(idx, 1);3549 await persistEntries();3550}355135523553export async function purgeExpiredTrash(retentionMs: number): Promise<number> {3554 if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;3555 const cutoff = Date.now() - retentionMs;3556 const before = entries.length;3557 for (const entry of entries) {3558 if (entry.deletedAt && entry.deletedAt < cutoff) {3559 tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));3560 }3561 }3562 entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));3563 const purged = before - entries.length;3564 if (purged > 0) await persistEntries();3565 return purged;3566}35673568export function queryDomain(domain: string): VaultEntry[] {3569 return domainIndex.get(domain) ?? [];3570}35713572export function getEntryById(id: string): VaultEntry | undefined {3573 return entries.find((entry) => entry.id === id && !entry.deletedAt);3574}35753576async function persistSlotA(3577 reason: VaultSnapshot["reason"] = "local_save",3578): Promise<StoredVault> {3579 if (!derivedKey) throw new Error("vault_locked");3580 const epoch = vaultEpoch;3581 const throwIfStale = () => {3582 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3583 };35843585 const slotA = await loadSlot(SLOT_A);3586 throwIfStale();3587 if (!slotA) throw new Error("missing slot A");35883589 3590 3591 await takeVaultSnapshot(reason);3592 throwIfStale();35933594 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3595 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3596 throwIfStale();35973598 3599 const nextSlotA: StoredVault = {3600 ...slotA,3601 nonce,3602 ciphertext,3603 tag,3604 3605 };36063607 3608 3609 3610 3611 3612 3613 let slotACommitted = false;3614 try {3615 throwIfStale();3616 await writeSlot(SLOT_A, nextSlotA);3617 slotACommitted = true;3618 throwIfStale();36193620 3621 3622 3623 if (!duressConfigured) {3624 throwIfStale();3625 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3626 throwIfStale();3627 }3628 3629 3630 3631 3632 3633 if (reason !== "sync_received") {3634 throwIfStale();3635 await stampLocalVaultMutation();3636 throwIfStale();3637 }3638 } catch (err) {3639 3640 3641 if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3642 if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3643 throw err;3644 }36453646 return nextSlotA;3647}36483649async function persistSlotB(): Promise<void> {3650 if (!derivedKey) throw new Error("vault_locked");36513652 const slotB = await loadSlot(SLOT_B);3653 if (!slotB) throw new Error("missing slot B");36543655 3656 3657 3658 3659 const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3660 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");36613662 await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3663 3664 3665 3666 try {3667 await stampLocalVaultMutation();3668 } catch (err) {3669 await writeSlot(SLOT_B, slotB).catch(() => {});3670 throw err;3671 }3672}36733674async function persistEntries(3675 reason: VaultSnapshot["reason"] = "local_save",3676): Promise<void> {3677 if (vaultCreatesInFlight) throw new Error("vault_changed");3678 vaultWritesInFlight++;3679 try {3680 if (!derivedKey) throw new Error("vault_locked");36813682 3683 3684 const previousTombstones = tombstones;3685 const pendingTombstones = new Map(tombstones);3686 tombstones = pendingTombstones;3687 reconcileTombstones();3688 try {3689 if (vaultMode === "decoy") {3690 await persistSlotB();3691 } else {3692 await persistSlotA(reason);3693 }3694 } catch (err) {3695 if (tombstones === pendingTombstones) tombstones = previousTombstones;3696 throw err;3697 }3698 buildDomainIndexSync(entries);3699 await refreshLockedSyncState();3700 } finally { vaultWritesInFlight--; }3701}3702370337043705370637073708function allowHttpUrl(url: string | undefined): string {3709 const trimmed = url?.trim() ?? "";3710 if (!trimmed) return "";3711 try {3712 const parsed = new URL(trimmed);3713 if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3714 } catch {3715 3716 }3717 return trimmed;3718}37193720function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3721 if (!Array.isArray(values)) return undefined;3722 const seen = new Set<string>();3723 const cleaned: string[] = [];3724 for (const value of values) {3725 const trimmed = typeof value === "string" ? value.trim() : "";3726 if (!trimmed) continue;3727 if (!allowHttpUrl(trimmed)) continue;3728 const key = trimmed.toLowerCase();3729 if (seen.has(key)) continue;3730 seen.add(key);3731 cleaned.push(trimmed);3732 }3733 return cleaned.length > 0 ? cleaned : undefined;3734}37353736function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3737 const title = entry.title.trim();3738 const type: VaultEntry["type"] = entry.type ?? "login";37393740 if (!title) throw new Error("title is required");37413742 if (entry.passkey) {3743 const p = entry.passkey;3744 if (3745 !p.rpId ||3746 !p.credentialId ||3747 !p.publicKeyCose ||3748 !p.userHandle ||3749 !p.userName ||3750 (p.algorithm !== -7 && p.algorithm !== -8)3751 ) {3752 throw new Error("invalid passkey credential");3753 }3754 }3755 if (type === "card") {3756 if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3757 throw new Error("cardholder name and card number are required");3758 }3759 }37603761 return {3762 type,3763 title,3764 username: type === "login" ? entry.username?.trim() ?? "" : undefined,3765 email: type === "login" ? entry.email?.trim() || undefined : undefined,3766 password: type === "login" ? entry.password : undefined,3767 url: type === "login" ? allowHttpUrl(entry.url) : undefined,3768 additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3769 totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3770 3771 3772 totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3773 totpDigits: type === "login" ? entry.totpDigits : undefined,3774 totpPeriod: type === "login" ? entry.totpPeriod : undefined,3775 notes: entry.notes?.trim() || undefined,3776 breach: type === "login" ? entry.breach : undefined,3777 3778 3779 canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3780 tags: sanitizeTags(entry.tags),3781 passkey: entry.passkey,3782 cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3783 cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3784 expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3785 expYear: type === "card" ? entry.expYear?.trim() : undefined,3786 cvc: type === "card" ? entry.cvc?.trim() : undefined,3787 cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3788 network: type === "card" ? entry.network : undefined,3789 last4: type === "card" ? entry.last4?.trim() : undefined,3790 };3791}37923793function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3794 const nextPatch: Partial<VaultEntry> = {};37953796 if ("type" in patch) {3797 nextPatch.type = patch.type;3798 }37993800 if ("title" in patch) {3801 const title = patch.title?.trim() ?? "";3802 if (!title) throw new Error("title is required");3803 nextPatch.title = title;3804 }38053806 if ("url" in patch) {3807 nextPatch.url = allowHttpUrl(patch.url);3808 }38093810 if ("additionalUrls" in patch) {3811 const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3812 const seen = new Set<string>();3813 const cleaned: string[] = [];3814 for (const value of incoming) {3815 const trimmed = typeof value === "string" ? value.trim() : "";3816 if (!trimmed || !allowHttpUrl(trimmed)) continue;3817 const key = trimmed.toLowerCase();3818 if (seen.has(key)) continue;3819 seen.add(key);3820 cleaned.push(trimmed);3821 }3822 nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3823 }38243825 if ("username" in patch) {3826 nextPatch.username = patch.username?.trim() ?? "";3827 }38283829 if ("email" in patch) {3830 nextPatch.email = patch.email?.trim() || undefined;3831 }38323833 if ("password" in patch) {3834 const password = patch.password ?? "";3835 3836 nextPatch.password = password || undefined;3837 }38383839 if ("totp" in patch) {3840 nextPatch.totp = patch.totp?.trim() || undefined;3841 }38423843 if ("totpAlgorithm" in patch) {3844 nextPatch.totpAlgorithm = patch.totpAlgorithm;3845 }38463847 if ("totpDigits" in patch) {3848 nextPatch.totpDigits = patch.totpDigits;3849 }38503851 if ("totpPeriod" in patch) {3852 nextPatch.totpPeriod = patch.totpPeriod;3853 }38543855 if ("notes" in patch) {3856 nextPatch.notes = patch.notes?.trim() || undefined;3857 }38583859 if ("breach" in patch) {3860 nextPatch.breach = patch.breach;3861 }38623863 if ("canary" in patch) {3864 3865 3866 nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3867 }38683869 if ("passkey" in patch) {3870 3871 3872 if (patch.passkey === undefined || patch.passkey === null) {3873 nextPatch.passkey = undefined;3874 } else {3875 const sanitized = sanitizePasskey(patch.passkey);3876 if (!sanitized) throw new Error("invalid passkey credential");3877 nextPatch.passkey = sanitized;3878 }3879 }38803881 if ("tags" in patch) {3882 3883 nextPatch.tags = sanitizeTags(patch.tags);3884 }38853886 if ("cardholderName" in patch) {3887 nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3888 }3889 if ("cardNumber" in patch) {3890 const n = patch.cardNumber ?? "";3891 nextPatch.cardNumber = n || undefined;3892 }3893 if ("expMonth" in patch) {3894 nextPatch.expMonth = patch.expMonth?.trim() || undefined;3895 }3896 if ("expYear" in patch) {3897 nextPatch.expYear = patch.expYear?.trim() || undefined;3898 }3899 if ("cvc" in patch) {3900 nextPatch.cvc = patch.cvc?.trim() || undefined;3901 }3902 if ("cardNickname" in patch) {3903 nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3904 }3905 if ("network" in patch) {3906 nextPatch.network = patch.network;3907 }3908 if ("last4" in patch) {3909 nextPatch.last4 = patch.last4?.trim() || undefined;3910 }39113912 return nextPatch;3913}39143915function normalizeEntry(entry: VaultEntry): VaultEntry {3916 const base: VaultEntry = {3917 id: entry.id,3918 type: entry.type,3919 title: entry.title,3920 username: entry.username,3921 email: entry.email,3922 password: entry.password,3923 url: entry.url,3924 additionalUrls:3925 "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3926 ? entry.additionalUrls3927 : undefined,3928 totp: entry.totp,3929 3930 totpAlgorithm: entry.totpAlgorithm,3931 totpDigits: entry.totpDigits,3932 totpPeriod: entry.totpPeriod,3933 notes: entry.notes,3934 breach: entry.breach,3935 3936 3937 3938 passwordChangedAt:3939 "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3940 3941 3942 3943 passwordHistory:3944 "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3945 ? entry.passwordHistory3946 : undefined,3947 canary: entry.canary,3948 passkey: entry.passkey,3949 createdAt: entry.createdAt,3950 modifiedAt: entry.modifiedAt,3951 deletedAt: entry.deletedAt,3952 tags: entry.tags,3953 cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3954 cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3955 expMonth: "expMonth" in entry ? entry.expMonth : undefined,3956 expYear: "expYear" in entry ? entry.expYear : undefined,3957 cvc: "cvc" in entry ? entry.cvc : undefined,3958 cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3959 network: "network" in entry ? entry.network : undefined,3960 last4: "last4" in entry ? entry.last4 : undefined,3961 };39623963 return base;3964}3965396639673968396939703971function entryDupeKey(e: VaultEntry): string {3972 if (e.passkey) {3973 3974 const content = Object.fromEntries(Object.entries(e)3975 .filter(([key]) => key !== "id" && key !== "createdAt" && key !== "modifiedAt")3976 .sort(([a], [b]) => a.localeCompare(b)));3977 return `passkey|${e.passkey.rpId}|${e.passkey.credentialId}|${JSON.stringify(content)}`;3978 }3979 if (e.type === "note") return `note|${e.title.toLowerCase()}`;3980 return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3981}398239833984export function countDuplicates(): number {3985 const best = new Map<string, VaultEntry>();3986 let dupeCount = 0;3987 for (const e of entries.filter((e) => !e.deletedAt)) {3988 const key = entryDupeKey(e);3989 const existing = best.get(key);3990 if (!existing) {3991 best.set(key, e);3992 } else {3993 dupeCount++;3994 3995 if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3996 best.set(key, e);3997 }3998 }3999 }4000 return dupeCount;4001}400240034004400540064007export async function deduplicateEntries(): Promise<number> {4008 if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");4009 4010 4011 if (vaultMode === "decoy") {4012 throw new Error("deduplicate disabled in decoy mode");4013 }40144015 const best = new Map<string, VaultEntry>();4016 for (const e of entries.filter((en) => !en.deletedAt)) {4017 const key = entryDupeKey(e);4018 const existing = best.get(key);4019 if (!existing) {4020 best.set(key, e);4021 } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {4022 best.set(key, e);4023 }4024 }40254026 const keepIds = new Set(Array.from(best.values()).map((e) => e.id));4027 let removed = 0;4028 entries = entries.map((e) => {4029 if (!e.deletedAt && !keepIds.has(e.id)) {4030 removed++;4031 const deletedAt = monotonicEntryTimestamp(Math.max(4032 e.modifiedAt,4033 tombstones.get(e.id) ?? 0,4034 ));4035 tombstones.set(e.id, deletedAt);4036 return { ...e, deletedAt };4037 }4038 return e;4039 });40404041 if (removed > 0) await persistEntries();4042 return removed;4043}404440454046404740484049405040514052const HISTORY_KEY = "peach_vault_history";4053const HISTORY_MAX = 5;405440554056405740584059function bucketEntryCount(n: number): number {4060 if (n <= 0) return 0;4061 if (n <= 10) return 10;4062 if (n <= 25) return 25;4063 if (n <= 50) return 50;4064 if (n <= 100) return 100;4065 if (n <= 250) return 250;4066 if (n <= 500) return 500;4067 return Math.ceil(n / 500) * 500;4068}40694070407140724073407440754076export async function takeVaultSnapshot(4077 reason: VaultSnapshot["reason"],4078): Promise<void> {4079 if (recoveryInFlight || vaultCreatesInFlight) return;4080 4081 4082 4083 if (vaultMode === "decoy") return;4084 vaultWritesInFlight++;4085 try {4086 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);4087 const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];4088 const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];40894090 4091 4092 4093 if (!slotA) return;40944095 const vault_a = JSON.stringify(slotA);4096 const vault_b = JSON.stringify(slotB ?? slotA);40974098 4099 4100 4101 4102 4103 4104 let entryCount: number | null = null;4105 if (derivedKey && vaultMode === "real") {4106 try {4107 entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);4108 } catch {4109 entryCount = null;4110 }4111 }41124113 const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];4114 const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)4115 ? existingRaw4116 : { snapshots: [] };41174118 4119 4120 4121 const latest = history.snapshots[0];4122 if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {4123 return;4124 }41254126 const snapshot: VaultSnapshot = {4127 id: crypto.randomUUID(),4128 savedAt: Date.now(),4129 reason,4130 vault_a,4131 vault_b,4132 entryCount,4133 };41344135 history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);4136 if (recoveryInFlight || vaultCreatesInFlight) return;4137 await chrome.storage.local.set({ [HISTORY_KEY]: history });4138 } catch (err) {4139 4140 4141 4142 4143 console.warn('[Peach] takeVaultSnapshot failed:', err);4144 if (String(err).includes('QUOTA') || String(err).includes('quota')) {4145 try {4146 await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });4147 } catch {4148 4149 }4150 }4151 } finally { vaultWritesInFlight--; }4152}415341544155export async function clearVaultHistory(): Promise<void> {4156 if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");4157 vaultWritesInFlight++;4158 try {4159 await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });4160 } catch {4161 4162 } finally { vaultWritesInFlight--; }4163}416441654166export async function getVaultHistory(): Promise<VaultSnapshot[]> {4167 if (vaultMode === "decoy") return [];4168 const raw = await chrome.storage.local.get(HISTORY_KEY);4169 const value = (raw as Record<string, unknown>)[HISTORY_KEY];4170 return sanitizeHistory(value);4171}417241734174417541764177export async function restoreVaultSnapshot(4178 snapshotId: string,4179): Promise<{ ok: true } | { ok: false; error: string }> {4180 if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };4181 vaultReplacementInFlight = true;4182 try {4183 if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };4184 const history = await getVaultHistory();4185 const snapshot = history.find((s) => s.id === snapshotId);4186 if (!snapshot) return { ok: false, error: "snapshot_not_found" };41874188 const restoredA = parseHistorySlot(snapshot.vault_a);4189 const restoredB = parseHistorySlot(snapshot.vault_b);4190 if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };41914192 await takeVaultSnapshot("restore");4193 const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);4194 const previousA = (current as Record<string, unknown>)[SLOT_A];4195 const previousB = (current as Record<string, unknown>)[SLOT_B];4196 try {4197 if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };4198 await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });4199 await stampLocalVaultMutation();4200 } catch {4201 try {4202 await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });4203 } catch {4204 4205 }4206 return { ok: false, error: "snapshot_corrupt" };4207 }42084209 await lock();4210 return { ok: true };4211 } finally {4212 vaultReplacementInFlight = false;4213 }4214}421542164217421842194220422142224223422442254226422742284229export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {4230 if (vaultCreatesInFlight) throw new Error("vault_changed");4231 const rotationEpoch = vaultEpoch;4232 const removalEpoch = vaultRemovalEpoch;4233 vaultWritesInFlight++;4234 try {4235 if (!derivedKey || vaultMode !== "real") {4236 return { ok: false, error: "vault_locked" };4237 }4238 const slotA = await loadSlot(SLOT_A);4239 if (!slotA) return { ok: false, error: "missing_slot_a" };42404241 4242 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =4243 await generateAndWrapRootKey();42444245 4246 const newRootKey = unhex(rawRootKey);4247 const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");4248 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);42494250 4251 4252 4253 4254 await takeVaultSnapshot("local_save");4255 const nextSlotA: StoredVault = {4256 ...slotA,4257 recovery_vault_key: recoveryVaultKey,4258 recovery_salt: recoverySalt,4259 recovery_wrapped_root_key: wrappedRootKey,4260 recovery_nonce: wrappedNonce,4261 recovery_tag: wrappedTag,4262 ...pwRoot,4263 };4264 await writeSlot(SLOT_A, nextSlotA);42654266 4267 if (rotationEpoch === vaultEpoch && derivedKey && rootKey) {4268 const oldRootKey = rootKey;4269 4270 4271 4272 4273 await serializeRecallMutation(async () => {4274 await rekeyManualSummonRecall(oldRootKey, newRootKey).catch((error) => {4275 console.warn("[Peach] manual-summon recall re-key failed:", error);4276 });4277 if (rootKey === oldRootKey) {4278 rootKey = newRootKey;4279 zeroKey(oldRootKey);4280 } else {4281 zeroKey(newRootKey);4282 }4283 });4284 } else {4285 zeroKey(newRootKey);4286 }42874288 4289 4290 await notifyIdentityKeysRotated();42914292 4293 4294 4295 await clearPairedDevices();4296 await clearPairSecrets();42974298 4299 if (removalEpoch === vaultRemovalEpoch) {4300 await setRecoveryConfirmPending(rotationEpoch === vaultEpoch && isUnlocked());4301 touchAutoLock();4302 }43034304 await stampLocalVaultMutation();4305 return { ok: true };4306 } finally { vaultWritesInFlight--; }4307}43084309431043114312431343144315export async function changePassword(4316 currentPassword: string,4317 newPassword: string4318): Promise<boolean> {4319 if (vaultCreatesInFlight) throw new Error("vault_changed");4320 vaultWritesInFlight++;4321 try {43224323 const epoch = vaultEpoch;4324 const stale = () => epoch !== vaultEpoch;4325 if (!derivedKey || vaultMode !== "real") return false;43264327 4328 const valid = await verifyMainPassword(currentPassword);4329 if (!valid) return false;43304331 const slotA = await loadSlot(SLOT_A);4332 if (!slotA) return false;4333 if (!rootKey) return false;43344335 4336 const newSalt = generateSalt();4337 const newKey = await deriveKey(newPassword, newSalt);4338 if (stale()) {4339 zeroKey(newKey);4340 return false;4341 }43424343 4344 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);4345 const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");43464347 4348 4349 4350 const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);43514352 const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");4353 const finalSlotA: StoredVault = {4354 ...slotA,4355 recovery_vault_key: recoveryVaultKey,4356 salt: hex(newSalt),4357 nonce,4358 ciphertext,4359 tag,4360 ...pwRoot,4361 };43624363 4364 4365 4366 await takeVaultSnapshot("local_save");43674368 4369 4370 4371 4372 await writeSlot(SLOT_A, finalSlotA);4373 if (stale()) {4374 zeroKey(newKey);4375 return false;4376 }43774378 4379 4380 4381 zeroKey(derivedKey);4382 cancelBreachScan();4383 derivedKey = newKey;43844385 4386 4387 4388 4389 if (stale()) {4390 await lock();4391 return false;4392 }4393 await saveSessionKey(newKey, "real", epoch);4394 if (stale()) return false;43954396 4397 4398 4399 await notifyIdentityKeysRotated();4400 if (stale()) return false;44014402 4403 4404 4405 if (!duressConfigured) {4406 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));4407 }4408 await clearPinUnlockStorage();4409 await stampLocalVaultMutation();44104411 return true;4412 } finally { vaultWritesInFlight--; }4413}