12345678910111213141516171819202122232425import { HKDF } from "@stablelib/hkdf";26import { SHA256 } from "@stablelib/sha256";27import type { DeviceManifestBody } from "../shared/sync-types";28import type { SyncVaultAdapter } from "./sync-coordinator";29import { getDeviceName, getLocalPairingIdentity, getOrCreateDeviceId } from "./device-identity";30import {31 computeVaultId,32 hexToPubkey,33 pubkeyToHex,34} from "../shared/sync-identity";35import {36 buildSignedDeviceManifest,37 signDeviceRevocation,38 verifyDeviceManifest,39 verifyDeviceRevocation,40} from "../shared/device-manifest";41import { constantTimeEqualHex } from "../shared/constant-time";42import {43 applyMergedRemoteEntries,44 getTombstoneManifest,45 getRootKeyHex,46 getEntries,47 getEntryById,48 getVaultVersion,49 isUnlocked,50 isDecoyMode,51 ensureSettingsLoaded,52 lockedSyncRequiresUnlock,53} from "./vault";54import {55 findPairedDeviceById,56 findPairedDeviceByPubkey,57 isDeviceRevoked,58 listDeviceRevocations,59 listPairedDevices,60 listRevocationIssuerKeyMap,61 upsertPairedDevicesAndMergeRevocations,62} from "./paired-devices";63import { setPairSecret } from "./pair-secrets";64import {65 removePendingVouchedDevice,66} from "./pending-vouched-devices";67import {68 bytesToHex as rendezvousBytesToHex,69 deriveMeshRendezvousSecret,70 normalizeRelayUrl,71} from "../shared/rendezvous";72import { recordSyncAlerts } from "./sync-alerts";73import { SYNC_LIMITS, clampSyncTimestamp } from "../shared/sync-limits";74import type { VaultEntry } from "../shared/types";75import {76 MAX_VOUCH_DEPTH,77 type ManifestDeviceEntry,78 type PairedDevice,79 type SignedDeviceManifest,80} from "../shared/sync-types";81import { replaceLockedSyncSpool, drainLockedSyncInbox, setLockedSyncPrivateKey } from "./locked-sync-spool";82838485const ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1";86const ENTRY_AAD = "peach-sync-entry-v1";8788export class VaultLockedError extends Error {89 constructor() {90 super("vault_locked");91 this.name = "VaultLockedError";92 }93}9495export function createSyncVaultAdapter(96 _context: { deviceName?: string } = {},97): SyncVaultAdapter {98 return {99 async computeVaultId() {100 const master = requireMasterKey();101 return computeVaultId(master);102 },103104 async getOurDeviceId() {105 return getOrCreateDeviceId();106 },107108 async getLocalVersion() {109 return getVaultVersion();110 },111112 async buildEntryManifest() {113 requireRealUnlocked();114 const manifest: Record<string, number> = {};115 for (const entry of getEntries()) {116 manifest[entry.id] = entry.modifiedAt;117 }118 return manifest;119 },120121 async buildTombstoneManifest() {122 requireRealUnlocked();123 return getTombstoneManifest();124 },125126 async getEncryptedEntries(entryIds) {127 requireRealUnlocked();128 const masterKey = requireMasterKey();129 const out: Record<string, string> = {};130 for (const id of entryIds) {131 const entry = getEntryById(id);132 if (!entry) continue;133 const key = await deriveEntryKey(masterKey, id);134 out[id] = await encryptEntry(key, entry);135 }136 return out;137 },138139 async applyEntries(entries) {140 requireRealUnlocked();141 const entryList = Object.entries(entries);142 if (entryList.length > SYNC_LIMITS.MAX_ENTRY_COUNT) {143 throw new Error(144 `sync entry count ${entryList.length} exceeds limit ${SYNC_LIMITS.MAX_ENTRY_COUNT}`,145 );146 }147 const masterKey = requireMasterKey();148 const decrypted: VaultEntry[] = [];149 for (const [id, envelope] of entryList) {150 if (envelope.length > (SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3 + 64) continue;151 const key = await deriveEntryKey(masterKey, id);152 const entry = await decryptEntryOrNull(key, envelope);153 if (!entry) continue;154 if (JSON.stringify(entry).length > SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES) continue;155 if (entry.id !== id) continue;156 decrypted.push(entry);157 }158 if (decrypted.length > 0) {159 requireRealUnlocked();160 await applyMergedRemoteEntries(decrypted, {});161 }162 },163164 async applyTombstones(tombstones) {165 requireRealUnlocked();166 const tombstoneList = Object.entries(tombstones);167 if (tombstoneList.length > SYNC_LIMITS.MAX_TOMBSTONE_COUNT) {168 throw new Error(169 `sync tombstone count ${tombstoneList.length} exceeds limit ${SYNC_LIMITS.MAX_TOMBSTONE_COUNT}`,170 );171 }172 const cleaned: Record<string, number> = {};173 for (const [id, ts] of tombstoneList) {174 if (typeof ts === "number" && Number.isFinite(ts) && ts > 0) {175 cleaned[id] = clampSyncTimestamp(ts);176 }177 }178 if (Object.keys(cleaned).length > 0) {179 requireRealUnlocked();180 await applyMergedRemoteEntries([], cleaned);181 }182 },183184 async buildOutgoingDeviceManifest() {185 requireRealUnlocked();186 const local = await getLocalPairingIdentity();187 try {188 const issuerDeviceId = local.identity.deviceId;189 const revoked = await listDeviceRevocations();190 const revokedIds = new Set(revoked.map((r) => r.deviceId));191 const devices = (await listPairedDevices())192 .filter((d) => !revokedIds.has(d.deviceId))193 .map(toManifestEntry)194 .filter((d): d is ManifestDeviceEntry => d !== null);195 const issuerKeys = await revocationIssuerKeys(local.identity);196 const signedRevoked = (197 await Promise.all(revoked.map(async (record) => {198 if (record.signatureHex) {199 200 201 202 203 for (const key of issuerKeys.get(record.revokedByDeviceId) ?? []) {204 if (await verifyDeviceRevocation(record, hexToPubkey(key))) return record;205 }206 throw new Error("revocation_issuer_unverifiable");207 }208 209 210 if (record.revokedByDeviceId !== issuerDeviceId) throw new Error("revocation_issuer_unverifiable");211 return signDeviceRevocation(record, local.signingPrivateKey);212 }))213 );214 return buildSignedDeviceManifest(215 issuerDeviceId,216 devices,217 local.signingPrivateKey,218 { revoked: signedRevoked },219 );220 } finally {221 local.privateKey.fill(0);222 local.publicKey.fill(0);223 }224 },225226 async applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey) {227 requireRealUnlocked();228 await applyVerifiedPeerManifest(229 manifest,230 authenticatedRemoteStaticPublicKey,231 );232 },233 };234}235236export async function refreshLockedSyncSpool(): Promise<void> {237 requireUnlocked();238 const masterKey = requireMasterKey();239 const deviceId = await getOrCreateDeviceId();240 const identity = await buildCachedIdentity(masterKey, deviceId);241 const cachedEntries: Record<string, { modifiedAt: number; ciphertext: string }> = {};242 try {243 for (const entry of getEntries()) {244 if (entry.deletedAt) continue;245 const key = await deriveEntryKey(masterKey, entry.id);246 cachedEntries[entry.id] = {247 modifiedAt: entry.modifiedAt,248 ciphertext: await encryptEntry(key, entry),249 };250 }251 const tombstones = getTombstoneManifest();252 await ensureSettingsLoaded();253 await setLockedSyncPrivateKey(identity.longTermPrivateKeyBytes, !lockedSyncRequiresUnlock());254 const { longTermPrivateKeyHex: _privateKeyHex, longTermPrivateKeyBytes: _privateKeyBytes, ...storedIdentity } = identity;255 await replaceLockedSyncSpool({256 ...storedIdentity,257 localVersion: await getVaultVersion(),258 entries: cachedEntries,259 tombstones,260 });261 } finally {262 masterKey.fill(0);263 identity.longTermPrivateKeyBytes.fill(0);264 }265}266267export async function drainAndRefreshLockedSyncSpool(): Promise<void> {268 const live = createSyncVaultAdapter();269 await drainLockedSyncInbox(live);270 await refreshLockedSyncSpool();271}272273async function buildCachedIdentity(masterKey: Uint8Array, _deviceId: string) {274 const vaultId = await computeVaultId(masterKey);275 const pairing = await getLocalPairingIdentity();276 const deviceName = await getDeviceName();277 return {278 vaultId,279 deviceId: pairing.identity.deviceId,280 deviceName,281 deviceType: "extension" as const,282 longTermPublicKeyHex: pubkeyToHex(pairing.publicKey),283 longTermPrivateKeyHex: bytesToHex(pairing.privateKey),284 longTermPrivateKeyBytes: pairing.privateKey,285 };286}287288function toManifestEntry(device: PairedDevice): ManifestDeviceEntry | null {289 if (290 !device.deviceId ||291 !device.deviceName ||292 !device.deviceType ||293 !device.longTermPublicKeyHex ||294 !/^[0-9a-f]{64}$/.test(device.longTermPublicKeyHex) ||295 !device.signingPublicKeyHex ||296 !/^[0-9a-f]{64}$/.test(device.signingPublicKeyHex)297 ) {298 return null;299 }300 return {301 deviceId: device.deviceId,302 deviceName: device.deviceName,303 deviceType: device.deviceType,304 longTermPublicKeyHex: device.longTermPublicKeyHex,305 signingPublicKeyHex: device.signingPublicKeyHex,306 wsPort: device.wsPort,307 relayUrl: device.relayUrl,308 pairedAt: device.pairedAt,309 vouchDepth: device.vouchDepth ?? 0,310 };311}312313314async function revocationIssuerKeys(local: { deviceId: string; signingPublicKeyHex: string }): Promise<Map<string, string[]>> {315 const keys = await listRevocationIssuerKeyMap();316 keys.set(local.deviceId, [...new Set([...(keys.get(local.deviceId) ?? []), local.signingPublicKeyHex])]);317 return keys;318}319320321322323324325326327328329330331332333334async function applyVerifiedPeerManifest(335 manifest: SignedDeviceManifest,336 authenticatedRemoteStaticPublicKey: Uint8Array,337): Promise<void> {338 const issuerId = manifest?.body?.issuerDeviceId;339 if (typeof issuerId !== "string" || !issuerId) { return; }340341 if (authenticatedRemoteStaticPublicKey.length !== 32) {342 return;343 }344 const authenticatedPubkeyHex = pubkeyToHex(authenticatedRemoteStaticPublicKey);345 const issuer = await findPairedDeviceByPubkey(authenticatedPubkeyHex);346 if (347 !issuer ||348 issuer.deviceId !== issuerId ||349 (350 issuer.trustSource !== "direct" &&351 issuer.trustSource !== "vouched"352 ) ||353 (issuer.vouchDepth ?? 0) >= MAX_VOUCH_DEPTH ||354 !issuer.signingPublicKeyHex ||355 !/^[0-9a-f]{64}$/.test(issuer.signingPublicKeyHex)356 ) {357 return;358 }359360 let body: DeviceManifestBody | undefined;361 let selectedSigningKey: { version: number; publicKeyHex: string } | undefined;362 const issuerSigningPublicKeyHex = issuer.signingPublicKeyHex;363 const historicalKeys = (issuer.signingKeyHistory ?? [])364 .filter((key) => Number.isInteger(key.version) && key.version > 0 && /^[0-9a-f]{64}$/i.test(key.publicKeyHex))365 .map((key) => ({ version: key.version, publicKeyHex: key.publicKeyHex.toLowerCase() }));366 const currentVersion = historicalKeys.find(367 (key) => key.publicKeyHex === issuerSigningPublicKeyHex.toLowerCase(),368 )?.version ?? (historicalKeys.reduce((max, key) => Math.max(max, key.version), 0) + 1);369 const signingKeys = [370 ...historicalKeys,371 { version: currentVersion, publicKeyHex: issuerSigningPublicKeyHex.toLowerCase() },372 ].filter((key, index, keys) =>373 keys.findIndex((candidate) => candidate.version === key.version && candidate.publicKeyHex === key.publicKeyHex) === index,374 );375 try {376 for (const key of signingKeys) {377 try {378 body = await verifyDeviceManifest(manifest, hexToPubkey(key.publicKeyHex));379 selectedSigningKey = key;380 break;381 } catch { }382 }383 if (!body || !selectedSigningKey) return;384 } catch {385 return;386 }387 if (body.issuerDeviceId !== issuer.deviceId) {388 return;389 }390 391 392 393 const localPairing = await getLocalPairingIdentity();394 const ourDeviceId = localPairing.identity.deviceId;395 const masterKey = requireMasterKey();396 const localKeys = { publicKey: localPairing.publicKey, secretKey: localPairing.privateKey };397 try {398 const issuerKeys = await revocationIssuerKeys(localPairing.identity);399 const allRevocationsAuthorised = (400 await Promise.all(401 body.revoked.map(async (record) => {402 403 404 405 for (const key of issuerKeys.get(record.revokedByDeviceId) ?? []) {406 if (await verifyDeviceRevocation(record, hexToPubkey(key))) return true;407 }408 return false;409 }),410 )411 ).every(Boolean);412 if (!allRevocationsAuthorised) return;413414 const pendingRegistry: PairedDevice[] = [];415 const pendingSecrets: { deviceId: string; secret: string }[] = [];416 const pendingVouchedIds: string[] = [];417 for (const entry of body.devices) {418 if (entry.deviceId === ourDeviceId || entry.deviceId === issuer.deviceId) continue;419 if (await isDeviceRevoked(entry.deviceId, entry.longTermPublicKeyHex)) continue;420 if ((entry.vouchDepth ?? 0) > (issuer.vouchDepth ?? 0) + 1) continue;421 const existing = await findPairedDeviceById(entry.deviceId);422 const meshRoute = deriveManifestMeshRoute(localKeys.secretKey, localKeys.publicKey, entry);423 if (!existing) {424 if (!meshRoute) continue;425 pendingRegistry.push({426 deviceId: entry.deviceId,427 deviceName: entry.deviceName,428 deviceType: entry.deviceType,429 longTermPublicKeyHex: entry.longTermPublicKeyHex.toLowerCase(),430 signingPublicKeyHex: entry.signingPublicKeyHex.toLowerCase(),431 wsPort: entry.wsPort,432 relayUrl: meshRoute.relayUrl,433 pairedAt: entry.pairedAt,434 trustSource: "vouched",435 vouchDepth: (issuer.vouchDepth ?? 0) + 1,436 });437 pendingSecrets.push({ deviceId: entry.deviceId, secret: meshRoute.rendezvousSecretHex });438 pendingVouchedIds.push(entry.deviceId);439 continue;440 }441 const longTermChanged = existing.longTermPublicKeyHex &&442 !constantTimeEqualHex(existing.longTermPublicKeyHex, entry.longTermPublicKeyHex);443 const existingSigning = existing.signingPublicKeyHex;444 const entrySigning = entry.signingPublicKeyHex;445 const signingChanged =446 Boolean(existingSigning) !== Boolean(entrySigning) ||447 (existingSigning !== undefined &&448 entrySigning !== undefined &&449 !constantTimeEqualHex(existingSigning, entrySigning));450 if (longTermChanged || signingChanged) {451 const knownName = existing.deviceName ?? entry.deviceName;452 notifyPopup({ type: "DEVICE_KEY_ROTATED", payload: { deviceName: knownName, deviceId: entry.deviceId } });453 void recordSyncAlerts([{454 type: "DEVICE_KEY_ROTATED",455 entryId: "",456 entryTitle: knownName,457 deviceName: knownName,458 timestamp: Date.now(),459 }]);460 continue;461 }462 pendingRegistry.push({463 ...existing,464 deviceId: entry.deviceId,465 deviceName: existing.deviceName ?? entry.deviceName,466 deviceType: entry.deviceType,467 longTermPublicKeyHex: existing.longTermPublicKeyHex ?? entry.longTermPublicKeyHex.toLowerCase(),468 signingPublicKeyHex: existing.signingPublicKeyHex ?? entry.signingPublicKeyHex.toLowerCase(),469 pairedAt: existing.pairedAt ?? entry.pairedAt,470 trustSource: existing.trustSource,471 wsPort: existing.wsPort ?? entry.wsPort,472 relayUrl: existing.trustSource === "vouched" && meshRoute ? meshRoute.relayUrl : existing.relayUrl,473 lastSyncedAt: existing.lastSyncedAt,474 });475 if (existing.trustSource === "vouched" && meshRoute) {476 pendingSecrets.push({ deviceId: entry.deviceId, secret: meshRoute.rendezvousSecretHex });477 }478 }479 const newlyRevoked = await upsertPairedDevicesAndMergeRevocations(480 pendingRegistry,481 body.revoked.filter((r) => r.deviceId !== ourDeviceId),482 );483 for (const deviceId of newlyRevoked) {484 await removePendingVouchedDevice(deviceId);485 void recordSyncAlerts([{486 type: "DEVICE_REVOKED",487 entryId: "",488 entryTitle: deviceId,489 deviceName: issuer.deviceName ?? "paired device",490 timestamp: Date.now(),491 }]);492 }493 for (const pending of pendingSecrets) {494 if (newlyRevoked.includes(pending.deviceId)) continue;495 await setPairSecret(pending.deviceId, pending.secret, masterKey);496 }497 for (const deviceId of pendingVouchedIds) {498 if (newlyRevoked.includes(deviceId)) continue;499 await removePendingVouchedDevice(deviceId);500 }501 } finally {502 masterKey.fill(0);503 localKeys.secretKey.fill(0);504 localKeys.publicKey.fill(0);505 }506}507508function deriveManifestMeshRoute(509 localPrivateKey: Uint8Array,510 localPublicKey: Uint8Array,511 entry: ManifestDeviceEntry,512): { rendezvousSecretHex: string; relayUrl: string } | null {513 try {514 if (!entry.relayUrl) return null;515 const relayUrl = normalizeRelayUrl(entry.relayUrl);516 const secret = deriveMeshRendezvousSecret(517 localPrivateKey,518 localPublicKey,519 hexToPubkey(entry.longTermPublicKeyHex),520 );521 try {522 return {523 rendezvousSecretHex: rendezvousBytesToHex(secret),524 relayUrl,525 };526 } finally {527 secret.fill(0);528 }529 } catch {530 return null;531 }532}533534function notifyPopup(msg: { type: string; payload?: unknown }): void {535 try {536 void chrome.runtime.sendMessage(msg).catch(() => undefined);537 } catch {538 539 }540}541542function requireUnlocked(): void {543 if (!isUnlocked()) throw new VaultLockedError();544}545546function requireRealUnlocked(): void {547 if (!isUnlocked() || isDecoyMode()) throw new VaultLockedError();548}549550551552553554555556function requireMasterKey(): Uint8Array {557 if (!isUnlocked()) throw new VaultLockedError();558 const hex = getRootKeyHex();559 if (!hex) throw new VaultLockedError();560 return hexToBytes(hex);561}562563async function deriveEntryKey(masterKey: Uint8Array, entryId: string): Promise<CryptoKey> {564 565 566 567 568 const info = new TextEncoder().encode(`${entryId}\x00${ENTRY_KEY_INFO_SUFFIX}`);569 const raw = new HKDF(SHA256, masterKey, new Uint8Array(0), info).expand(32);570 return crypto.subtle.importKey(571 "raw",572 raw.buffer as ArrayBuffer,573 { name: "AES-GCM" },574 false,575 ["encrypt", "decrypt"],576 );577}578579async function encryptEntry(key: CryptoKey, entry: VaultEntry): Promise<string> {580 const plaintext = new TextEncoder().encode(JSON.stringify(entry));581 const nonce = crypto.getRandomValues(new Uint8Array(12));582 const aad = new TextEncoder().encode(ENTRY_AAD);583 const ct = await crypto.subtle.encrypt(584 {585 name: "AES-GCM",586 iv: nonce.buffer as ArrayBuffer,587 additionalData: aad.buffer as ArrayBuffer,588 tagLength: 128,589 },590 key,591 plaintext.buffer as ArrayBuffer,592 );593 const ctBytes = new Uint8Array(ct);594 const envelope = new Uint8Array(nonce.length + ctBytes.length);595 envelope.set(nonce, 0);596 envelope.set(ctBytes, nonce.length);597 return bytesToBase64(envelope);598}599600async function decryptEntryOrNull(key: CryptoKey, envelopeB64: string): Promise<VaultEntry | null> {601 try {602 const bytes = base64ToBytes(envelopeB64);603 if (bytes.length < 12 + 16) return null;604 const nonce = bytes.subarray(0, 12);605 const ct = bytes.subarray(12);606 const aad = new TextEncoder().encode(ENTRY_AAD);607 const pt = await crypto.subtle.decrypt(608 {609 name: "AES-GCM",610 iv: nonce.buffer.slice(nonce.byteOffset, nonce.byteOffset + nonce.byteLength) as ArrayBuffer,611 additionalData: aad.buffer as ArrayBuffer,612 tagLength: 128,613 },614 key,615 ct.buffer.slice(ct.byteOffset, ct.byteOffset + ct.byteLength) as ArrayBuffer,616 );617 const json = new TextDecoder().decode(pt);618 const parsed = JSON.parse(json);619 if (!parsed || typeof parsed !== "object" || typeof parsed.id !== "string") return null;620 return parsed as VaultEntry;621 } catch {622 return null;623 }624}625626function hexToBytes(hex: string): Uint8Array {627 if (hex.length % 2 !== 0) throw new Error("hex length must be even");628 const out = new Uint8Array(hex.length / 2);629 for (let i = 0; i < out.length; i++) {630 out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);631 }632 return out;633}634635function bytesToBase64(bytes: Uint8Array): string {636 let bin = "";637 for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);638 return btoa(bin);639}640641function bytesToHex(bytes: Uint8Array): string {642 return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");643}644645function base64ToBytes(b64: string): Uint8Array {646 const bin = atob(b64);647 const out = new Uint8Array(bin.length);648 for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);649 return out;650}