12345678910111213141516171819202122232425import { HKDF } from "@stablelib/hkdf";26import { SHA256 } from "@stablelib/sha256";27import type { SyncVaultAdapter } from "./sync-coordinator";28import { getDeviceName, getOrCreateDeviceId } from "./device-identity";29import {30 computeVaultId,31 deriveSyncIdentityKeypair,32 deriveSyncSigningKeypair,33 hexToPubkey,34 pubkeyToHex,35} from "../shared/sync-identity";36import {37 buildSignedDeviceManifest,38 verifyDeviceManifest,39} from "../shared/device-manifest";40import { constantTimeEqualHex } from "../shared/constant-time";41import {42 applyMergedRemoteEntries,43 getTombstoneManifest,44 getRootKeyHex,45 getEntries,46 getEntryById,47 getVaultVersion,48 isUnlocked,49} from "./vault";50import {51 findPairedDeviceById,52 findPairedDeviceByPubkey,53 isDeviceRevoked,54 listDeviceRevocations,55 listPairedDevices,56 mergeDeviceRevocations,57 removePairedDeviceById,58 upsertPairedDevice,59} from "./paired-devices";60import {61 removePendingVouchedDevice,62} from "./pending-vouched-devices";63import {64 bytesToHex as rendezvousBytesToHex,65 deriveMeshRendezvousSecret,66 normalizeRelayUrl,67} from "../shared/rendezvous";68import { recordSyncAlerts } from "./sync-alerts";69import { SYNC_LIMITS, clampSyncTimestamp } from "../shared/sync-limits";70import type { VaultEntry } from "../shared/types";71import type {72 ManifestDeviceEntry,73 PairedDevice,74 SignedDeviceManifest,75} from "../shared/sync-types";76import { replaceLockedSyncSpool, drainLockedSyncInbox } from "./locked-sync-spool";77787980const ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1";81const ENTRY_AAD = "peach-sync-entry-v1";8283export class VaultLockedError extends Error {84 constructor() {85 super("vault_locked");86 this.name = "VaultLockedError";87 }88}8990export function createSyncVaultAdapter(91 context: { deviceName?: string } = {},92): SyncVaultAdapter {93 return {94 async computeVaultId() {95 const master = requireMasterKey();96 return computeVaultId(master);97 },9899 async getOurDeviceId() {100 return getOrCreateDeviceId();101 },102103 async getLocalVersion() {104 return getVaultVersion();105 },106107 async buildEntryManifest() {108 requireUnlocked();109 const manifest: Record<string, number> = {};110 for (const entry of getEntries()) {111 manifest[entry.id] = entry.modifiedAt;112 }113 return manifest;114 },115116 async buildTombstoneManifest() {117 requireUnlocked();118 return getTombstoneManifest();119 },120121 async getEncryptedEntries(entryIds) {122 requireUnlocked();123 const masterKey = requireMasterKey();124 const out: Record<string, string> = {};125 for (const id of entryIds) {126 const entry = getEntryById(id);127 if (!entry) continue;128 const key = await deriveEntryKey(masterKey, id);129 out[id] = await encryptEntry(key, entry);130 }131 return out;132 },133134 async applyEntries(entries) {135 requireUnlocked();136 const entryList = Object.entries(entries);137 138 if (entryList.length > SYNC_LIMITS.MAX_ENTRY_COUNT) {139 throw new Error(140 `sync entry count ${entryList.length} exceeds limit ${SYNC_LIMITS.MAX_ENTRY_COUNT}`,141 );142 }143 const masterKey = requireMasterKey();144 const decrypted: VaultEntry[] = [];145 for (const [id, envelope] of entryList) {146 147 148 if (envelope.length > (SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3 + 64) {149 continue; 150 }151 const key = await deriveEntryKey(masterKey, id);152 const entry = await decryptEntryOrNull(key, envelope);153 if (!entry) continue;154 155 if (JSON.stringify(entry).length > SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES) {156 continue;157 }158 159 160 if (entry.id !== id) continue;161 decrypted.push(entry);162 }163 if (decrypted.length > 0) {164 await applyMergedRemoteEntries(decrypted, {}, context);165 }166 },167168 async applyTombstones(tombstones) {169 requireUnlocked();170 const tombstoneList = Object.entries(tombstones);171 172 if (tombstoneList.length > SYNC_LIMITS.MAX_TOMBSTONE_COUNT) {173 throw new Error(174 `sync tombstone count ${tombstoneList.length} exceeds limit ${SYNC_LIMITS.MAX_TOMBSTONE_COUNT}`,175 );176 }177 const cleaned: Record<string, number> = {};178 for (const [id, ts] of tombstoneList) {179 if (typeof ts === "number" && Number.isFinite(ts) && ts > 0) {180 181 182 183 cleaned[id] = clampSyncTimestamp(ts);184 }185 }186 if (Object.keys(cleaned).length > 0) {187 await applyMergedRemoteEntries([], cleaned, context);188 }189 },190191 async buildOutgoingDeviceManifest() {192 requireUnlocked();193 const masterKey = requireMasterKey();194 const issuerDeviceId = await getOrCreateDeviceId();195 const signing = await deriveSyncSigningKeypair(masterKey, issuerDeviceId);196 const revoked = await listDeviceRevocations();197 const revokedIds = new Set(revoked.map((r) => r.deviceId));198 const devices = (await listPairedDevices())199 .filter((d) => !revokedIds.has(d.deviceId))200 .map(toManifestEntry)201 .filter((d): d is ManifestDeviceEntry => d !== null);202 return buildSignedDeviceManifest(203 issuerDeviceId,204 devices,205 signing.privateKey,206 { revoked },207 );208 },209210 async applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey) {211 requireUnlocked();212 await applyVerifiedPeerManifest(213 manifest,214 authenticatedRemoteStaticPublicKey,215 );216 },217 };218}219220export async function refreshLockedSyncSpool(): Promise<void> {221 requireUnlocked();222 const masterKey = requireMasterKey();223 const deviceId = await getOrCreateDeviceId();224 const identity = await buildCachedIdentity(masterKey, deviceId);225 const cachedEntries: Record<string, { modifiedAt: number; ciphertext: string }> = {};226 try {227 for (const entry of getEntries()) {228 if (entry.deletedAt) continue;229 const key = await deriveEntryKey(masterKey, entry.id);230 cachedEntries[entry.id] = {231 modifiedAt: entry.modifiedAt,232 ciphertext: await encryptEntry(key, entry),233 };234 }235 const tombstones = getTombstoneManifest();236 const { longTermPrivateKeyBytes: _privateKeyBytes, longTermPrivateKeyHex: _privateKeyHex, ...storedIdentity } = identity;237 await replaceLockedSyncSpool({238 ...storedIdentity,239 localVersion: await getVaultVersion(),240 entries: cachedEntries,241 tombstones,242 });243 } finally {244 masterKey.fill(0);245 identity.longTermPrivateKeyBytes.fill(0);246 }247}248249export async function drainAndRefreshLockedSyncSpool(): Promise<void> {250 const live = createSyncVaultAdapter();251 await drainLockedSyncInbox(live);252 await refreshLockedSyncSpool();253}254255async function buildCachedIdentity(masterKey: Uint8Array, deviceId: string) {256 const vaultId = await computeVaultId(masterKey);257 const keys = deriveSyncIdentityKeypair(masterKey, deviceId);258 const deviceName = await getDeviceName();259 return {260 vaultId,261 deviceId,262 deviceName,263 deviceType: "extension" as const,264 longTermPublicKeyHex: pubkeyToHex(keys.publicKey),265 longTermPrivateKeyHex: bytesToHex(keys.secretKey),266 longTermPrivateKeyBytes: keys.secretKey,267 };268}269270function toManifestEntry(device: PairedDevice): ManifestDeviceEntry | null {271 if (272 !device.deviceId ||273 !device.deviceName ||274 !device.deviceType ||275 !device.longTermPublicKeyHex ||276 !/^[0-9a-f]{64}$/.test(device.longTermPublicKeyHex) ||277 !device.signingPublicKeyHex ||278 !/^[0-9a-f]{64}$/.test(device.signingPublicKeyHex)279 ) {280 return null;281 }282 return {283 deviceId: device.deviceId,284 deviceName: device.deviceName,285 deviceType: device.deviceType,286 longTermPublicKeyHex: device.longTermPublicKeyHex,287 signingPublicKeyHex: device.signingPublicKeyHex,288 wsPort: device.wsPort,289 relayUrl: device.relayUrl,290 pairedAt: device.pairedAt,291 };292}293294295296297298299300301302303304305306307308async function applyVerifiedPeerManifest(309 manifest: SignedDeviceManifest,310 authenticatedRemoteStaticPublicKey: Uint8Array,311): Promise<void> {312 const issuerId = manifest?.body?.issuerDeviceId;313 if (typeof issuerId !== "string" || !issuerId) { return; }314315 if (authenticatedRemoteStaticPublicKey.length !== 32) {316 return;317 }318 const authenticatedPubkeyHex = pubkeyToHex(authenticatedRemoteStaticPublicKey);319 const issuer = await findPairedDeviceByPubkey(authenticatedPubkeyHex);320 if (321 !issuer ||322 issuer.deviceId !== issuerId ||323 (324 issuer.trustSource !== "direct" &&325 issuer.trustSource !== "vouched"326 ) ||327 !issuer.signingPublicKeyHex ||328 !/^[0-9a-f]{64}$/.test(issuer.signingPublicKeyHex)329 ) {330 return;331 }332333 let body: Awaited<ReturnType<typeof verifyDeviceManifest>>;334 try {335 body = await verifyDeviceManifest(336 manifest,337 hexToPubkey(issuer!.signingPublicKeyHex!),338 );339 } catch {340 341 342 343 344 345 const masterForIssuer = requireMasterKey();346 try {347 const derived = await deriveSyncSigningKeypair(348 masterForIssuer,349 issuer.deviceId,350 );351 body = await verifyDeviceManifest(manifest, derived.publicKeyRaw);352 } catch {353 return;354 } finally {355 masterForIssuer.fill(0);356 }357 }358 if (body.issuerDeviceId !== issuer.deviceId) {359 return;360 }361362 const ourDeviceId = await getOrCreateDeviceId();363 const masterKey = requireMasterKey();364 const localKeys = deriveSyncIdentityKeypair(masterKey, ourDeviceId);365366 try {367 368 369 370 371 const newlyRevoked = await mergeDeviceRevocations(372 body.revoked.filter((r) => r.deviceId !== ourDeviceId),373 );374 for (const deviceId of newlyRevoked) {375 await removePairedDeviceById(deviceId);376 await removePendingVouchedDevice(deviceId);377 void recordSyncAlerts([378 {379 type: "DEVICE_REVOKED",380 entryId: "",381 entryTitle: deviceId,382 deviceName: issuer.deviceName ?? "paired device",383 timestamp: Date.now(),384 },385 ]);386 }387388 for (const entry of body.devices) {389 if (entry.deviceId === ourDeviceId || entry.deviceId === issuer.deviceId) {390 continue;391 }392 393 394 395 396 397 if (await isDeviceRevoked(entry.deviceId, entry.longTermPublicKeyHex)) {398 continue;399 }400 const existing = await findPairedDeviceById(entry.deviceId);401 const meshRoute = deriveManifestMeshRoute(402 masterKey,403 localKeys.publicKey,404 entry,405 );406407 408 409 410 411 412 if (!existing) {413 if (!meshRoute) continue;414 await upsertPairedDevice({415 deviceId: entry.deviceId,416 deviceName: entry.deviceName,417 deviceType: entry.deviceType,418 longTermPublicKeyHex: entry.longTermPublicKeyHex.toLowerCase(),419 signingPublicKeyHex: entry.signingPublicKeyHex.toLowerCase(),420 wsPort: entry.wsPort,421 rendezvousSecretHex: meshRoute.rendezvousSecretHex,422 relayUrl: meshRoute.relayUrl,423 pairedAt: entry.pairedAt,424 trustSource: "vouched",425 });426 await removePendingVouchedDevice(entry.deviceId);427 continue;428 }429430 431 432 433 434 if (435 existing.longTermPublicKeyHex &&436 !constantTimeEqualHex(437 existing.longTermPublicKeyHex,438 entry.longTermPublicKeyHex,439 )440 ) {441 442 443 444 445 446 const knownName = existing.deviceName ?? entry.deviceName;447 notifyPopup({448 type: "DEVICE_KEY_ROTATED",449 payload: { deviceName: knownName, deviceId: entry.deviceId },450 });451 void recordSyncAlerts([452 {453 type: "DEVICE_KEY_ROTATED",454 entryId: "",455 entryTitle: knownName,456 deviceName: knownName,457 timestamp: Date.now(),458 },459 ]);460 }461462 463 464 465 466 await upsertPairedDevice({467 ...existing,468 deviceId: entry.deviceId,469 deviceName: existing.deviceName ?? entry.deviceName,470 deviceType: entry.deviceType,471 longTermPublicKeyHex: entry.longTermPublicKeyHex.toLowerCase(),472 signingPublicKeyHex: entry.signingPublicKeyHex.toLowerCase(),473 pairedAt: existing.pairedAt ?? entry.pairedAt,474 trustSource: existing.trustSource,475 wsPort: existing.wsPort ?? entry.wsPort,476 rendezvousSecretHex:477 existing.trustSource === "vouched" && meshRoute478 ? meshRoute.rendezvousSecretHex479 : existing.rendezvousSecretHex,480 relayUrl:481 existing.trustSource === "vouched" && meshRoute482 ? meshRoute.relayUrl483 : existing.relayUrl,484 lastSyncedAt: existing.lastSyncedAt,485 });486 }487 } finally {488 masterKey.fill(0);489 localKeys.secretKey.fill(0);490 }491}492493function deriveManifestMeshRoute(494 masterKey: Uint8Array,495 localPublicKey: Uint8Array,496 entry: ManifestDeviceEntry,497): { rendezvousSecretHex: string; relayUrl: string } | null {498 try {499 if (!entry.relayUrl) return null;500 const relayUrl = normalizeRelayUrl(entry.relayUrl);501 const secret = deriveMeshRendezvousSecret(502 masterKey,503 localPublicKey,504 hexToPubkey(entry.longTermPublicKeyHex),505 );506 try {507 return {508 rendezvousSecretHex: rendezvousBytesToHex(secret),509 relayUrl,510 };511 } finally {512 secret.fill(0);513 }514 } catch {515 return null;516 }517}518519function notifyPopup(msg: { type: string; payload?: unknown }): void {520 try {521 void chrome.runtime.sendMessage(msg).catch(() => undefined);522 } catch {523 524 }525}526527function requireUnlocked(): void {528 if (!isUnlocked()) throw new VaultLockedError();529}530531532533534535536537function requireMasterKey(): Uint8Array {538 if (!isUnlocked()) throw new VaultLockedError();539 const hex = getRootKeyHex();540 if (!hex) throw new VaultLockedError();541 return hexToBytes(hex);542}543544async function deriveEntryKey(masterKey: Uint8Array, entryId: string): Promise<CryptoKey> {545 546 547 548 549 const info = new TextEncoder().encode(`${entryId}\x00${ENTRY_KEY_INFO_SUFFIX}`);550 const raw = new HKDF(SHA256, masterKey, new Uint8Array(0), info).expand(32);551 return crypto.subtle.importKey(552 "raw",553 raw.buffer as ArrayBuffer,554 { name: "AES-GCM" },555 false,556 ["encrypt", "decrypt"],557 );558}559560async function encryptEntry(key: CryptoKey, entry: VaultEntry): Promise<string> {561 const plaintext = new TextEncoder().encode(JSON.stringify(entry));562 const nonce = crypto.getRandomValues(new Uint8Array(12));563 const aad = new TextEncoder().encode(ENTRY_AAD);564 const ct = await crypto.subtle.encrypt(565 {566 name: "AES-GCM",567 iv: nonce.buffer as ArrayBuffer,568 additionalData: aad.buffer as ArrayBuffer,569 tagLength: 128,570 },571 key,572 plaintext.buffer as ArrayBuffer,573 );574 const ctBytes = new Uint8Array(ct);575 const envelope = new Uint8Array(nonce.length + ctBytes.length);576 envelope.set(nonce, 0);577 envelope.set(ctBytes, nonce.length);578 return bytesToBase64(envelope);579}580581async function decryptEntryOrNull(key: CryptoKey, envelopeB64: string): Promise<VaultEntry | null> {582 try {583 const bytes = base64ToBytes(envelopeB64);584 if (bytes.length < 12 + 16) return null;585 const nonce = bytes.subarray(0, 12);586 const ct = bytes.subarray(12);587 const aad = new TextEncoder().encode(ENTRY_AAD);588 const pt = await crypto.subtle.decrypt(589 {590 name: "AES-GCM",591 iv: nonce.buffer.slice(nonce.byteOffset, nonce.byteOffset + nonce.byteLength) as ArrayBuffer,592 additionalData: aad.buffer as ArrayBuffer,593 tagLength: 128,594 },595 key,596 ct.buffer.slice(ct.byteOffset, ct.byteOffset + ct.byteLength) as ArrayBuffer,597 );598 const json = new TextDecoder().decode(pt);599 const parsed = JSON.parse(json);600 if (!parsed || typeof parsed !== "object" || typeof parsed.id !== "string") return null;601 return parsed as VaultEntry;602 } catch {603 return null;604 }605}606607function hexToBytes(hex: string): Uint8Array {608 if (hex.length % 2 !== 0) throw new Error("hex length must be even");609 const out = new Uint8Array(hex.length / 2);610 for (let i = 0; i < out.length; i++) {611 out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);612 }613 return out;614}615616function bytesToBase64(bytes: Uint8Array): string {617 let bin = "";618 for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);619 return btoa(bin);620}621622function bytesToHex(bytes: Uint8Array): string {623 return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");624}625626function base64ToBytes(b64: string): Uint8Array {627 const bin = atob(b64);628 const out = new Uint8Array(bin.length);629 for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);630 return out;631}