feat: per-orbit access grants and an Access console (auth M5)

Authorization
- one gate for every human endpoint: authenticate, resolve the resource, then
  admin_only / scoped / visible; require_admin* removed so each handler must choose
- grants (user or IdP group; global or one orbit; optional end date) read live on
  every request; only orbit.read, snapshot.read, capture.run and snapshot.download
  can be granted, everything else stays with configured administrators
- an orbit without orbit.read is 404, a visible one without the permission is 403,
  a caller with nothing to see gets 403 on lists; job history is filtered before LIMIT
- jobs and audit record the stable principal id, not the IdP display name
- restore targets and restore history are admin-only until self-service (M6)
- sessions keep the groups verified at sign-in

Administration
- /api/v1/access grants and users (enable, disable, sign out everywhere), validated
  and audited by id; admins cannot disable themselves or the emergency operator
- Access console with the shared Select and a themed DatePicker; non-administrators
  only see Vault and Activity and never call administrator endpoints
- the Window/Radar view is stored per account (/api/v1/me/preferences)
- UI tolerates older hubs and mocks (missing admin/grants) and a console that fails
  to render no longer blanks the app

Tests: a matrix generated from the endpoint contract exercises every human route
against real resources in two orbits for each kind of caller.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 14:45:41 +07:00
parent 54abd02250
commit d12472ba02
29 changed files with 2284 additions and 169 deletions

View File

