123456789101112import { deriveKey, deriveKeyRaw, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import { clampSyncTimestamp } from "../shared/sync-limits";15import { computeVaultId } from "../shared/sync-identity";16import { recordSyncAlerts, type SyncAlert } from "./sync-alerts";17import {18 rootKeyToWords,19 wordsToRootKeyMaterial,20 deriveRecoveryKey,21} from "../shared/recovery-words";22import type {23 AccentColorName,24 Canary,25 LegacyVaultEntry,26 ManualSummonRecord,27 PasskeyData,28 SavedIdentity,29 StoredVault,30 VaultEntry,31 VaultHistory,32 VaultSnapshot,33} from "../shared/types";34import { decrypt, encrypt, zeroKey } from "./aes";35import { clearAutoLock, touchAutoLock } from "./alarms";36import { setRecoveryConfirmPending } from "./recovery-pending";3738type EntryDraft = Omit<39 VaultEntry,40 "id" | "createdAt" | "modifiedAt" | "deletedAt"41>;424344454647const SLOT_A = "peach_vault_a";48const SLOT_B = "peach_vault_b";495051const LEGACY_MAIN = "peach_vault";52const LEGACY_DECOY = "peach_decoy_vault";53const LEGACY_DURESS_FLAG = "peach_duress";54555657const PAD_BLOCK = 1024;5859606162const PASSWORD_HISTORY_MAX = 50;6364656667686970717273const DURESS_SLOT_SIZE = 262_144;7475let derivedKey: Uint8Array | null = null;7677787980let rootKey: Uint8Array | null = null;81let entries: VaultEntry[] = [];82let domainIndex: Map<string, VaultEntry[]> = new Map();83let vaultMode: "real" | "decoy" = "real";84858687let duressConfigured = false;8889let migrationRan = false;90919293949596979899100let lastUnlockFailureReason: string | null = null;101102export function consumeLastUnlockFailureReason(): string | null {103 const r = lastUnlockFailureReason;104 lastUnlockFailureReason = null;105 return r;106}107108109110111112export type TextSize = "small" | "medium" | "large";113114export interface VaultSettings {115 accentColor?: AccentColorName;116 theme?: "dark" | "light";117 autoLockMinutes?: number;118 clipboardClearSeconds?: number;119 lockOnClose?: boolean;120 breachMonitoring?: boolean;121 passkeyProviderEnabled?: boolean;122 trashRetentionDays?: number;123 manualSummonDomains?: Record<string, ManualSummonRecord>;124 declinedCardFingerprints?: string[];125 126127128129130 textSize?: TextSize;131 132133134135136 reduceMotion?: boolean;137 138139140141142 biometricsEnabled?: boolean;143 144145146147148149150 shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;151}152153let settings: VaultSettings = {};154155export function getSettings(): VaultSettings {156 return settings;157}158159export async function ensureSettingsLoaded(): Promise<VaultSettings> {160 await loadSettings();161 return settings;162}163164export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {165 await loadSettings();166 167 168 169 170 const safe = Object.fromEntries(171 Object.entries(patch).filter(172 ([k]) => !["__proto__", "constructor", "prototype"].includes(k),173 ),174 ) as Partial<VaultSettings>;175 settings = { ...settings, ...safe };176 await persistSettings();177}178179async function persistSettings(): Promise<void> {180 try {181 await chrome.storage.local.set({ peach_settings: settings });182 } catch (err) {183 throw mapStorageError(err);184 }185}186187function mapStorageError(err: unknown): Error {188 const message = err instanceof Error ? err.message : String(err);189 if (/QUOTA_BYTES|quota/i.test(message)) {190 return new Error("STORAGE_QUOTA_EXCEEDED");191 }192 return err instanceof Error ? err : new Error(message);193}194195async function loadSettings(): Promise<void> {196 const result = await chrome.storage.local.get("peach_settings");197 settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};198}199200201202203204205function fireSyncTrigger(reason: "vault_change"): void {206 void import("./sync-trigger")207 .then((mod) => mod.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}617618async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {619 const raw = await chrome.storage.local.get("peach_last_modified_at");620 const previous = Number(621 (raw as Record<string, unknown>).peach_last_modified_at,622 );623 const next = Math.max(624 Date.now(),625 Number.isFinite(previous) ? previous + 1 : 0,626 );627 try {628 await chrome.storage.local.set({629 [SLOT_A]: slotA,630 [SLOT_B]: slotB,631 peach_last_modified_at: String(next),632 });633 } catch (err) {634 throw mapStorageError(err);635 }636}637638639640641642643644645let lastEntryTimestamp = 0;646function monotonicEntryTimestamp(currentModifiedAt?: number): number {647 const base = Math.max(648 Date.now(),649 (currentModifiedAt ?? 0) + 1,650 lastEntryTimestamp + 1,651 );652 lastEntryTimestamp = base;653 return base;654}655656async function stampLocalVaultMutation(): Promise<void> {657 const raw = await chrome.storage.local.get("peach_last_modified_at");658 const previous = Number(659 (raw as Record<string, unknown>).peach_last_modified_at,660 );661 const next = Math.max(662 Date.now(),663 Number.isFinite(previous) ? previous + 1 : 0,664 );665 await chrome.storage.local.set({666 peach_last_modified_at: String(next),667 });668}669670671672673674675async function ensureMigrated(): Promise<void> {676 if (migrationRan) return;677 migrationRan = true;678679 const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];680 const raw = await chrome.storage.local.get(keys);681 const slotAExists = raw[SLOT_A] !== undefined;682 const slotBExists = raw[SLOT_B] !== undefined;683 const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;684 const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;685686 687 if (!slotAExists && !legacyMain) return;688689 690 if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;691692 let didMigrate = false;693 if (legacyMain && !slotAExists) {694 await writeSlot(SLOT_A, legacyMain);695 didMigrate = true;696 }697698 699 if (!slotBExists) {700 const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;701 if (legacyDecoy) {702 await writeSlot(SLOT_B, legacyDecoy);703 didMigrate = true;704 } else if (target) {705 await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));706 didMigrate = true;707 }708 }709710 const toRemove: string[] = [];711 if (legacyMain) toRemove.push(LEGACY_MAIN);712 if (legacyDecoy) toRemove.push(LEGACY_DECOY);713 if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);714 if (toRemove.length > 0) {715 await chrome.storage.local.remove(toRemove);716 didMigrate = true;717 }718 if (didMigrate) {719 await stampLocalVaultMutation();720 }721}722723724725726727728729730731732733function padPlaintext(json: string, minBytes = 0): string {734 const encoded = new TextEncoder().encode(json);735 const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);736 737 const target = Math.max(bucket, minBytes);738 const padLen = target - encoded.length;739 return json + " ".repeat(padLen);740}741742743744745746747748749750751752const CSPRNG_CHUNK = 65_536;753754function fillRandom(buf: Uint8Array): Uint8Array {755 for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {756 const end = Math.min(offset + CSPRNG_CHUNK, buf.length);757 const chunk = new Uint8Array(end - offset);758 crypto.getRandomValues(chunk);759 buf.set(chunk, offset);760 }761 return buf;762}763764function generateNoiseBlob(ciphertextBytes: number): StoredVault {765 const salt = crypto.getRandomValues(new Uint8Array(16));766 const nonce = crypto.getRandomValues(new Uint8Array(12));767 const cipher = fillRandom(new Uint8Array(ciphertextBytes));768 const tag = crypto.getRandomValues(new Uint8Array(16));769 return {770 version: 1,771 salt: hex(salt),772 nonce: hex(nonce),773 ciphertext: hex(cipher),774 tag: hex(tag),775 };776}777778779780781782type VaultPayload = {783 entries: VaultEntry[];784 duressConfigured?: boolean;785};786787type DecryptedPayload = {788 entries: VaultEntry[];789 duressConfigured: boolean;790 791792793794795796797 migratedFromLegacy: boolean;798};799800function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {801 const envelope: VaultPayload = { entries, duressConfigured: duress };802 return padPlaintext(JSON.stringify(envelope), minBytes);803}804805function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {806 if ("created" in raw || "updated" in raw) return true;807 const flat = raw as Partial<VaultEntry>;808 if (flat.type === "passkey") return true;809 810 if (flat.rpId !== undefined && flat.passkey === undefined) return true;811 return false;812}813814function decodePayload(plain: string): DecryptedPayload {815 const parsed = JSON.parse(plain) as816 | Array<VaultEntry | LegacyVaultEntry>817 | VaultPayload;818819 const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];820 const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);821822 const normalized = rawEntries.map(normalizeEntry);823 const { merged } = mergePasskeyOnlyIntoLogins(normalized);824825 if (Array.isArray(parsed)) {826 return {827 entries: normalized,828 duressConfigured: false,829 migratedFromLegacy: true, 830 };831 }832833 return {834 entries: normalized,835 duressConfigured: parsed.duressConfigured === true,836 migratedFromLegacy: flatMigrationNeeded || merged,837 };838}839840841842843844845846847848849850851852853854855856857858859860861862863function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {864 let merged = false;865 const now = Date.now();866867 const candidates = entries.filter((e) => !e.deletedAt && e.passkey);868 const byRpId = new Map<string, VaultEntry[]>();869 for (const e of candidates) {870 const rpId = e.passkey!.rpId;871 const list = byRpId.get(rpId);872 if (list) list.push(e);873 else byRpId.set(rpId, [e]);874 }875876 for (const [rpId, group] of byRpId) {877 if (group.length === 0) continue;878 group.sort((a, b) => {879 const aT =880 a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;881 const bT =882 b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;883 return bT - aT;884 });885 const winner = group[0]!;886887 888 889 890 const loginTarget = entries.find((e) => {891 if (e.deletedAt || e.passkey || e.type !== "login") return false;892 if (e.url && extractDomain(e.url) === rpId) return true;893 for (const extra of e.additionalUrls ?? []) {894 if (extractDomain(extra) === rpId) return true;895 }896 return false;897 });898899 if (loginTarget) {900 loginTarget.passkey = winner.passkey;901 loginTarget.modifiedAt = now;902 for (const dup of group) {903 if (!dup.deletedAt) {904 dup.deletedAt = now;905 dup.modifiedAt = now;906 }907 }908 merged = true;909 } else if (group.length > 1) {910 for (let i = 1; i < group.length; i += 1) {911 const dup = group[i]!;912 if (!dup.deletedAt) {913 dup.deletedAt = now;914 dup.modifiedAt = now;915 }916 }917 merged = true;918 }919 }920921 return { merged };922}923924925926927928929930function hasValidVaultSchema(v: unknown): v is StoredVault {931 if (typeof v !== "object" || v === null) return false;932 const r = v as Record<string, unknown>;933 return (934 r.version === 1 &&935 typeof r.salt === "string" &&936 typeof r.nonce === "string" &&937 typeof r.ciphertext === "string" &&938 typeof r.tag === "string"939 );940}941942export type TryDecryptResult =943 | { status: "ok"; payload: DecryptedPayload }944 | { status: "wrong_key" }945 | { status: "corrupted"; reason: string };946947948949950951952export async function tryDecryptSlot(953 vault: StoredVault,954 key: Uint8Array,955 aadTag?: string,956): Promise<DecryptedPayload | null> {957 const res = await tryDecryptSlotResult(vault, key, aadTag);958 return res.status === "ok" ? res.payload : null;959}960961export async function tryDecryptSlotResult(962 vault: StoredVault,963 key: Uint8Array,964 aadTag?: string,965): Promise<TryDecryptResult> {966 if (!hasValidVaultSchema(vault)) {967 return { status: "corrupted", reason: "invalid_slot_schema" };968 }969 let plain: string;970 try {971 plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);972 } catch {973 return { status: "wrong_key" };974 }975 try {976 const parsed = JSON.parse(plain) as unknown;977 if (typeof parsed !== "object" || parsed === null) {978 return { status: "corrupted", reason: "invalid_payload_shape" };979 }980 if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {981 return { status: "corrupted", reason: "invalid_payload_shape" };982 }983 return { status: "ok", payload: decodePayload(plain) };984 } catch {985 return { status: "corrupted", reason: "invalid_payload_json" };986 }987}988989990991992993function buildDomainIndexSync(all: VaultEntry[]): void {994 domainIndex = new Map();995996 for (const entry of all) {997 if (entry.deletedAt) continue;998 if (entry.type === "note" || entry.type === "card") continue;9991000 1001 1002 1003 1004 const domains = new Set<string>();1005 const primary = extractDomain(entry.url ?? "");1006 if (primary) domains.add(primary);1007 for (const extra of entry.additionalUrls ?? []) {1008 const d = extractDomain(extra);1009 if (d) domains.add(d);1010 }1011 if (domains.size === 0) continue;10121013 for (const domain of domains) {1014 const bucket = domainIndex.get(domain) ?? [];1015 bucket.push(entry);1016 domainIndex.set(domain, bucket);1017 }1018 }1019}10201021export async function createVault(password: string): Promise<void> {1022 await ensureMigrated();10231024 const salt = generateSalt();1025 derivedKey = await deriveKey(password, salt);1026 entries = [];1027 vaultMode = "real";1028 duressConfigured = false;1029 buildDomainIndexSync(entries);10301031 1032 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =1033 await generateAndWrapRootKey();1034 rootKey = unhex(rawRootKey);10351036 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1037 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");10381039 1040 1041 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);10421043 const slotA: StoredVault = {1044 version: 1,1045 salt: hex(salt),1046 nonce,1047 ciphertext,1048 tag,1049 recovery_salt: recoverySalt,1050 recovery_wrapped_root_key: wrappedRootKey,1051 recovery_nonce: wrappedNonce,1052 recovery_tag: wrappedTag,1053 ...pwRoot,1054 };1055 await writeSlot(SLOT_A, slotA);10561057 1058 1059 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1060 await stampLocalVaultMutation();10611062 touchAutoLock();1063}1064106510661067106810691070export async function createVaultFromRootKey(1071 password: string,1072 rootKeyHex: string,1073): Promise<{ vaultId: string }> {1074 if (typeof password !== "string" || password.length === 0) {1075 throw new Error("ADOPT_INVALID_PASSWORD");1076 }1077 if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1078 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1079 }10801081 const rootKeyBytes = unhex(rootKeyHex);1082 if (rootKeyBytes.length !== 32) {1083 rootKeyBytes.fill(0);1084 throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1085 }10861087 let nextDerivedKey: Uint8Array | null = null;1088 let sessionRootKey: Uint8Array | null = null;1089 try {1090 await ensureMigrated();10911092 const nextEntries: VaultEntry[] = [];1093 const nextDuressConfigured = false;1094 const vaultId = await computeVaultId(rootKeyBytes);1095 const salt = generateSalt();1096 nextDerivedKey = await deriveKey(password, salt);1097 const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);10981099 sessionRootKey = new Uint8Array(rootKeyBytes);1100 const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1101 const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1102 const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1103 const slotA: StoredVault = {1104 version: 1,1105 salt: hex(salt),1106 nonce,1107 ciphertext,1108 tag,1109 recovery_salt: recovery.recoverySalt,1110 recovery_wrapped_root_key: recovery.wrappedRootKey,1111 recovery_nonce: recovery.wrappedNonce,1112 recovery_tag: recovery.wrappedTag,1113 ...pwRoot,1114 };1115 const slotB = generateNoiseBlob(ciphertext.length / 2);1116 await commitCreatedVaultSlots(slotA, slotB);11171118 const previousDerivedKey = derivedKey;1119 const previousRootKey = rootKey;1120 derivedKey = nextDerivedKey;1121 rootKey = sessionRootKey;1122 nextDerivedKey = null;1123 sessionRootKey = null;1124 entries = nextEntries;1125 vaultMode = "real";1126 duressConfigured = nextDuressConfigured;1127 buildDomainIndexSync(entries);1128 if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1129 if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1130 touchAutoLock();11311132 return { vaultId };1133 } finally {1134 rootKeyBytes.fill(0);1135 if (nextDerivedKey) zeroKey(nextDerivedKey);1136 if (sessionRootKey) sessionRootKey.fill(0);1137 }1138}11391140export async function hasVault(): Promise<boolean> {1141 await ensureMigrated();1142 return (await loadSlot(SLOT_A)) !== null;1143}1144114511461147114811491150export async function isDuressEnabled(): Promise<boolean> {1151 return vaultMode === "real" && duressConfigured;1152}11531154export async function setupDuress(duressPassword: string): Promise<void> {1155 if (!derivedKey || vaultMode !== "real") {1156 throw new Error("vault must be unlocked in real mode");1157 }1158 await ensureMigrated();11591160 1161 1162 1163 const slotA = await loadSlot(SLOT_A);1164 if (!slotA) throw new Error("missing slot A");11651166 const decoySalt = generateSalt();1167 const decoyKey = await deriveKey(duressPassword, decoySalt);1168 try {1169 1170 1171 1172 1173 const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1174 const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1175 await writeSlot(SLOT_B, {1176 version: 1,1177 salt: hex(decoySalt),1178 nonce,1179 ciphertext,1180 tag,1181 });1182 } finally {1183 zeroKey(decoyKey);1184 }11851186 1187 1188 duressConfigured = true;1189 await persistSlotA();1190}11911192export async function disableDuress(): Promise<void> {1193 if (!derivedKey || vaultMode !== "real") {1194 throw new Error("vault must be unlocked in real mode");1195 }1196 await ensureMigrated();11971198 1199 1200 1201 const slotA = await loadSlot(SLOT_A);1202 if (slotA) {1203 await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1204 }12051206 duressConfigured = false;1207 await persistSlotA();1208}12091210121112121213121412151216export async function verifyMainPassword(password: string): Promise<boolean> {1217 await ensureMigrated();1218 const slotA = await loadSlot(SLOT_A);1219 if (!slotA) return false;1220 const key = await deriveKey(password, unhex(slotA.salt));1221 try {1222 return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1223 } finally {1224 zeroKey(key);1225 }1226}12271228export async function unlock(password: string): Promise<boolean> {1229 1230 1231 1232 if (await attemptUnlockWithDerive(password, deriveKey)) return true;12331234 const nfc = password.normalize("NFC");1235 if (password === nfc) return false; 12361237 if (await attemptUnlockWithDerive(password, deriveKeyRaw)) {1238 1239 1240 1241 if (vaultMode === "real") {1242 try {1243 const newSalt = generateSalt();1244 const newKey = await deriveKey(password, newSalt);1245 await changePasswordWithNewKey(newSalt, newKey);1246 } catch (healErr) {1247 console.warn("[Peach] LV-1 NFC heal failed:", healErr);1248 }1249 }1250 return true;1251 }1252 return false;1253}12541255async function attemptUnlockWithDerive(1256 password: string,1257 derive: typeof deriveKey,1258): Promise<boolean> {1259 await ensureMigrated();12601261 1262 1263 1264 1265 1266 const [slotA, slotB] = await Promise.all([1267 loadSlot(SLOT_A),1268 loadSlot(SLOT_B),1269 ]);12701271 1272 const [keyA, keyB] = await Promise.all([1273 slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1274 slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1275 ]);12761277 1278 1279 1280 const [resultA, resultB] = await Promise.all([1281 keyA && slotA1282 ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1283 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1284 keyB && slotB1285 ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1286 : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1287 ]);1288 const payloadA = resultA.status === "ok" ? resultA.payload : null;1289 const payloadB = resultB.status === "ok" ? resultB.payload : null;12901291 if (payloadA && keyA) {1292 derivedKey = keyA;1293 void saveSessionKey(keyA, "real");1294 vaultMode = "real";1295 entries = payloadA.entries;1296 duressConfigured = payloadA.duressConfigured;1297 buildDomainIndexSync(entries);1298 await loadSettings();1299 touchAutoLock();1300 if (keyB) zeroKey(keyB);13011302 1303 if (slotA) {1304 const needsRecoverySetup =1305 !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1306 if (!needsRecoverySetup) {1307 rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1308 }1309 1310 1311 1312 1313 if (needsRecoverySetup || !rootKey) {1314 try {1315 await migrateToRecovery();1316 if (needsRecoverySetup) {1317 1318 1319 1320 await chrome.storage.local.set({ peach_recovery_pending: '1' });1321 }1322 } catch (migrationErr) {1323 console.warn('[Peach] recovery migration failed:', migrationErr);1324 }1325 }1326 }13271328 1329 1330 1331 if (payloadA.migratedFromLegacy) {1332 await persistSlotA();1333 }1334 return true;1335 }13361337 if (payloadB && keyB) {1338 derivedKey = keyB;1339 void saveSessionKey(keyB, "decoy");1340 vaultMode = "decoy";1341 entries = payloadB.entries;1342 duressConfigured = false;1343 buildDomainIndexSync(entries);1344 await loadSettings();1345 touchAutoLock();1346 if (keyA) zeroKey(keyA);1347 return true;1348 }13491350 if (keyA) zeroKey(keyA);1351 if (keyB) zeroKey(keyB);1352 1353 1354 if (resultA.status === "corrupted") {1355 lastUnlockFailureReason = resultA.reason;1356 } else if (resultB.status === "corrupted") {1357 lastUnlockFailureReason = resultB.reason;1358 }1359 return false;1360}13611362136313641365136613671368const SESSION_KEY_STORAGE = "peach_session_dk";13691370async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1371 if (!chrome.storage.session) return;1372 await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1373}13741375async function clearSessionKey(): Promise<void> {1376 if (!chrome.storage.session) return;1377 await chrome.storage.session.remove(SESSION_KEY_STORAGE);1378}13791380138113821383138413851386export async function restoreFromSession(): Promise<boolean> {1387 if (derivedKey !== null) return true;1388 if (!chrome.storage.session) return false;1389 const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1390 const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1391 if (!entry?.keyHex) return false;13921393 const key = unhex(entry.keyHex);1394 const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1395 const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1396 const slot = await loadSlot(slotKey);1397 if (!slot) { await clearSessionKey(); return false; }13981399 const result = await tryDecryptSlotResult(slot, key, aadTag);1400 if (result.status !== "ok") { await clearSessionKey(); return false; }14011402 derivedKey = key;1403 vaultMode = entry.mode;1404 entries = result.payload.entries;1405 duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1406 buildDomainIndexSync(entries);1407 await loadSettings();1408 touchAutoLock();14091410 if (entry.mode === "real" && slot.recovery_salt && slot.recovery_wrapped_root_key) {1411 try { rootKey = await deriveRootKeyFromDerivedKey(key, slot); } catch { }1412 }14131414 return true;1415}14161417export function lock(): void {1418 void clearSessionKey();1419 if (derivedKey) {1420 zeroKey(derivedKey);1421 derivedKey = null;1422 }1423 if (rootKey) {1424 rootKey.fill(0);1425 rootKey = null;1426 }14271428 entries = [];1429 domainIndex = new Map();1430 vaultMode = "real";1431 duressConfigured = false;1432 clearAutoLock();1433}14341435export function isUnlocked(): boolean {1436 return derivedKey !== null;1437}1438143914401441export async function unlockWithKey(1442 masterKeyHex: string,1443): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1444 try {1445 const masterKeyBytes = unhex(masterKeyHex);1446 const stored = await loadSlot(SLOT_A);1447 if (!stored) return { ok: false, error: "invalid_key" };1448 const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1449 if (!payload) return { ok: false, error: "invalid_key" };14501451 derivedKey = masterKeyBytes;1452 vaultMode = "real";1453 entries = payload.entries;1454 duressConfigured = payload.duressConfigured;1455 buildDomainIndexSync(entries);1456 await loadSettings();1457 touchAutoLock();14581459 1460 1461 1462 1463 1464 if (stored.recovery_salt && stored.recovery_wrapped_root_key) {1465 try {1466 rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);1467 } catch { }1468 }1469 return { ok: true, entries };1470 } catch {1471 return { ok: false, error: "invalid_key" };1472 }1473}14741475147614771478147914801481148214831484148514861487148814891490149114921493export async function unlockFromCodex(params: {1494 slotA: string; 1495 slotB: string | null; 1496 timestamp: number;1497 masterPassphrase: string;1498}): Promise<1499 | { ok: true; entryCount: number }1500 | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1501> {1502 let parsedSlotA: StoredVault;1503 let parsedSlotB: StoredVault | null = null;1504 try {1505 const rawA = JSON.parse(params.slotA) as unknown;1506 if (!hasValidVaultSchema(rawA)) {1507 return { ok: false, reason: "invalid_slot_format" };1508 }1509 parsedSlotA = rawA;1510 if (params.slotB !== null) {1511 const rawB = JSON.parse(params.slotB) as unknown;1512 if (!hasValidVaultSchema(rawB)) {1513 return { ok: false, reason: "invalid_slot_format" };1514 }1515 parsedSlotB = rawB;1516 }1517 } catch {1518 return { ok: false, reason: "invalid_slot_format" };1519 }15201521 1522 1523 const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1524 const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1525 if (!trialPayload) {1526 zeroKey(trialKey);1527 return { ok: false, reason: "wrong_passphrase" };1528 }1529 1530 1531 zeroKey(trialKey);15321533 1534 1535 await takeVaultSnapshot("restore");15361537 await writeSlot(SLOT_A, parsedSlotA);1538 if (parsedSlotB) {1539 await writeSlot(SLOT_B, parsedSlotB);1540 } else {1541 1542 1543 1544 await writeSlot(1545 SLOT_B,1546 generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1547 );1548 }1549 await chrome.storage.local.set({1550 peach_last_modified_at: String(params.timestamp),1551 });15521553 1554 1555 const ok = await unlock(params.masterPassphrase);1556 if (!ok) {1557 1558 1559 1560 return { ok: false, reason: "wrong_passphrase" };1561 }1562 return { ok: true, entryCount: getEntries().length };1563}1564156515661567export function getDerivedKeyHex(): string {1568 if (!derivedKey) throw new Error("vault_not_unlocked");1569 return hex(derivedKey);1570}15711572157315741575157615771578157915801581158215831584158515861587export function getRootKeyHex(): string | null {1588 return rootKey ? hex(rootKey) : null;1589}15901591export function getEntries(): VaultEntry[] {1592 if (!derivedKey) throw new Error("vault_locked");1593 return entries.filter((entry) => !entry.deletedAt);1594}15951596const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;15971598export function getIdentities(): SavedIdentity[] {1599 if (!derivedKey) throw new Error("vault_locked");1600 const active = entries.filter((e) => !e.deletedAt && e.type === "login");16011602 const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1603 const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();16041605 for (const entry of active) {1606 const domain = extractDomain(entry.url ?? "") ?? "";1607 const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;16081609 function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1610 const existing = map.get(v);1611 if (!existing || modifiedAt > existing.lastUsed) {1612 map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1613 } else {1614 map.set(v, { ...existing, count: existing.count + 1 });1615 }1616 }16171618 const uVal = entry.username?.trim();1619 if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);16201621 1622 1623 const eVal = entry.email?.trim();1624 if (eVal) tally(emailMap, eVal);1625 }16261627 const toIdentity = (type: "email" | "username") =>1628 ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1629 value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1630 });16311632 return [1633 ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1634 ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1635 ];1636}16371638export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1639 if (!derivedKey) throw new Error("vault_locked");16401641 const now = Date.now();1642 const added: VaultEntry[] = [];1643 for (const draft of drafts) {1644 try {1645 const sanitized = sanitizeEntryDraft(draft);1646 const nextEntry: VaultEntry = {1647 ...sanitized,1648 id: crypto.randomUUID(),1649 createdAt: now,1650 modifiedAt: monotonicEntryTimestamp(),1651 };1652 entries.push(nextEntry);1653 added.push(nextEntry);1654 } catch {1655 1656 }1657 }16581659 if (added.length > 0) {1660 await persistEntries();1661 }16621663 return added;1664}166516661667166816691670167116721673export async function restoreEntries(1674 incoming: VaultEntry[],1675 mode: "replace" | "merge"1676): Promise<{ added: number; updated: number; skipped: number }> {1677 if (!derivedKey) throw new Error("vault_locked");16781679 1680 1681 1682 if (mode === "replace" && incoming.length === 0) {1683 throw new Error("refuse to replace with empty entry set");1684 }16851686 let added = 0;1687 let updated = 0;1688 let skipped = 0;16891690 if (mode === "replace") {1691 entries = [];1692 for (const entry of incoming) {1693 const normalized = sanitizeRestoredEntry(entry);1694 if (!normalized) {1695 skipped += 1;1696 continue;1697 }1698 entries.push(normalized);1699 added += 1;1700 }1701 } else {1702 const byId = new Map<string, VaultEntry>();1703 for (const e of entries) byId.set(e.id, e);17041705 for (const entry of incoming) {1706 const normalized = sanitizeRestoredEntry(entry);1707 if (!normalized) {1708 skipped += 1;1709 continue;1710 }1711 const existing = byId.get(normalized.id);1712 if (!existing) {1713 entries.push(normalized);1714 added += 1;1715 } else if (normalized.modifiedAt > existing.modifiedAt) {1716 const idx = entries.findIndex((e) => e.id === existing.id);1717 if (idx !== -1) {1718 entries[idx] = normalized;1719 updated += 1;1720 }1721 } else {1722 skipped += 1;1723 }1724 }1725 }17261727 await persistEntries("import");1728 return { added, updated, skipped };1729}173017311732173317341735173617371738function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1739 if (!entry || typeof entry !== "object") return null;1740 const title = typeof entry.title === "string" ? entry.title.trim() : "";1741 if (!title) return null;1742 const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1743 const now = Date.now();1744 const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1745 const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;17461747 1748 1749 1750 1751 const normalized = normalizeEntry({1752 ...entry,1753 id,1754 title,1755 type: entry.type ?? "login",1756 createdAt,1757 modifiedAt,1758 });17591760 if (normalized.passkey) {1761 normalized.passkey = sanitizePasskey(normalized.passkey);1762 }1763 if (normalized.canary) {1764 normalized.canary = sanitizeCanary(normalized.canary);1765 }1766 1767 normalized.tags = sanitizeTags(normalized.tags);17681769 1770 1771 if (1772 normalized.type === "login" &&1773 !normalized.passkey &&1774 typeof normalized.password !== "string"1775 ) {1776 return null;1777 }1778 if (entry.passkey && !normalized.passkey) {1779 1780 1781 return null;1782 }17831784 return normalized;1785}1786178717881789179017911792function sanitizePasskey(pk: unknown): PasskeyData | undefined {1793 if (!pk || typeof pk !== "object") return undefined;1794 const r = pk as Record<string, unknown>;1795 if (1796 typeof r.rpId !== "string" || !r.rpId ||1797 typeof r.credentialId !== "string" || !r.credentialId ||1798 typeof r.publicKeyCose !== "string" ||1799 typeof r.userHandle !== "string" ||1800 typeof r.userName !== "string"1801 ) {1802 return undefined;1803 }1804 return {1805 rpId: r.rpId,1806 rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,1807 credentialId: r.credentialId,1808 publicKeyCose: r.publicKeyCose,1809 privateKeyJwk:1810 r.privateKeyJwk && typeof r.privateKeyJwk === "object"1811 ? (r.privateKeyJwk as JsonWebKey)1812 : undefined,1813 userHandle: r.userHandle,1814 userName: r.userName,1815 userDisplayName:1816 typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,1817 algorithm: r.algorithm === -8 ? -8 : -7,1818 signCount: typeof r.signCount === "number" ? r.signCount : 0,1819 aaguid: typeof r.aaguid === "string" ? r.aaguid : "",1820 backupEligible: r.backupEligible === true,1821 backupState: r.backupState === true,1822 lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,1823 browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,1824 transports: Array.isArray(r.transports)1825 ? r.transports.filter((t): t is string => typeof t === "string")1826 : undefined,1827 createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),1828 };1829}18301831183218331834183518361837183818391840function sanitizeCanary(c: unknown): Canary | undefined {1841 if (!c || typeof c !== "object") return undefined;1842 const r = c as Record<string, unknown>;1843 if (typeof r.webhookUrl !== "string") return undefined;1844 let url: URL;1845 try {1846 url = new URL(r.webhookUrl);1847 } catch {1848 return undefined;1849 }1850 if (url.protocol !== "https:") return undefined;1851 return {1852 webhookUrl: url.toString(),1853 label: typeof r.label === "string" ? r.label : undefined,1854 lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,1855 pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,1856 };1857}18581859186018611862186318641865function sanitizeTags(tags: unknown): string[] | undefined {1866 if (!Array.isArray(tags)) return undefined;1867 const out: string[] = [];1868 for (const t of tags) {1869 if (typeof t !== "string") continue;1870 const trimmed = t.trim();1871 if (!trimmed) continue;1872 out.push(trimmed.slice(0, 256));1873 if (out.length >= 255) break;1874 }1875 return out.length > 0 ? out : undefined;1876}187718781879188018811882export async function clearVaultEntries(1883 confirmation: "REPLACE_ALL"1884): Promise<void> {1885 if (confirmation !== "REPLACE_ALL") {1886 throw new Error("clearVaultEntries requires explicit confirmation");1887 }1888 if (!derivedKey) throw new Error("vault_locked");1889 for (const entry of entries) {1890 if (!entry.deletedAt) {1891 const stamp = monotonicEntryTimestamp(entry.modifiedAt);1892 entry.deletedAt = stamp;1893 entry.modifiedAt = stamp;1894 }1895 }1896 await persistEntries();1897}18981899export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1900 if (!derivedKey) throw new Error("vault_locked");19011902 const sanitized = sanitizeEntryDraft(entry);1903 const now = Date.now();1904 const stamp = monotonicEntryTimestamp();1905 const nextEntry: VaultEntry = {1906 ...sanitized,1907 id: crypto.randomUUID(),1908 createdAt: now,1909 modifiedAt: stamp,1910 1911 1912 passwordChangedAt: sanitized.password ? stamp : undefined,1913 };19141915 1916 1917 1918 const rollback = entries;1919 entries = [...entries, nextEntry];1920 try {1921 await persistEntries();1922 } catch (err) {1923 entries = rollback;1924 throw err;1925 }19261927 1928 if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1929 checkBreach(nextEntry.password).then(async (count) => {1930 if (count > 0) {1931 const idx = entries.findIndex((e) => e.id === nextEntry.id);1932 if (idx !== -1) {1933 entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };1934 await persistEntries();1935 }1936 }1937 });1938 }19391940 fireSyncTrigger("vault_change");19411942 return nextEntry;1943}19441945194619471948194919501951export async function consolidatePasskeyEntries(): Promise<void> {1952 if (!derivedKey) return;1953 const { merged } = mergePasskeyOnlyIntoLogins(entries);1954 if (merged) {1955 await persistEntries();1956 }1957}19581959export async function updateEntry(1960 id: string,1961 patch: Partial<VaultEntry>1962): Promise<void> {1963 if (!derivedKey) throw new Error("vault_locked");19641965 const idx = entries.findIndex((entry) => entry.id === id);1966 if (idx === -1 || entries[idx].deletedAt) {1967 throw new Error("entry_not_found");1968 }19691970 const current = entries[idx];1971 const sanitizedPatch = sanitizeEntryPatch(patch);1972 1973 1974 1975 const passwordChanged =1976 "password" in patch &&1977 typeof sanitizedPatch.password === "string" &&1978 sanitizedPatch.password !== current.password;1979 const stamp = monotonicEntryTimestamp(current.modifiedAt);1980 1981 1982 1983 1984 1985 1986 1987 const priorPassword = current.password;1988 const shouldCapture =1989 passwordChanged &&1990 typeof priorPassword === "string" &&1991 priorPassword.length > 0 &&1992 current.passwordHistory?.[0]?.password !== priorPassword;1993 const nextHistory = shouldCapture1994 ? [1995 { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },1996 ...(current.passwordHistory ?? []),1997 ].slice(0, PASSWORD_HISTORY_MAX)1998 : current.passwordHistory;1999 entries[idx] = {2000 ...current,2001 ...sanitizedPatch,2002 modifiedAt: stamp,2003 ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2004 };2005200620072008 2009 if (entries[idx].type === "card" && !entries[idx].cardNumber) {2010 entries[idx] = current;2011 throw new Error("card number is required for card entries");2012 }20132014 2015 2016 2017 2018 try {2019 await persistEntries();2020 } catch (err) {2021 entries[idx] = current;2022 throw err;2023 }20242025 2026 2027 if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2028 entries[idx] = { ...entries[idx], breach: undefined };2029 await persistEntries();2030 const password = entries[idx].password;2031 if (password) {2032 checkBreach(password).then(async (count) => {2033 const i = entries.findIndex((e) => e.id === id);2034 if (i !== -1 && count > 0) {2035 entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2036 await persistEntries();2037 }2038 });2039 }2040 }20412042 fireSyncTrigger("vault_change");2043}20442045export async function deleteEntry(id: string): Promise<void> {2046 if (!derivedKey) throw new Error("vault_locked");20472048 const entry = entries.find((item) => item.id === id);2049 if (!entry || entry.deletedAt) {2050 throw new Error("entry_not_found");2051 }20522053 2054 2055 2056 const previousModifiedAt = entry.modifiedAt;2057 const stamp = monotonicEntryTimestamp(entry.modifiedAt);2058 entry.deletedAt = stamp;2059 entry.modifiedAt = stamp;2060 2061 2062 try {2063 await persistEntries();2064 } catch (err) {2065 delete entry.deletedAt;2066 entry.modifiedAt = previousModifiedAt;2067 throw err;2068 }2069 fireSyncTrigger("vault_change");2070}20712072export function getDeletedEntries(): VaultEntry[] {2073 if (!derivedKey) return [];2074 return entries.filter((e) => !!e.deletedAt);2075}2076207720782079208020812082export async function getVaultVersion(): Promise<number> {2083 try {2084 const raw = await chrome.storage.local.get("peach_last_modified_at");2085 const v = (raw as Record<string, unknown>).peach_last_modified_at;2086 if (typeof v === "number") return v;2087 if (typeof v === "string" && v !== "") {2088 const n = Number.parseInt(v, 10);2089 return Number.isFinite(n) ? n : 0;2090 }2091 return 0;2092 } catch {2093 return 0;2094 }2095}209620972098209921002101210221032104210521062107export async function addEntryDirect(entry: VaultEntry): Promise<void> {2108 if (!derivedKey) throw new Error("vault_locked");2109 entries = [...entries, entry];2110 await persistEntries("sync_received");2111}21122113export async function updateEntryDirect(patch: VaultEntry): Promise<void> {2114 if (!derivedKey) throw new Error("vault_locked");2115 const idx = entries.findIndex((e) => e.id === patch.id);2116 if (idx === -1) throw new Error("entry_not_found");2117 entries[idx] = { ...entries[idx], ...patch };2118 await persistEntries("sync_received");2119}21202121export async function deleteEntryDirect(id: string, deletedAt: number): Promise<void> {2122 if (!derivedKey) throw new Error("vault_locked");2123 const idx = entries.findIndex((e) => e.id === id);2124 if (idx === -1) throw new Error("entry_not_found");2125 entries[idx] = { ...entries[idx], deletedAt, modifiedAt: deletedAt };2126 await persistEntries("sync_received");2127}2128212921302131213221332134213521362137213821392140export async function applyMergedRemoteEntries(2141 remoteEntries: VaultEntry[],2142 remoteTombstones: Record<string, number>,2143 context: { deviceName?: string } = {},2144): Promise<{ received: number; applied: number; conflicts: number }> {2145 2146 2147 2148 2149 2150 2151 if (!derivedKey) throw new Error("vault_locked");21522153 const received = remoteEntries.length + Object.keys(remoteTombstones).length;2154 let applied = 0;2155 let conflicts = 0;21562157 const byId = new Map<string, VaultEntry>();2158 for (const e of entries) byId.set(e.id, e);21592160 const alerts: SyncAlert[] = [];2161 const deviceName = context.deviceName ?? "paired device";2162 const mergeNow = Date.now();21632164 for (const remote of remoteEntries) {2165 const sanitized = sanitizeRestoredEntry(remote);2166 if (!sanitized) continue;2167 2168 2169 2170 sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2171 if (typeof sanitized.deletedAt === "number") {2172 sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2173 }2174 const tombstoneTs = remoteTombstones[sanitized.id];2175 if (tombstoneTs !== undefined && clampSyncTimestamp(tombstoneTs, mergeNow) >= sanitized.modifiedAt) {2176 continue;2177 }2178 const local = byId.get(sanitized.id);2179 if (!local) {2180 entries.push(sanitized);2181 byId.set(sanitized.id, sanitized);2182 applied += 1;2183 } else if (sanitized.modifiedAt > local.modifiedAt) {2184 const idx = entries.findIndex((e) => e.id === local.id);2185 if (idx !== -1) {2186 2187 2188 if (2189 !local.deletedAt &&2190 typeof sanitized.password === "string" &&2191 typeof local.password === "string" &&2192 sanitized.password !== local.password2193 ) {2194 alerts.push({2195 type: "REMOTE_PASSWORD_CHANGE",2196 entryId: sanitized.id,2197 entryTitle: sanitized.title,2198 deviceName,2199 timestamp: mergeNow,2200 });2201 }2202 entries[idx] = sanitized;2203 byId.set(sanitized.id, sanitized);2204 applied += 1;2205 if (!local.deletedAt) conflicts += 1;2206 }2207 }2208 }22092210 for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2211 if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt)) continue;2212 2213 const deletedAt = clampSyncTimestamp(rawDeletedAt, mergeNow);2214 const local = byId.get(id);2215 if (!local) continue;2216 if (local.deletedAt && local.deletedAt >= deletedAt) continue;2217 if (deletedAt < local.modifiedAt) continue;2218 const idx = entries.findIndex((e) => e.id === id);2219 if (idx !== -1) {2220 2221 if (!local.deletedAt) {2222 alerts.push({2223 type: "REMOTE_DELETE",2224 entryId: id,2225 entryTitle: local.title,2226 deviceName,2227 timestamp: mergeNow,2228 });2229 }2230 entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2231 applied += 1;2232 }2233 }22342235 if (applied > 0) {2236 await persistEntries("sync_received");2237 buildDomainIndexSync(entries);2238 }2239 2240 2241 await recordSyncAlerts(alerts);2242 return { received, applied, conflicts };2243}22442245export async function restoreEntry(id: string): Promise<void> {2246 if (!derivedKey) throw new Error("vault_locked");2247 const entry = entries.find((e) => e.id === id && e.deletedAt);2248 if (!entry) throw new Error("deleted entry not found");2249 delete entry.deletedAt;2250 entry.modifiedAt = monotonicEntryTimestamp(entry.modifiedAt);2251 await persistEntries();2252 buildDomainIndexSync(entries);2253}22542255export async function purgeEntry(id: string): Promise<void> {2256 if (!derivedKey) throw new Error("vault_locked");2257 const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2258 if (idx === -1) throw new Error("deleted entry not found");2259 entries.splice(idx, 1);2260 await persistEntries();2261}226222632264export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2265 if (!derivedKey || retentionMs === 0) return 0;2266 const cutoff = Date.now() - retentionMs;2267 const before = entries.length;2268 entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2269 const purged = before - entries.length;2270 if (purged > 0) await persistEntries();2271 return purged;2272}22732274export function queryDomain(domain: string): VaultEntry[] {2275 return domainIndex.get(domain) ?? [];2276}22772278export function getEntryById(id: string): VaultEntry | undefined {2279 return entries.find((entry) => entry.id === id && !entry.deletedAt);2280}22812282async function persistSlotA(2283 reason: VaultSnapshot["reason"] = "local_save",2284): Promise<StoredVault> {2285 if (!derivedKey) throw new Error("vault_locked");22862287 const slotA = await loadSlot(SLOT_A);2288 if (!slotA) throw new Error("missing slot A");22892290 2291 2292 await takeVaultSnapshot(reason);22932294 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2295 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");22962297 2298 const nextSlotA: StoredVault = {2299 ...slotA,2300 nonce,2301 ciphertext,2302 tag,2303 2304 };2305 await writeSlot(SLOT_A, nextSlotA);23062307 2308 2309 2310 2311 2312 2313 try {2314 2315 2316 2317 if (!duressConfigured) {2318 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2319 }2320 2321 2322 2323 2324 2325 if (reason !== "sync_received") {2326 await stampLocalVaultMutation();2327 }2328 } catch (err) {2329 2330 2331 await writeSlot(SLOT_A, slotA).catch(() => {});2332 throw err;2333 }23342335 return nextSlotA;2336}23372338async function persistSlotB(): Promise<void> {2339 if (!derivedKey) throw new Error("vault_locked");23402341 const slotB = await loadSlot(SLOT_B);2342 if (!slotB) throw new Error("missing slot B");23432344 2345 2346 2347 2348 const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);2349 const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");23502351 await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });2352 2353 2354 2355 try {2356 await stampLocalVaultMutation();2357 } catch (err) {2358 await writeSlot(SLOT_B, slotB).catch(() => {});2359 throw err;2360 }2361}23622363async function persistEntries(2364 reason: VaultSnapshot["reason"] = "local_save",2365): Promise<void> {2366 if (!derivedKey) throw new Error("vault_locked");23672368 if (vaultMode === "decoy") {2369 await persistSlotB();2370 } else {2371 await persistSlotA(reason);2372 }2373 buildDomainIndexSync(entries);2374}23752376function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {2377 if (!Array.isArray(values)) return undefined;2378 const seen = new Set<string>();2379 const cleaned: string[] = [];2380 for (const value of values) {2381 const trimmed = typeof value === "string" ? value.trim() : "";2382 if (!trimmed) continue;2383 const key = trimmed.toLowerCase();2384 if (seen.has(key)) continue;2385 seen.add(key);2386 cleaned.push(trimmed);2387 }2388 return cleaned.length > 0 ? cleaned : undefined;2389}23902391function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {2392 const title = entry.title.trim();2393 2394 2395 2396 let type: VaultEntry["type"] = entry.type ?? "login";2397 if (type === "passkey") type = "login";23982399 if (!title) throw new Error("title is required");24002401 if (entry.passkey) {2402 const p = entry.passkey;2403 if (2404 !p.rpId ||2405 !p.credentialId ||2406 !p.publicKeyCose ||2407 !p.userHandle ||2408 !p.userName ||2409 (p.algorithm !== -7 && p.algorithm !== -8)2410 ) {2411 throw new Error("invalid passkey credential");2412 }2413 }2414 if (type === "card") {2415 if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {2416 throw new Error("cardholder name and card number are required");2417 }2418 }24192420 return {2421 type,2422 title,2423 username: type === "login" ? entry.username?.trim() ?? "" : undefined,2424 email: type === "login" ? entry.email?.trim() || undefined : undefined,2425 password: type === "login" ? entry.password : undefined,2426 url: type === "login" ? entry.url?.trim() ?? "" : undefined,2427 additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,2428 totp: type === "login" ? entry.totp?.trim() || undefined : undefined,2429 2430 2431 totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,2432 totpDigits: type === "login" ? entry.totpDigits : undefined,2433 totpPeriod: type === "login" ? entry.totpPeriod : undefined,2434 notes: entry.notes?.trim() || undefined,2435 breach: type === "login" ? entry.breach : undefined,2436 2437 2438 canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,2439 tags: sanitizeTags(entry.tags),2440 passkey: entry.passkey,2441 cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,2442 cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,2443 expMonth: type === "card" ? entry.expMonth?.trim() : undefined,2444 expYear: type === "card" ? entry.expYear?.trim() : undefined,2445 cvc: type === "card" ? entry.cvc?.trim() : undefined,2446 cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,2447 network: type === "card" ? entry.network : undefined,2448 last4: type === "card" ? entry.last4?.trim() : undefined,2449 };2450}24512452function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2453 const nextPatch: Partial<VaultEntry> = {};24542455 if ("type" in patch) {2456 nextPatch.type = patch.type;2457 }24582459 if ("title" in patch) {2460 const title = patch.title?.trim() ?? "";2461 if (!title) throw new Error("title is required");2462 nextPatch.title = title;2463 }24642465 if ("url" in patch) {2466 nextPatch.url = patch.url?.trim() ?? "";2467 }24682469 if ("additionalUrls" in patch) {2470 const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2471 const seen = new Set<string>();2472 const cleaned: string[] = [];2473 for (const value of incoming) {2474 const trimmed = typeof value === "string" ? value.trim() : "";2475 if (!trimmed) continue;2476 const key = trimmed.toLowerCase();2477 if (seen.has(key)) continue;2478 seen.add(key);2479 cleaned.push(trimmed);2480 }2481 nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2482 }24832484 if ("username" in patch) {2485 nextPatch.username = patch.username?.trim() ?? "";2486 }24872488 if ("email" in patch) {2489 nextPatch.email = patch.email?.trim() || undefined;2490 }24912492 if ("password" in patch) {2493 const password = patch.password ?? "";2494 2495 nextPatch.password = password || undefined;2496 }24972498 if ("totp" in patch) {2499 nextPatch.totp = patch.totp?.trim() || undefined;2500 }25012502 if ("notes" in patch) {2503 nextPatch.notes = patch.notes?.trim() || undefined;2504 }25052506 if ("breach" in patch) {2507 nextPatch.breach = patch.breach;2508 }25092510 if ("canary" in patch) {2511 2512 2513 nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;2514 }25152516 if ("passkey" in patch) {2517 2518 2519 2520 if (patch.passkey === undefined || patch.passkey === null) {2521 nextPatch.passkey = undefined;2522 } else {2523 const sanitized = sanitizePasskey(patch.passkey);2524 if (!sanitized) throw new Error("invalid passkey credential");2525 nextPatch.passkey = sanitized;2526 }2527 }25282529 if ("tags" in patch) {2530 2531 nextPatch.tags = sanitizeTags(patch.tags);2532 }25332534 if ("cardholderName" in patch) {2535 nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2536 }2537 if ("cardNumber" in patch) {2538 const n = patch.cardNumber ?? "";2539 nextPatch.cardNumber = n || undefined;2540 }2541 if ("expMonth" in patch) {2542 nextPatch.expMonth = patch.expMonth?.trim() || undefined;2543 }2544 if ("expYear" in patch) {2545 nextPatch.expYear = patch.expYear?.trim() || undefined;2546 }2547 if ("cvc" in patch) {2548 nextPatch.cvc = patch.cvc?.trim() || undefined;2549 }2550 if ("cardNickname" in patch) {2551 nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2552 }2553 if ("network" in patch) {2554 nextPatch.network = patch.network;2555 }2556 if ("last4" in patch) {2557 nextPatch.last4 = patch.last4?.trim() || undefined;2558 }25592560 return nextPatch;2561}25622563function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2564 const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2565 const modifiedAt =2566 "modifiedAt" in entry ? entry.modifiedAt : entry.updated;25672568 const base: VaultEntry = {2569 id: entry.id,2570 type: "type" in entry ? entry.type : "login",2571 title: entry.title,2572 username: entry.username,2573 email: "email" in entry ? entry.email : undefined,2574 password: entry.password,2575 url: entry.url,2576 additionalUrls:2577 "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2578 ? entry.additionalUrls2579 : undefined,2580 totp: entry.totp,2581 2582 totpAlgorithm: entry.totpAlgorithm,2583 totpDigits: entry.totpDigits,2584 totpPeriod: entry.totpPeriod,2585 notes: entry.notes,2586 breach: entry.breach,2587 2588 2589 2590 passwordChangedAt:2591 "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2592 2593 2594 2595 passwordHistory:2596 "passwordHistory" in entry && Array.isArray(entry.passwordHistory)2597 ? entry.passwordHistory2598 : undefined,2599 canary: "canary" in entry ? entry.canary : undefined,2600 passkey: "passkey" in entry ? entry.passkey : undefined,2601 createdAt,2602 modifiedAt,2603 deletedAt: entry.deletedAt,2604 tags: "tags" in entry ? entry.tags : undefined,2605 cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2606 cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2607 expMonth: "expMonth" in entry ? entry.expMonth : undefined,2608 expYear: "expYear" in entry ? entry.expYear : undefined,2609 cvc: "cvc" in entry ? entry.cvc : undefined,2610 cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2611 network: "network" in entry ? entry.network : undefined,2612 last4: "last4" in entry ? entry.last4 : undefined,2613 };26142615 return migrateLegacyPasskey(base, entry);2616}261726182619262026212622262326242625function migrateLegacyPasskey(2626 base: VaultEntry,2627 raw: VaultEntry | LegacyVaultEntry2628): VaultEntry {2629 if (base.passkey) return base;2630 const flat = raw as Partial<VaultEntry>;2631 const isPasskeyType = base.type === "passkey";2632 const hasFlatPasskeyFields =2633 typeof flat.rpId === "string" &&2634 typeof flat.credentialId === "string" &&2635 typeof flat.publicKeyCose === "string" &&2636 typeof flat.userHandle === "string" &&2637 typeof flat.userName === "string";2638 if (!isPasskeyType && !hasFlatPasskeyFields) return base;2639 if (!hasFlatPasskeyFields) return base;26402641 const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2642 base.passkey = {2643 rpId: flat.rpId!,2644 rpName: flat.rpName ?? flat.rpId!,2645 credentialId: flat.credentialId!,2646 publicKeyCose: flat.publicKeyCose!,2647 privateKeyJwk: flat.privateKeyJwk,2648 userHandle: flat.userHandle!,2649 userName: flat.userName!,2650 userDisplayName: flat.userDisplayName ?? flat.userName!,2651 algorithm,2652 signCount: flat.signCount ?? 0,2653 aaguid: flat.aaguid ?? "",2654 backupEligible: flat.backupEligible === true,2655 backupState: flat.backupState === true,2656 lastUsedAt: flat.lastUsedAt,2657 browser: flat.browser,2658 transports: flat.transports,2659 createdAt: base.createdAt,2660 };2661 2662 2663 2664 if (isPasskeyType) base.type = "login";2665 if (!base.username) base.username = flat.userName;2666 if (!base.url) base.url = `https://${flat.rpId}`;2667 return base;2668}2669267026712672267326742675function entryDupeKey(e: VaultEntry): string {2676 if (e.type === "note") return `note|${e.title.toLowerCase()}`;2677 2678 2679 2680 2681 if (e.passkey) {2682 return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2683 }2684 return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2685}268626872688export function countDuplicates(): number {2689 const best = new Map<string, VaultEntry>();2690 let dupeCount = 0;2691 for (const e of entries.filter((e) => !e.deletedAt)) {2692 const key = entryDupeKey(e);2693 const existing = best.get(key);2694 if (!existing) {2695 best.set(key, e);2696 } else {2697 dupeCount++;2698 2699 if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2700 best.set(key, e);2701 }2702 }2703 }2704 return dupeCount;2705}270627072708270927102711export async function deduplicateEntries(): Promise<number> {2712 if (!derivedKey) throw new Error("vault_locked");2713 2714 2715 if (vaultMode === "decoy") {2716 throw new Error("deduplicate disabled in decoy mode");2717 }27182719 const best = new Map<string, VaultEntry>();2720 for (const e of entries.filter((en) => !en.deletedAt)) {2721 const key = entryDupeKey(e);2722 const existing = best.get(key);2723 if (!existing) {2724 best.set(key, e);2725 } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2726 best.set(key, e);2727 }2728 }27292730 const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2731 let removed = 0;2732 entries = entries.map((e) => {2733 if (!e.deletedAt && !keepIds.has(e.id)) {2734 removed++;2735 return { ...e, deletedAt: monotonicEntryTimestamp(e.modifiedAt) };2736 }2737 return e;2738 });27392740 if (removed > 0) await persistEntries();2741 return removed;2742}274327442745274627472748274927502751const HISTORY_KEY = "peach_vault_history";2752const HISTORY_MAX = 5;275327542755275627572758function bucketEntryCount(n: number): number {2759 if (n <= 0) return 0;2760 if (n <= 10) return 10;2761 if (n <= 25) return 25;2762 if (n <= 50) return 50;2763 if (n <= 100) return 100;2764 if (n <= 250) return 250;2765 if (n <= 500) return 500;2766 return Math.ceil(n / 500) * 500;2767}27682769277027712772277327742775export async function takeVaultSnapshot(2776 reason: VaultSnapshot["reason"],2777): Promise<void> {2778 try {2779 const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2780 const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2781 const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];27822783 2784 2785 2786 if (!slotA) return;27872788 const vault_a = JSON.stringify(slotA);2789 const vault_b = JSON.stringify(slotB ?? slotA);27902791 2792 2793 2794 2795 2796 2797 let entryCount: number | null = null;2798 if (derivedKey && vaultMode === "real") {2799 try {2800 entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);2801 } catch {2802 entryCount = null;2803 }2804 }28052806 const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2807 const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2808 ? existingRaw2809 : { snapshots: [] };28102811 2812 2813 2814 const latest = history.snapshots[0];2815 if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {2816 return;2817 }28182819 const snapshot: VaultSnapshot = {2820 id: crypto.randomUUID(),2821 savedAt: Date.now(),2822 reason,2823 vault_a,2824 vault_b,2825 entryCount,2826 };28272828 history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);2829 await chrome.storage.local.set({ [HISTORY_KEY]: history });2830 } catch (err) {2831 2832 2833 2834 2835 console.warn('[Peach] takeVaultSnapshot failed:', err);2836 if (String(err).includes('QUOTA') || String(err).includes('quota')) {2837 try {2838 await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });2839 } catch {2840 2841 }2842 }2843 }2844}284528462847export async function clearVaultHistory(): Promise<void> {2848 try {2849 await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });2850 } catch {2851 2852 }2853}285428552856export async function getVaultHistory(): Promise<VaultSnapshot[]> {2857 const raw = await chrome.storage.local.get(HISTORY_KEY);2858 const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2859 if (!history || !Array.isArray(history.snapshots)) return [];2860 return history.snapshots;2861}28622863286428652866286728682869export async function restoreVaultSnapshot(2870 snapshotId: string,2871): Promise<{ ok: true } | { ok: false; error: string }> {2872 const history = await getVaultHistory();2873 const snapshot = history.find((s) => s.id === snapshotId);2874 if (!snapshot) return { ok: false, error: "snapshot_not_found" };28752876 2877 2878 2879 await takeVaultSnapshot("restore");28802881 let restoredA: StoredVault;2882 let restoredB: StoredVault;2883 try {2884 restoredA = JSON.parse(snapshot.vault_a) as StoredVault;2885 restoredB = JSON.parse(snapshot.vault_b) as StoredVault;2886 } catch {2887 return { ok: false, error: "snapshot_corrupt" };2888 }28892890 await writeSlot(SLOT_A, restoredA);2891 await writeSlot(SLOT_B, restoredB);2892 await stampLocalVaultMutation();28932894 2895 2896 2897 lock();28982899 return { ok: true };2900}290129022903290429052906290729082909291029112912291329142915export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {2916 if (!derivedKey || vaultMode !== "real") {2917 return { ok: false, error: "vault_locked" };2918 }2919 const slotA = await loadSlot(SLOT_A);2920 if (!slotA) return { ok: false, error: "missing_slot_a" };29212922 2923 const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =2924 await generateAndWrapRootKey();29252926 2927 const newRootKey = unhex(rawRootKey);2928 const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);29292930 2931 2932 2933 2934 await takeVaultSnapshot("local_save");2935 const nextSlotA: StoredVault = {2936 ...slotA,2937 recovery_salt: recoverySalt,2938 recovery_wrapped_root_key: wrappedRootKey,2939 recovery_nonce: wrappedNonce,2940 recovery_tag: wrappedTag,2941 ...pwRoot,2942 };2943 await writeSlot(SLOT_A, nextSlotA);29442945 2946 if (rootKey) zeroKey(rootKey);2947 rootKey = newRootKey;29482949 2950 const { clearPairedDevices } = await import("./paired-devices");2951 await clearPairedDevices();29522953 2954 await setRecoveryConfirmPending(); 29552956 await stampLocalVaultMutation();2957 return { ok: true };2958}29592960296129622963296429652966export async function changePassword(2967 currentPassword: string,2968 newPassword: string2969): Promise<boolean> {2970 if (!derivedKey || vaultMode !== "real") return false;29712972 2973 const valid = await verifyMainPassword(currentPassword);2974 if (!valid) return false;29752976 const slotA = await loadSlot(SLOT_A);2977 if (!slotA) return false;2978 if (!rootKey) return false;29792980 2981 const newSalt = generateSalt();2982 const newKey = await deriveKey(newPassword, newSalt);29832984 2985 const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2986 const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");29872988 2989 2990 2991 const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);29922993 const finalSlotA: StoredVault = {2994 ...slotA,2995 salt: hex(newSalt),2996 nonce,2997 ciphertext,2998 tag,2999 ...pwRoot,3000 };30013002 3003 3004 3005 await takeVaultSnapshot("local_save");30063007 3008 3009 3010 3011 await writeSlot(SLOT_A, finalSlotA);30123013 3014 3015 3016 zeroKey(derivedKey);3017 derivedKey = newKey;30183019 3020 3021 3022 3023 void saveSessionKey(newKey, "real");30243025 3026 3027 3028 if (!duressConfigured) {3029 await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3030 }3031 await stampLocalVaultMutation();30323033 return true;3034}