export type Snapshot = { id: string; orbit_id?: string; taken_at: string; orbit_name: string; size_bytes: number; capture?: { job_id: string; application_id: string; engine: "postgres" | "mysql"; format: string; restore_ready: boolean } | null; }; export type BackupSource = "filesystem" | "database"; export type BackupAccess = "hub" | "outpost"; export type Orbit = { id: string; name: string; provider: string; source: BackupSource | null; access: BackupAccess; last_status: string; dry_run: boolean; schedule?: string | null; decay_preset?: string; retention?: RetentionPolicy | null; application_id?: string | null; capture_schedule?: { hour: number; minute: number; timezone: string } | null; capture_retention?: { mode: "age"; days: number } | { mode: "count"; keep: number } | null; retention_source?: "orbit" | "profile" | "default"; }; export type RetentionPolicy = { keep_daily: number; keep_weekly: number; keep_monthly: number; keep_yearly: number; }; export type RetentionSettings = { decay_preset: string } | { retention: RetentionPolicy }; export type CreateOrbitInput = { name: string; schedule?: string; dry_run: boolean; } & RetentionSettings & ( | { source: "filesystem"; access: "hub"; provider_config: { paths: string[] } } | { source: "database"; access: "hub"; provider_config: { engine: "postgres" | "mysql"; transport?: "direct"; host: string; port?: number; database: string; user: string; password_file: string; tls?: { mode: "verify_full_with_ca" | "verify_identity_with_ca"; ca_file: string }; } } | { source: BackupSource; access: "outpost"; provider_config: Record } ); export type OperatorSession = { login_enabled: boolean; oidc_enabled: boolean; authorized: boolean; admin: boolean; actor: string | null; csrf: string | null; expires_at: number | null; }; export type MyGrant = { permission: string; orbit_id: string | null }; export type Me = { id: string; kind: string; auth_method: string; display_name: string; admin: boolean; capabilities: string[]; grants: MyGrant[]; /** Relations this person may refresh through (empty for an administrator, who may use all). */ refresh_relations?: string[]; }; export async function fetchMe(signal?: AbortSignal): Promise { return api("/api/v1/me", { signal }); } export type Environment = "production" | "staging" | "development"; export type RelationView = { id: string; version: number; source_orbit_id: string; target_id: string; engine: string; verified: boolean; active: boolean; deactivated_reason: string | null; source_name: string; source_environment: Environment | null; target_name: string; target_environment: Environment | null; usable: boolean; unusable_reason: string | null; }; export type OrbitSetup = { id: string; name: string; environment: Environment | null; application_id: string | null; engine: string | null; ready: boolean; reason: string | null; }; export type TargetSetup = { id: string; name: string; engine: string; identity: { instance: string; database: string }; application_id: string; environment: Environment | null; outpost_active: boolean; }; export type RelationOverview = { relations: RelationView[]; orbits: OrbitSetup[]; targets: TargetSetup[] }; export type RelationGrant = { id: string; principal_type: "user" | "group"; principal: string; expires_at: number | null; created_at: number }; /** The rule a refused relation request names (`{"reason": "..."}`), if the error carries one. */ export function refusalReason(error: unknown): string | undefined { try { return JSON.parse((error as Error).message).reason; } catch { return undefined; } } const json = (method: string, body: unknown) => ({ method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); export const fetchRelations = () => api("/api/v1/relations"); export const setOrbitEnvironment = (id: string, environment: Environment) => api(`/api/v1/orbits/${id}/environment`, json("PUT", { environment })); export const setTargetEnvironment = (id: string, environment: Environment) => api<{ ended_relations: string[] }>(`/api/v1/restore-targets/${id}/environment`, json("PUT", { environment })); export const createRelation = (source_orbit_id: string, target_id: string) => api("/api/v1/relations", json("POST", { source_orbit_id, target_id })); export const retargetRelation = (id: string, target_id: string) => api(`/api/v1/relations/${id}`, json("PUT", { target_id })); export const endRelation = (id: string) => api(`/api/v1/relations/${id}`, { method: "DELETE" }); export const fetchRelationAccess = (id: string) => api(`/api/v1/relations/${id}/access`); export const grantRelationAccess = (id: string, grant: { principal_type: "user" | "group"; principal: string; expires_at?: string }) => api(`/api/v1/relations/${id}/access`, json("POST", grant)); export const revokeRelationAccess = (id: string, grant: string) => api(`/api/v1/relations/${id}/access/${grant}`, { method: "DELETE" }); export type RefreshRelation = { id: string; version: number; source_name: string; source_environment: Environment | null; target_name: string; target_environment: Environment | null; usable: boolean; unusable_reason: string | null; }; export type RefreshRun = { id: string; relation_id: string; source_name: string; target_name: string; status: string; blocked_reason: string | null; capture_status: string | null; capture_phase: string | null; snapshot_taken_at: number | null; restore_status: string | null; restore_phase: string | null; created_at: number; updated_at: number; expires_at: number; requested_by?: string; }; export const fetchRefreshRelations = () => api("/api/v1/refresh-relations"); export const fetchRefreshRuns = () => api("/api/v1/refresh-runs"); export const startRefresh = (relation: RefreshRelation, idempotency_key: string) => api("/api/v1/refresh-runs", json("POST", { relation_id: relation.id, // exactly what the person was shown, so a relation changed in the meantime is refused confirmation: `REFRESH ${relation.source_name} TO ${relation.target_name} v${relation.version}`, idempotency_key, })); export const cancelRefresh = (id: string) => api(`/api/v1/refresh-runs/${id}`, { method: "DELETE" }); export type Look = "window" | "radar"; /** The account's saved display choices. A hub without this endpoint, or an account without one, yields `{}`. */ export async function fetchPreferences(signal?: AbortSignal): Promise<{ look?: Look }> { const data = await api("/api/v1/me/preferences", { signal }).catch(() => undefined); const look = (data as { look?: unknown } | undefined)?.look; return look === "window" || look === "radar" ? { look } : {}; } export const savePreferences = (preferences: { look?: Look }) => api("/api/v1/me/preferences", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(preferences) }); export type Grant = { id: string; principal_type: "user" | "group"; principal: string; permission: string; scope_type: "global" | "orbit"; scope_id: string | null; expires_at: number | null; created_by: string; created_at: number; }; export type GrantList = { grants: Grant[]; roles: { name: string; permissions: string[] }[]; grantable: string[] }; export type AccessUser = { id: string; issuer: string; display_name: string; active: boolean; created_at: number; last_login_at: number | null; is_emergency: boolean; }; export type NewGrant = { principal_type: "user" | "group"; principal: string; role?: string; orbit_id?: string; expires_at?: string; }; export const fetchGrants = () => api("/api/v1/access/grants"); export const fetchAccessUsers = () => api("/api/v1/access/users"); export const createGrant = (grant: NewGrant) => api("/api/v1/access/grants", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(grant) }); export const deleteGrant = (id: string) => api(`/api/v1/access/grants/${id}`, { method: "DELETE" }); export const setUserActive = (id: string, active: boolean) => api(`/api/v1/access/users/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ active }) }); export const revokeUserSessions = (id: string) => api(`/api/v1/access/users/${id}/revoke-sessions`, { method: "POST" }); let csrf: string | null = null; export async function fetchOperatorSession(signal?: AbortSignal): Promise { const session = await api("/api/v1/operator/session", { signal }); csrf = session.csrf; return session; } export async function loginOperator(password: string): Promise { const session = await api("/api/v1/operator/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password }), }); csrf = session.csrf; return session; } export async function logoutOperator(): Promise { await request("/api/v1/operator/session", { method: "DELETE" }); csrf = null; } async function request(path: string, init?: RequestInit): Promise { const headers = new Headers(init?.headers); if (csrf && init?.method && init.method !== "GET") headers.set("X-Tessera-CSRF", csrf); const r = await fetch(path, { ...init, headers }); if (!r.ok) { const text = await r.text().catch(() => ""); throw new Error(text || `${path} failed`); } return r; } async function api(path: string, init?: RequestInit): Promise { const r = await request(path, init); if (r.status === 204) return undefined as T; return r.json(); } export async function fetchHealth(): Promise { const r = await fetch("/health"); if (!r.ok) throw new Error("hub offline"); return r.text(); } export async function fetchSnapshots(): Promise { return api("/api/v1/snapshots"); } export async function fetchOrbits(): Promise { return api("/api/v1/orbits"); } export async function createOrbit(input: CreateOrbitInput): Promise { return api("/api/v1/orbits", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input), }); } export async function updateOrbitRetention(id: string, settings: RetentionSettings): Promise { await api(`/api/v1/orbits/${id}/retention`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(settings), }); } export async function startPairing(): Promise<{ code: string; expires_at: string }> { return api("/api/v1/wormhole/pairing", { method: "POST" }); } export async function runOrbit(id: string): Promise { const response = await request(`/api/v1/orbits/${id}/run`, { method: "POST" }); return response.headers.get("X-Tessera-Snapshot-Id"); } export async function startReconstitute( snapshotId: string, target: string, ): Promise<{ session_id: string; session: { seconds_remaining: number; state: string }; }> { return api("/api/v1/reconstitute", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ snapshot_id: snapshotId, target_path: target }), }); } export async function abortReconstitute(sessionId: string): Promise { await api(`/api/v1/reconstitute/${sessionId}`, { method: "DELETE" }); } export async function pollReconstitute(sessionId: string) { const response = await fetch(`/api/v1/reconstitute/${sessionId}`); if (response.status === 404) return { state: "unavailable", seconds_remaining: 0 }; if (!response.ok) throw new Error("Could not read restore status"); return response.json() as Promise<{ state: string; seconds_remaining: number }>; } export type CaptureProfile = { application_id: string; orbit_id: string; outpost_id: string; format: "postgres_custom" | "postgres_sql" | "mysql_sql" | "filesystem"; schedule?: Orbit["capture_schedule"]; }; export function registerCaptureProfile(profile: CaptureProfile): Promise { return api("/api/v1/capture-profiles", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(profile), }); } export type CaptureJob = { id: string; profile: CaptureProfile; actor: string; status: "queued" | "running" | "completed" | "failed"; phase: string; created_at: number; snapshot_id: string | null; offsite_status: "pending" | "failed" | "copied" | null; }; export type CaptureEvent = { at: number; phase: string }; export function fetchCaptureProfiles(): Promise { return api("/api/v1/capture-profiles"); } export function enqueueCapture(application: string): Promise { return api(`/api/v1/capture-profiles/${application}/jobs`, { method: "POST" }); } export function fetchCaptureJobs(application: string, status: string): Promise { const filter = new URLSearchParams(); if (application) filter.set("application_id", application); if (status) filter.set("status", status); return api(`/api/v1/capture-jobs?${filter}`); } export function fetchCaptureEvents(job: string): Promise { return api(`/api/v1/capture-jobs/${job}/events`); } export function deleteSnapshot(snapshot: string): Promise { return api(`/api/v1/snapshots/${snapshot}`, { method: "DELETE" }); } export type Outpost = { id: string; name: string | null; last_seen: string | null; pairing_state: string }; export function fetchOutposts(): Promise { return api("/api/v1/wormhole/outposts"); } export type RestoreTarget = { id: string; name: string; outpost_id: string; engine: "postgres" | "mysql"; application_id: string; identity: { instance: string; database: string }; }; export type SnapshotRestoreTarget = RestoreTarget & { ineligible_reason: string | null }; export function registerRestoreTarget(target: RestoreTarget): Promise { return api("/api/v1/restore-targets", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(target), }); } export type RestoreJob = { id: string; snapshot_id: string; target: RestoreTarget; status: "queued" | "running" | "applying" | "failed" | "completed" | "recovery_required" | "reconciled" | "cancelled"; phase: string; safety_snapshot_id: string | null; actor: string; /** Seconds since the epoch. */ created_at: number; updated_at: number; }; /** The newest restore jobs across every snapshot. Older hubs answer 404 or 405. */ export function fetchRecentRestoreJobs(limit = 100): Promise { return api(`/api/v1/restore-jobs?limit=${limit}`); } export function fetchRestoreTargets(snapshot: string): Promise { return api(`/api/v1/snapshots/${snapshot}/restore-targets`); } export function fetchRestoreJobs(snapshot: string): Promise { return api(`/api/v1/snapshots/${snapshot}/restore-jobs`); } export function enqueueRestore(snapshot: string, target: string, confirmation: string): Promise { return api("/api/v1/restore-jobs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ snapshot_id: snapshot, target_id: target, confirmation }), }); } export function cancelRestore(job: string): Promise { return api(`/api/v1/restore-jobs/${job}`, { method: "DELETE" }); } export function reconcileRestore(job: string, confirmation: string): Promise { return api(`/api/v1/restore-jobs/${job}/reconcile`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ confirmation }), }); }