sync-generation.ts

15.8 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";7071/**72 * The storage boundary. The trust probe is split per class so a test can assert73 * the refusal for each one, and archival and clearing are separate steps so a74 * crash between them is injectable.75 */76export interface SyncGenerationIo {77  readBlob(): Promise<unknown>;78  writeBlob(blob: SyncGenerationBlob): Promise<boolean>;79  hasPairedDevices(): Promise<boolean>;80  hasRevocations(): Promise<boolean>;81  hasArchivedIssuers(): Promise<boolean>;82  hasPendingHolders(): Promise<boolean>;83  hasLegacyRouteMaterial(): Promise<boolean>;84  archiveLegacyState(generation: number): Promise<string | null>;85  clearLegacyTrustState(): Promise<boolean>;86  ensureV2Identity(): Promise<boolean>;87  getDeviceId(): Promise<string>;88}8990const STATE_NAMES: Record<string, true> = {91  LEGACY_ACTIVE: true,92  RESET_REQUIRED: true,93  RESET_CONFIRMED: true,94  V2_ANCHOR: true,95  REPAIRING: true,96  V2_ACTIVE: true,97};9899export function isGenerationState(value: unknown): value is KnownGenerationState {100  return typeof value === "string" && STATE_NAMES[value] === true;101}102103export function encodeGeneration(blob: SyncGenerationBlob): string {104  return JSON.stringify(blob);105}106107/**108 * A record this build cannot read is not a record: another schema, an109 * unrecognised state, or a nonsensical generation all resolve to null, so the110 * caller refuses rather than misreading a newer generation as legacy trust.111 */112export function decodeGeneration(value: unknown): SyncGenerationBlob | null {113  try {114    const parsed: unknown = typeof value === "string" ? JSON.parse(value) : value;115    if (!parsed || typeof parsed !== "object") return null;116    const blob = parsed as Partial<SyncGenerationBlob>;117    if (blob.schemaVersion !== SCHEMA_VERSION) return null;118    const active = blob.active as Partial<SyncGeneration> | undefined;119    if (!active || !isGenerationState(active.state)) return null;120    if (!Number.isInteger(active.generation)) return null;121    if ((active.generation ?? 0) < LEGACY_GENERATION) return null;122    return blob as SyncGenerationBlob;123  } catch {124    return null;125  }126}127128export async function hasLegacyTrustState(io: SyncGenerationIo): Promise<boolean> {129  const [paired, revocations, archivedIssuers, pending, route] = await Promise.all([130    io.hasPairedDevices(),131    io.hasRevocations(),132    io.hasArchivedIssuers(),133    io.hasPendingHolders(),134    io.hasLegacyRouteMaterial(),135  ]);136  return paired || revocations || archivedIssuers || pending || route;137}138139/**140 * Read the persisted record, or derive one when none has ever been written. A141 * derived record that cannot be persisted is not trusted: the caller must not142 * act on a generation this installation may not actually hold.143 */144export async function resolveGeneration(145  io: SyncGenerationIo,146  nowMs: number = Date.now(),147): Promise<SyncGeneration> {148  const unknown: SyncGeneration = {149    schemaVersion: SCHEMA_VERSION,150    generation: LEGACY_GENERATION,151    state: GENERATION_UNKNOWN,152    createdAt: nowMs,153  };154  const raw = await io.readBlob();155  if (raw !== null && raw !== undefined) {156    return decodeGeneration(raw)?.active ?? unknown;157  }158  const hasTrust = await hasLegacyTrustState(io);159  const derived: SyncGeneration = {160    schemaVersion: SCHEMA_VERSION,161    generation: hasTrust ? LEGACY_GENERATION : V2_GENERATION,162    state: hasTrust ? LEGACY_ACTIVE : V2_ACTIVE,163    createdAt: nowMs,164  };165  return (await io.writeBlob({ schemaVersion: SCHEMA_VERSION, active: derived }))166    ? derived167    : unknown;168}169170/**171 * Enter the state that blocks sync and states the migration. Reached by the172 * user asking for a reset, and by the create-on-miss refusal. Idempotent, and173 * never moves a device that has already reset back into the legacy generation.174 */175export async function enterResetRequired(176  io: SyncGenerationIo,177  nowMs: number = Date.now(),178): Promise<SyncGeneration> {179  const current = await resolveGeneration(io, nowMs);180  if (current.state !== LEGACY_ACTIVE && current.state !== RESET_REQUIRED) return current;181  const next: SyncGeneration = { ...current, state: RESET_REQUIRED };182  await io.writeBlob({ schemaVersion: SCHEMA_VERSION, active: next, previous: current });183  return next;184}185186/**187 * Archive the legacy generation, mint the v2 identity, then flip the pointer —188 * in that order, so every crash point leaves either a recoverable189 * RESET_CONFIRMED or a committed V2_ANCHOR, and never a lost archive (§11.3).190 *191 * The caller has already confirmed the master password. `checkpoint` fires192 * immediately before each step that can fail; a test throws from it to inject a193 * crash at exactly that point.194 */195export async function confirmSecureReset(196  io: SyncGenerationIo,197  opts: { nowMs: number; checkpoint?: (name: string) => void },198): Promise<ResetResult> {199  const { nowMs } = opts;200  const checkpoint = opts.checkpoint ?? (() => {});201  const current = await resolveGeneration(io, nowMs);202  if (203    current.state !== LEGACY_ACTIVE &&204    current.state !== RESET_REQUIRED &&205    current.state !== RESET_CONFIRMED206  ) {207    return "reset_not_completed";208  }209210  const persist = (state: SyncGeneration): Promise<boolean> =>211    io.writeBlob({ schemaVersion: SCHEMA_VERSION, active: state, previous: current });212213  checkpoint("before-confirmed");214  if (!(await persist({ ...current, state: RESET_CONFIRMED }))) return "reset_not_completed";215216  checkpoint("before-archive");217  const archiveRef = await io.archiveLegacyState(current.generation);218  if (!archiveRef) return "reset_not_completed";219  checkpoint("after-archive");220221  checkpoint("before-clear");222  if (!(await io.clearLegacyTrustState())) return "reset_not_completed";223  checkpoint("after-clear");224225  checkpoint("before-identity");226  if (!(await io.ensureV2Identity())) return "reset_not_completed";227  checkpoint("after-identity");228229  // The identity exists by now; a read failure here is not worth abandoning a230  // reset whose archive is already durable.231  const anchorDeviceId = await io.getDeviceId().catch(() => undefined);232  const next: SyncGeneration = {233    schemaVersion: SCHEMA_VERSION,234    generation: current.generation + 1,235    state: V2_ANCHOR,236    anchorDeviceId,237    legacyArchiveRef: archiveRef,238    createdAt: nowMs,239  };240  checkpoint("before-generation-write");241  if (!(await io.writeBlob({ schemaVersion: SCHEMA_VERSION, active: next, previous: current }))) {242    return "reset_not_completed";243  }244  checkpoint("after-generation-write");245  return "V2_ANCHOR";246}247248/** An anchored device stops being "not re-paired" once a direct v2 peer exists. */249export async function onDirectV2PairingEstablished(250  io: SyncGenerationIo,251  hasDirectDevice: boolean,252  nowMs: number = Date.now(),253): Promise<void> {254  const current = await resolveGeneration(io, nowMs);255  if (current.state !== V2_ANCHOR && current.state !== REPAIRING) return;256  const next: SyncGeneration = { ...current, state: hasDirectDevice ? V2_ACTIVE : REPAIRING };257  await io258    .writeBlob({ schemaVersion: SCHEMA_VERSION, active: next, previous: current })259    .catch(() => false);260}261262/** Consulted before a sync session or an adoption grant is opened. */263export async function assertSyncAllowed(264  io: SyncGenerationIo,265  nowMs: number = Date.now(),266): Promise<SyncDecision> {267  const current = await resolveGeneration(io, nowMs);268  if (current.state === RESET_REQUIRED || current.state === RESET_CONFIRMED) return "reset_required";269  return isGenerationState(current.state) ? "allowed" : "sync_generation_unknown";270}271272/** True once a reset has retired the legacy generation. */273export async function isPostReset(274  io: SyncGenerationIo,275  nowMs: number = Date.now(),276): Promise<boolean> {277  const current = await resolveGeneration(io, nowMs);278  return current.state === V2_ANCHOR || current.state === REPAIRING || current.state === V2_ACTIVE;279}280281/**282 * Whether a missing or corrupt identity may be minted (§11.5). A missing283 * identity is only mintable on a genuinely fresh installation, never over any284 * trust this device already holds.285 */286export async function mintDecision(287  io: SyncGenerationIo,288  nowMs: number = Date.now(),289): Promise<"MINT" | "REFUSE_RESET_REQUIRED"> {290  if (!(await hasLegacyTrustState(io))) return "MINT";291  await enterResetRequired(io, nowMs);292  return "REFUSE_RESET_REQUIRED";293}294295/**296 * Minting and reading the device identity, supplied by `./device-identity` the297 * same way `vault.ts` receives its identity hooks. Injecting it keeps this298 * module free of device-identity and therefore free of an import cycle: the299 * identity loader is a consumer of the generation state, not the reverse.300 */301export type GenerationIdentity = {302  /** True once a usable current identity exists; may mint at RESET_CONFIRMED. */303  ensureIdentity(): Promise<boolean>;304  deviceId(): Promise<string>;305};306307let generationIdentity: GenerationIdentity | null = null;308309export function setGenerationIdentity(identity: GenerationIdentity): void {310  generationIdentity = identity;311}312313314function emptyRecord(value: unknown): boolean {315  return !value || typeof value !== "object" || Object.keys(value as object).length === 0;316}317318export const browserGenerationIo: SyncGenerationIo = {319  async readBlob() {320    return (await chrome.storage.local.get(GENERATION_KEY))[GENERATION_KEY];321  },322323  async writeBlob(blob) {324    const encoded = encodeGeneration(blob);325    try {326      await storageSet(GENERATION_KEY, encoded);327      // Read back rather than trusting the set: a successful write is what328      // licenses retiring the legacy generation.329      return (await storageGet(GENERATION_KEY)) === encoded;330    } catch {331      return false;332    }333  },334335  async hasPairedDevices() {336    return (await listPairedDevices()).length > 0;337  },338339  async hasArchivedIssuers() {340    return hasRevocationIssuerArchive();341  },342343  async hasRevocations() {344    const value = (await chrome.storage.local.get(REVOCATIONS_KEY))[REVOCATIONS_KEY];345    if (value === undefined) return false;346    if (!Array.isArray(value)) throw new TrustDataCorruptedError(REVOCATIONS_KEY, `expected array, got ${typeof value}`);347    return value.length > 0;348  },349350  async hasPendingHolders() {351    const stored = await chrome.storage.local.get([352      PENDING_ADOPTION_HOLDER_KEY,353      PENDING_ADOPTION_IDENTITY_KEY,354    ]);355    return !!stored[PENDING_ADOPTION_HOLDER_KEY] || !!stored[PENDING_ADOPTION_IDENTITY_KEY];356  },357358  async hasLegacyRouteMaterial() {359    return !emptyRecord((await chrome.storage.local.get(PAIR_SECRETS_KEY))[PAIR_SECRETS_KEY]);360  },361362  /**363   * Copy the legacy trust material verbatim into an archive tagged with its364   * generation. The registry, the ledger and the pair secrets are exactly what365   * §11.4 retains; the generation is tagged both in the key and in the record,366   * so a rollback build can tell which generation it is looking at.367   */368  async archiveLegacyState(generation) {369    const ref = `peach_sync_archive_g${generation}_v1`;370    try {371      const stored = await chrome.storage.local.get([372        REGISTRY_KEY,373        REVOCATIONS_KEY,374        REVOCATION_ISSUERS_KEY,375        PENDING_ADOPTION_HOLDER_KEY,376        PENDING_ADOPTION_IDENTITY_KEY,377        PAIR_SECRETS_KEY,378      ]);379      const archive = {380        schemaVersion: 1,381        generation,382        archivedAt: Date.now(),383        pairedDevices: stored[REGISTRY_KEY] ?? null,384        revocations: stored[REVOCATIONS_KEY] ?? null,385        revocationIssuers: stored[REVOCATION_ISSUERS_KEY] ?? null,386        pendingHolder: stored[PENDING_ADOPTION_HOLDER_KEY] ?? null,387        pendingIdentity: stored[PENDING_ADOPTION_IDENTITY_KEY] ?? null,388        pairSecrets: stored[PAIR_SECRETS_KEY] ?? null,389      };390      await chrome.storage.local.set({ [ref]: archive });391      // Read back to prove the archive is durable, but compare the fields that392      // identify this write. Chrome re-encodes stored objects and does not393      // return their keys in insertion order, so comparing the serialized text394      // never matches on a real device — it failed every reset while the395      // archive had in fact been written.396      const written = (await chrome.storage.local.get(ref))[ref] as typeof archive | undefined;397      if (!written) return null;398      return written.schemaVersion === archive.schemaVersion &&399        written.generation === archive.generation &&400        written.archivedAt === archive.archivedAt401        ? ref402        : null;403    } catch {404      return null;405    }406  },407408  async clearLegacyTrustState() {409    try {410      await chrome.storage.local.remove([411        REGISTRY_KEY,412        REVOCATIONS_KEY,413        REVOCATION_ISSUERS_KEY,414        PENDING_ADOPTION_HOLDER_KEY,415        PENDING_ADOPTION_IDENTITY_KEY,416        PAIR_SECRETS_KEY,417      ]);418      await dropSessionCache();419      // Verified rather than assumed: the clear is what licenses the mint.420      const [paired, revocations, archivedIssuers, pending, route, session] = await Promise.all([421        browserGenerationIo.hasPairedDevices(),422        browserGenerationIo.hasRevocations(),423        browserGenerationIo.hasArchivedIssuers(),424        browserGenerationIo.hasPendingHolders(),425        browserGenerationIo.hasLegacyRouteMaterial(),426        chrome.storage.session.get(SESSION_PAIR_SECRETS_KEY),427      ]);428      return !paired && !revocations && !archivedIssuers && !pending && !route && session[SESSION_PAIR_SECRETS_KEY] === undefined;429    } catch {430      return false;431    }432  },433434  async ensureV2Identity() {435    return generationIdentity ? generationIdentity.ensureIdentity() : false;436  },437438  async getDeviceId() {439    if (!generationIdentity) throw new Error("generation_identity_unconfigured");440    return generationIdentity.deviceId();441  },442};