locked-sync-spool.ts

7.3 KB · raw

1import type { SyncVaultAdapter } from "./sync-coordinator";2import type { SyncPeerIdentity } from "../shared/sync-transport";3import { SYNC_LIMITS, clampSyncTimestamp } from "../shared/sync-limits";4import type { DeviceType } from "../shared/sync-types";56const STORAGE_KEY = "peach_locked_sync_spool_v1";78interface CachedEntry {9  modifiedAt: number;10  ciphertext: string;11}1213interface StagedEntry extends CachedEntry {}1415interface LockedSyncSpool {16  version: 1;17  vaultId: string;18  deviceId: string;19  deviceName: string;20  deviceType: DeviceType;21  localVersion: number;22  longTermPublicKeyHex: string;23  longTermPrivateKeyHex: string;24  entries: Record<string, CachedEntry>;25  tombstones: Record<string, number>;26  inboxEntries: Record<string, StagedEntry>;27  inboxTombstones: Record<string, number>;28}2930let spoolMutation: Promise<void> = Promise.resolve();3132export async function replaceLockedSyncSpool(33  next: Omit<LockedSyncSpool, "version" | "inboxEntries" | "inboxTombstones">,34): Promise<void> {35  await mutateSpool(async (current) => {36    await saveSpool({37      ...next,38      version: 1,39      inboxEntries: current?.inboxEntries ?? {},40      inboxTombstones: current?.inboxTombstones ?? {},41    });42  });43}4445export async function getLockedSyncIdentity(): Promise<SyncPeerIdentity | null> {46  const spool = await loadSpool();47  if (!spool) return null;48  return {49    deviceId: spool.deviceId,50    deviceName: spool.deviceName,51    deviceType: spool.deviceType,52    longTermPublicKeyHex: spool.longTermPublicKeyHex,53    longTermPrivateKey: hexToBytes(spool.longTermPrivateKeyHex),54  };55}5657export async function drainLockedSyncInbox(58  live: SyncVaultAdapter,59): Promise<void> {60  const snapshot = await loadSpool();61  if (!snapshot) return;62  const entries = Object.fromEntries(63    Object.entries(snapshot.inboxEntries).map(([id, entry]) => [id, entry.ciphertext]),64  );65  const manifest = Object.fromEntries(66    Object.entries(snapshot.inboxEntries).map(([id, entry]) => [id, entry.modifiedAt]),67  );68  if (Object.keys(entries).length > 0) await live.applyEntries(entries, manifest);69  if (Object.keys(snapshot.inboxTombstones).length > 0) {70    await live.applyTombstones(snapshot.inboxTombstones);71  }72  await mutateSpool(async (current) => {73    if (!current) return;74    const inboxEntries = { ...current.inboxEntries };75    const inboxTombstones = { ...current.inboxTombstones };76    for (const [id, applied] of Object.entries(snapshot.inboxEntries)) {77      if (inboxEntries[id]?.ciphertext === applied.ciphertext) delete inboxEntries[id];78    }79    for (const [id, appliedAt] of Object.entries(snapshot.inboxTombstones)) {80      if (inboxTombstones[id] === appliedAt) delete inboxTombstones[id];81    }82    await saveSpool({ ...current, inboxEntries, inboxTombstones });83  });84}8586export async function createLockedSyncVaultAdapter(): Promise<SyncVaultAdapter | null> {87  const snapshot = await loadSpool();88  if (!snapshot) return null;89  return {90    async computeVaultId() { return snapshot.vaultId; },91    async getOurDeviceId() { return snapshot.deviceId; },92    async getLocalVersion() { return snapshot.localVersion; },93    async buildEntryManifest() {94      return Object.fromEntries(95        Object.entries(snapshot.entries).map(([id, entry]) => [id, entry.modifiedAt]),96      );97    },98    async buildTombstoneManifest() { return { ...snapshot.tombstones }; },99    async getEncryptedEntries(entryIds) {100      const out: Record<string, string> = {};101      for (const id of entryIds) {102        const entry = snapshot.entries[id];103        if (entry) out[id] = entry.ciphertext;104      }105      return out;106    },107    async applyEntries(entries, remoteManifest = {}) {108      const list = Object.entries(entries);109      if (list.length > SYNC_LIMITS.MAX_ENTRY_COUNT) throw new Error("sync_entry_count_exceeded");110      await mutateSpool(async (current) => {111        if (!current || current.vaultId !== snapshot.vaultId) return;112        const inbox = { ...current.inboxEntries };113        const now = Date.now();114        for (const [id, ciphertext] of list) {115          const claimed = remoteManifest[id];116          if (117            typeof claimed !== "number" || !Number.isFinite(claimed) || claimed <= 0 ||118            ciphertext.length > (SYNC_LIMITS.MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3 + 64119          ) continue;120          const modifiedAt = clampSyncTimestamp(claimed, now);121          if ((inbox[id]?.modifiedAt ?? 0) < modifiedAt) {122            inbox[id] = { modifiedAt, ciphertext };123          }124        }125        if (Object.keys(inbox).length > SYNC_LIMITS.MAX_ENTRY_COUNT) {126          throw new Error("sync_entry_count_exceeded");127        }128        await saveSpool({ ...current, inboxEntries: inbox });129      });130    },131    async applyTombstones(tombstones) {132      const list = Object.entries(tombstones);133      if (list.length > SYNC_LIMITS.MAX_TOMBSTONE_COUNT) throw new Error("sync_tombstone_count_exceeded");134      await mutateSpool(async (current) => {135        if (!current || current.vaultId !== snapshot.vaultId) return;136        const inbox = { ...current.inboxTombstones };137        const now = Date.now();138        for (const [id, value] of list) {139          if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) continue;140          const deletedAt = clampSyncTimestamp(value, now);141          if ((inbox[id] ?? 0) < deletedAt) inbox[id] = deletedAt;142        }143        if (Object.keys(inbox).length > SYNC_LIMITS.MAX_TOMBSTONE_COUNT) {144          throw new Error("sync_tombstone_count_exceeded");145        }146        await saveSpool({ ...current, inboxTombstones: inbox });147      });148    },149  };150}151152async function mutateSpool(work: (spool: LockedSyncSpool | null) => Promise<void>): Promise<void> {153  const next = spoolMutation.then(async () => work(await loadSpool()));154  spoolMutation = next.catch(() => undefined);155  return next;156}157158async function loadSpool(): Promise<LockedSyncSpool | null> {159  const result = await chrome.storage.local.get(STORAGE_KEY);160  const value = (result as Record<string, unknown>)[STORAGE_KEY];161  return isLockedSyncSpool(value) ? value : null;162}163164async function saveSpool(spool: LockedSyncSpool): Promise<void> {165  await chrome.storage.local.set({ [STORAGE_KEY]: spool });166}167168function isLockedSyncSpool(value: unknown): value is LockedSyncSpool {169  if (!value || typeof value !== "object") return false;170  const candidate = value as Partial<LockedSyncSpool>;171  return candidate.version === 1 &&172    typeof candidate.vaultId === "string" && /^[0-9a-f]{64}$/.test(candidate.vaultId) &&173    typeof candidate.deviceId === "string" && candidate.deviceId.length > 0 &&174    typeof candidate.deviceName === "string" &&175    typeof candidate.longTermPublicKeyHex === "string" && /^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) &&176    typeof candidate.longTermPrivateKeyHex === "string" && /^[0-9a-f]{64}$/.test(candidate.longTermPrivateKeyHex) &&177    typeof candidate.localVersion === "number" &&178    isRecord(candidate.entries) && isRecord(candidate.tombstones) &&179    isRecord(candidate.inboxEntries) && isRecord(candidate.inboxTombstones);180}181182function isRecord(value: unknown): value is Record<string, unknown> {183  return !!value && typeof value === "object" && !Array.isArray(value);184}185186function hexToBytes(hex: string): Uint8Array {187  const out = new Uint8Array(hex.length / 2);188  for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);189  return out;190}