@@ -2,20 +2,22 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { AnimatePresence, useMotionValue } from "motion/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
abortReconstitute, fetchCaptureJobs, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute,
abortReconstitute, fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchSnapshots, pollReconstitute, savePreferences,
enqueueCapture, runOrbit, startReconstitute, type Orbit,
} from "./api";
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
import { HUDPanel } from "./components/hud/HUDPanel";
import { HUDRail, type HUDMode } from "./components/hud/HUDRail";
import { accessItem, HUDRail, hudItems, type HUDMode } from "./components/hud/HUDRail";
import { AccessView } from "./components/access/AccessView";
import { SearchIcon, VaultSearch } from "./components/hud/VaultSearch";
import { OperatorGate } from "./components/operator/OperatorGate";
import { OperatorGate, type Caps } from "./components/operator/OperatorGate";
import { OrbitsView } from "./components/orbits/OrbitsView";
import { WormholeView } from "./components/outposts/WormholeView";
import { ActivityView } from "./components/activity/ActivityView";
import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard";
import { VaultScene } from "./components/scene/VaultScene";
import { EmptyState } from "./components/ui/EmptyState";
import { PanelBoundary } from "./components/ui/PanelBoundary";
import { QueryGate } from "./components/ui/QueryGate";
import { SpringPane } from "./components/ui/SpringPane";
import { SnapshotSheet } from "./components/vault/SnapshotSheet";
@@ -31,6 +33,7 @@ const panelTitles: Record<HUDMode, string> = {
orbits: "Orbits",
wormhole: "Wormhole uplink",
activity: "Activity",
access: "Access",
reconstitute: "Restore snapshot",
snapshot: "Snapshot detail",
};
@@ -39,10 +42,11 @@ const panelLabels: Record<HUDMode, string> = {
orbits: "Console 02 · Orbit management",
wormhole: "Console 03 · Outposts",
activity: "Console 04 · Activity",
access: "Console 05 · Access",
reconstitute: "Restore from a snapshot",
snapshot: "Recovery point",
};
const panelWidths: Record<HUDMode, number> = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, reconstitute: 760, snapshot: 640 };
const panelWidths: Record<HUDMode, number> = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, reconstitute: 760, snapshot: 640 };
const LOOK_KEY = "tessera.look";
@@ -64,11 +68,15 @@ export default function App() {
return <OperatorGate>{(operator) => <VaultApp {...operator} />}</OperatorGate>;
}
function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promise<void> }) {
function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => Promise<void>; caps: Caps }) {
const [logoutError, setLogoutError] = useState(false);
const workspaceScroll = useRef<number>(undefined);
const [bigScreen, setBigScreen] = useState(false);
const [radar, setRadar] = useState(readRadar);
// The look follows the account: the server's saved choice wins once, and a choice made before this existed is
// carried over. The browser copy stays as the instant first paint and as the fallback when there is no account.
const preferences = useQuery({ queryKey: ["preferences"], queryFn: ({ signal }) => fetchPreferences(signal), retry: false, staleTime: Infinity });
const adoptedLook = useRef(false);
const [mode, setMode] = useState<HUDMode>("scene");
const [searchOpen, setSearchOpen] = useState(false);
const searchTrigger = useRef<HTMLButtonElement>(null);
@@ -83,6 +91,21 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
const reducedMotion = useReducedMotion();
const qc = useQueryClient();
useEffect(() => {
if (adoptedLook.current || !preferences.isSuccess) return;
adoptedLook.current = true;
const saved = preferences.data.look;
if (saved) {
setRadar(saved === "radar");
try {
window.localStorage.setItem(LOOK_KEY, saved === "radar" ? "radar" : "realistic");
} catch {
// Not remembered in this browser; the account copy still applies.
}
}
else if (radar) void savePreferences({ look: "radar" }).catch(() => undefined);
}, [preferences.isSuccess, preferences.data, radar]);
useLayoutEffect(() => {
function searchKeys(event: KeyboardEvent) {
const composing = event.isComposing || event.keyCode === 229;
@@ -137,6 +160,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
function toggleRadar() {
const next = !radar;
setRadar(next);
void savePreferences({ look: next ? "radar" : "window" }).catch(() => undefined);
try {
window.localStorage.setItem(LOOK_KEY, next ? "radar" : "realistic");
} catch {
@@ -207,7 +231,12 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
? { orbitId: captureOrbitId, key: capture.submittedAt, snapshotId: capture.data ?? undefined }
: undefined, [captureOrbitId, capture.submittedAt, capture.isError, capture.data]);
const captureReady = !!captureEffect?.snapshotId && !!snaps.data?.some(({ id }) => id === captureEffect.snapshotId);
const activity = useActivity(snaps.data, orbits.data);
const activity = useActivity(snaps.data, orbits.data, caps.admin);
// Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access.
const railItems = useMemo(
() => (caps.admin ? [...hudItems, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")),
[caps.admin],
);
const failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length;
const orbitMessage = orbits.isPending ? "Receiving orbit telemetry…" : orbits.isError
@@ -246,6 +275,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
}
function openConsole(next: HUDMode, target: string | null = null) {
if (!caps.admin && next !== "scene" && next !== "activity" && next !== "snapshot") return;
if (next === "reconstitute" && !restoreBusy &&
(!restoreTarget || (target !== null && target !== restoreTarget.id))) {
setRestoreTarget({ id: target });
@@ -283,7 +313,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
</svg>
<div><strong>Tessera</strong><span>Flight deck · Backup control</span></div>
</div>
<HUDRail active={mode === "snapshot" || mode === "reconstitute" ? "scene" : mode} alerts={{ activity: activity.counts.needs > 0 }} floating={bigScreen} panelOpen={panelOpen} reducedMotion={reducedMotion} onSelect={openConsole} />
<HUDRail active={mode === "snapshot" || mode === "reconstitute" ? "scene" : mode} items={railItems} alerts={{ activity: activity.counts.needs > 0 }} floating={bigScreen} panelOpen={panelOpen} reducedMotion={reducedMotion} onSelect={openConsole} />
<div className="vault-topbar-tools">
<p className="hub-link" role="status">
<span className={`register-signal signal-${online ? "green" : "grey"}`} />
@@ -329,7 +359,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
/>
<OrbitRegister
orbits={register} selected={selected?.id} message={orbitMessage} bigScreen={bigScreen}
onSelect={selectOrbit} onManage={() => setMode("orbits")}
onSelect={selectOrbit} onManage={() => openConsole("orbits")}
/>
<OrbitInspector
orbit={selected} snapshots={history} snapshotMessage={snapshotMessage}
@@ -337,7 +367,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
onSelectSnapshot={openSnapshot}
capture={selected && (
<>
<button
{caps.can("capture.run", selected.id) && <button
type="button" className="console-control capture-button"
onClick={() => runCapture(selected)}
disabled={!online || capture.isPending || orbitStatus(selected.last_status).busy ||
@@ -345,7 +375,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
>
<span aria-hidden="true">↘</span>
<span>{selected.application_id ? "Queue backup for" : selected.dry_run ? "Rehearse" : "Capture"} {selected.name}</span>
</button>
</button>}
{noticeInInspector && mode !== "orbits" && captureNotice}
</>
)}
@@ -369,8 +399,9 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
subtitle={mode === "reconstitute" ? "Review the destination before starting the restore." : undefined}
onClose={() => setMode("scene")}
>
<PanelBoundary key={mode}>
<AnimatePresence initial={false}>
{mode === "orbits" && (
{mode === "orbits" && caps.admin && (
<SpringPane key="orbits">
<QueryGate query={orbits}>
{() => <OrbitsView snapshots={snaps.isSuccess ? snaps.data : undefined} orbits={sceneOrbits} onRun={runCapture} onOpenSnapshot={openSnapshot} captureDisabled={!online || capture.isPending} notice={captureNotice} />}
@@ -392,13 +423,16 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
/>
</SpringPane>
)}
{mode === "wormhole" && (
{mode === "wormhole" && caps.admin && (
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
)}
{mode === "access" && caps.admin && (
<SpringPane key="access"><AccessView orbits={orbits.data ?? []} /></SpringPane>
)}
{mode === "snapshot" && (
<SpringPane key="snapshot">
{snapshot
? <SnapshotSheet snap={snapshot} siblings={snapshotSiblings} onDeleted={() => openConsole("scene")} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
? <SnapshotSheet snap={snapshot} siblings={snapshotSiblings} canManage={caps.admin} canDownload={caps.can("snapshot.download", snapshot.orbit_id)} onDeleted={() => openConsole("scene")} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
: <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />}
</SpringPane>
)}
@@ -416,6 +450,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis
</QueryGate>
))}
</SpringPane>
</PanelBoundary>
</HUDPanel>
<VaultSearch
open={searchOpen} reducedMotion={reducedMotion}

View File

@@ -54,11 +54,77 @@ 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[];
};
export async function fetchMe(signal?: AbortSignal): Promise<Me> {
return api<Me>("/api/v1/me", { signal });
}
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> {

View File

@@ -0,0 +1,189 @@
import { useState, type FormEvent } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
createGrant, deleteGrant, fetchAccessUsers, fetchGrants, fetchMe, revokeUserSessions, setUserActive,
type Grant, type NewGrant, type Orbit,
} from "../../api";
import { Button } from "../ui/Button";
import { DatePicker } from "../ui/DatePicker";
import { Select } from "../ui/Select";
const field = "field";
/** Today as `YYYY-MM-DD` in the viewer's own calendar (not UTC). */
function localToday() {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
}
function when(seconds: number | null) {
return seconds ? new Date(seconds * 1000).toLocaleString() : "never";
}
/** Who may see and do what. Everything here is administrator-only and takes effect on the user's next request. */
export function AccessView({ orbits }: { orbits: Orbit[] }) {
const qc = useQueryClient();
const grants = useQuery({ queryKey: ["access-grants"], queryFn: fetchGrants, refetchInterval: 10_000 });
const users = useQuery({ queryKey: ["access-users"], queryFn: fetchAccessUsers, refetchInterval: 10_000 });
const me = useQuery({ queryKey: ["me"], queryFn: ({ signal }) => fetchMe(signal) });
const refresh = () => {
void qc.invalidateQueries({ queryKey: ["access-grants"] });
void qc.invalidateQueries({ queryKey: ["access-users"] });
};
const add = useMutation({ mutationFn: (grant: NewGrant) => createGrant(grant), onSuccess: refresh });
const remove = useMutation({ mutationFn: deleteGrant, onSuccess: refresh });
const toggle = useMutation({ mutationFn: (v: { id: string; active: boolean }) => setUserActive(v.id, v.active), onSuccess: refresh });
const signOut = useMutation({ mutationFn: revokeUserSessions, onSuccess: refresh });
const [kind, setKind] = useState<"user" | "group">("user");
// Only trust a response that has the expected shape; an older hub or a mock may send something else.
const grantList = grants.data && Array.isArray(grants.data.grants) && Array.isArray(grants.data.roles) ? grants.data : undefined;
const userList = Array.isArray(users.data) ? users.data : undefined;
const userName = (id: string) => userList?.find((u) => u.id === id)?.display_name ?? id;
const orbitName = (id: string | null) => (id ? orbits.find((o) => o.id === id)?.name ?? id : "All orbits");
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const data = new FormData(event.currentTarget);
const text = (name: string) => String(data.get(name) ?? "").trim();
const expiry = text("expires");
add.mutate({
principal_type: kind,
principal: text("principal"),
role: text("role"),
...(text("orbit") ? { orbit_id: text("orbit") } : {}),
...(expiry ? { expires_at: new Date(`${expiry}T23:59:59`).toISOString() } : {}),
});
}
// Administrators hold every permission without grants, so only people other than you are worth listing here.
const pendingUsers = (userList ?? []).filter(
(u) => !u.is_emergency && `oidc:${u.id}` !== me.data?.id &&
!(grantList?.grants ?? []).some((g) => g.principal_type === "user" && g.principal === u.id),
);
return (
<div className="space-y-8 p-6">
<section aria-labelledby="grant-heading">
<h3 id="grant-heading" className="text-lg font-semibold text-star-100">Give access</h3>
<p className="mt-1 text-sm text-star-300">
Administrators come from the SSO configuration. Everyone else sees only the orbits you grant here.
Group names are the values in the sign-in token's groups claim.
</p>
<form onSubmit={submit} className="mt-4 grid gap-4 sm:grid-cols-2">
<label className="text-sm text-star-300">
Grant to
<Select value={kind} onChange={(e) => setKind(e.target.value as "user" | "group")}>
<option value="user">A person who has signed in</option>
<option value="group">An identity-provider group</option>
</Select>
</label>
{kind === "user" ? (
<label className="text-sm text-star-300">
Person
<Select name="principal" required>
<option value="" disabled>Choose…</option>
{(userList ?? []).filter((u) => !u.is_emergency && u.active).map((u) => (
<option key={u.id} value={u.id}>{u.display_name}</option>
))}
</Select>
</label>
) : (
<label className="text-sm text-star-300">
Group name
<input name="principal" required maxLength={128} className={field} autoComplete="off" />
</label>
)}
<label className="text-sm text-star-300">
Access
<Select name="role" required defaultValue="viewer">
{(grantList?.roles ?? []).map((r) => (
<option key={r.name} value={r.name}>{r.name} — {r.permissions.join(", ")}</option>
))}
</Select>
</label>
<label className="text-sm text-star-300">
Orbit
<Select name="orbit">
<option value="">All orbits</option>
{orbits.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
</Select>
</label>
<label className="text-sm text-star-300">
Ends on (optional)
<DatePicker name="expires" aria-label="Ends on" placeholder="No end date" min={localToday()} />
</label>
<div className="flex items-end">
<Button type="submit" variant="primary" disabled={add.isPending}>{add.isPending ? "Saving…" : "Grant access"}</Button>
</div>
</form>
{add.isError && <p role="alert" className="mt-3 text-sm text-orbit-red">Could not grant access. Check the person, the orbit and the end date; an identical grant may already exist.</p>}
</section>
<section aria-labelledby="grants-heading">
<h3 id="grants-heading" className="text-lg font-semibold text-star-100">Current access</h3>
{grants.isPending ? <p role="status" className="mt-2 text-star-300">Loading…</p>
: grants.isError || !grantList ? <p role="alert" className="mt-2 text-star-300">Could not load grants. This hub may not support access management.</p>
: grantList.grants.length === 0 ? <p className="mt-2 text-star-300">Nobody has been granted access yet.</p>
: (
<div className="mt-3 overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="text-star-300">
<tr><th className="py-2 pr-4">Who</th><th className="pr-4">Permission</th><th className="pr-4">Orbit</th><th className="pr-4">Ends</th><th /></tr>
</thead>
<tbody>
{grantList.grants.map((g: Grant) => (
<tr key={g.id} className="border-t border-space-700 text-star-100">
<td className="py-2 pr-4">{g.principal_type === "group" ? `Group ${g.principal}` : userName(g.principal)}</td>
<td className="pr-4">{g.permission}</td>
<td className="pr-4">{orbitName(g.scope_id)}</td>
<td className="pr-4">{when(g.expires_at)}</td>
<td className="text-right">
<Button disabled={remove.isPending} onClick={() => remove.mutate(g.id)} aria-label={`Remove ${g.permission} from ${g.principal_type === "group" ? g.principal : userName(g.principal)}`}>Remove</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
<section aria-labelledby="users-heading">
<h3 id="users-heading" className="text-lg font-semibold text-star-100">People who have signed in</h3>
{pendingUsers.length > 0 && (
<p className="mt-1 text-sm text-star-300">
Signed in but not granted anything yet: {pendingUsers.map((u) => u.display_name).join(", ")}. Administrators from the SSO settings are not shown as waiting.
</p>
)}
{userList && (
<div className="mt-3 overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="text-star-300"><tr><th className="py-2 pr-4">Name</th><th className="pr-4">Last sign-in</th><th className="pr-4">Status</th><th /></tr></thead>
<tbody>
{userList.map((u) => (
<tr key={u.id} className="border-t border-space-700 text-star-100">
<td className="py-2 pr-4">{u.display_name}{u.is_emergency ? " (emergency operator)" : ""}</td>
<td className="pr-4">{when(u.last_login_at)}</td>
<td className="pr-4">{u.active ? "Active" : "Disabled"}</td>
<td className="space-x-2 text-right">
{!u.is_emergency && (
<>
<Button disabled={signOut.isPending} onClick={() => signOut.mutate(u.id)}>Sign out everywhere</Button>
<Button disabled={toggle.isPending} onClick={() => toggle.mutate({ id: u.id, active: !u.active })}>
{u.active ? "Disable" : "Enable"}
</Button>
</>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{(toggle.isError || signOut.isError) && <p role="alert" className="mt-3 text-sm text-orbit-red">That change was refused. You cannot disable yourself or the emergency operator.</p>}
</section>
</div>
);
}

View File

@@ -3,7 +3,7 @@ import { useCallback, useId, useLayoutEffect, useRef, type PointerEvent } from "
import { useScreenTransition } from "../../hooks/useScreenTransition";
import { uiSpring } from "../../lib/motion";
export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "reconstitute" | "snapshot";
export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "access" | "reconstitute" | "snapshot";
export const hudItems = [
{ id: "scene", label: "Vault", icon: "M4 9l8-4 8 4v6l-8 4-8-4z M4 9l8 4 8-4 M12 13v6" },
@@ -12,12 +12,22 @@ export const hudItems = [
{ id: "activity", label: "Activity", icon: "M3 12h4l3-7 4 14 3-7h4" },
] as const;
export type HUDItem = { id: HUDMode; label: string; icon: string };
/** Only for administrators: who may see and do what. */
export const accessItem: HUDItem = {
id: "access", label: "Access",
icon: "M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z M9.5 12l2 2 3.5-4",
};
type Slot = { center: number; width: number };
type Gesture = { pointer: number; x: number; y: number; origin?: number };
export function HUDRail({
active, floating, panelOpen, reducedMotion, alerts, onSelect,
active, floating, panelOpen, reducedMotion, alerts, items = hudItems, onSelect,
}: {
/** The systems this user may open. */
items?: readonly HUDItem[];
active: HUDMode;
/** Tabs with something that needs a person: their lamp turns ember even when they are not the active tab. */
alerts?: Partial<Record<HUDMode, boolean>>;
@@ -36,7 +46,7 @@ export function HUDRail({
const velocity = useVelocity(center);
const tail = useTransform(() => center.get() - Math.max(-22, Math.min(22, velocity.get() * 0.032)));
const id = useId();
const activeIndex = Math.max(0, hudItems.findIndex(item => item.id === active));
const activeIndex = Math.max(0, items.findIndex(item => item.id === active));
const snap = useCallback((index: number, immediate = false) => {
const slot = slots.current[index];
@@ -117,7 +127,7 @@ export function HUDRail({
Math.abs(slot.center - projected) < Math.abs(slots.current[nearest].center - projected) ? index : nearest,
0);
if (next === activeIndex) snap(activeIndex);
else onSelect(hudItems[next].id);
else onSelect(items[next].id);
}
return (
@@ -166,7 +176,7 @@ export function HUDRail({
<span aria-hidden="true" className="nav-text-dock" />
<motion.span aria-hidden="true" className="nav-underline" style={{ x: center, width }}
initial={false} animate={{ opacity: floating ? 0 : 1 }} />
{hudItems.map(({ id, label, icon }) => (
{items.map(({ id, label, icon }) => (
<button
key={id}
type="button"

View File

@@ -1,6 +1,6 @@
import { useEffect, useState, type FormEvent, type ReactNode } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { fetchOperatorSession, loginOperator, logoutOperator } from "../../api";
import { fetchMe, fetchOperatorSession, loginOperator, logoutOperator, type Me } from "../../api";
import { Button } from "../ui/Button";
const SSO_ERRORS: Record<string, string> = {
@@ -20,10 +20,25 @@ function useSsoError() {
return code ? SSO_ERRORS[code] ?? SSO_ERRORS.failed : undefined;
}
/** What the signed-in user may do. The hub enforces it; this only decides what is worth showing. */
export type Caps = {
admin: boolean;
can: (permission: string, orbitId?: string) => boolean;
};
export function capsFrom(me: Me | undefined, admin: boolean): Caps {
return {
admin,
can: (permission, orbitId) =>
// A hub or mock that does not send grants simply grants nothing here; the server decides anyway.
admin || (Array.isArray(me?.grants) && me.grants.some((g) => g.permission === permission && (g.orbit_id === null || g.orbit_id === orbitId))),
};
}
export function OperatorGate({
children,
}: {
children: (operator: { actor?: string; onLogout?: () => Promise<void> }) => ReactNode;
children: (operator: { actor?: string; onLogout?: () => Promise<void>; caps: Caps }) => ReactNode;
}) {
const queryClient = useQueryClient();
const session = useQuery({
@@ -32,6 +47,8 @@ export function OperatorGate({
refetchInterval: 15_000,
retry: false,
});
const signedIn = session.isSuccess && session.data.authorized;
const me = useQuery({ queryKey: ["me"], queryFn: ({ signal }) => fetchMe(signal), enabled: signedIn, refetchInterval: 15_000, retry: false });
const [pending, setPending] = useState(false);
const [error, setError] = useState<string>();
const ssoError = useSsoError();
@@ -61,14 +78,20 @@ export function OperatorGate({
await logoutOperator();
queryClient.setQueryData(["operator-session"], {
login_enabled: session.data.login_enabled, oidc_enabled: session.data.oidc_enabled,
authorized: false, actor: null, csrf: null, expires_at: null,
authorized: false, admin: false, actor: null, csrf: null, expires_at: null,
});
queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== "operator-session" });
}
if (session.isSuccess && session.data.authorized) {
const actor = session.data.actor ?? undefined;
return children({ actor, onLogout: actor ? signOut : undefined });
// Hold the app back for a moment so a viewer never fires an administrator-only request while permissions load.
// A hub older than the access model sends no `admin` flag and only ever had administrators.
const admin = session.data.admin ?? true;
if (!admin && !me.isSuccess) {
return <main className="vault-app flex min-h-screen items-center justify-center"><p role="status" className="text-star-300">Loading your access…</p></main>;
}
return children({ actor, onLogout: actor ? signOut : undefined, caps: capsFrom(me.data, admin) });
}
return (

View File

@@ -0,0 +1,193 @@
import { useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
import { createPortal } from "react-dom";
import { motion } from "motion/react";
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const WEEKDAYS = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"];
type Day = { y: number; m: number; d: number };
const pad = (n: number) => String(n).padStart(2, "0");
const iso = ({ y, m, d }: Day) => `${y}-${pad(m + 1)}-${pad(d)}`;
const sameDay = (a: Day, b: Day) => a.y === b.y && a.m === b.m && a.d === b.d;
const fromDate = (date: Date): Day => ({ y: date.getFullYear(), m: date.getMonth(), d: date.getDate() });
const toDate = ({ y, m, d }: Day) => new Date(y, m, d);
const shift = (day: Day, days: number): Day => fromDate(new Date(day.y, day.m, day.d + days));
const shiftMonth = (day: Day, months: number): Day => {
const target = new Date(day.y, day.m + months, 1);
const last = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
return { y: target.getFullYear(), m: target.getMonth(), d: Math.min(day.d, last) };
};
function parse(text: string): Day | undefined {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
if (!match) return undefined;
const day = { y: +match[1], m: +match[2] - 1, d: +match[3] };
return iso(fromDate(toDate(day))) === text ? day : undefined;
}
const label = (day: Day) => toDate(day).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
type Place = { left: number; top?: number; bottom?: number };
/**
* A themed date field in the same family as `Select`: a trigger styled like every other field, a calendar drawn in a
* portal so a console's scroll never clips it, and a hidden input that carries `YYYY-MM-DD` into forms. The grid is a
* roving-tabindex table driven by the arrow keys, PageUp/PageDown for months, Home/End for the week, Escape to close.
*/
export function DatePicker({
name, value, defaultValue = "", onChange, min, "aria-label": ariaLabel, placeholder = "Pick a date", clearable = true,
}: {
name?: string;
value?: string;
defaultValue?: string;
onChange?: (value: string) => void;
/** Earliest selectable day, `YYYY-MM-DD`. */
min?: string;
"aria-label"?: string;
placeholder?: string;
clearable?: boolean;
}) {
const [inner, setInner] = useState(defaultValue);
const current = value ?? inner;
const selected = parse(current);
const earliest = min ? parse(min) : undefined;
const today = fromDate(new Date());
const [open, setOpen] = useState(false);
const [focus, setFocus] = useState<Day>(selected ?? today);
const [place, setPlace] = useState<Place>();
const trigger = useRef<HTMLButtonElement>(null);
const panel = useRef<HTMLDivElement>(null);
const id = useId();
const blocked = (day: Day) => !!earliest && toDate(day) < toDate(earliest);
function commit(day: Day | undefined) {
const next = day ? iso(day) : "";
setInner(next);
onChange?.(next);
setOpen(false);
trigger.current?.focus();
}
function show() {
const start = selected ?? (earliest && blocked(today) ? earliest : today);
setFocus(start);
setOpen(true);
}
useLayoutEffect(() => {
if (!open) return;
const rect = trigger.current!.getBoundingClientRect();
const height = 330;
const flip = window.innerHeight - rect.bottom < height + 12 && rect.top > window.innerHeight - rect.bottom;
setPlace({
left: Math.max(8, Math.min(rect.left, window.innerWidth - 300)),
...(flip ? { bottom: window.innerHeight - rect.top + 6 } : { top: rect.bottom + 6 }),
});
}, [open]);
useEffect(() => {
if (!open) return;
const close = () => setOpen(false);
const outside = (event: PointerEvent) => {
const target = event.target as Node;
if (!panel.current?.contains(target) && !trigger.current?.contains(target)) setOpen(false);
};
window.addEventListener("pointerdown", outside, true);
window.addEventListener("resize", close);
return () => {
window.removeEventListener("pointerdown", outside, true);
window.removeEventListener("resize", close);
};
}, [open]);
// Keep keyboard focus on the day the arrows point at.
useEffect(() => {
if (open && place) panel.current?.querySelector<HTMLButtonElement>(`[data-day="${iso(focus)}"]`)?.focus();
}, [open, place, focus]);
function keys(event: KeyboardEvent<HTMLElement>) {
const moves: Record<string, () => Day> = {
ArrowLeft: () => shift(focus, -1),
ArrowRight: () => shift(focus, 1),
ArrowUp: () => shift(focus, -7),
ArrowDown: () => shift(focus, 7),
PageUp: () => shiftMonth(focus, -1),
PageDown: () => shiftMonth(focus, 1),
Home: () => shift(focus, -((toDate(focus).getDay() + 6) % 7)),
End: () => shift(focus, 6 - ((toDate(focus).getDay() + 6) % 7)),
};
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
setOpen(false);
trigger.current?.focus();
} else if (moves[event.key]) {
event.preventDefault();
setFocus(moves[event.key]());
}
}
// Six weeks starting on Monday, so the grid never changes height.
const first = new Date(focus.y, focus.m, 1);
const lead = (first.getDay() + 6) % 7;
const cells = Array.from({ length: 42 }, (_, i) => fromDate(new Date(focus.y, focus.m, 1 - lead + i)));
return (
<>
<button
ref={trigger} type="button" className="field select-trigger" aria-label={ariaLabel} aria-haspopup="dialog"
aria-expanded={open} aria-controls={open ? id : undefined}
onClick={() => (open ? setOpen(false) : show())}
onKeyDown={(event) => {
if (!open && (event.key === "ArrowDown" || event.key === "Enter" || event.key === " ")) {
event.preventDefault();
show();
}
}}
>
<span className="select-value" data-placeholder={!selected || undefined}>{selected ? label(selected) : placeholder}</span>
<svg viewBox="0 0 16 16" width="15" height="15" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"
strokeLinejoin="round" aria-hidden="true" className="select-chevron">
<rect x="2.5" y="3.5" width="11" height="10" rx="1.5" /><path d="M2.5 6.5h11M5.5 2v3M10.5 2v3" />
</svg>
</button>
<input className="select-proxy" tabIndex={-1} aria-hidden="true" name={name} value={current} onChange={() => {}} />
{open && place && createPortal(
<motion.div
ref={panel} id={id} role="dialog" aria-label={`${ariaLabel ?? "Date"} calendar`} className="datepicker"
style={{ left: place.left, top: place.top, bottom: place.bottom }}
initial={{ opacity: 0, y: place.bottom === undefined ? -6 : 6 }} animate={{ opacity: 1, y: 0 }}
onKeyDown={keys}
>
<div className="datepicker-head">
<button type="button" aria-label="Previous month" onClick={() => setFocus(shiftMonth(focus, -1))}>‹</button>
<span aria-live="polite">{MONTHS[focus.m]} {focus.y}</span>
<button type="button" aria-label="Next month" onClick={() => setFocus(shiftMonth(focus, 1))}>›</button>
</div>
<div className="datepicker-grid" role="grid" aria-label={`${MONTHS[focus.m]} ${focus.y}`}>
{WEEKDAYS.map((day) => <span key={day} className="datepicker-weekday" role="columnheader">{day}</span>)}
{cells.map((day) => {
const outside = day.m !== focus.m;
const disabled = blocked(day);
return (
<button
key={iso(day)} type="button" role="gridcell" data-day={iso(day)} disabled={disabled}
tabIndex={sameDay(day, focus) ? 0 : -1}
data-outside={outside || undefined} data-today={sameDay(day, today) || undefined}
aria-selected={!!selected && sameDay(day, selected)} aria-current={sameDay(day, today) ? "date" : undefined}
onClick={() => commit(day)}
>
{day.d}
</button>
);
})}
</div>
<div className="datepicker-foot">
<button type="button" disabled={blocked(today)} onClick={() => commit(today)}>Today</button>
{clearable && <button type="button" disabled={!selected} onClick={() => commit(undefined)}>Clear</button>}
</div>
</motion.div>,
document.body,
)}
</>
);
}

View File

@@ -0,0 +1,24 @@
import { Component, type ReactNode } from "react";
/** One console failing to render must not blank the whole app. */
export class PanelBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
componentDidCatch(error: unknown) {
console.error("console failed to render", error);
}
render() {
if (!this.state.failed) return this.props.children;
return (
<div role="alert" className="mx-auto max-w-sm px-4 py-12 text-center">
<h3 className="text-lg font-semibold text-star-100">This console could not be shown</h3>
<p className="mt-2 text-sm text-star-300">The hub sent something this version does not understand. Close the panel and try again.</p>
</div>
);
}
}

View File

@@ -17,12 +17,17 @@ export function SnapshotSheet({
siblings = [],
onReconstitute,
onDeleted,
canManage = false,
canDownload = false,
}: {
snap: Snapshot;
/** Every snapshot of the same orbit, newest first, including this one. */
siblings?: Snapshot[];
onReconstitute: () => void;
onDeleted: () => void;
/** Administrators only: restore and delete. */
canManage?: boolean;
canDownload?: boolean;
}) {
const [confirmDelete, setConfirmDelete] = useState(false);
const [copied, setCopied] = useState(false);
@@ -99,17 +104,17 @@ export function SnapshotSheet({
</div>
<div className="sheet-actions">
<Button variant="primary" className="sheet-primary" onClick={onReconstitute}>
{canManage && <Button variant="primary" className="sheet-primary" onClick={onReconstitute}>
{database ? "Database recovery options" : "Export file on hub"}
<span aria-hidden="true">→</span>
</Button>
<a href={`/api/v1/snapshots/${snap.id}/download`} download className="console-control sheet-link">
</Button>}
{canDownload && <a href={`/api/v1/snapshots/${snap.id}/download`} download className="console-control sheet-link">
Download snapshot
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M8 2v8M4.5 7 8 10.5 11.5 7M3 13.5h10" />
</svg>
</a>
{confirmDelete ? (
</a>}
{canManage && (confirmDelete ? (
<div className="sheet-confirm" role="alertdialog" aria-label="Confirm deletion">
<p>Remove this recovery point from the hub catalogue? This cannot be undone.</p>
{deletion.isError && <p role="alert" className="text-orbit-red">Snapshot could not be removed. It may be in use.</p>}
@@ -122,7 +127,7 @@ export function SnapshotSheet({
</div>
) : (
<button type="button" className="sheet-delete" onClick={() => setConfirmDelete(true)}>Delete snapshot</button>
)}
))}
</div>
<TelemetryPanel label="Snapshot record">{JSON.stringify(snap, null, 2)}</TelemetryPanel>
</div>

View File

@@ -4,8 +4,9 @@ import { fetchCaptureJobs, fetchRecentRestoreJobs, type Orbit, type Snapshot } f
import { activityCounts, buildActivity } from "../lib/activity";
/** Everything the hub reports as backups and restores, folded into one log. Polling shares keys with the Orbits console. */
export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[]) {
const restores = useQuery({ queryKey: ["restore-jobs-recent"], queryFn: () => fetchRecentRestoreJobs(100), refetchInterval: 5_000, retry: false });
export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[], canSeeRestores = true) {
// Restore history is administrator-only; asking would only produce a 403.
const restores = useQuery({ queryKey: ["restore-jobs-recent"], queryFn: () => fetchRecentRestoreJobs(100), refetchInterval: 5_000, retry: false, enabled: canSeeRestores });
const captures = useQuery({ queryKey: ["capture-jobs", "", ""], queryFn: () => fetchCaptureJobs("", ""), refetchInterval: 5_000, retry: 1 });
const restoreData = restores.data;
const captureData = captures.data;
@@ -19,7 +20,7 @@ export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[]) {
return {
entries,
counts: activityCounts(entries),
restoresUnavailable: restores.isError,
restoresUnavailable: canSeeRestores && restores.isError,
capturesUnavailable: captures.isError,
updatedAt: Math.max(restores.dataUpdatedAt, captures.dataUpdatedAt),
};

View File

@@ -1025,3 +1025,31 @@ button.act-row[data-group="needs"]:hover { background: #20161a; }
.act-state { grid-column: 3; grid-row: 1; flex-direction: row; align-items: center; gap: 8px; }
.act-open { grid-column: 1 / -1; grid-row: 3; justify-self: start; }
}
/* Date field: the calendar shares the select list's surface so every popover on a console looks alike. */
.select-value[data-placeholder] { color: var(--quiet); }
.datepicker {
position: fixed; z-index: 80; width: 284px; box-sizing: border-box; padding: 10px;
background: #111418; border: 1px solid #3a3f46; border-radius: 9px;
box-shadow: 0 18px 50px #000c, inset 0 1px 0 #ffffff10;
}
.datepicker-head { display: flex; align-items: center; justify-content: space-between; padding: 2px 2px 8px; font: 500 13px var(--font-sans); color: var(--color-star-100); }
.datepicker-head button, .datepicker-foot button {
min-width: 32px; height: 32px; padding: 0 10px; border: 1px solid #2f343b; border-radius: 6px; background: #14171b;
color: var(--color-star-200); font: 13px var(--font-sans); cursor: pointer;
}
.datepicker-head button:hover:not(:disabled), .datepicker-foot button:hover:not(:disabled) { border-color: #5a6068; color: var(--color-star-100); }
.datepicker-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; }
.datepicker-weekday { padding: 4px 0; text-align: center; font: 500 9.5px/1.4 var(--font-mono); letter-spacing: .1em; text-transform: uppercase; color: var(--quiet); }
.datepicker-grid button {
height: 34px; border: 0; border-radius: 6px; background: transparent; color: var(--color-star-200);
font: 13px var(--font-sans); cursor: pointer;
}
.datepicker-grid button[data-outside] { color: #5d636c; }
.datepicker-grid button[data-today] { box-shadow: inset 0 0 0 1px #4a4f57; }
.datepicker-grid button:hover:not(:disabled) { background: #1e1c20; color: var(--color-star-100); }
.datepicker-grid button:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.datepicker-grid button[aria-selected="true"] { background: #2a2118; color: #ffd0a9; box-shadow: inset 0 0 0 1px var(--accent); }
.datepicker-grid button:disabled { opacity: .35; cursor: default; }
.datepicker-foot { display: flex; justify-content: space-between; padding-top: 8px; }
.datepicker-foot button:disabled { opacity: .4; cursor: default; }