12345678910111213import { 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";333435export 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};55565758596061export 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";70717273747576export 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}106107108109110111112export 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}138139140141142143144export 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}169170171172173174175export 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}185186187188189190191192193194195export 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 230 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}247248249export 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}261262263export 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}271272273export 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}280281282283284285286export 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}294295296297298299300301export type GenerationIdentity = {302 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 328 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 363364365366367368 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 392 393 394 395 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 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};