chirp-sync-vault-adapter.ts

11.8 KB · raw

1// Production adapter that backs `runChirpSyncInitiator` with the live vault.2//3// The coordinator (chirp-sync-coordinator.ts) never decrypts vault data; it4// only moves opaque base64 entry blobs and metadata. This adapter is the5// boundary where vault plaintext meets the sync layer — entries leave the6// vault as encrypted envelopes here, and incoming envelopes are decrypted7// here before being merged via `applyMergedRemoteEntries`.8//9// Envelope cipher: AES-GCM with a PER-ENTRY key derived as10//   HKDF-SHA256(ikm = syncMasterKey, salt = "", info = entryId + "sync-entry-v1")11// (random 12B nonce, aad = "peach-sync-entry-v1"). Binding the key to the12// entry id means a ciphertext minted for one entry slot cannot be replayed13// into another: decryptEntryOrNull rejects any envelope whose decrypted14// entry.id does not match the map key it arrived under. Both sides hold the15// same syncMasterKey (same vault) so keys match without prior negotiation. The16// Noise XX session encrypts the transport on top — the envelope is17// belt-and-braces so a transport-layer leak doesn't expose plaintext entries.18//19// Device-manifest exchange (v2 brief §4.3) is plumbed here. The extension is20// the trust anchor: manifests are signed with its vault-derived Ed25519 key,21// and receivers only apply manifests whose issuer is a paired extension.2223import { 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 { clampSyncTimestamp } from "../shared/sync-limits";51import type { VaultEntry } from "../shared/types";52import type {53  ManifestDeviceEntry,54  PairedDevice,55  SignedDeviceManifest,56} from "../shared/sync-types";5758// Each entry uses a unique AES-GCM key: HKDF(masterKey, info = entryId + "sync-entry-v1").59// The info binding prevents a ciphertext from one entry slot being replayed into another.60const ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1";61const ENTRY_AAD = "peach-sync-entry-v1";6263export class VaultLockedError extends Error {64  constructor() {65    super("vault_locked");66    this.name = "VaultLockedError";67  }68}6970export function createChirpSyncVaultAdapter(71  context: { deviceName?: string } = {},72): ChirpSyncVaultAdapter {73  return {74    async computeVaultId() {75      const master = requireMasterKey();76      return computeVaultId(master);77    },7879    async getOurDeviceId() {80      return getOrCreateDeviceId();81    },8283    async getLocalVersion() {84      return getVaultVersion();85    },8687    async buildEntryManifest() {88      requireUnlocked();89      const manifest: Record<string, number> = {};90      for (const entry of getEntries()) {91        manifest[entry.id] = entry.modifiedAt;92      }93      return manifest;94    },9596    async buildTombstoneManifest() {97      // KNOWN LIMITATION: tombstones accumulate without bound. Every deleted98      // entry leaves a {id, deletedAt} record that persists indefinitely and is99      // sent in every sync session, so a long-lived vault's manifest grows with100      // total deletions, not live entries. Acceptable for now (records are tiny101      // and the trash-retention purge eventually splices the entry array).102      // Future: prune tombstones older than N months once every paired device103      // has confirmed it holds no entry with that id.104      requireUnlocked();105      const manifest: Record<string, number> = {};106      for (const entry of getDeletedEntries()) {107        if (typeof entry.deletedAt === "number") {108          manifest[entry.id] = entry.deletedAt;109        }110      }111      return manifest;112    },113114    async getEncryptedEntries(entryIds) {115      requireUnlocked();116      const masterKey = requireMasterKey();117      const out: Record<string, string> = {};118      for (const id of entryIds) {119        const entry = getEntryById(id);120        if (!entry) continue;121        const key = await deriveEntryKey(masterKey, id);122        out[id] = await encryptEntry(key, entry);123      }124      return out;125    },126127    async applyEntries(entries) {128      requireUnlocked();129      const masterKey = requireMasterKey();130      const decrypted: VaultEntry[] = [];131      for (const [id, envelope] of Object.entries(entries)) {132        const key = await deriveEntryKey(masterKey, id);133        const entry = await decryptEntryOrNull(key, envelope);134        if (!entry) continue;135        // The map key is the authority on id — refuse mismatched envelopes136        // so a swapped envelope can't poison a different entry slot.137        if (entry.id !== id) continue;138        decrypted.push(entry);139      }140      if (decrypted.length > 0) {141        await applyMergedRemoteEntries(decrypted, {}, context);142      }143    },144145    async applyTombstones(tombstones) {146      requireUnlocked();147      const cleaned: Record<string, number> = {};148      for (const [id, ts] of Object.entries(tombstones)) {149        if (typeof ts === "number" && Number.isFinite(ts) && ts > 0) {150          // HV-1c: clamp before the value participates in any comparison.151          // vault.ts clamps again defensively; clamping here keeps the152          // invariant local to the boundary where peer data enters.153          cleaned[id] = clampSyncTimestamp(ts);154        }155      }156      if (Object.keys(cleaned).length > 0) {157        await applyMergedRemoteEntries([], cleaned, context);158      }159    },160161    async buildOutgoingDeviceManifest() {162      requireUnlocked();163      const masterKey = requireMasterKey();164      const issuerDeviceId = await getOrCreateDeviceId();165      const signing = await deriveSyncSigningKeypair(masterKey, issuerDeviceId);166      const devices = (await listPairedDevices())167        .map(toManifestEntry)168        .filter((d): d is ManifestDeviceEntry => d !== null);169      return buildSignedDeviceManifest(170        issuerDeviceId,171        devices,172        signing.privateKey,173      );174    },175176    async applyIncomingDeviceManifest(manifest) {177      requireUnlocked();178      await applyVerifiedExtensionManifest(manifest);179    },180  };181}182183function toManifestEntry(device: PairedDevice): ManifestDeviceEntry | null {184  if (185    !device.deviceId ||186    !device.deviceName ||187    !device.deviceType ||188    !device.longTermPublicKeyHex ||189    !/^[0-9a-f]{64}$/.test(device.longTermPublicKeyHex) ||190    !device.signingPublicKeyHex ||191    !/^[0-9a-f]{64}$/.test(device.signingPublicKeyHex)192  ) {193    return null;194  }195  return {196    deviceId: device.deviceId,197    deviceName: device.deviceName,198    deviceType: device.deviceType,199    longTermPublicKeyHex: device.longTermPublicKeyHex,200    signingPublicKeyHex: device.signingPublicKeyHex,201    wsPort: device.wsPort,202    pairedAt: device.pairedAt,203  };204}205206async function applyVerifiedExtensionManifest(207  manifest: SignedDeviceManifest,208): Promise<void> {209  const issuerId = manifest?.body?.issuerDeviceId;210  if (typeof issuerId !== "string" || !issuerId) return;211212  const issuer = await findPairedDeviceById(issuerId);213  if (214    !issuer ||215    issuer.deviceType !== "extension" ||216    !issuer.signingPublicKeyHex ||217    !/^[0-9a-f]{64}$/.test(issuer.signingPublicKeyHex)218  ) {219    return;220  }221222  let body: Awaited<ReturnType<typeof verifyDeviceManifest>>;223  try {224    body = await verifyDeviceManifest(225      manifest,226      hexToPubkey(issuer.signingPublicKeyHex),227    );228  } catch {229    return;230  }231  if (body.issuerDeviceId !== issuer.deviceId) return;232233  const ourDeviceId = await getOrCreateDeviceId();234  for (const entry of body.devices) {235    if (entry.deviceId === ourDeviceId || entry.deviceId === issuer.deviceId) {236      continue;237    }238    const existing = await findPairedDeviceById(entry.deviceId);239    await upsertPairedDevice({240      ...(existing ?? {}),241      deviceId: entry.deviceId,242      deviceName: entry.deviceName,243      deviceType: entry.deviceType,244      longTermPublicKeyHex: entry.longTermPublicKeyHex.toLowerCase(),245      signingPublicKeyHex: entry.signingPublicKeyHex.toLowerCase(),246      pairedAt: existing?.pairedAt ?? entry.pairedAt,247      trustSource: existing?.trustSource ?? (existing ? "direct" : "vouched"),248      wsPort: existing?.wsPort ?? entry.wsPort,249      lastSyncedAt: existing?.lastSyncedAt,250    });251  }252}253254function requireUnlocked(): void {255  if (!isUnlocked()) throw new VaultLockedError();256}257258// Sync derives everything — vault_id, the Noise XX static key, the Ed25519259// manifest signing key, and the per-entry envelope keys — from the vault's260// stable root key, NOT the password-derived key. This keeps paired devices'261// identities and envelope keys constant across a master-password change on262// either side (SEV-2-B); two paired devices with independently-rotated263// passwords still share this key and can decrypt each other's entries.264function requireMasterKey(): Uint8Array {265  if (!isUnlocked()) throw new VaultLockedError();266  const hex = getRootKeyHex();267  if (!hex) throw new VaultLockedError();268  return hexToBytes(hex);269}270271async function deriveEntryKey(masterKey: Uint8Array, entryId: string): Promise<CryptoKey> {272  const info = new TextEncoder().encode(entryId + ENTRY_KEY_INFO_SUFFIX);273  const raw = new HKDF(SHA256, masterKey, new Uint8Array(0), info).expand(32);274  return crypto.subtle.importKey(275    "raw",276    raw.buffer as ArrayBuffer,277    { name: "AES-GCM" },278    false,279    ["encrypt", "decrypt"],280  );281}282283async function encryptEntry(key: CryptoKey, entry: VaultEntry): Promise<string> {284  const plaintext = new TextEncoder().encode(JSON.stringify(entry));285  const nonce = crypto.getRandomValues(new Uint8Array(12));286  const aad = new TextEncoder().encode(ENTRY_AAD);287  const ct = await crypto.subtle.encrypt(288    {289      name: "AES-GCM",290      iv: nonce.buffer as ArrayBuffer,291      additionalData: aad.buffer as ArrayBuffer,292      tagLength: 128,293    },294    key,295    plaintext.buffer as ArrayBuffer,296  );297  const ctBytes = new Uint8Array(ct);298  const envelope = new Uint8Array(nonce.length + ctBytes.length);299  envelope.set(nonce, 0);300  envelope.set(ctBytes, nonce.length);301  return bytesToBase64(envelope);302}303304async function decryptEntryOrNull(key: CryptoKey, envelopeB64: string): Promise<VaultEntry | null> {305  try {306    const bytes = base64ToBytes(envelopeB64);307    if (bytes.length < 12 + 16) return null;308    const nonce = bytes.subarray(0, 12);309    const ct = bytes.subarray(12);310    const aad = new TextEncoder().encode(ENTRY_AAD);311    const pt = await crypto.subtle.decrypt(312      {313        name: "AES-GCM",314        iv: nonce.buffer.slice(nonce.byteOffset, nonce.byteOffset + nonce.byteLength) as ArrayBuffer,315        additionalData: aad.buffer as ArrayBuffer,316        tagLength: 128,317      },318      key,319      ct.buffer.slice(ct.byteOffset, ct.byteOffset + ct.byteLength) as ArrayBuffer,320    );321    const json = new TextDecoder().decode(pt);322    const parsed = JSON.parse(json);323    if (!parsed || typeof parsed !== "object" || typeof parsed.id !== "string") return null;324    return parsed as VaultEntry;325  } catch {326    return null;327  }328}329330function hexToBytes(hex: string): Uint8Array {331  if (hex.length % 2 !== 0) throw new Error("hex length must be even");332  const out = new Uint8Array(hex.length / 2);333  for (let i = 0; i < out.length; i++) {334    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);335  }336  return out;337}338339function bytesToBase64(bytes: Uint8Array): string {340  let bin = "";341  for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);342  return btoa(bin);343}344345function base64ToBytes(b64: string): Uint8Array {346  const bin = atob(b64);347  const out = new Uint8Array(bin.length);348  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);349  return out;350}