import type { CoordinatorScope } from "./coordinator-store-contract.js"; import type { Database } from "./db.js"; import { getEffectiveCachedScopeAuthorization, type ScopeMembershipCacheAuthority, } from "./scope-membership-cache-read.js"; /* * When a transitioned group's devices may transfer its scopes. * * After a group transitions, its proofs authorize transfers for one hour after * a refresh that this process verified: every coordinator response of that * refresh echoed the nonce this process signed into its request, so a cached or * replayed response cannot renew it. The hour is measured on this process's * monotonic clock. Moving the wall clock does not reopen it, and a process that * starts has no window until its own verified refresh succeeds. * * `transitionedTransferAllowed` is the only decision. Every transfer gate calls * it immediately before a scoped request, before serving or advertising a * scope, and before applying what arrived. A closed window pauses transfers: * cursors, baselines and pairings stay as they are, and local history stays * readable. Groups that have not transitioned never pause here. */ export const TRANSITIONED_PROOF_OFFLINE_VALIDITY_MS = 60 * 60 * 1000; /** Why a transitioned group cannot renew its window from a plain HTTP coordinator. */ export const TRANSITIONED_COORDINATOR_NEEDS_HTTPS = "Transitioned groups need an HTTPS coordinator URL. Their transfers stay paused until it uses HTTPS."; export const isHttpsCoordinator = (url: string) => url.trim().toLowerCase().startsWith("https://"); /** * Whether this store has a transitioned group and the configured coordinator * URL cannot renew its window, because it is not HTTPS. `sync doctor` reports it. */ export function transitionedCoordinatorNeedsHttps(db: Database, coordinatorUrl: string): boolean { return ( coordinatorUrl.trim() !== "" && !isHttpsCoordinator(coordinatorUrl) && hasTransitionedGroup(db) ); } /** A transfer of a transitioned scope waited for a verified refresh. Nothing was changed. */ export class TransferPausedError extends Error { constructor(readonly scopeId: string) { super("transfer_paused"); this.name = "TransferPausedError"; } } type Deadlines = Map; // File stores are keyed by path, so every handle this process opens on one store // shares its window. An in-memory store has only its own handle. const byPath = new Map(); let byHandle = new WeakMap(); /** This process's windows for the store. `create` makes the map when there is none yet. */ function deadlines(db: Database, { create }: { create: boolean }): Deadlines | undefined { if (db.memory) { const existing = byHandle.get(db); if (existing || !create) return existing; const made: Deadlines = new Map(); byHandle.set(db, made); return made; } const existing = byPath.get(db.name); if (existing || !create) return existing; const made: Deadlines = new Map(); byPath.set(db.name, made); return made; } const authorityKey = (authority: ScopeMembershipCacheAuthority) => JSON.stringify([authority.coordinatorId, authority.groupId]); const monotonicNow = () => performance.now(); /** Whether this store has prepared the group for per-Project serving. */ /** * Whether this store has ever prepared the group for per-Project serving. * Transition state is keyed by group ID, never by the coordinator URL: a * different coordinator URL, such as an override, cannot make a transitioned * group look untransitioned. Preparations are never deleted. */ export function isTransitionedGroup(db: Database, group: { groupId: string }): boolean { if ( !db .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?") .get("scope_serving_preparations") ) return false; return !!db .prepare("SELECT 1 FROM scope_serving_preparations WHERE group_id = ?") .get(group.groupId); } /** Whether any group of this store has transitioned. */ export function hasTransitionedGroup(db: Database): boolean { if ( !db .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?") .get("scope_serving_preparations") ) return false; return !!db.prepare("SELECT 1 FROM scope_serving_preparations LIMIT 1").get(); } function scopeGroup(scope: CoordinatorScope | null): { groupId: string } | null { const groupId = scope?.group_id?.trim(); if (scope?.authority_type !== "coordinator" || !groupId) return null; return { groupId }; } /** Whether the scope belongs to a transitioned group, so its transfers depend on the window. */ export function isTransitionedScope(db: Database, scope: CoordinatorScope | null): boolean { const group = scopeGroup(scope); return group !== null && isTransitionedGroup(db, group); } /** * Opens the window after a successful refresh. For a transitioned group the * refresh only succeeds when every response echoed this process's nonce. A * group that transitions later loses its proofs in the transition and needs * such a refresh before it can transfer. */ export function recordRequestBoundRefresh( db: Database, authority: ScopeMembershipCacheAuthority, ): void { deadlines(db, { create: true })?.set( authorityKey(authority), monotonicNow() + TRANSITIONED_PROOF_OFFLINE_VALIDITY_MS, ); } /** Whether this process has an open window for the group. */ export function transitionedWindowOpen( db: Database, authority: ScopeMembershipCacheAuthority, ): boolean { const deadline = deadlines(db, { create: false })?.get(authorityKey(authority)); return deadline !== undefined && monotonicNow() < deadline; } /** Forgets every window, as a process restart does. */ export function forgetTransitionedTransferWindows(): void { byPath.clear(); byHandle = new WeakMap(); } export interface TransferPeer { deviceId: string; expectedPublicKey?: string; expectedFingerprint?: string; } /** * Whether a transfer of `scopeId` with `peer` may run now. For a transitioned * group it requires an open window and current cached authorization for both * this device and the peer. Other groups are always allowed here, and their * gates keep their own authorization checks. */ export function transitionedTransferAllowed( db: Database, scopeId: string, peer: TransferPeer, ): boolean { // A store that never transitioned has nothing to decide here. if (!scopeId || !hasTransitionedGroup(db)) return true; const scope = scopeId ? (db .prepare( "SELECT authority_type, coordinator_id, group_id FROM replication_scopes WHERE scope_id = ?", ) .get(scopeId) as CoordinatorScope | undefined) : undefined; const group = scopeGroup(scope ?? null); if (!group || !isTransitionedGroup(db, group)) return true; // The window comes from a refresh by the coordinator the scope records, which no // refresh can rewrite. A scope with no recorded coordinator has no window. const coordinatorId = scope?.coordinator_id?.trim(); if (!coordinatorId || !peer.deviceId) return false; if (!transitionedWindowOpen(db, { coordinatorId, groupId: group.groupId })) return false; const local = db.prepare("SELECT device_id, public_key FROM sync_device LIMIT 1").get() as | { device_id: string; public_key: string | null } | undefined; if (!local?.device_id) return false; const localAuthorization = getEffectiveCachedScopeAuthorization(db, { deviceId: local.device_id, scopeId, expectedPublicKey: local.public_key ?? "", }); if (!localAuthorization.authorized) return false; return getEffectiveCachedScopeAuthorization(db, { scopeId, ...peer }).authorized; } /** Throws TransferPausedError when `transitionedTransferAllowed` says no. */ export function requireTransitionedTransfer( db: Database, scopeId: string, peer: TransferPeer, ): void { if (!transitionedTransferAllowed(db, scopeId, peer)) throw new TransferPausedError(scopeId); }