123456789101112import { deriveKey, deriveKeyRaw, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import { clampSyncTimestamp } from "../shared/sync-limits";15import { computeVaultId } from "../shared/sync-identity";161718import { triggerSyncIfReachable } from "./sync-trigger";19import { clearPairedDevices } from "./paired-devices";20import {21 rootKeyToWords,22 wordsToRootKeyMaterial,23 deriveRecoveryKey,24} from "../shared/recovery-words";25import type {26 AccentColorName,27 Canary,28 LegacyVaultEntry,29 ManualSummonRecord,30 PasskeyData,31 SavedIdentity,32 StoredVault,33 VaultEntry,34 VaultHistory,35 VaultSnapshot,36} from "../shared/types";37import { decrypt, encrypt, zeroKey } from "./aes";38import { clearAutoLock, touchAutoLock } from "./alarms";39import { setRecoveryConfirmPending } from "./recovery-pending";4041type EntryDraft = Omit<42 VaultEntry,43 "id" | "createdAt" | "modifiedAt" | "deletedAt"44>;454647484950const SLOT_A = "peach_vault_a";51const SLOT_B = "peach_vault_b";525354const LEGACY_MAIN = "peach_vault";55const LEGACY_DECOY = "peach_decoy_vault";56const LEGACY_DURESS_FLAG = "peach_duress";57585960const PAD_BLOCK = 1024;6162636465const PASSWORD_HISTORY_MAX = 50;6667686970717273747576const DURESS_SLOT_SIZE = 262_144;7778let derivedKey: Uint8Array | null = null;7980818283let rootKey: Uint8Array | null = null;84let entries: VaultEntry[] = [];85let domainIndex: Map<string, VaultEntry[]> = new Map();86let vaultMode: "real" | "decoy" = "real";87888990let duressConfigured = false;9192let migrationRan = false;93949596979899100101102103let lastUnlockFailureReason: string | null = null;104105export function consumeLastUnlockFailureReason(): string | null {106 const r = lastUnlockFailureReason;107 lastUnlockFailureReason = null;108 return r;109}110111112113114115export type TextSize = "small" | "medium" | "large";116117export interface VaultSettings {118 accentColor?: AccentColorName;119 theme?: "dark" | "light";120 autoLockMinutes?: number;121 clipboardClearSeconds?: number;122 lockOnClose?: boolean;123 breachMonitoring?: boolean;124 passkeyProviderEnabled?: boolean;125 trashRetentionDays?: number;126 manualSummonDomains?: Record<string, ManualSummonRecord>;127 declinedCardFingerprints?: string[];128 129130131132133 textSize?: TextSize;134 135136137138139 reduceMotion?: boolean;140 141142143144145 biometricsEnabled?: boolean;146 147148149150151152153 shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;154}155156let settings: VaultSettings = {};157158export function getSettings(): VaultSettings {159 return settings;160}161162export async function ensureSettingsLoaded(): Promise<VaultSettings> {163 await loadSettings();164 return settings;165}166167export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {168 await loadSettings();169 170 171 172 173 const safe = Object.fromEntries(174 Object.entries(patch).filter(175 ([k]) => !["__proto__", "constructor", "prototype"].includes(k),176 ),177 ) as Partial<VaultSettings>;178 settings = { ...settings, ...safe };179 await persistSettings();180}181182async function persistSettings(): Promise<void> {183 try {184 await chrome.storage.local.set({ peach_settings: settings });185 } catch (err) {186 throw mapStorageError(err);187 }188}189190function mapStorageError(err: unknown): Error {191 const message = err instanceof Error ? err.message : String(err);192 if (/QUOTA_BYTES|quota/i.test(message)) {193 return new Error("STORAGE_QUOTA_EXCEEDED");194 }195 return err instanceof Error ? err : new Error(message);196}197198async function loadSettings(): Promise<void> {199 const result = await chrome.storage.local.get("peach_settings");200 settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};201}202203204205function fireSyncTrigger(reason: "vault_change"): void {206 void Promise.resolve()207 .then(() => triggerSyncIfReachable({ reason }))208 .catch(() => {209 210 });211}212213214215216217export async function checkBreach(password: string): Promise<number> {218 219 220 const encoder = new TextEncoder();221 const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));222 const hashHex = Array.from(new Uint8Array(hashBuffer))223 .map((b) => b.toString(16).padStart(2, "0"))224 .join("")225 .toUpperCase();226227 const prefix = hashHex.slice(0, 5);228 const suffix = hashHex.slice(5);229230 try {231 232 233 const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {234 headers: { "Add-Padding": "true" },235 });236 if (!res.ok) return 0;237 const text = await res.text();238 const match = text.split("\r\n").find((l) => l.startsWith(suffix));239 return match ? parseInt(match.split(":")[1], 10) : 0;240 } catch {241 return 0; 242 }243}244245export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {246 const fingerprint = await cardFingerprint(last4, expMonth, expYear);247 await loadSettings();248 settings = {249 ...settings,250 declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],251 };252 await persistSettings();253}254255export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {256 await loadSettings();257 const fingerprint = await cardFingerprint(last4, expMonth, expYear);258 return (settings.declinedCardFingerprints ?? []).includes(fingerprint);259}260261async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {262 const encoder = new TextEncoder();263 const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));264 return Array.from(new Uint8Array(buf).slice(0, 8))265 .map((b) => b.toString(16).padStart(2, "0"))266 .join("");267}268269function hex(buf: Uint8Array): string {270 return Array.from(buf)271 .map((b) => b.toString(16).padStart(2, "0"))272 .join("");273}274275function unhex(s: string): Uint8Array {276 const out = new Uint8Array(s.length / 2);277 for (let i = 0; i < s.length; i += 2) {278 out[i / 2] = parseInt(s.slice(i, i + 2), 16);279 }280 return out;281}282283284285286287288289290291292293294295296297298299300301302async function generateAndWrapRootKey(): Promise<{303 rawRootKey: string; 304 recoverySalt: string;305 wrappedRootKey: string;306 wrappedNonce: string;307 wrappedTag: string;308}> {309 const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));310311 312 const words = await rootKeyToWords(rootKeyBytes);313 const wordMaterial = await wordsToRootKeyMaterial(words);314 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));315 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);316317 318 319 const nonce = crypto.getRandomValues(new Uint8Array(12));320 const encoded = new TextEncoder().encode(hex(rootKeyBytes));321 const raw = await crypto.subtle.encrypt(322 {323 name: "AES-GCM",324 iv: nonce,325 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,326 tagLength: 128,327 },328 recoveryKey,329 encoded330 );331 332 const rawU8 = new Uint8Array(raw);333 const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));334 const tag = hex(rawU8.slice(rawU8.length - 16));335336 return {337 rawRootKey: hex(rootKeyBytes),338 recoverySalt: hex(recoverySalt),339 wrappedRootKey: ciphertext,340 wrappedNonce: hex(nonce),341 wrappedTag: tag,342 };343}344345async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{346 recoverySalt: string;347 wrappedRootKey: string;348 wrappedNonce: string;349 wrappedTag: string;350}> {351 if (rootKeyBytes.length !== 32) {352 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");353 }354355 const words = await rootKeyToWords(rootKeyBytes);356 const wordMaterial = await wordsToRootKeyMaterial(words);357 const recoverySalt = crypto.getRandomValues(new Uint8Array(16));358 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);359 const nonce = crypto.getRandomValues(new Uint8Array(12));360 const encoded = new TextEncoder().encode(hex(rootKeyBytes));361 const raw = await crypto.subtle.encrypt(362 {363 name: "AES-GCM",364 iv: nonce,365 additionalData: new Uint8Array([1]).buffer as ArrayBuffer,366 tagLength: 128,367 },368 recoveryKey,369 encoded,370 );371 const rawU8 = new Uint8Array(raw);372 return {373 recoverySalt: hex(recoverySalt),374 wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),375 wrappedNonce: hex(nonce),376 wrappedTag: hex(rawU8.slice(rawU8.length - 16)),377 };378}379380381382383384385export async function unwrapRootKeyForRecovery(386 wrappedRootKey: string,387 wrappedNonce: string,388 wrappedTag: string,389 recoverySaltHex: string,390 words: string[]391): Promise<void> {392 const wordMaterial = await wordsToRootKeyMaterial(words);393 const recoverySalt = unhex(recoverySaltHex);394 const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);395396 397 398 399 400 401 const nonceRaw = unhex(wrappedNonce);402 const ciphertextRaw = unhex(wrappedRootKey);403 const tagRaw = unhex(wrappedTag);404 405 406 const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;407 const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);408 combined.set(ciphertextRaw, 0);409 combined.set(tagRaw, ciphertextRaw.length);410 const raw = await crypto.subtle.decrypt(411 { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },412 recoveryKey,413 combined414 );415 const decryptedHex = new TextDecoder().decode(raw);416 rootKey = unhex(decryptedHex);417}418419420421422423424425426427428export async function rewrapRootKeyForPassword(429 newDerivedKey: Uint8Array,430 _newSalt: Uint8Array431): Promise<void> {432 if (!rootKey) throw new Error("root key not set");433 const slotA = await loadSlot(SLOT_A);434 if (!slotA) throw new Error("missing slot A");435 const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);436 await writeSlot(SLOT_A, { ...slotA, ...pwRoot });437}438439440441442443444async function reencryptVaultForNewKey(445 newKey: Uint8Array,446 slotA: StoredVault447): Promise<void> {448 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);449 const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");450 await writeSlot(SLOT_A, {451 ...slotA,452 nonce,453 ciphertext,454 tag,455 });456}457458459460461462463export async function changePasswordWithNewKey(464 newSalt: Uint8Array,465 newKey: Uint8Array466): Promise<void> {467 const slotA = await loadSlot(SLOT_A);468 if (!slotA) throw new Error("missing slot A");469 470 471 await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });472 if (derivedKey) zeroKey(derivedKey);473 derivedKey = newKey;474 475 476 477 void saveSessionKey(newKey, "real");478 479 480 481 482 if (rootKey) {483 const slotAfter = await loadSlot(SLOT_A);484 if (slotAfter) {485 const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);486 await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });487 }488 }489 if (!duressConfigured) {490 await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));491 }492 await stampLocalVaultMutation();493}494495496497498499500export { deriveKey, generateSalt };501502export async function loadSlotA(): Promise<StoredVault | null> {503 return loadSlot(SLOT_A);504}505506507508509510511512513514515516517518async function deriveRootKeyFromDerivedKey(519 derivedKeyBytes: Uint8Array,520 slotA: StoredVault,521): Promise<Uint8Array | null> {522 if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {523 return null;524 }525 try {526 const rootHex = await decrypt(527 derivedKeyBytes,528 slotA.pw_root_nonce,529 slotA.pw_root_ciphertext,530 slotA.pw_root_tag,531 "pw_root_v1",532 );533 return unhex(rootHex);534 } catch {535 return null;536 }537}538539540541async function wrapRootKeyForDerivedKey(542 derivedKeyBytes: Uint8Array,543 rootKeyBytes: Uint8Array,544): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {545 const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");546 return {547 pw_root_ciphertext: ciphertext,548 pw_root_nonce: nonce,549 pw_root_tag: tag,550 };551}552553554555556557558559560export async function migrateToRecovery(): Promise<void> {561 if (!derivedKey || vaultMode !== "real") {562 throw new Error("vault must be unlocked in real mode");563 }564 const slotA = await loadSlot(SLOT_A);565 if (!slotA) throw new Error("missing slot A");566 const hasRecoveryEscrow =567 !!slotA.recovery_salt && !!slotA.recovery_wrapped_root_key;568 const hasPwRoot = !!slotA.pw_root_ciphertext && !!slotA.pw_root_nonce;569 if (hasRecoveryEscrow && hasPwRoot) return; 570571 572 573 574 575 576 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =577 await generateAndWrapRootKey();578 rootKey = unhex(rawRootKey);579580 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);581 const nextSlotA: StoredVault = {582 ...slotA,583 recovery_salt: recoverySalt,584 recovery_wrapped_root_key: wrappedRootKey,585 recovery_nonce: wrappedNonce,586 recovery_tag: wrappedTag,587 ...pwRoot,588 };589 await writeSlot(SLOT_A, nextSlotA);590 await stampLocalVaultMutation();591}592593594595596597598export async function getRecoveryWords(): Promise<string[]> {599 if (!rootKey) {600 throw new Error("recovery not set up — vault may need migration");601 }602 return rootKeyToWords(rootKey);603}604605async function loadSlot(key: string): Promise<StoredVault | null> {606 const result = await chrome.storage.local.get(key);607 return (result as Record<string, StoredVault | undefined>)[key] ?? null;608}609610async function writeSlot(key: string, vault: StoredVault): Promise<void> {611 try {612 await chrome.storage.local.set({ [key]: vault });613 } catch (err) {614 throw mapStorageError(err);615 }616}617618619620621622623624625626627export async function rollbackAdoptedVault(): Promise<void> {628 lock();629 try {630 await chrome.storage.local.remove([631 SLOT_A,632 SLOT_B,633 "peach_last_modified_at",634 ]);635 } catch (err) {636 throw mapStorageError(err);637 }638}639640async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {641 const raw = await chrome.storage.local.get("peach_last_modified_at");642 const previous = Number(643 (raw as Record<string, unknown>).peach_last_modified_at,644 );645 const next = Math.max(646 Date.now(),647 Number.isFinite(previous) ? previous + 1 : 0,648 );649 try {650 await chrome.storage.local.set({651 [SLOT_A]: slotA,652 [SLOT_B]: slotB,653 peach_last_modified_at: String(next),654 });655 } catch (err) {656 throw mapStorageError(err);657 }658}659660661662663664665666667let lastEntryTimestamp = 0;668function monotonicEntryTimestamp(currentModifiedAt?: number): number {669 const base = Math.max(670 Date.now(),671 (currentModifiedAt ?? 0) + 1,672 lastEntryTimestamp + 1,673 );674 lastEntryTimestamp = base;675 return base;676}677678async function stampLocalVaultMutation(): Promise<void> {679 const raw = await chrome.storage.local.get("peach_last_modified_at");680 const previous = Number(681 (raw as Record<string, unknown>).peach_last_modified_at,682 );683 const next = Math.max(684 Date.now(),685 Number.isFinite(previous) ? previous + 1 : 0,686 );687 await chrome.storage.local.set({688 peach_last_modified_at: String(next),689 });690}691692693694695696697async function ensureMigrated(): Promise<void> {698 if (migrationRan) return;699 migrationRan = true;700701 const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];702 const raw = await chrome.storage.local.get(keys);703 const slotAExists = raw[SLOT_A] !== undefined;704 const slotBExists = raw[SLOT_B] !== undefined;705 const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;706 const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;707708 709 if (!slotAExists && !legacyMain) return;710711 712 if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;713714 let didMigrate = false;715 if (legacyMain && !slotAExists) {716 await writeSlot(SLOT_A, legacyMain);717 didMigrate = true;718 }719720 721 if (!slotBExists) {722 const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;723 if (legacyDecoy) {724 await writeSlot(SLOT_B, legacyDecoy);725 didMigrate = true;726 } else if (target) {727 await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));728 didMigrate = true;729 }730 }731732 const toRemove: string[] = [];733 if (legacyMain) toRemove.push(LEGACY_MAIN);734 if (legacyDecoy) toRemove.push(LEGACY_DECOY);735 if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);736 if (toRemove.length > 0) {737 await chrome.storage.local.remove(toRemove);738 didMigrate = true;739 }740 if (didMigrate) {741 await stampLocalVaultMutation();742 }743}744745746747748749750751752753754755function padPlaintext(json: string, minBytes = 0): string {756 const encoded = new TextEncoder().encode(json);757 const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);758 759 const target = Math.max(bucket, minBytes);760 const padLen = target - encoded.length;761 return json + " ".repeat(padLen);762}763764765766767768769770771772773774const CSPRNG_CHUNK = 65_536;775776function fillRandom(buf: Uint8Array): Uint8Array {777 for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {778 const end = Math.min(offset + CSPRNG_CHUNK, buf.length);779 const chunk = new Uint8Array(end - offset);780 crypto.getRandomValues(chunk);781 buf.set(chunk, offset);782 }783 return buf;784}785786function generateNoiseBlob(ciphertextBytes: number): StoredVault {787 const salt = crypto.getRandomValues(new Uint8Array(16));788 const nonce = crypto.getRandomValues(new Uint8Array(12));789 const cipher = fillRandom(new Uint8Array(ciphertextBytes));790 const tag = crypto.getRandomValues(new Uint8Array(16));791 return {792 version: 1,793 salt: hex(salt),794 nonce: hex(nonce),795 ciphertext: hex(cipher),796 tag: hex(tag),797 };798}799800801802803804type VaultPayload = {805 entries: VaultEntry[];806 duressConfigured?: boolean;807};808809type DecryptedPayload = {810 entries: VaultEntry[];811 duressConfigured: boolean;812 813814815816817818819 migratedFromLegacy: boolean;820};821822function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {823 const envelope: VaultPayload = { entries, duressConfigured: duress };824 return padPlaintext(JSON.stringify(envelope), minBytes);825}826827function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {828 if ("created" in raw || "updated" in raw) return true;829 const flat = raw as Partial<VaultEntry>;830 if (flat.type === "passkey") return true;831 832 if (flat.rpId !== undefined && flat.passkey === undefined) return true;833 return false;834}835836function decodePayload(plain: string): DecryptedPayload {837 const parsed = JSON.parse(plain) as838 | Array<VaultEntry | LegacyVaultEntry>839 | VaultPayload;840841 const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];842 const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);843844 const normalized = rawEntries.map(normalizeEntry);845 const { merged } = mergePasskeyOnlyIntoLogins(normalized);846847 if (Array.isArray(parsed)) {848 return {849 entries: normalized,850 duressConfigured: false,851 migratedFromLegacy: true, 852 };853 }854855 return {856 entries: normalized,857 duressConfigured: parsed.duressConfigured === true,858 migratedFromLegacy: flatMigrationNeeded || merged,859 };860}861862863864865866867868869870871872873874875876877878879880881882883884885function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {886 let merged = false;887 const now = Date.now();888889 const candidates = entries.filter((e) => !e.deletedAt && e.passkey);890 const byRpId = new Map<string, VaultEntry[]>();891 for (const e of candidates) {892 const rpId = e.passkey!.rpId;893 const list = byRpId.get(rpId);894 if (list) list.push(e);895 else byRpId.set(rpId, [e]);896 }897898 for (const [rpId, group] of byRpId) {899 if (group.length === 0) continue;900 group.sort((a, b) => {901 const aT =902 a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;903 const bT =904 b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;905 return bT - aT;906 });907 const winner = group[0]!;908909 910 911 912 const loginTarget = entries.find((e) => {913 if (e.deletedAt || e.passkey || e.type !== "login") return false;914 if (e.url && extractDomain(e.url) === rpId) return true;915 for (const extra of e.additionalUrls ?? []) {916 if (extractDomain(extra) === rpId) return true;917 }918 return false;919 });920921 if (loginTarget) {922 loginTarget.passkey = winner.passkey;923 loginTarget.modifiedAt = now;924 for (const dup of group) {925 if (!dup.deletedAt) {926 dup.deletedAt = now;927 dup.modifiedAt = now;928 }929 }930 merged = true;931 } else if (group.length > 1) {932 for (let i = 1; i < group.length; i += 1) {933 const dup = group[i]!;934 if (!dup.deletedAt) {935 dup.deletedAt = now;936 dup.modifiedAt = now;937 }938 }939 merged = true;940 }941 }942943 return { merged };944}945946947948949950951952function hasValidVaultSchema(v: unknown): v is StoredVault {953 if (typeof v !== "object" || v === null) return false;954 const r = v as Record<string, unknown>;955 return (956 r.version === 1 &&957 typeof r.salt === "string" &&958 typeof r.nonce === "string" &&959 typeof r.ciphertext === "string" &&960 typeof r.tag === "string"961 );962}963964export type TryDecryptResult =965 | { status: "ok"; payload: DecryptedPayload }966 | { status: "wrong_key" }967 | { status: "corrupted"; reason: string };968969970971972973974export async function tryDecryptSlot(975 vault: StoredVault,976 key: Uint8Array,977 aadTag?: string,978): Promise<DecryptedPayload | null> {979 const res = await tryDecryptSlotResult(vault, key, aadTag);980 return res.status === "ok" ? res.payload : null;981}982983export async function tryDecryptSlotResult(984 vault: StoredVault,985 key: Uint8Array,986 aadTag?: string,987): Promise<TryDecryptResult> {988 if (!hasValidVaultSchema(vault)) {989 return { status: "corrupted", reason: "invalid_slot_schema" };990 }991 let plain: string;992 try {993 plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);994 } catch {995 return { status: "wrong_key" };996 }997 try {998 const parsed = JSON.parse(plain) as unknown;999 if (typeof parsed !== "object" || parsed === null) {1000 return { status: "corrupted", reason: "invalid_payload_shape" };1001 }1002 if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1003 return { status: "corrupted", reason: "invalid_payload_shape" };1004 }1005 return { status: "ok", payload: decodePayload(plain) };1006 } catch {1007 return { status: "corrupted", reason: "invalid_payload_json" };1008 }1009}101010111012101310141015function buildDomainIndexSync(all: VaultEntry[]): void {1016 domainIndex = new Map();10171018 for (const entry of all) {1019 if (entry.deletedAt) continue;1020 if (entry.type === "note" || entry.type === "card") continue;10211022 1023 1024 1025 1026 const domains = new Set<string>();1027 const primary = extractDomain(entry.url ?? "");1028 if (primary) domains.add(primary);1029 for (const extra of entry.additionalUrls ?? []) {1030 const d = extractDomain(extra);1031 if (d) domains.add(d);1032 }1033 if (domains.size === 0) continue;10341035 for (const domain of domains) {1036 const bucket = domainIndex.get(domain) ?? [];1037 bucket.push(entry);1038 domainIndex.set(domain, bucket);1039 }1040 }1041}10421043export async function createVault(password: string): Promise<void> {1044 await ensureMigrated();10451046 const salt = generateSalt();1047 derivedKey = await deriveKey(password, salt);1048 entries = [];1049 vaultMode = "real";1050 duressConfigured = false;1051 buildDomainIndexSync(entries);10521053 1054 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =1055 await generateAndWrapRootKey();1056 rootKey = unhex(rawRootKey);10571058 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1059 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");10601061 1062 1063 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);10641065 const slotA: StoredVault = {1066 version: 1,1067 salt: hex(salt),1068 nonce,1069 ciphertext,1070 tag,1071 recovery_salt: recoverySalt,1072 recovery_wrapped_root_key: wrappedRootKey,1073 recovery_nonce: wrappedNonce,1074 recovery_tag: wrappedTag,1075 ...pwRoot,1076 };1077 await writeSlot(SLOT_A, slotA);10781079 1080 1081 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1082 await stampLocalVaultMutation();10831084 touchAutoLock();1085}1086108710881089109010911092export async function createVaultFromRootKey(1093 password: string,1094 rootKeyHex: string,1095): Promise<{ vaultId: string }> {1096 if (typeof password !== "string" || password.length === 0) {1097 throw new Error("ADOPT_INVALID_PASSWORD");1098 }1099 if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1100 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1101 }11021103 const rootKeyBytes = unhex(rootKeyHex);1104 if (rootKeyBytes.length !== 32) {1105 rootKeyBytes.fill(0);1106 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1107 }11081109 let nextDerivedKey: Uint8Array | null = null;1110 let sessionRootKey: Uint8Array | null = null;1111 try {1112 await ensureMigrated();1113 if ((await loadSlot(SLOT_A)) !== null) {1114 throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1115 }11161117 const nextEntries: VaultEntry[] = [];1118 const nextDuressConfigured = false;1119 const vaultId = await computeVaultId(rootKeyBytes);1120 const salt = generateSalt();1121 nextDerivedKey = await deriveKey(password, salt);1122 const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);11231124 sessionRootKey = new Uint8Array(rootKeyBytes);1125 const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1126 const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1127 const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1128 const slotA: StoredVault = {1129 version: 1,1130 salt: hex(salt),1131 nonce,1132 ciphertext,1133 tag,1134 recovery_salt: recovery.recoverySalt,1135 recovery_wrapped_root_key: recovery.wrappedRootKey,1136 recovery_nonce: recovery.wrappedNonce,1137 recovery_tag: recovery.wrappedTag,1138 ...pwRoot,1139 };1140 const slotB = generateNoiseBlob(ciphertext.length / 2);1141 await commitCreatedVaultSlots(slotA, slotB);11421143 const previousDerivedKey = derivedKey;1144 const previousRootKey = rootKey;1145 derivedKey = nextDerivedKey;1146 rootKey = sessionRootKey;1147 nextDerivedKey = null;1148 sessionRootKey = null;1149 entries = nextEntries;1150 vaultMode = "real";1151 duressConfigured = nextDuressConfigured;1152 buildDomainIndexSync(entries);1153 if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1154 if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1155 touchAutoLock();11561157 return { vaultId };1158 } finally {1159 rootKeyBytes.fill(0);1160 if (nextDerivedKey) zeroKey(nextDerivedKey);1161 if (sessionRootKey) sessionRootKey.fill(0);1162 }1163}11641165export async function hasVault(): Promise<boolean> {1166 await ensureMigrated();1167 return (await loadSlot(SLOT_A)) !== null;1168}1169117011711172117311741175export async function isDuressEnabled(): Promise<boolean> {1176 return vaultMode === "real" && duressConfigured;1177}11781179export async function setupDuress(duressPassword: string): Promise<void> {1180 if (!derivedKey || vaultMode !== "real") {1181 throw new Error("vault must be unlocked in real mode");1182 }1183 await ensureMigrated();11841185 1186 1187 1188 const slotA = await loadSlot(SLOT_A);1189 if (!slotA) throw new Error("missing slot A");11901191 const decoySalt = generateSalt();1192 const decoyKey = await deriveKey(duressPassword, decoySalt);1193 try {1194 1195 1196 1197 1198 const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1199 const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1200 await writeSlot(SLOT_B, {1201 version: 1,1202 salt: hex(decoySalt),1203 nonce,1204 ciphertext,1205 tag,1206 });1207 } finally {1208 zeroKey(decoyKey);1209 }12101211 1212 1213 duressConfigured = true;1214 await persistSlotA();1215}12161217export async function disableDuress(): Promise<void> {1218 if (!derivedKey || vaultMode !== "real") {1219 throw new Error("vault must be unlocked in real mode");1220 }1221 await ensureMigrated();12221223 1224 1225 1226 const slotA = await loadSlot(SLOT_A);1227 if (slotA) {1228 await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1229 }12301231 duressConfigured = false;1232 await persistSlotA();1233}12341235123612371238123912401241export async function verifyMainPassword(password: string): Promise<boolean> {1242 await ensureMigrated();1243 const slotA = await loadSlot(SLOT_A);1244 if (!slotA) return false;1245 const key = await deriveKey(password, unhex(slotA.salt));1246 try {1247 return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1248 } finally {1249 zeroKey(key);1250 }1251}12521253export async function unlock(password: string): Promise<boolean> {1254 1255 1256 1257 if (await attemptUnlockWithDerive(password, deriveKey)) return true;12581259 const nfc = password.normalize("NFC");1260 if (password === nfc) return false; 12611262 if (await attemptUnlockWithDerive(password, deriveKeyRaw)) {1263 1264 1265 1266 if (vaultMode === "real") {1267 try {1268 const newSalt = generateSalt();1269 const newKey = await deriveKey(password, newSalt);1270 await changePasswordWithNewKey(newSalt, newKey);1271 } catch (healErr) {1272 console.warn("[Peach] LV-1 NFC heal failed:", healErr);1273 }1274 }1275 return true;1276 }1277 return false;1278}12791280async function attemptUnlockWithDerive(1281 password: string,1282 derive: typeof deriveKey,1283): Promise<boolean> {1284 await ensureMigrated();12851286 1287 1288 1289 1290 1291 const [slotA, slotB] = await Promise.all([1292 loadSlot(SLOT_A),1293 loadSlot(SLOT_B),1294 ]);12951296 1297 const [keyA, keyB] = await Promise.all([1298 slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1299 slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1300 ]);13011302 1303 1304 1305 const [resultA, resultB] = await Promise.all([1306 keyA && slotA1307 ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1308 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1309 keyB && slotB1310 ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1311 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1312 ]);1313 const payloadA = resultA.status === "ok" ? resultA.payload : null;1314 const payloadB = resultB.status === "ok" ? resultB.payload : null;13151316 if (payloadA && keyA) {1317 derivedKey = keyA;1318 void saveSessionKey(keyA, "real");1319 vaultMode = "real";1320 entries = payloadA.entries;1321 duressConfigured = payloadA.duressConfigured;1322 buildDomainIndexSync(entries);1323 await loadSettings();1324 touchAutoLock();1325 if (keyB) zeroKey(keyB);13261327 1328 if (slotA) {1329 const needsRecoverySetup =1330 !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1331 if (!needsRecoverySetup) {1332 rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1333 }1334 1335 1336 1337 1338 if (needsRecoverySetup || !rootKey) {1339 try {1340 await migrateToRecovery();1341 if (needsRecoverySetup) {1342 1343 1344 1345 await chrome.storage.local.set({ peach_recovery_pending: '1' });1346 }1347 } catch (migrationErr) {1348 console.warn('[Peach] recovery migration failed:', migrationErr);1349 }1350 }1351 }13521353 1354 1355 1356 if (payloadA.migratedFromLegacy) {1357 await persistSlotA();1358 }1359 return true;1360 }13611362 if (payloadB && keyB) {1363 derivedKey = keyB;1364 void saveSessionKey(keyB, "decoy");1365 vaultMode = "decoy";1366 entries = payloadB.entries;1367 duressConfigured = false;1368 buildDomainIndexSync(entries);1369 await loadSettings();1370 touchAutoLock();1371 if (keyA) zeroKey(keyA);1372 return true;1373 }13741375 if (keyA) zeroKey(keyA);1376 if (keyB) zeroKey(keyB);1377 1378 1379 if (resultA.status === "corrupted") {1380 lastUnlockFailureReason = resultA.reason;1381 } else if (resultB.status === "corrupted") {1382 lastUnlockFailureReason = resultB.reason;1383 }1384 return false;1385}13861387138813891390139113921393const SESSION_KEY_STORAGE = "peach_session_dk";13941395async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1396 if (!chrome.storage.session) return;1397 await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1398}13991400async function clearSessionKey(): Promise<void> {1401 if (!chrome.storage.session) return;1402 await chrome.storage.session.remove(SESSION_KEY_STORAGE);1403}14041405140614071408140914101411export async function restoreFromSession(): Promise<boolean> {1412 if (derivedKey !== null) return true;1413 if (!chrome.storage.session) return false;1414 const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1415 const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1416 if (!entry?.keyHex) return false;14171418 const key = unhex(entry.keyHex);1419 const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1420 const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1421 const slot = await loadSlot(slotKey);1422 if (!slot) { await clearSessionKey(); return false; }14231424 const result = await tryDecryptSlotResult(slot, key, aadTag);1425 if (result.status !== "ok") { await clearSessionKey(); return false; }14261427 derivedKey = key;1428 vaultMode = entry.mode;1429 entries = result.payload.entries;1430 duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1431 buildDomainIndexSync(entries);1432 await loadSettings();1433 touchAutoLock();14341435 if (entry.mode === "real" && slot.recovery_salt && slot.recovery_wrapped_root_key) {1436 try { rootKey = await deriveRootKeyFromDerivedKey(key, slot); } catch { }1437 }14381439 return true;1440}14411442export function lock(): void {1443 void clearSessionKey();1444 if (derivedKey) {1445 zeroKey(derivedKey);1446 derivedKey = null;1447 }1448 if (rootKey) {1449 rootKey.fill(0);1450 rootKey = null;1451 }14521453 entries = [];1454 domainIndex = new Map();1455 vaultMode = "real";1456 duressConfigured = false;1457 clearAutoLock();1458}14591460export function isUnlocked(): boolean {1461 return derivedKey !== null;1462}14631464146514661467export async function unlockWithKey(1468 masterKeyHex: string,1469): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1470 try {1471 const masterKeyBytes = unhex(masterKeyHex);1472 const stored = await loadSlot(SLOT_A);1473 if (!stored) return { ok: false, error: "invalid_key" };1474 const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1475 if (!payload) return { ok: false, error: "invalid_key" };14761477 derivedKey = masterKeyBytes;1478 vaultMode = "real";1479 entries = payload.entries;1480 duressConfigured = payload.duressConfigured;1481 buildDomainIndexSync(entries);1482 await loadSettings();1483 touchAutoLock();14841485 1486 1487 1488 1489 1490 if (stored.recovery_salt && stored.recovery_wrapped_root_key) {1491 try {1492 rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);1493 } catch { }1494 }1495 return { ok: true, entries };1496 } catch {1497 return { ok: false, error: "invalid_key" };1498 }1499}15001501150215031504150515061507150815091510151115121513151415151516151715181519export async function unlockFromCodex(params: {1520 slotA: string; 1521 slotB: string | null; 1522 timestamp: number;1523 masterPassphrase: string;1524}): Promise<1525 | { ok: true; entryCount: number }1526 | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1527> {1528 let parsedSlotA: StoredVault;1529 let parsedSlotB: StoredVault | null = null;1530 try {1531 const rawA = JSON.parse(params.slotA) as unknown;1532 if (!hasValidVaultSchema(rawA)) {1533 return { ok: false, reason: "invalid_slot_format" };1534 }1535 parsedSlotA = rawA;1536 if (params.slotB !== null) {1537 const rawB = JSON.parse(params.slotB) as unknown;1538 if (!hasValidVaultSchema(rawB)) {1539 return { ok: false, reason: "invalid_slot_format" };1540 }1541 parsedSlotB = rawB;1542 }1543 } catch {1544 return { ok: false, reason: "invalid_slot_format" };1545 }15461547 1548 1549 const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1550 const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1551 if (!trialPayload) {1552 zeroKey(trialKey);1553 return { ok: false, reason: "wrong_passphrase" };1554 }1555 1556 1557 zeroKey(trialKey);15581559 1560 1561 await takeVaultSnapshot("restore");15621563 await writeSlot(SLOT_A, parsedSlotA);1564 if (parsedSlotB) {1565 await writeSlot(SLOT_B, parsedSlotB);1566 } else {1567 1568 1569 1570 await writeSlot(1571 SLOT_B,1572 generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1573 );1574 }1575 await chrome.storage.local.set({1576 peach_last_modified_at: String(params.timestamp),1577 });15781579 1580 1581 const ok = await unlock(params.masterPassphrase);1582 if (!ok) {1583 1584 1585 1586 return { ok: false, reason: "wrong_passphrase" };1587 }1588 return { ok: true, entryCount: getEntries().length };1589}1590159115921593export function getDerivedKeyHex(): string {1594 if (!derivedKey) throw new Error("vault_not_unlocked");1595 return hex(derivedKey);1596}15971598159916001601160216031604160516061607160816091610161116121613export function getRootKeyHex(): string | null {1614 return rootKey ? hex(rootKey) : null;1615}16161617export function getEntries(): VaultEntry[] {1618 if (!derivedKey) throw new Error("vault_locked");1619 return entries.filter((entry) => !entry.deletedAt);1620}16211622const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;16231624export function getIdentities(): SavedIdentity[] {1625 if (!derivedKey) throw new Error("vault_locked");1626 const active = entries.filter((e) => !e.deletedAt && e.type === "login");16271628 const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1629 const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();16301631 for (const entry of active) {1632 const domain = extractDomain(entry.url ?? "") ?? "";1633 const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;16341635 function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1636 const existing = map.get(v);1637 if (!existing || modifiedAt > existing.lastUsed) {1638 map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1639 } else {1640 map.set(v, { ...existing, count: existing.count + 1 });1641 }1642 }16431644 const uVal = entry.username?.trim();1645 if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);16461647 1648 1649 const eVal = entry.email?.trim();1650 if (eVal) tally(emailMap, eVal);1651 }16521653 const toIdentity = (type: "email" | "username") =>1654 ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1655 value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1656 });16571658 return [1659 ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1660 ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1661 ];1662}16631664export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1665 if (!derivedKey) throw new Error("vault_locked");16661667 const now = Date.now();1668 const added: VaultEntry[] = [];1669 for (const draft of drafts) {1670 try {1671 const sanitized = sanitizeEntryDraft(draft);1672 const nextEntry: VaultEntry = {1673 ...sanitized,1674 id: crypto.randomUUID(),1675 createdAt: now,1676 modifiedAt: monotonicEntryTimestamp(),1677 };1678 entries.push(nextEntry);1679 added.push(nextEntry);1680 } catch {1681 1682 }1683 }16841685 if (added.length > 0) {1686 await persistEntries();1687 }16881689 return added;1690}169116921693169416951696169716981699export async function restoreEntries(1700 incoming: VaultEntry[],1701 mode: "replace" | "merge"1702): Promise<{ added: number; updated: number; skipped: number }> {1703 if (!derivedKey) throw new Error("vault_locked");17041705 1706 1707 1708 if (mode === "replace" && incoming.length === 0) {1709 throw new Error("refuse to replace with empty entry set");1710 }17111712 let added = 0;1713 let updated = 0;1714 let skipped = 0;17151716 if (mode === "replace") {1717 entries = [];1718 for (const entry of incoming) {1719 const normalized = sanitizeRestoredEntry(entry);1720 if (!normalized) {1721 skipped += 1;1722 continue;1723 }1724 entries.push(normalized);1725 added += 1;1726 }1727 } else {1728 const byId = new Map<string, VaultEntry>();1729 for (const e of entries) byId.set(e.id, e);17301731 for (const entry of incoming) {1732 const normalized = sanitizeRestoredEntry(entry);1733 if (!normalized) {1734 skipped += 1;1735 continue;1736 }1737 const existing = byId.get(normalized.id);1738 if (!existing) {1739 entries.push(normalized);1740 added += 1;1741 } else if (normalized.modifiedAt > existing.modifiedAt) {1742 const idx = entries.findIndex((e) => e.id === existing.id);1743 if (idx !== -1) {1744 entries[idx] = normalized;1745 updated += 1;1746 }1747 } else {1748 skipped += 1;1749 }1750 }1751 }17521753 await persistEntries("import");1754 return { added, updated, skipped };1755}175617571758175917601761176217631764function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1765 if (!entry || typeof entry !== "object") return null;1766 const title = typeof entry.title === "string" ? entry.title.trim() : "";1767 if (!title) return null;1768 const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1769 const now = Date.now();1770 const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1771 const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;17721773 1774 1775 1776 1777 const normalized = normalizeEntry({1778 ...entry,1779 id,1780 title,1781 type: entry.type ?? "login",1782 createdAt,1783 modifiedAt,1784 });17851786 if (normalized.passkey) {1787 normalized.passkey = sanitizePasskey(normalized.passkey);1788 }1789 if (normalized.canary) {1790 normalized.canary = sanitizeCanary(normalized.canary);1791 }1792 1793 normalized.tags = sanitizeTags(normalized.tags);17941795 1796 1797 if (1798 normalized.type === "login" &&1799 !normalized.passkey &&1800 typeof normalized.password !== "string"1801 ) {1802 return null;1803 }1804 if (entry.passkey && !normalized.passkey) {1805 1806 1807 return null;1808 }18091810 return normalized;1811}1812181318141815181618171818function sanitizePasskey(pk: unknown): PasskeyData | undefined {1819 if (!pk || typeof pk !== "object") return undefined;1820 const r = pk as Record<string, unknown>;1821 if (1822 typeof r.rpId !== "string" || !r.rpId ||1823 typeof r.credentialId !== "string" || !r.credentialId ||1824 typeof r.publicKeyCose !== "string" ||1825 typeof r.userHandle !== "string" ||1826 typeof r.userName !== "string"1827 ) {1828 return undefined;1829 }1830 return {1831 rpId: r.rpId,1832 rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,1833 credentialId: r.credentialId,1834 publicKeyCose: r.publicKeyCose,1835 privateKeyJwk:1836 r.privateKeyJwk && typeof r.privateKeyJwk === "object"1837 ? (r.privateKeyJwk as JsonWebKey)1838 : undefined,1839 userHandle: r.userHandle,1840 userName: r.userName,1841 userDisplayName:1842 typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,1843 algorithm: r.algorithm === -8 ? -8 : -7,1844 signCount: typeof r.signCount === "number" ? r.signCount : 0,1845 aaguid: typeof r.aaguid === "string" ? r.aaguid : "",1846 backupEligible: r.backupEligible === true,1847 backupState: r.backupState === true,1848 lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,1849 browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,1850 transports: Array.isArray(r.transports)1851 ? r.transports.filter((t): t is string => typeof t === "string")1852 : undefined,1853 createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),1854 };1855}18561857185818591860186118621863186418651866function sanitizeCanary(c: unknown): Canary | undefined {1867 if (!c || typeof c !== "object") return undefined;1868 const r = c as Record<string, unknown>;1869 if (typeof r.webhookUrl !== "string") return undefined;1870 let url: URL;1871 try {1872 url = new URL(r.webhookUrl);1873 } catch {1874 return undefined;1875 }1876 if (url.protocol !== "https:") return undefined;1877 return {1878 webhookUrl: url.toString(),1879 label: typeof r.label === "string" ? r.label : undefined,1880 lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,1881 pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,1882 };1883}18841885188618871888188918901891function sanitizeTags(tags: unknown): string[] | undefined {1892 if (!Array.isArray(tags)) return undefined;1893 const out: string[] = [];1894 for (const t of tags) {1895 if (typeof t !== "string") continue;1896 const trimmed = t.trim();1897 if (!trimmed) continue;1898 out.push(trimmed.slice(0, 256));1899 if (out.length >= 255) break;1900 }1901 return out.length > 0 ? out : undefined;1902}190319041905190619071908export async function clearVaultEntries(1909 confirmation: "REPLACE_ALL"1910): Promise<void> {1911 if (confirmation !== "REPLACE_ALL") {1912 throw new Error("clearVaultEntries requires explicit confirmation");1913 }1914 if (!derivedKey) throw new Error("vault_locked");1915 for (const entry of entries) {1916 if (!entry.deletedAt) {1917 const stamp = monotonicEntryTimestamp(entry.modifiedAt);1918 entry.deletedAt = stamp;1919 entry.modifiedAt = stamp;1920 }1921 }1922 await persistEntries();1923}19241925export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1926 if (!derivedKey) throw new Error("vault_locked");19271928 const sanitized = sanitizeEntryDraft(entry);1929 const now = Date.now();1930 const stamp = monotonicEntryTimestamp();1931 const nextEntry: VaultEntry = {1932 ...sanitized,1933 id: crypto.randomUUID(),1934 createdAt: now,1935 modifiedAt: stamp,1936 1937 1938 passwordChangedAt: sanitized.password ? stamp : undefined,1939 };19401941 1942 1943 1944 const rollback = entries;1945 entries = [...entries, nextEntry];1946 try {1947 await persistEntries();1948 } catch (err) {1949 entries = rollback;1950 throw err;1951 }19521953 1954 if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1955 checkBreach(nextEntry.password).then(async (count) => {1956 if (count > 0) {1957 const idx = entries.findIndex((e) => e.id === nextEntry.id);1958 if (idx !== -1) {1959 entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };1960 await persistEntries();1961 }1962 }1963 });1964 }19651966 fireSyncTrigger("vault_change");19671968 return nextEntry;1969}19701971197219731974197519761977export async function consolidatePasskeyEntries(): Promise<void> {1978 if (!derivedKey) return;1979 const { merged } = mergePasskeyOnlyIntoLogins(entries);1980 if (merged) {1981 await persistEntries();1982 }1983}19841985export async function updateEntry(1986 id: string,1987 patch: Partial<VaultEntry>1988): Promise<void> {1989 if (!derivedKey) throw new Error("vault_locked");19901991 const idx = entries.findIndex((entry) => entry.id === id);1992 if (idx === -1 || entries[idx].deletedAt) {1993 throw new Error("entry_not_found");1994 }19951996 const current = entries[idx];1997 const sanitizedPatch = sanitizeEntryPatch(patch);1998 1999 2000 2001 const passwordChanged =2002 "password" in patch &&2003 typeof sanitizedPatch.password === "string" &&2004 sanitizedPatch.password !== current.password;2005 const stamp = monotonicEntryTimestamp(current.modifiedAt);2006 2007 2008 2009 2010 2011 2012 2013 const priorPassword = current.password;2014 const shouldCapture =2015 passwordChanged &&2016 typeof priorPassword === "string" &&2017 priorPassword.length > 0 &&2018 current.passwordHistory?.[0]?.password !== priorPassword;2019 const nextHistory = shouldCapture2020 ? [2021 { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2022 ...(current.passwordHistory ?? []),2023 ].slice(0, PASSWORD_HISTORY_MAX)2024 : current.passwordHistory;2025 entries[idx] = {2026 ...current,2027 ...sanitizedPatch,2028 modifiedAt: stamp,2029 ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2030 };2031203220332034 2035 if (entries[idx].type === "card" && !entries[idx].cardNumber) {2036 entries[idx] = current;2037 throw new Error("card number is required for card entries");2038 }20392040 2041 2042 2043 2044 try {2045 await persistEntries();2046 } catch (err) {2047 entries[idx] = current;2048 throw err;2049 }20502051 2052 2053 if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2054 entries[idx] = { ...entries[idx], breach: undefined };2055 await persistEntries();2056 const password = entries[idx].password;2057 if (password) {2058 checkBreach(password).then(async (count) => {2059 const i = entries.findIndex((e) => e.id === id);2060 if (i !== -1 && count > 0) {2061 entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2062 await persistEntries();2063 }2064 });2065 }2066 }20672068 fireSyncTrigger("vault_change");2069}20702071export async function deleteEntry(id: string): Promise<void> {2072 if (!derivedKey) throw new Error("vault_locked");20732074 const entry = entries.find((item) => item.id === id);2075 if (!entry || entry.deletedAt) {2076 throw new Error("entry_not_found");2077 }20782079 2080 2081 2082 const previousModifiedAt = entry.modifiedAt;2083 const stamp = monotonicEntryTimestamp(entry.modifiedAt);2084 entry.deletedAt = stamp;2085 entry.modifiedAt = stamp;2086 2087 2088 try {2089 await persistEntries();2090 } catch (err) {2091 delete entry.deletedAt;2092 entry.modifiedAt = previousModifiedAt;2093 throw err;2094 }2095 fireSyncTrigger("vault_change");2096}20972098export function getDeletedEntries(): VaultEntry[] {2099 if (!derivedKey) return [];2100 return entries.filter((e) => !!e.deletedAt);2101}2102210321042105210621072108export async function getVaultVersion(): Promise<number> {2109 try {2110 const raw = await chrome.storage.local.get("peach_last_modified_at");2111 const v = (raw as Record<string, unknown>).peach_last_modified_at;2112 if (typeof v === "number") return v;2113 if (typeof v === "string" && v !== "") {2114 const n = Number.parseInt(v, 10);2115 return Number.isFinite(n) ? n : 0;2116 }2117 return 0;2118 } catch {2119 return 0;2120 }2121}212221232124212521262127212821292130213121322133export async function addEntryDirect(entry: VaultEntry): Promise<void> {2134 if (!derivedKey) throw new Error("vault_locked");2135 entries = [...entries, entry];2136 await persistEntries("sync_received");2137}21382139export async function updateEntryDirect(patch: VaultEntry): Promise<void> {2140 if (!derivedKey) throw new Error("vault_locked");2141 const idx = entries.findIndex((e) => e.id === patch.id);2142 if (idx === -1) throw new Error("entry_not_found");2143 entries[idx] = { ...entries[idx], ...patch };2144 await persistEntries("sync_received");2145}21462147export async function deleteEntryDirect(id: string, deletedAt: number): Promise<void> {2148 if (!derivedKey) throw new Error("vault_locked");2149 const idx = entries.findIndex((e) => e.id === id);2150 if (idx === -1) throw new Error("entry_not_found");2151 entries[idx] = { ...entries[idx], deletedAt, modifiedAt: deletedAt };2152 await persistEntries("sync_received");2153}2154215521562157215821592160216121622163216421652166export async function applyMergedRemoteEntries(2167 remoteEntries: VaultEntry[],2168 remoteTombstones: Record<string, number>,2169 _context: { deviceName?: string } = {},2170): Promise<{ received: number; applied: number; conflicts: number }> {2171 2172 2173 2174 2175 2176 2177 if (!derivedKey) throw new Error("vault_locked");21782179 const received = remoteEntries.length + Object.keys(remoteTombstones).length;2180 let applied = 0;2181 let conflicts = 0;21822183 const byId = new Map<string, VaultEntry>();2184 for (const e of entries) byId.set(e.id, e);21852186 const mergeNow = Date.now();21872188 for (const remote of remoteEntries) {2189 const sanitized = sanitizeRestoredEntry(remote);2190 if (!sanitized) continue;2191 2192 2193 2194 sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2195 if (typeof sanitized.deletedAt === "number") {2196 sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2197 }2198 const tombstoneTs = remoteTombstones[sanitized.id];2199 if (tombstoneTs !== undefined && clampSyncTimestamp(tombstoneTs, mergeNow) >= sanitized.modifiedAt) {2200 continue;2201 }2202 const local = byId.get(sanitized.id);2203 if (!local) {2204 entries.push(sanitized);2205 byId.set(sanitized.id, sanitized);2206 applied += 1;2207 } else if (sanitized.modifiedAt > local.modifiedAt) {2208 const idx = entries.findIndex((e) => e.id === local.id);2209 if (idx !== -1) {2210 entries[idx] = sanitized;2211 byId.set(sanitized.id, sanitized);2212 applied += 1;2213 if (!local.deletedAt) conflicts += 1;2214 }2215 }2216 }22172218 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2219 if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt)) continue;2220 2221 const deletedAt = clampSyncTimestamp(rawDeletedAt, mergeNow);2222 const local = byId.get(id);2223 if (!local) continue;2224 if (local.deletedAt && local.deletedAt >= deletedAt) continue;2225 if (deletedAt < local.modifiedAt) continue;2226 const idx = entries.findIndex((e) => e.id === id);2227 if (idx !== -1) {2228 entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2229 applied += 1;2230 }2231 }22322233 if (applied > 0) {2234 await persistEntries("sync_received");2235 buildDomainIndexSync(entries);2236 }2237 return { received, applied, conflicts };2238}22392240export async function restoreEntry(id: string): Promise<void> {2241 if (!derivedKey) throw new Error("vault_locked");2242 const entry = entries.find((e) => e.id === id && e.deletedAt);2243 if (!entry) throw new Error("deleted entry not found");2244 delete entry.deletedAt;2245 entry.modifiedAt = monotonicEntryTimestamp(entry.modifiedAt);2246 await persistEntries();2247 buildDomainIndexSync(entries);2248}22492250export async function purgeEntry(id: string): Promise<void> {2251 if (!derivedKey) throw new Error("vault_locked");2252 const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2253 if (idx === -1) throw new Error("deleted entry not found");2254 entries.splice(idx, 1);2255 await persistEntries();2256}225722582259export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2260 if (!derivedKey || retentionMs === 0) return 0;2261 const cutoff = Date.now() - retentionMs;2262 const before = entries.length;2263 entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2264 const purged = before - entries.length;2265 if (purged > 0) await persistEntries();2266 return purged;2267}22682269export function queryDomain(domain: string): VaultEntry[] {2270 return domainIndex.get(domain) ?? [];2271}22722273export function getEntryById(id: string): VaultEntry | undefined {2274 return entries.find((entry) => entry.id === id && !entry.deletedAt);2275}22762277async function persistSlotA(2278 reason: VaultSnapshot["reason"] = "local_save",2279): Promise<StoredVault> {2280 if (!derivedKey) throw new Error("vault_locked");22812282 const slotA = await loadSlot(SLOT_A);2283 if (!slotA) throw new Error("missing slot A");22842285 2286 2287 await takeVaultSnapshot(reason);22882289 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2290 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");22912292 2293 const nextSlotA: StoredVault = {2294 ...slotA,2295 nonce,2296 ciphertext,2297 tag,2298 2299 };2300 await writeSlot(SLOT_A, nextSlotA);23012302 2303 2304 2305 2306 2307 2308 try {2309 2310 2311 2312 if (!duressConfigured) {2313 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2314 }2315 2316 2317 2318 2319 2320 if (reason !== "sync_received") {2321 await stampLocalVaultMutation();2322 }2323 } catch (err) {2324 2325 2326 await writeSlot(SLOT_A, slotA).catch(() => {});2327 throw err;2328 }23292330 return nextSlotA;2331}23322333async function persistSlotB(): Promise<void> {2334 if (!derivedKey) throw new Error("vault_locked");23352336 const slotB = await loadSlot(SLOT_B);2337 if (!slotB) throw new Error("missing slot B");23382339 2340 2341 2342 2343 const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);2344 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");23452346 await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });2347 2348 2349 2350 try {2351 await stampLocalVaultMutation();2352 } catch (err) {2353 await writeSlot(SLOT_B, slotB).catch(() => {});2354 throw err;2355 }2356}23572358async function persistEntries(2359 reason: VaultSnapshot["reason"] = "local_save",2360): Promise<void> {2361 if (!derivedKey) throw new Error("vault_locked");23622363 if (vaultMode === "decoy") {2364 await persistSlotB();2365 } else {2366 await persistSlotA(reason);2367 }2368 buildDomainIndexSync(entries);2369}23702371function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {2372 if (!Array.isArray(values)) return undefined;2373 const seen = new Set<string>();2374 const cleaned: string[] = [];2375 for (const value of values) {2376 const trimmed = typeof value === "string" ? value.trim() : "";2377 if (!trimmed) continue;2378 const key = trimmed.toLowerCase();2379 if (seen.has(key)) continue;2380 seen.add(key);2381 cleaned.push(trimmed);2382 }2383 return cleaned.length > 0 ? cleaned : undefined;2384}23852386function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {2387 const title = entry.title.trim();2388 2389 2390 2391 let type: VaultEntry["type"] = entry.type ?? "login";2392 if (type === "passkey") type = "login";23932394 if (!title) throw new Error("title is required");23952396 if (entry.passkey) {2397 const p = entry.passkey;2398 if (2399 !p.rpId ||2400 !p.credentialId ||2401 !p.publicKeyCose ||2402 !p.userHandle ||2403 !p.userName ||2404 (p.algorithm !== -7 && p.algorithm !== -8)2405 ) {2406 throw new Error("invalid passkey credential");2407 }2408 }2409 if (type === "card") {2410 if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {2411 throw new Error("cardholder name and card number are required");2412 }2413 }24142415 return {2416 type,2417 title,2418 username: type === "login" ? entry.username?.trim() ?? "" : undefined,2419 email: type === "login" ? entry.email?.trim() || undefined : undefined,2420 password: type === "login" ? entry.password : undefined,2421 url: type === "login" ? entry.url?.trim() ?? "" : undefined,2422 additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,2423 totp: type === "login" ? entry.totp?.trim() || undefined : undefined,2424 2425 2426 totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,2427 totpDigits: type === "login" ? entry.totpDigits : undefined,2428 totpPeriod: type === "login" ? entry.totpPeriod : undefined,2429 notes: entry.notes?.trim() || undefined,2430 breach: type === "login" ? entry.breach : undefined,2431 2432 2433 canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,2434 tags: sanitizeTags(entry.tags),2435 passkey: entry.passkey,2436 cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,2437 cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,2438 expMonth: type === "card" ? entry.expMonth?.trim() : undefined,2439 expYear: type === "card" ? entry.expYear?.trim() : undefined,2440 cvc: type === "card" ? entry.cvc?.trim() : undefined,2441 cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,2442 network: type === "card" ? entry.network : undefined,2443 last4: type === "card" ? entry.last4?.trim() : undefined,2444 };2445}24462447function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2448 const nextPatch: Partial<VaultEntry> = {};24492450 if ("type" in patch) {2451 nextPatch.type = patch.type;2452 }24532454 if ("title" in patch) {2455 const title = patch.title?.trim() ?? "";2456 if (!title) throw new Error("title is required");2457 nextPatch.title = title;2458 }24592460 if ("url" in patch) {2461 nextPatch.url = patch.url?.trim() ?? "";2462 }24632464 if ("additionalUrls" in patch) {2465 const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2466 const seen = new Set<string>();2467 const cleaned: string[] = [];2468 for (const value of incoming) {2469 const trimmed = typeof value === "string" ? value.trim() : "";2470 if (!trimmed) continue;2471 const key = trimmed.toLowerCase();2472 if (seen.has(key)) continue;2473 seen.add(key);2474 cleaned.push(trimmed);2475 }2476 nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2477 }24782479 if ("username" in patch) {2480 nextPatch.username = patch.username?.trim() ?? "";2481 }24822483 if ("email" in patch) {2484 nextPatch.email = patch.email?.trim() || undefined;2485 }24862487 if ("password" in patch) {2488 const password = patch.password ?? "";2489 2490 nextPatch.password = password || undefined;2491 }24922493 if ("totp" in patch) {2494 nextPatch.totp = patch.totp?.trim() || undefined;2495 }24962497 if ("notes" in patch) {2498 nextPatch.notes = patch.notes?.trim() || undefined;2499 }25002501 if ("breach" in patch) {2502 nextPatch.breach = patch.breach;2503 }25042505 if ("canary" in patch) {2506 2507 2508 nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;2509 }25102511 if ("passkey" in patch) {2512 2513 2514 2515 if (patch.passkey === undefined || patch.passkey === null) {2516 nextPatch.passkey = undefined;2517 } else {2518 const sanitized = sanitizePasskey(patch.passkey);2519 if (!sanitized) throw new Error("invalid passkey credential");2520 nextPatch.passkey = sanitized;2521 }2522 }25232524 if ("tags" in patch) {2525 2526 nextPatch.tags = sanitizeTags(patch.tags);2527 }25282529 if ("cardholderName" in patch) {2530 nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2531 }2532 if ("cardNumber" in patch) {2533 const n = patch.cardNumber ?? "";2534 nextPatch.cardNumber = n || undefined;2535 }2536 if ("expMonth" in patch) {2537 nextPatch.expMonth = patch.expMonth?.trim() || undefined;2538 }2539 if ("expYear" in patch) {2540 nextPatch.expYear = patch.expYear?.trim() || undefined;2541 }2542 if ("cvc" in patch) {2543 nextPatch.cvc = patch.cvc?.trim() || undefined;2544 }2545 if ("cardNickname" in patch) {2546 nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2547 }2548 if ("network" in patch) {2549 nextPatch.network = patch.network;2550 }2551 if ("last4" in patch) {2552 nextPatch.last4 = patch.last4?.trim() || undefined;2553 }25542555 return nextPatch;2556}25572558function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2559 const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2560 const modifiedAt =2561 "modifiedAt" in entry ? entry.modifiedAt : entry.updated;25622563 const base: VaultEntry = {2564 id: entry.id,2565 type: "type" in entry ? entry.type : "login",2566 title: entry.title,2567 username: entry.username,2568 email: "email" in entry ? entry.email : undefined,2569 password: entry.password,2570 url: entry.url,2571 additionalUrls:2572 "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2573 ? entry.additionalUrls2574 : undefined,2575 totp: entry.totp,2576 2577 totpAlgorithm: entry.totpAlgorithm,2578 totpDigits: entry.totpDigits,2579 totpPeriod: entry.totpPeriod,2580 notes: entry.notes,2581 breach: entry.breach,2582 2583 2584 2585 passwordChangedAt:2586 "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2587 2588 2589 2590 passwordHistory:2591 "passwordHistory" in entry && Array.isArray(entry.passwordHistory)2592 ? entry.passwordHistory2593 : undefined,2594 canary: "canary" in entry ? entry.canary : undefined,2595 passkey: "passkey" in entry ? entry.passkey : undefined,2596 createdAt,2597 modifiedAt,2598 deletedAt: entry.deletedAt,2599 tags: "tags" in entry ? entry.tags : undefined,2600 cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2601 cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2602 expMonth: "expMonth" in entry ? entry.expMonth : undefined,2603 expYear: "expYear" in entry ? entry.expYear : undefined,2604 cvc: "cvc" in entry ? entry.cvc : undefined,2605 cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2606 network: "network" in entry ? entry.network : undefined,2607 last4: "last4" in entry ? entry.last4 : undefined,2608 };26092610 return migrateLegacyPasskey(base, entry);2611}261226132614261526162617261826192620function migrateLegacyPasskey(2621 base: VaultEntry,2622 raw: VaultEntry | LegacyVaultEntry2623): VaultEntry {2624 if (base.passkey) return base;2625 const flat = raw as Partial<VaultEntry>;2626 const isPasskeyType = base.type === "passkey";2627 const hasFlatPasskeyFields =2628 typeof flat.rpId === "string" &&2629 typeof flat.credentialId === "string" &&2630 typeof flat.publicKeyCose === "string" &&2631 typeof flat.userHandle === "string" &&2632 typeof flat.userName === "string";2633 if (!isPasskeyType && !hasFlatPasskeyFields) return base;2634 if (!hasFlatPasskeyFields) return base;26352636 const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2637 base.passkey = {2638 rpId: flat.rpId!,2639 rpName: flat.rpName ?? flat.rpId!,2640 credentialId: flat.credentialId!,2641 publicKeyCose: flat.publicKeyCose!,2642 privateKeyJwk: flat.privateKeyJwk,2643 userHandle: flat.userHandle!,2644 userName: flat.userName!,2645 userDisplayName: flat.userDisplayName ?? flat.userName!,2646 algorithm,2647 signCount: flat.signCount ?? 0,2648 aaguid: flat.aaguid ?? "",2649 backupEligible: flat.backupEligible === true,2650 backupState: flat.backupState === true,2651 lastUsedAt: flat.lastUsedAt,2652 browser: flat.browser,2653 transports: flat.transports,2654 createdAt: base.createdAt,2655 };2656 2657 2658 2659 if (isPasskeyType) base.type = "login";2660 if (!base.username) base.username = flat.userName;2661 if (!base.url) base.url = `https://${flat.rpId}`;2662 return base;2663}2664266526662667266826692670function entryDupeKey(e: VaultEntry): string {2671 if (e.type === "note") return `note|${e.title.toLowerCase()}`;2672 2673 2674 2675 2676 if (e.passkey) {2677 return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2678 }2679 return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2680}268126822683export function countDuplicates(): number {2684 const best = new Map<string, VaultEntry>();2685 let dupeCount = 0;2686 for (const e of entries.filter((e) => !e.deletedAt)) {2687 const key = entryDupeKey(e);2688 const existing = best.get(key);2689 if (!existing) {2690 best.set(key, e);2691 } else {2692 dupeCount++;2693 2694 if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2695 best.set(key, e);2696 }2697 }2698 }2699 return dupeCount;2700}270127022703270427052706export async function deduplicateEntries(): Promise<number> {2707 if (!derivedKey) throw new Error("vault_locked");2708 2709 2710 if (vaultMode === "decoy") {2711 throw new Error("deduplicate disabled in decoy mode");2712 }27132714 const best = new Map<string, VaultEntry>();2715 for (const e of entries.filter((en) => !en.deletedAt)) {2716 const key = entryDupeKey(e);2717 const existing = best.get(key);2718 if (!existing) {2719 best.set(key, e);2720 } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2721 best.set(key, e);2722 }2723 }27242725 const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2726 let removed = 0;2727 entries = entries.map((e) => {2728 if (!e.deletedAt && !keepIds.has(e.id)) {2729 removed++;2730 return { ...e, deletedAt: monotonicEntryTimestamp(e.modifiedAt) };2731 }2732 return e;2733 });27342735 if (removed > 0) await persistEntries();2736 return removed;2737}273827392740274127422743274427452746const HISTORY_KEY = "peach_vault_history";2747const HISTORY_MAX = 5;274827492750275127522753function bucketEntryCount(n: number): number {2754 if (n <= 0) return 0;2755 if (n <= 10) return 10;2756 if (n <= 25) return 25;2757 if (n <= 50) return 50;2758 if (n <= 100) return 100;2759 if (n <= 250) return 250;2760 if (n <= 500) return 500;2761 return Math.ceil(n / 500) * 500;2762}27632764276527662767276827692770export async function takeVaultSnapshot(2771 reason: VaultSnapshot["reason"],2772): Promise<void> {2773 try {2774 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2775 const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2776 const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];27772778 2779 2780 2781 if (!slotA) return;27822783 const vault_a = JSON.stringify(slotA);2784 const vault_b = JSON.stringify(slotB ?? slotA);27852786 2787 2788 2789 2790 2791 2792 let entryCount: number | null = null;2793 if (derivedKey && vaultMode === "real") {2794 try {2795 entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);2796 } catch {2797 entryCount = null;2798 }2799 }28002801 const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2802 const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2803 ? existingRaw2804 : { snapshots: [] };28052806 2807 2808 2809 const latest = history.snapshots[0];2810 if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {2811 return;2812 }28132814 const snapshot: VaultSnapshot = {2815 id: crypto.randomUUID(),2816 savedAt: Date.now(),2817 reason,2818 vault_a,2819 vault_b,2820 entryCount,2821 };28222823 history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);2824 await chrome.storage.local.set({ [HISTORY_KEY]: history });2825 } catch (err) {2826 2827 2828 2829 2830 console.warn('[Peach] takeVaultSnapshot failed:', err);2831 if (String(err).includes('QUOTA') || String(err).includes('quota')) {2832 try {2833 await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });2834 } catch {2835 2836 }2837 }2838 }2839}284028412842export async function clearVaultHistory(): Promise<void> {2843 try {2844 await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });2845 } catch {2846 2847 }2848}284928502851export async function getVaultHistory(): Promise<VaultSnapshot[]> {2852 const raw = await chrome.storage.local.get(HISTORY_KEY);2853 const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2854 if (!history || !Array.isArray(history.snapshots)) return [];2855 return history.snapshots;2856}28572858285928602861286228632864export async function restoreVaultSnapshot(2865 snapshotId: string,2866): Promise<{ ok: true } | { ok: false; error: string }> {2867 const history = await getVaultHistory();2868 const snapshot = history.find((s) => s.id === snapshotId);2869 if (!snapshot) return { ok: false, error: "snapshot_not_found" };28702871 2872 2873 2874 await takeVaultSnapshot("restore");28752876 let restoredA: StoredVault;2877 let restoredB: StoredVault;2878 try {2879 restoredA = JSON.parse(snapshot.vault_a) as StoredVault;2880 restoredB = JSON.parse(snapshot.vault_b) as StoredVault;2881 } catch {2882 return { ok: false, error: "snapshot_corrupt" };2883 }28842885 await writeSlot(SLOT_A, restoredA);2886 await writeSlot(SLOT_B, restoredB);2887 await stampLocalVaultMutation();28882889 2890 2891 2892 lock();28932894 return { ok: true };2895}289628972898289929002901290229032904290529062907290829092910export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {2911 if (!derivedKey || vaultMode !== "real") {2912 return { ok: false, error: "vault_locked" };2913 }2914 const slotA = await loadSlot(SLOT_A);2915 if (!slotA) return { ok: false, error: "missing_slot_a" };29162917 2918 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =2919 await generateAndWrapRootKey();29202921 2922 const newRootKey = unhex(rawRootKey);2923 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);29242925 2926 2927 2928 2929 await takeVaultSnapshot("local_save");2930 const nextSlotA: StoredVault = {2931 ...slotA,2932 recovery_salt: recoverySalt,2933 recovery_wrapped_root_key: wrappedRootKey,2934 recovery_nonce: wrappedNonce,2935 recovery_tag: wrappedTag,2936 ...pwRoot,2937 };2938 await writeSlot(SLOT_A, nextSlotA);29392940 2941 if (rootKey) zeroKey(rootKey);2942 rootKey = newRootKey;29432944 2945 await clearPairedDevices();29462947 2948 await setRecoveryConfirmPending(); 29492950 await stampLocalVaultMutation();2951 return { ok: true };2952}29532954295529562957295829592960export async function changePassword(2961 currentPassword: string,2962 newPassword: string2963): Promise<boolean> {2964 if (!derivedKey || vaultMode !== "real") return false;29652966 2967 const valid = await verifyMainPassword(currentPassword);2968 if (!valid) return false;29692970 const slotA = await loadSlot(SLOT_A);2971 if (!slotA) return false;2972 if (!rootKey) return false;29732974 2975 const newSalt = generateSalt();2976 const newKey = await deriveKey(newPassword, newSalt);29772978 2979 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2980 const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");29812982 2983 2984 2985 const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);29862987 const finalSlotA: StoredVault = {2988 ...slotA,2989 salt: hex(newSalt),2990 nonce,2991 ciphertext,2992 tag,2993 ...pwRoot,2994 };29952996 2997 2998 2999 await takeVaultSnapshot("local_save");30003001 3002 3003 3004 3005 await writeSlot(SLOT_A, finalSlotA);30063007 3008 3009 3010 zeroKey(derivedKey);3011 derivedKey = newKey;30123013 3014 3015 3016 3017 void saveSessionKey(newKey, "real");30183019 3020 3021 3022 if (!duressConfigured) {3023 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3024 }3025 await stampLocalVaultMutation();30263027 return true;3028}