Files
tessera/web/src/api.ts
Adnan Zahir d7fe99edd7 feat: refresh console for QA and refresh-only access (auth M6d)
- web: Refresh console (relation cards, overwrite confirmation, progress,
  cancel, distinct failure messages), rail item, and a single-screen view
  for people who may only refresh
- hub: refresh-only users are authorized; /me exposes refresh_relations
- docs and auth plan record the real rehearsal (Postgres, agent, Keycloak,
  browser) and what was not verified

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 19:03:47 +07:00

430 lines
16 KiB
TypeScript

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<string, never> }
);
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<Me> {
return api<Me>("/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<RelationOverview>("/api/v1/relations");
export const setOrbitEnvironment = (id: string, environment: Environment) => api<void>(`/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<RelationView>("/api/v1/relations", json("POST", { source_orbit_id, target_id }));
export const retargetRelation = (id: string, target_id: string) => api<RelationView>(`/api/v1/relations/${id}`, json("PUT", { target_id }));
export const endRelation = (id: string) => api<void>(`/api/v1/relations/${id}`, { method: "DELETE" });
export const fetchRelationAccess = (id: string) => api<RelationGrant[]>(`/api/v1/relations/${id}/access`);
export const grantRelationAccess = (id: string, grant: { principal_type: "user" | "group"; principal: string; expires_at?: string }) =>
api<RelationGrant>(`/api/v1/relations/${id}/access`, json("POST", grant));
export const revokeRelationAccess = (id: string, grant: string) => api<void>(`/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<RefreshRelation[]>("/api/v1/refresh-relations");
export const fetchRefreshRuns = () => api<RefreshRun[]>("/api/v1/refresh-runs");
export const startRefresh = (relation: RefreshRelation, idempotency_key: string) =>
api<RefreshRun>("/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<RefreshRun>(`/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<unknown>("/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<void>("/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<GrantList>("/api/v1/access/grants");
export const fetchAccessUsers = () => api<AccessUser[]>("/api/v1/access/users");
export const createGrant = (grant: NewGrant) =>
api<Grant[]>("/api/v1/access/grants", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(grant) });
export const deleteGrant = (id: string) => api<void>(`/api/v1/access/grants/${id}`, { method: "DELETE" });
export const setUserActive = (id: string, active: boolean) =>
api<void>(`/api/v1/access/users/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ active }) });
export const revokeUserSessions = (id: string) => api<void>(`/api/v1/access/users/${id}/revoke-sessions`, { method: "POST" });
let csrf: string | null = null;
export async function fetchOperatorSession(signal?: AbortSignal): Promise<OperatorSession> {
const session = await api<OperatorSession>("/api/v1/operator/session", { signal });
csrf = session.csrf;
return session;
}
export async function loginOperator(password: string): Promise<OperatorSession> {
const session = await api<OperatorSession>("/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<void> {
await request("/api/v1/operator/session", { method: "DELETE" });
csrf = null;
}
async function request(path: string, init?: RequestInit): Promise<Response> {
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<T>(path: string, init?: RequestInit): Promise<T> {
const r = await request(path, init);
if (r.status === 204) return undefined as T;
return r.json();
}
export async function fetchHealth(): Promise<string> {
const r = await fetch("/health");
if (!r.ok) throw new Error("hub offline");
return r.text();
}
export async function fetchSnapshots(): Promise<Snapshot[]> {
return api("/api/v1/snapshots");
}
export async function fetchOrbits(): Promise<Orbit[]> {
return api("/api/v1/orbits");
}
export async function createOrbit(input: CreateOrbitInput): Promise<Orbit> {
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<void> {
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<string | null> {
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<void> {
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<CaptureProfile> {
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<CaptureProfile[]> {
return api("/api/v1/capture-profiles");
}
export function enqueueCapture(application: string): Promise<CaptureJob> {
return api(`/api/v1/capture-profiles/${application}/jobs`, { method: "POST" });
}
export function fetchCaptureJobs(application: string, status: string): Promise<CaptureJob[]> {
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<CaptureEvent[]> {
return api(`/api/v1/capture-jobs/${job}/events`);
}
export function deleteSnapshot(snapshot: string): Promise<void> {
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<Outpost[]> {
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<RestoreTarget> {
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<RestoreJob[]> {
return api(`/api/v1/restore-jobs?limit=${limit}`);
}
export function fetchRestoreTargets(snapshot: string): Promise<SnapshotRestoreTarget[]> {
return api(`/api/v1/snapshots/${snapshot}/restore-targets`);
}
export function fetchRestoreJobs(snapshot: string): Promise<RestoreJob[]> {
return api(`/api/v1/snapshots/${snapshot}/restore-jobs`);
}
export function enqueueRestore(snapshot: string, target: string, confirmation: string): Promise<RestoreJob> {
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<void> {
return api(`/api/v1/restore-jobs/${job}`, { method: "DELETE" });
}
export function reconcileRestore(job: string, confirmation: string): Promise<void> {
return api(`/api/v1/restore-jobs/${job}/reconcile`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ confirmation }),
});
}