sync-generation.ts

20.5 KB · raw

1// The durable Sync-generation record and its state machine (protocol §11).2//3// One record per installation, under a key no legacy build knows, so an older4// build cannot overwrite it and a fresh install can tell itself apart from an5// install that merely lost its identity. A missing or corrupt identity over any6// existing trust is a reset condition, never a silent re-mint.7//8// The record carries no secret, so this module reads and writes it while the9// vault is locked. Everything else it touches is injected through10// [SyncGenerationIo], which keeps every transition — and every crash point11// inside one — testable without Chrome.1213import { storageGet, storageSet } from "../shared/storage";14import { PAIR_SECRETS_KEY, SESSION_PAIR_SECRETS_KEY, dropSessionCache } from "./pair-secrets";15import {16  PENDING_ADOPTION_HOLDER_KEY,17  PENDING_ADOPTION_IDENTITY_KEY,18} from "./pending-adoption-holder";19import { REGISTRY_KEY, REVOCATIONS_KEY, REVOCATION_ISSUERS_KEY, hasRevocationIssuerArchive, listPairedDevices, TrustDataCorruptedError } from "./paired-devices";2021export const GENERATION_KEY = "peach_sync_generation_v1";2223const SCHEMA_VERSION = 1;24const LEGACY_GENERATION = 1;25const V2_GENERATION = 2;2627export const LEGACY_ACTIVE = "LEGACY_ACTIVE";28export const RESET_REQUIRED = "RESET_REQUIRED";29export const RESET_CONFIRMED = "RESET_CONFIRMED";30export const V2_ANCHOR = "V2_ANCHOR";31export const REPAIRING = "REPAIRING";32export const V2_ACTIVE = "V2_ACTIVE";3334/** No record could be read or derived. Refuses sync rather than guessing. */35export const GENERATION_UNKNOWN = "UNKNOWN";3637export type KnownGenerationState =38  | typeof LEGACY_ACTIVE39  | typeof RESET_REQUIRED40  | typeof RESET_CONFIRMED41  | typeof V2_ANCHOR42  | typeof REPAIRING43  | typeof V2_ACTIVE;4445export type GenerationState = KnownGenerationState | typeof GENERATION_UNKNOWN;4647export type SyncGeneration = {48  schemaVersion: number;49  generation: number;50  state: GenerationState;51  anchorDeviceId?: string;52  legacyArchiveRef?: string;53  createdAt: number;54};5556/**57 * `previous` is retained so a rewrite of the active record can be validated58 * against what it replaces, and so a crash on either side of that write leaves59 * a recoverable record (§11.2, seal before switch).60 */61export type SyncGenerationBlob = {62  schemaVersion: number;63  active: SyncGeneration;64  previous?: SyncGeneration;65};6667export type SyncDecision = "allowed" | "reset_required" | "sync_generation_unknown";6869export type ResetResult = "V2_ANCHOR" | "reset_not_completed" | "reset_archive_review_required";7071class ResetArchiveReviewRequiredError extends Error {}7273/**74 * The storage boundary. The trust probe is split per class so a test can assert75 * the refusal for each one, and archival and clearing are separate steps so a76 * crash between them is injectable.77 */78export interface SyncGenerationIo {79  readBlob(): Promise<unknown>;80  writeBlob(blob: SyncGenerationBlob): Promise<boolean>;81  hasPairedDevices(): Promise<boolean>;82  hasRevocations(): Promise<boolean>;83  hasArchivedIssuers(): Promise<boolean>;84  hasPendingHolders(): Promise<boolean>;85  hasLegacyRouteMaterial(): Promise<boolean>;86  archiveLegacyState(generation: number): Promise<string | null>;87  clearLegacyTrustState(): Promise<boolean>;88  ensureV2Identity(): Promise<boolean>;89  getDeviceId(): Promise<string>;90}9192const STATE_NAMES: Record<string, true> = {93  LEGACY_ACTIVE: true,94  RESET_REQUIRED: true,95  RESET_CONFIRMED: true,96  V2_ANCHOR: true,97  REPAIRING: true,98  V2_ACTIVE: true,99};100101export function isGenerationState(value: unknown): value is KnownGenerationState {102  return typeof value === "string" && STATE_NAMES[value] === true;103}104105export function encodeGeneration(blob: SyncGenerationBlob): string {106  return JSON.stringify(blob);107}108109/**110 * A record this build cannot read is not a record: another schema, an111 * unrecognised state, or a nonsensical generation all resolve to null, so the112 * caller refuses rather than misreading a newer generation as legacy trust.113 */114export function decodeGeneration(value: unknown): SyncGenerationBlob | null {115  try {116    const parsed: unknown = typeof value === "string" ? JSON.parse(value) : value;117    if (!parsed || typeof parsed !== "object") return null;118    const blob = parsed as Partial<SyncGenerationBlob>;119    if (blob.schemaVersion !== SCHEMA_VERSION) return null;120    const active = blob.active as Partial<SyncGeneration> | undefined;121    if (!active || !isGenerationState(active.state)) return null;122    if (!Number.isInteger(active.generation)) return null;123    if ((active.generation ?? 0) < LEGACY_GENERATION) return null;124    return blob as SyncGenerationBlob;125  } catch {126    return null;127  }128}129130export async function hasLegacyTrustState(io: SyncGenerationIo): Promise<boolean> {131  const [paired, revocations, archivedIssuers, pending, route] = await Promise.all([132    io.hasPairedDevices(),133    io.hasRevocations(),134    io.hasArchivedIssuers(),135    io.hasPendingHolders(),136    io.hasLegacyRouteMaterial(),137  ]);138  return paired || revocations || archivedIssuers || pending || route;139}140141/**142 * Read the persisted record, or derive one when none has ever been written. A143 * derived record that cannot be persisted is not trusted: the caller must not144 * act on a generation this installation may not actually hold.145 */146export async function resolveGeneration(147  io: SyncGenerationIo,148  nowMs: number = Date.now(),149): Promise<SyncGeneration> {150  const unknown: SyncGeneration = {151    schemaVersion: SCHEMA_VERSION,152    generation: LEGACY_GENERATION,153    state: GENERATION_UNKNOWN,154    createdAt: nowMs,155  };156  const raw = await io.readBlob();157  if (raw !== null && raw !== undefined) {158    return decodeGeneration(raw)?.active ?? unknown;159  }160  const hasTrust = await hasLegacyTrustState(io);161  const derived: SyncGeneration = {162    schemaVersion: SCHEMA_VERSION,163    generation: hasTrust ? LEGACY_GENERATION : V2_GENERATION,164    state: hasTrust ? LEGACY_ACTIVE : V2_ACTIVE,165    createdAt: nowMs,166  };167  return (await io.writeBlob({ schemaVersion: SCHEMA_VERSION, active: derived }))168    ? derived169    : unknown;170}171172/**173 * Enter the state that blocks sync and states the migration. Reached by the174 * user asking for a reset, and by the create-on-miss refusal. Idempotent, and175 * never moves a device that has already reset back into the legacy generation.176 */177export async function enterResetRequired(178  io: SyncGenerationIo,179  nowMs: number = Date.now(),180): Promise<SyncGeneration> {181  const current = await resolveGeneration(io, nowMs);182  if (current.state !== LEGACY_ACTIVE && current.state !== RESET_REQUIRED) return current;183  const next: SyncGeneration = { ...current, state: RESET_REQUIRED };184  await io.writeBlob({ schemaVersion: SCHEMA_VERSION, active: next, previous: current });185  return next;186}187188const resetAttempts = new WeakMap<SyncGenerationIo, Promise<ResetResult>>();189190/**191 * Archive the legacy generation, mint the v2 identity, then flip the pointer —192 * in that order, so every crash point leaves either a recoverable193 * RESET_CONFIRMED or a committed V2_ANCHOR, and never a lost archive (§11.3).194 *195 * The caller has already confirmed the master password. `checkpoint` fires196 * immediately before each step that can fail; a test throws from it to inject a197 * crash at exactly that point.198 */199export function confirmSecureReset(200  io: SyncGenerationIo,201  opts: { nowMs: number; checkpoint?: (name: string) => void },202): Promise<ResetResult> {203  const current = resetAttempts.get(io);204  if (current) return current;205  const attempt = runSecureReset(io, opts).then(206    (result) => { resetAttempts.delete(io); return result; },207    (error: unknown) => { resetAttempts.delete(io); throw error; },208  );209  resetAttempts.set(io, attempt);210  return attempt;211}212213async function runSecureReset(214  io: SyncGenerationIo,215  opts: { nowMs: number; checkpoint?: (name: string) => void },216): Promise<ResetResult> {217  const { nowMs } = opts;218  const checkpoint = opts.checkpoint ?? (() => {});219  const current = await resolveGeneration(io, nowMs);220  if (221    current.state !== LEGACY_ACTIVE &&222    current.state !== RESET_REQUIRED &&223    current.state !== RESET_CONFIRMED224  ) {225    return "reset_not_completed";226  }227228  const persist = (state: SyncGeneration): Promise<boolean> =>229    io.writeBlob({ schemaVersion: SCHEMA_VERSION, active: state, previous: current });230231  checkpoint("before-confirmed");232  if (!(await persist({ ...current, state: RESET_CONFIRMED }))) return "reset_not_completed";233234  checkpoint("before-archive");235  let archiveRef: string | null;236  try {237    archiveRef = await io.archiveLegacyState(current.generation);238  } catch (error) {239    if (error instanceof ResetArchiveReviewRequiredError) return "reset_archive_review_required";240    throw error;241  }242  if (!archiveRef) return "reset_not_completed";243  checkpoint("after-archive");244245  checkpoint("before-clear");246  if (!(await io.clearLegacyTrustState())) return "reset_not_completed";247  checkpoint("after-clear");248249  checkpoint("before-identity");250  if (!(await io.ensureV2Identity())) return "reset_not_completed";251  checkpoint("after-identity");252253  // The identity exists by now; a read failure here is not worth abandoning a254  // reset whose archive is already durable.255  const anchorDeviceId = await io.getDeviceId().catch(() => undefined);256  const next: SyncGeneration = {257    schemaVersion: SCHEMA_VERSION,258    generation: current.generation + 1,259    state: V2_ANCHOR,260    anchorDeviceId,261    legacyArchiveRef: archiveRef,262    createdAt: nowMs,263  };264  checkpoint("before-generation-write");265  if (!(await io.writeBlob({ schemaVersion: SCHEMA_VERSION, active: next, previous: current }))) {266    return "reset_not_completed";267  }268  checkpoint("after-generation-write");269  return "V2_ANCHOR";270}271272/** An anchored device stops being "not re-paired" once a direct v2 peer exists. */273export async function onDirectV2PairingEstablished(274  io: SyncGenerationIo,275  hasDirectDevice: boolean,276  nowMs: number = Date.now(),277): Promise<void> {278  const current = await resolveGeneration(io, nowMs);279  if (current.state !== V2_ANCHOR && current.state !== REPAIRING) return;280  const next: SyncGeneration = { ...current, state: hasDirectDevice ? V2_ACTIVE : REPAIRING };281  await io282    .writeBlob({ schemaVersion: SCHEMA_VERSION, active: next, previous: current })283    .catch(() => false);284}285286/** Consulted before a sync session or an adoption grant is opened. */287export async function assertSyncAllowed(288  io: SyncGenerationIo,289  nowMs: number = Date.now(),290): Promise<SyncDecision> {291  const current = await resolveGeneration(io, nowMs);292  if (current.state === RESET_REQUIRED || current.state === RESET_CONFIRMED) return "reset_required";293  return isGenerationState(current.state) ? "allowed" : "sync_generation_unknown";294}295296/** True once a reset has retired the legacy generation. */297export async function isPostReset(298  io: SyncGenerationIo,299  nowMs: number = Date.now(),300): Promise<boolean> {301  const current = await resolveGeneration(io, nowMs);302  return current.state === V2_ANCHOR || current.state === REPAIRING || current.state === V2_ACTIVE;303}304305/**306 * Whether a missing or corrupt identity may be minted (§11.5). A missing307 * identity is only mintable on a genuinely fresh installation, never over any308 * trust this device already holds.309 */310export async function mintDecision(311  io: SyncGenerationIo,312  nowMs: number = Date.now(),313): Promise<"MINT" | "REFUSE_RESET_REQUIRED"> {314  if (!(await hasLegacyTrustState(io))) return "MINT";315  await enterResetRequired(io, nowMs);316  return "REFUSE_RESET_REQUIRED";317}318319/**320 * Minting and reading the device identity, supplied by `./device-identity` the321 * same way `vault.ts` receives its identity hooks. Injecting it keeps this322 * module free of device-identity and therefore free of an import cycle: the323 * identity loader is a consumer of the generation state, not the reverse.324 */325export type GenerationIdentity = {326  /** True once a usable current identity exists; may mint at RESET_CONFIRMED. */327  ensureIdentity(): Promise<boolean>;328  deviceId(): Promise<string>;329};330331let generationIdentity: GenerationIdentity | null = null;332333export function setGenerationIdentity(identity: GenerationIdentity): void {334  generationIdentity = identity;335}336337338function emptyRecord(value: unknown): boolean {339  return !value || typeof value !== "object" || Object.keys(value as object).length === 0;340}341342const RESET_SNAPSHOT_FIELDS = [343  ["pairedDevices", REGISTRY_KEY],344  ["revocations", REVOCATIONS_KEY],345  ["revocationIssuers", REVOCATION_ISSUERS_KEY],346  ["pendingHolder", PENDING_ADOPTION_HOLDER_KEY],347  ["pendingIdentity", PENDING_ADOPTION_IDENTITY_KEY],348  ["pairSecrets", PAIR_SECRETS_KEY],349] as const;350351type ResetArchive = {352  schemaVersion: 2;353  generation: number;354  archivedAt: number;355  snapshotJson: string;356  completionSha256Hex: string;357};358359async function resetArchiveDigest(archive: ResetArchive): Promise<string> {360  const bytes = new TextEncoder().encode(JSON.stringify([361    "peach.sync-reset-archive.v2", archive.schemaVersion, archive.generation,362    archive.archivedAt, archive.snapshotJson,363  ]));364  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));365  return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");366}367368function exactObjectKeys(value: unknown, keys: readonly string[]): value is Record<string, unknown> {369  return value !== null && typeof value === "object" && !Array.isArray(value) &&370    Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));371}372373async function validResetArchive(value: unknown, generation: number): Promise<boolean> {374  if (!exactObjectKeys(value, ["schemaVersion", "generation", "archivedAt", "snapshotJson", "completionSha256Hex"]) ||375    value.schemaVersion !== 2 || value.generation !== generation ||376    !Number.isSafeInteger(value.generation) || generation < 1 ||377    typeof value.archivedAt !== "number" || !Number.isSafeInteger(value.archivedAt) || value.archivedAt < 0 ||378    typeof value.snapshotJson !== "string" || typeof value.completionSha256Hex !== "string" ||379    !/^[0-9a-f]{64}$/.test(value.completionSha256Hex)) return false;380  let snapshot: unknown;381  try { snapshot = JSON.parse(value.snapshotJson); } catch { return false; }382  if (!exactObjectKeys(snapshot, RESET_SNAPSHOT_FIELDS.map(([field]) => field))) return false;383  return await resetArchiveDigest(value as ResetArchive) === value.completionSha256Hex;384}385386function resetSnapshot(stored: Record<string, unknown>): Record<string, unknown> {387  return Object.fromEntries(RESET_SNAPSHOT_FIELDS.map(([field, key]) => [field, stored[key] ?? null]));388}389390function emptyTrust(value: unknown): boolean {391  return value === null || value === undefined ||392    (typeof value === "object" && Object.keys(value).length === 0);393}394395function equalSnapshotValue(left: unknown, right: unknown): boolean {396  if (left === right) return true;397  if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false;398  if (Array.isArray(left) || Array.isArray(right)) {399    return Array.isArray(left) && Array.isArray(right) && left.length === right.length &&400      left.every((value, index) => equalSnapshotValue(value, right[index]));401  }402  const keys = Object.keys(left);403  return exactObjectKeys(right, keys) && keys.every((key) =>404    equalSnapshotValue((left as Record<string, unknown>)[key], right[key]),405  );406}407408async function archivedResetSnapshot(value: unknown, generation: number): Promise<Record<string, unknown> | null> {409  if (await validResetArchive(value, generation)) return JSON.parse((value as ResetArchive).snapshotJson);410  const fields = RESET_SNAPSHOT_FIELDS.map(([field]) => field);411  const legacyKeys = ["schemaVersion", "generation", "archivedAt", ...fields];412  const preIssuerKeys = legacyKeys.filter((field) => field !== "revocationIssuers");413  if ((!exactObjectKeys(value, legacyKeys) && !exactObjectKeys(value, preIssuerKeys)) ||414    value.schemaVersion !== 1 || value.generation !== generation || !Number.isSafeInteger(generation) || generation < 1 ||415    typeof value.archivedAt !== "number" || !Number.isSafeInteger(value.archivedAt) || value.archivedAt < 0) return null;416  // Old builds wrote one complete object but provided no content digest.417  return Object.fromEntries(fields.map((field) => [field, value[field] ?? null]));418}419420export const browserGenerationIo: SyncGenerationIo = {421  async readBlob() {422    return (await chrome.storage.local.get(GENERATION_KEY))[GENERATION_KEY];423  },424425  async writeBlob(blob) {426    const encoded = encodeGeneration(blob);427    try {428      await storageSet(GENERATION_KEY, encoded);429      // Read back rather than trusting the set: a successful write is what430      // licenses retiring the legacy generation.431      return (await storageGet(GENERATION_KEY)) === encoded;432    } catch {433      return false;434    }435  },436437  async hasPairedDevices() {438    return (await listPairedDevices()).length > 0;439  },440441  async hasArchivedIssuers() {442    return hasRevocationIssuerArchive();443  },444445  async hasRevocations() {446    const value = (await chrome.storage.local.get(REVOCATIONS_KEY))[REVOCATIONS_KEY];447    if (value === undefined) return false;448    if (!Array.isArray(value)) throw new TrustDataCorruptedError(REVOCATIONS_KEY, `expected array, got ${typeof value}`);449    return value.length > 0;450  },451452  async hasPendingHolders() {453    const stored = await chrome.storage.local.get([454      PENDING_ADOPTION_HOLDER_KEY,455      PENDING_ADOPTION_IDENTITY_KEY,456    ]);457    return !!stored[PENDING_ADOPTION_HOLDER_KEY] || !!stored[PENDING_ADOPTION_IDENTITY_KEY];458  },459460  async hasLegacyRouteMaterial() {461    return !emptyRecord((await chrome.storage.local.get(PAIR_SECRETS_KEY))[PAIR_SECRETS_KEY]);462  },463464  /// Preserve the first complete snapshot for this generation; older builds cannot safely resume it.465  async archiveLegacyState(generation) {466    const ref = `peach_sync_archive_g${generation}_v1`;467    try {468      const existing = (await chrome.storage.local.get(ref))[ref];469      if (existing !== undefined) {470        const snapshot = await archivedResetSnapshot(existing, generation);471        if (!snapshot) throw new ResetArchiveReviewRequiredError();472        const live = resetSnapshot(await chrome.storage.local.get(RESET_SNAPSHOT_FIELDS.map(([, key]) => key)));473        const fields = RESET_SNAPSHOT_FIELDS.map(([field]) => field);474        const cleared = fields.every((field) => emptyTrust(live[field]));475        const unchanged = fields.every((field) =>476          (emptyTrust(live[field]) && emptyTrust(snapshot[field])) || equalSnapshotValue(live[field], snapshot[field]),477        );478        if (!cleared && !unchanged) throw new ResetArchiveReviewRequiredError();479        return ref;480      }481      const stored = await chrome.storage.local.get(RESET_SNAPSHOT_FIELDS.map(([, key]) => key));482      const snapshotJson = JSON.stringify(resetSnapshot(stored));483      const archive: ResetArchive = {484        schemaVersion: 2,485        generation,486        archivedAt: Date.now(),487        snapshotJson,488        completionSha256Hex: "",489      };490      archive.completionSha256Hex = await resetArchiveDigest(archive);491      await chrome.storage.local.set({ [ref]: archive });492      const written: unknown = (await chrome.storage.local.get(ref))[ref];493      if (!(await validResetArchive(written, generation)) || !Object.keys(archive).every((key) =>494        (written as ResetArchive)[key as keyof ResetArchive] === archive[key as keyof ResetArchive],495      )) throw new ResetArchiveReviewRequiredError();496      return ref;497    } catch (error) {498      if (error instanceof ResetArchiveReviewRequiredError) throw error;499      return null;500    }501  },502503  async clearLegacyTrustState() {504    try {505      await chrome.storage.local.remove([506        REGISTRY_KEY,507        REVOCATIONS_KEY,508        REVOCATION_ISSUERS_KEY,509        PENDING_ADOPTION_HOLDER_KEY,510        PENDING_ADOPTION_IDENTITY_KEY,511        PAIR_SECRETS_KEY,512      ]);513      await dropSessionCache();514      // Verified rather than assumed: the clear is what licenses the mint.515      const [paired, revocations, archivedIssuers, pending, route, session] = await Promise.all([516        browserGenerationIo.hasPairedDevices(),517        browserGenerationIo.hasRevocations(),518        browserGenerationIo.hasArchivedIssuers(),519        browserGenerationIo.hasPendingHolders(),520        browserGenerationIo.hasLegacyRouteMaterial(),521        chrome.storage.session.get(SESSION_PAIR_SECRETS_KEY),522      ]);523      return !paired && !revocations && !archivedIssuers && !pending && !route && session[SESSION_PAIR_SECRETS_KEY] === undefined;524    } catch {525      return false;526    }527  },528529  async ensureV2Identity() {530    return generationIdentity ? generationIdentity.ensureIdentity() : false;531  },532533  async getDeviceId() {534    if (!generationIdentity) throw new Error("generation_identity_unconfigured");535    return generationIdentity.deviceId();536  },537};