1234567891011121314151617181920212223import { HKDF } from "@stablelib/hkdf";24import { SHA256 } from "@stablelib/sha256";25import type { ChirpSyncVaultAdapter } from "./chirp-sync-coordinator";26import { getOrCreateDeviceId } from "./chirp-identity";27import {28 computeVaultId,29 deriveSyncSigningKeypair,30 hexToPubkey,31} from "../shared/sync-identity";32import {33 buildSignedDeviceManifest,34 verifyDeviceManifest,35} from "../shared/device-manifest";36import {37 applyMergedRemoteEntries,38 getDeletedEntries,39 getRootKeyHex,40 getEntries,41 getEntryById,42 getVaultVersion,43 isUnlocked,44} from "./vault";45import {46 findPairedDeviceById,47 listPairedDevices,48 upsertPairedDevice,49} from "./paired-devices";50import { addPendingVouchedDevice } from "./pending-vouched-devices";51import { recordSyncAlerts } from "./sync-alerts";52import { SYNC_LIMITS, clampSyncTimestamp } from "../shared/sync-limits";53import type { VaultEntry } from "../shared/types";54import type {55 ManifestDeviceEntry,56 PairedDevice,57 SignedDeviceManifest,58} from "../shared/sync-types";59606162const ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1";63const ENTRY_AAD = "peach-sync-entry-v1";6465export class VaultLockedError extends Error {66 constructor() {67 super("vault_locked");68 this.name = "VaultLockedError";69 }70}7172export function createChirpSyncVaultAdapter(73 context: { deviceName?: string } = {},74): ChirpSyncVaultAdapter {75 return {76 async computeVaultId() {77 const master = requireMasterKey();78 return computeVaultId(master);79 },8081 async getOurDeviceId() {82 return getOrCreateDeviceId();83 },8485 async getLocalVersion() {86 return getVaultVersion();87 },8889 async buildEntryManifest() {90 requireUnlocked();91 const manifest: Record<string, number> = {};92 for (const entry of getEntries()) {93 manifest[entry.id] = entry.modifiedAt;94 }95 return manifest;96 },9798 async buildTombstoneManifest() {99 100 101 102 103 104 105 106 requireUnlocked();107 const manifest: Record<string, number> = {};108 for (const entry of getDeletedEntries()) {109 if (typeof entry.deletedAt === "number") {110 manifest[entry.id] = entry.deletedAt;111 }112 }113 return manifest;114 },115116 async getEncryptedEntries(entryIds) {117 requireUnlocked();118 const masterKey = requireMasterKey();119 const out: Record<string, string> = {};120 for (const id of entryIds) {121 const entry = getEntryById(id);122 if (!entry) continue;123 const key = await deriveEntryKey(masterKey, id);124 out[id] = await encryptEntry(key, entry);125 }126 return out;127 },128129 async applyEntries(entries) {130 requireUnlocked();131 const entryList = Object.entries(entries);132 133 if (entryList.length > SYNC_LIMITS.MAX_ENTRY_COUNT) {134 throw new Error(135 `sync entry count ${entryList.length} exceeds limit ${SYNC_LIMITS.MAX_ENTRY_COUNT}`,136 );137 }138 const masterKey = requireMasterKey();139 const decrypted: VaultEntry[] = [];140 for (const [id, envelope] of entryList) {141 142 143 if (envelope.length > (SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3 + 64) {144 continue; 145 }146 const key = await deriveEntryKey(masterKey, id);147 const entry = await decryptEntryOrNull(key, envelope);148 if (!entry) continue;149 150 if (JSON.stringify(entry).length > SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES) {151 continue;152 }153 154 155 if (entry.id !== id) continue;156 decrypted.push(entry);157 }158 if (decrypted.length > 0) {159 await applyMergedRemoteEntries(decrypted, {}, context);160 }161 },162163 async applyTombstones(tombstones) {164 requireUnlocked();165 const tombstoneList = Object.entries(tombstones);166 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 176 177 178 cleaned[id] = clampSyncTimestamp(ts);179 }180 }181 if (Object.keys(cleaned).length > 0) {182 await applyMergedRemoteEntries([], cleaned, context);183 }184 },185186 async buildOutgoingDeviceManifest() {187 requireUnlocked();188 const masterKey = requireMasterKey();189 const issuerDeviceId = await getOrCreateDeviceId();190 const signing = await deriveSyncSigningKeypair(masterKey, issuerDeviceId);191 const devices = (await listPairedDevices())192 .map(toManifestEntry)193 .filter((d): d is ManifestDeviceEntry => d !== null);194 return buildSignedDeviceManifest(195 issuerDeviceId,196 devices,197 signing.privateKey,198 );199 },200201 async applyIncomingDeviceManifest(manifest) {202 requireUnlocked();203 await applyVerifiedExtensionManifest(manifest);204 },205 };206}207208function toManifestEntry(device: PairedDevice): ManifestDeviceEntry | null {209 if (210 !device.deviceId ||211 !device.deviceName ||212 !device.deviceType ||213 !device.longTermPublicKeyHex ||214 !/^[0-9a-f]{64}$/.test(device.longTermPublicKeyHex) ||215 !device.signingPublicKeyHex ||216 !/^[0-9a-f]{64}$/.test(device.signingPublicKeyHex)217 ) {218 return null;219 }220 return {221 deviceId: device.deviceId,222 deviceName: device.deviceName,223 deviceType: device.deviceType,224 longTermPublicKeyHex: device.longTermPublicKeyHex,225 signingPublicKeyHex: device.signingPublicKeyHex,226 wsPort: device.wsPort,227 pairedAt: device.pairedAt,228 };229}230231async function applyVerifiedExtensionManifest(232 manifest: SignedDeviceManifest,233): Promise<void> {234 const issuerId = manifest?.body?.issuerDeviceId;235 if (typeof issuerId !== "string" || !issuerId) return;236237 const issuer = await findPairedDeviceById(issuerId);238 if (239 !issuer ||240 issuer.deviceType !== "extension" ||241 !issuer.signingPublicKeyHex ||242 !/^[0-9a-f]{64}$/.test(issuer.signingPublicKeyHex)243 ) {244 return;245 }246247 let body: Awaited<ReturnType<typeof verifyDeviceManifest>>;248 try {249 body = await verifyDeviceManifest(250 manifest,251 hexToPubkey(issuer.signingPublicKeyHex),252 );253 } catch {254 return;255 }256 if (body.issuerDeviceId !== issuer.deviceId) return;257258 const ourDeviceId = await getOrCreateDeviceId();259 for (const entry of body.devices) {260 if (entry.deviceId === ourDeviceId || entry.deviceId === issuer.deviceId) {261 continue;262 }263 const existing = await findPairedDeviceById(entry.deviceId);264265 266 267 268 269 270 if (!existing) {271 await addPendingVouchedDevice({272 deviceId: entry.deviceId,273 deviceName: entry.deviceName,274 deviceType: entry.deviceType,275 longTermPublicKeyHex: entry.longTermPublicKeyHex.toLowerCase(),276 signingPublicKeyHex: entry.signingPublicKeyHex.toLowerCase(),277 wsPort: entry.wsPort,278 pairedAt: entry.pairedAt,279 receivedAt: Date.now(),280 vouchedByDeviceId: issuer.deviceId,281 });282 notifyPopup({283 type: "VOUCHED_DEVICE_PENDING",284 payload: { deviceName: entry.deviceName, deviceId: entry.deviceId },285 });286 continue; 287 }288289 290 291 292 293 if (294 existing.longTermPublicKeyHex &&295 existing.longTermPublicKeyHex !== entry.longTermPublicKeyHex.toLowerCase()296 ) {297 notifyPopup({298 type: "DEVICE_KEY_ROTATED",299 payload: { deviceName: entry.deviceName, deviceId: entry.deviceId },300 });301 void recordSyncAlerts([302 {303 type: "DEVICE_KEY_ROTATED",304 entryId: "",305 entryTitle: entry.deviceName,306 deviceName: entry.deviceName,307 timestamp: Date.now(),308 },309 ]);310 }311312 313 await upsertPairedDevice({314 ...existing,315 deviceId: entry.deviceId,316 deviceName: entry.deviceName,317 deviceType: entry.deviceType,318 longTermPublicKeyHex: entry.longTermPublicKeyHex.toLowerCase(),319 signingPublicKeyHex: entry.signingPublicKeyHex.toLowerCase(),320 pairedAt: existing.pairedAt ?? entry.pairedAt,321 trustSource: existing.trustSource ?? "direct",322 wsPort: existing.wsPort ?? entry.wsPort,323 lastSyncedAt: existing.lastSyncedAt,324 });325 }326}327328329330function notifyPopup(msg: { type: string; payload?: unknown }): void {331 try {332 void chrome.runtime.sendMessage(msg).catch(() => undefined);333 } catch {334 335 }336}337338function requireUnlocked(): void {339 if (!isUnlocked()) throw new VaultLockedError();340}341342343344345346347348function requireMasterKey(): Uint8Array {349 if (!isUnlocked()) throw new VaultLockedError();350 const hex = getRootKeyHex();351 if (!hex) throw new VaultLockedError();352 return hexToBytes(hex);353}354355async function deriveEntryKey(masterKey: Uint8Array, entryId: string): Promise<CryptoKey> {356 357 358 359 360 const info = new TextEncoder().encode(`${entryId}\x00${ENTRY_KEY_INFO_SUFFIX}`);361 const raw = new HKDF(SHA256, masterKey, new Uint8Array(0), info).expand(32);362 return crypto.subtle.importKey(363 "raw",364 raw.buffer as ArrayBuffer,365 { name: "AES-GCM" },366 false,367 ["encrypt", "decrypt"],368 );369}370371async function encryptEntry(key: CryptoKey, entry: VaultEntry): Promise<string> {372 const plaintext = new TextEncoder().encode(JSON.stringify(entry));373 const nonce = crypto.getRandomValues(new Uint8Array(12));374 const aad = new TextEncoder().encode(ENTRY_AAD);375 const ct = await crypto.subtle.encrypt(376 {377 name: "AES-GCM",378 iv: nonce.buffer as ArrayBuffer,379 additionalData: aad.buffer as ArrayBuffer,380 tagLength: 128,381 },382 key,383 plaintext.buffer as ArrayBuffer,384 );385 const ctBytes = new Uint8Array(ct);386 const envelope = new Uint8Array(nonce.length + ctBytes.length);387 envelope.set(nonce, 0);388 envelope.set(ctBytes, nonce.length);389 return bytesToBase64(envelope);390}391392async function decryptEntryOrNull(key: CryptoKey, envelopeB64: string): Promise<VaultEntry | null> {393 try {394 const bytes = base64ToBytes(envelopeB64);395 if (bytes.length < 12 + 16) return null;396 const nonce = bytes.subarray(0, 12);397 const ct = bytes.subarray(12);398 const aad = new TextEncoder().encode(ENTRY_AAD);399 const pt = await crypto.subtle.decrypt(400 {401 name: "AES-GCM",402 iv: nonce.buffer.slice(nonce.byteOffset, nonce.byteOffset + nonce.byteLength) as ArrayBuffer,403 additionalData: aad.buffer as ArrayBuffer,404 tagLength: 128,405 },406 key,407 ct.buffer.slice(ct.byteOffset, ct.byteOffset + ct.byteLength) as ArrayBuffer,408 );409 const json = new TextDecoder().decode(pt);410 const parsed = JSON.parse(json);411 if (!parsed || typeof parsed !== "object" || typeof parsed.id !== "string") return null;412 return parsed as VaultEntry;413 } catch {414 return null;415 }416}417418function hexToBytes(hex: string): Uint8Array {419 if (hex.length % 2 !== 0) throw new Error("hex length must be even");420 const out = new Uint8Array(hex.length / 2);421 for (let i = 0; i < out.length; i++) {422 out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);423 }424 return out;425}426427function bytesToBase64(bytes: Uint8Array): string {428 let bin = "";429 for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);430 return btoa(bin);431}432433function base64ToBytes(b64: string): Uint8Array {434 const bin = atob(b64);435 const out = new Uint8Array(bin.length);436 for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);437 return out;438}