12345678910111213141516171819202122232425import { HKDF } from "@stablelib/hkdf";26import { SHA256 } from "@stablelib/sha256";27import type { SyncVaultAdapter } from "./sync-coordinator";28import { 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 getDeletedEntries,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";76777879const ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1";80const ENTRY_AAD = "peach-sync-entry-v1";8182export class VaultLockedError extends Error {83 constructor() {84 super("vault_locked");85 this.name = "VaultLockedError";86 }87}8889export function createSyncVaultAdapter(90 context: { deviceName?: string } = {},91): SyncVaultAdapter {92 return {93 async computeVaultId() {94 const master = requireMasterKey();95 return computeVaultId(master);96 },9798 async getOurDeviceId() {99 return getOrCreateDeviceId();100 },101102 async getLocalVersion() {103 return getVaultVersion();104 },105106 async buildEntryManifest() {107 requireUnlocked();108 const manifest: Record<string, number> = {};109 for (const entry of getEntries()) {110 manifest[entry.id] = entry.modifiedAt;111 }112 return manifest;113 },114115 async buildTombstoneManifest() {116 117 118 119 120 121 122 123 124 125 126 requireUnlocked();127 const manifest: Record<string, number> = {};128 for (const entry of getDeletedEntries()) {129 if (typeof entry.deletedAt === "number") {130 manifest[entry.id] = entry.deletedAt;131 }132 }133 return manifest;134 },135136 async getEncryptedEntries(entryIds) {137 requireUnlocked();138 const masterKey = requireMasterKey();139 const out: Record<string, string> = {};140 for (const id of entryIds) {141 const entry = getEntryById(id);142 if (!entry) continue;143 const key = await deriveEntryKey(masterKey, id);144 out[id] = await encryptEntry(key, entry);145 }146 return out;147 },148149 async applyEntries(entries) {150 requireUnlocked();151 const entryList = Object.entries(entries);152 153 if (entryList.length > SYNC_LIMITS.MAX_ENTRY_COUNT) {154 throw new Error(155 `sync entry count ${entryList.length} exceeds limit ${SYNC_LIMITS.MAX_ENTRY_COUNT}`,156 );157 }158 const masterKey = requireMasterKey();159 const decrypted: VaultEntry[] = [];160 for (const [id, envelope] of entryList) {161 162 163 if (envelope.length > (SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3 + 64) {164 continue; 165 }166 const key = await deriveEntryKey(masterKey, id);167 const entry = await decryptEntryOrNull(key, envelope);168 if (!entry) continue;169 170 if (JSON.stringify(entry).length > SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES) {171 continue;172 }173 174 175 if (entry.id !== id) continue;176 decrypted.push(entry);177 }178 if (decrypted.length > 0) {179 await applyMergedRemoteEntries(decrypted, {}, context);180 }181 },182183 async applyTombstones(tombstones) {184 requireUnlocked();185 const tombstoneList = Object.entries(tombstones);186 187 if (tombstoneList.length > SYNC_LIMITS.MAX_TOMBSTONE_COUNT) {188 throw new Error(189 `sync tombstone count ${tombstoneList.length} exceeds limit ${SYNC_LIMITS.MAX_TOMBSTONE_COUNT}`,190 );191 }192 const cleaned: Record<string, number> = {};193 for (const [id, ts] of tombstoneList) {194 if (typeof ts === "number" && Number.isFinite(ts) && ts > 0) {195 196 197 198 cleaned[id] = clampSyncTimestamp(ts);199 }200 }201 if (Object.keys(cleaned).length > 0) {202 await applyMergedRemoteEntries([], cleaned, context);203 }204 },205206 async buildOutgoingDeviceManifest() {207 requireUnlocked();208 const masterKey = requireMasterKey();209 const issuerDeviceId = await getOrCreateDeviceId();210 const signing = await deriveSyncSigningKeypair(masterKey, issuerDeviceId);211 const revoked = await listDeviceRevocations();212 const revokedIds = new Set(revoked.map((r) => r.deviceId));213 const devices = (await listPairedDevices())214 .filter((d) => !revokedIds.has(d.deviceId))215 .map(toManifestEntry)216 .filter((d): d is ManifestDeviceEntry => d !== null);217 return buildSignedDeviceManifest(218 issuerDeviceId,219 devices,220 signing.privateKey,221 { revoked },222 );223 },224225 async applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey) {226 requireUnlocked();227 228 console.info("[Peach diag] applyIncomingDeviceManifest: issuerDeviceId=" + manifest?.body?.issuerDeviceId + " devices=" + (manifest?.body?.devices ?? []).map((d) => d.deviceId).join(",") + " revoked=" + (manifest?.body?.revoked ?? []).length);229 try {230 await applyVerifiedPeerManifest(231 manifest,232 authenticatedRemoteStaticPublicKey,233 );234 } catch (diagError) {235 console.info("[Peach diag] applyVerifiedPeerManifest threw:", diagError);236 }237 const all = await listPairedDevices();238 console.info("[Peach diag] post-manifest paired-devices:", all.map((d) => d.deviceId + "/" + d.trustSource).join(","));239 },240 };241}242243function toManifestEntry(device: PairedDevice): ManifestDeviceEntry | null {244 if (245 !device.deviceId ||246 !device.deviceName ||247 !device.deviceType ||248 !device.longTermPublicKeyHex ||249 !/^[0-9a-f]{64}$/.test(device.longTermPublicKeyHex) ||250 !device.signingPublicKeyHex ||251 !/^[0-9a-f]{64}$/.test(device.signingPublicKeyHex)252 ) {253 return null;254 }255 return {256 deviceId: device.deviceId,257 deviceName: device.deviceName,258 deviceType: device.deviceType,259 longTermPublicKeyHex: device.longTermPublicKeyHex,260 signingPublicKeyHex: device.signingPublicKeyHex,261 wsPort: device.wsPort,262 relayUrl: device.relayUrl,263 pairedAt: device.pairedAt,264 };265}266267268269270271272273274275276277278279280281async function applyVerifiedPeerManifest(282 manifest: SignedDeviceManifest,283 authenticatedRemoteStaticPublicKey: Uint8Array,284): Promise<void> {285 286 console.info("[Peach diag] applyVerifiedPeerManifest enter: authPubKeyLen=" + authenticatedRemoteStaticPublicKey.length + " manifestIssuer=" + manifest?.body?.issuerDeviceId);287 const issuerId = manifest?.body?.issuerDeviceId;288 if (typeof issuerId !== "string" || !issuerId) { console.info("[Peach diag] early return: missing issuerId"); return; }289290 if (authenticatedRemoteStaticPublicKey.length !== 32) {291 console.info("[Peach diag] early return: auth key not 32 bytes");292 return;293 }294 const authenticatedPubkeyHex = pubkeyToHex(authenticatedRemoteStaticPublicKey);295 const issuer = await findPairedDeviceByPubkey(authenticatedPubkeyHex);296 console.info("[Peach diag] lookup issuer: found=" + (issuer !== null) + " storedDeviceId=" + (issuer === null ? "<none>" : issuer.deviceId) + " manifestIssuerId=" + issuerId + " trustSource=" + (issuer === null ? "<none>" : issuer.trustSource) + " hasSigningKey=" + (issuer !== null && issuer.signingPublicKeyHex !== undefined));297 if (298 !issuer ||299 issuer.deviceId !== issuerId ||300 (301 issuer.trustSource !== "direct" &&302 issuer.trustSource !== "vouched"303 ) ||304 !issuer.signingPublicKeyHex ||305 !/^[0-9a-f]{64}$/.test(issuer.signingPublicKeyHex)306 ) {307 console.info("[Peach diag] early return: issuer gate");308 return;309 }310311 let body: Awaited<ReturnType<typeof verifyDeviceManifest>>;312 try {313 body = await verifyDeviceManifest(314 manifest,315 hexToPubkey(issuer!.signingPublicKeyHex!),316 );317 } catch {318 319 320 321 322 323 const masterForIssuer = requireMasterKey();324 try {325 const derived = await deriveSyncSigningKeypair(326 masterForIssuer,327 issuer.deviceId,328 );329 body = await verifyDeviceManifest(manifest, derived.publicKeyRaw);330 } catch {331 return;332 } finally {333 masterForIssuer.fill(0);334 }335 }336 console.info("[Peach diag] body parsed: bodyIssuerId=" + body.issuerDeviceId + " issuerStoredId=" + issuer.deviceId);337 if (body.issuerDeviceId !== issuer.deviceId) { console.info("[Peach diag] early return: body issuer mismatch"); return; }338339 const ourDeviceId = await getOrCreateDeviceId();340 const masterKey = requireMasterKey();341 const localKeys = deriveSyncIdentityKeypair(masterKey, ourDeviceId);342343 try {344 345 346 347 348 const newlyRevoked = await mergeDeviceRevocations(349 body.revoked.filter((r) => r.deviceId !== ourDeviceId),350 );351 for (const deviceId of newlyRevoked) {352 await removePairedDeviceById(deviceId);353 await removePendingVouchedDevice(deviceId);354 void recordSyncAlerts([355 {356 type: "DEVICE_REVOKED",357 entryId: "",358 entryTitle: deviceId,359 deviceName: issuer.deviceName ?? "paired device",360 timestamp: Date.now(),361 },362 ]);363 }364365 for (const entry of body.devices) {366 if (entry.deviceId === ourDeviceId || entry.deviceId === issuer.deviceId) {367 368 console.info("[Peach diag] skip entry (self or issuer):", entry.deviceId);369 continue;370 }371 372 373 374 375 376 if (await isDeviceRevoked(entry.deviceId, entry.longTermPublicKeyHex)) {377 378 console.info("[Peach diag] skip entry (revoked):", entry.deviceId, "longTerm=" + entry.longTermPublicKeyHex?.slice(0, 12) + "...", "hasRelay=" + !!entry.relayUrl);379 continue;380 }381 const existing = await findPairedDeviceById(entry.deviceId);382 const meshRoute = deriveManifestMeshRoute(383 masterKey,384 localKeys.publicKey,385 entry,386 );387 388 if (existing) {389 console.info("[Peach diag] skip entry (existing):", entry.deviceId, "trustSource=" + existing.trustSource);390 } else if (!meshRoute) {391 console.info("[Peach diag] skip entry (no mesh route):", entry.deviceId, "hasRelay=" + !!entry.relayUrl);392 } else {393 console.info("[Peach diag] admit entry:", entry.deviceId, "relay=" + meshRoute.relayUrl);394 }395396 397 398 399 400 401 if (!existing) {402 if (!meshRoute) continue;403 await upsertPairedDevice({404 deviceId: entry.deviceId,405 deviceName: entry.deviceName,406 deviceType: entry.deviceType,407 longTermPublicKeyHex: entry.longTermPublicKeyHex.toLowerCase(),408 signingPublicKeyHex: entry.signingPublicKeyHex.toLowerCase(),409 wsPort: entry.wsPort,410 rendezvousSecretHex: meshRoute.rendezvousSecretHex,411 relayUrl: meshRoute.relayUrl,412 pairedAt: entry.pairedAt,413 trustSource: "vouched",414 });415 await removePendingVouchedDevice(entry.deviceId);416 continue;417 }418419 420 421 422 423 if (424 existing.longTermPublicKeyHex &&425 !constantTimeEqualHex(426 existing.longTermPublicKeyHex,427 entry.longTermPublicKeyHex,428 )429 ) {430 431 432 433 434 435 const knownName = existing.deviceName ?? entry.deviceName;436 notifyPopup({437 type: "DEVICE_KEY_ROTATED",438 payload: { deviceName: knownName, deviceId: entry.deviceId },439 });440 void recordSyncAlerts([441 {442 type: "DEVICE_KEY_ROTATED",443 entryId: "",444 entryTitle: knownName,445 deviceName: knownName,446 timestamp: Date.now(),447 },448 ]);449 }450451 452 453 454 455 await upsertPairedDevice({456 ...existing,457 deviceId: entry.deviceId,458 deviceName: existing.deviceName ?? entry.deviceName,459 deviceType: entry.deviceType,460 longTermPublicKeyHex: entry.longTermPublicKeyHex.toLowerCase(),461 signingPublicKeyHex: entry.signingPublicKeyHex.toLowerCase(),462 pairedAt: existing.pairedAt ?? entry.pairedAt,463 trustSource: existing.trustSource ?? "direct",464 wsPort: existing.wsPort ?? entry.wsPort,465 rendezvousSecretHex:466 existing.trustSource === "vouched" && meshRoute467 ? meshRoute.rendezvousSecretHex468 : existing.rendezvousSecretHex,469 relayUrl:470 existing.trustSource === "vouched" && meshRoute471 ? meshRoute.relayUrl472 : existing.relayUrl,473 lastSyncedAt: existing.lastSyncedAt,474 });475 }476 } finally {477 masterKey.fill(0);478 localKeys.secretKey.fill(0);479 }480}481482function deriveManifestMeshRoute(483 masterKey: Uint8Array,484 localPublicKey: Uint8Array,485 entry: ManifestDeviceEntry,486): { rendezvousSecretHex: string; relayUrl: string } | null {487 try {488 if (!entry.relayUrl) return null;489 const relayUrl = normalizeRelayUrl(entry.relayUrl);490 const secret = deriveMeshRendezvousSecret(491 masterKey,492 localPublicKey,493 hexToPubkey(entry.longTermPublicKeyHex),494 );495 try {496 return {497 rendezvousSecretHex: rendezvousBytesToHex(secret),498 relayUrl,499 };500 } finally {501 secret.fill(0);502 }503 } catch {504 return null;505 }506}507508function notifyPopup(msg: { type: string; payload?: unknown }): void {509 try {510 void chrome.runtime.sendMessage(msg).catch(() => undefined);511 } catch {512 513 }514}515516function requireUnlocked(): void {517 if (!isUnlocked()) throw new VaultLockedError();518}519520521522523524525526function requireMasterKey(): Uint8Array {527 if (!isUnlocked()) throw new VaultLockedError();528 const hex = getRootKeyHex();529 if (!hex) throw new VaultLockedError();530 return hexToBytes(hex);531}532533async function deriveEntryKey(masterKey: Uint8Array, entryId: string): Promise<CryptoKey> {534 535 536 537 538 const info = new TextEncoder().encode(`${entryId}\x00${ENTRY_KEY_INFO_SUFFIX}`);539 const raw = new HKDF(SHA256, masterKey, new Uint8Array(0), info).expand(32);540 return crypto.subtle.importKey(541 "raw",542 raw.buffer as ArrayBuffer,543 { name: "AES-GCM" },544 false,545 ["encrypt", "decrypt"],546 );547}548549async function encryptEntry(key: CryptoKey, entry: VaultEntry): Promise<string> {550 const plaintext = new TextEncoder().encode(JSON.stringify(entry));551 const nonce = crypto.getRandomValues(new Uint8Array(12));552 const aad = new TextEncoder().encode(ENTRY_AAD);553 const ct = await crypto.subtle.encrypt(554 {555 name: "AES-GCM",556 iv: nonce.buffer as ArrayBuffer,557 additionalData: aad.buffer as ArrayBuffer,558 tagLength: 128,559 },560 key,561 plaintext.buffer as ArrayBuffer,562 );563 const ctBytes = new Uint8Array(ct);564 const envelope = new Uint8Array(nonce.length + ctBytes.length);565 envelope.set(nonce, 0);566 envelope.set(ctBytes, nonce.length);567 return bytesToBase64(envelope);568}569570async function decryptEntryOrNull(key: CryptoKey, envelopeB64: string): Promise<VaultEntry | null> {571 try {572 const bytes = base64ToBytes(envelopeB64);573 if (bytes.length < 12 + 16) return null;574 const nonce = bytes.subarray(0, 12);575 const ct = bytes.subarray(12);576 const aad = new TextEncoder().encode(ENTRY_AAD);577 const pt = await crypto.subtle.decrypt(578 {579 name: "AES-GCM",580 iv: nonce.buffer.slice(nonce.byteOffset, nonce.byteOffset + nonce.byteLength) as ArrayBuffer,581 additionalData: aad.buffer as ArrayBuffer,582 tagLength: 128,583 },584 key,585 ct.buffer.slice(ct.byteOffset, ct.byteOffset + ct.byteLength) as ArrayBuffer,586 );587 const json = new TextDecoder().decode(pt);588 const parsed = JSON.parse(json);589 if (!parsed || typeof parsed !== "object" || typeof parsed.id !== "string") return null;590 return parsed as VaultEntry;591 } catch {592 return null;593 }594}595596function hexToBytes(hex: string): Uint8Array {597 if (hex.length % 2 !== 0) throw new Error("hex length must be even");598 const out = new Uint8Array(hex.length / 2);599 for (let i = 0; i < out.length; i++) {600 out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);601 }602 return out;603}604605function bytesToBase64(bytes: Uint8Array): string {606 let bin = "";607 for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);608 return btoa(bin);609}610611function base64ToBytes(b64: string): Uint8Array {612 const bin = atob(b64);613 const out = new Uint8Array(bin.length);614 for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);615 return out;616}