- 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>
169 lines
8.1 KiB
TypeScript
169 lines
8.1 KiB
TypeScript
import { useEffect, useState, type FormEvent, type ReactNode } from "react";
|
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|
import { fetchMe, fetchOperatorSession, loginOperator, logoutOperator, type Me } from "../../api";
|
|
import { Button } from "../ui/Button";
|
|
|
|
const SSO_ERRORS: Record<string, string> = {
|
|
invalid_state: "That sign-in expired or was started in another browser. Please try again.",
|
|
denied: "The identity provider declined the sign-in.",
|
|
unavailable: "The identity provider is unreachable. Try again shortly.",
|
|
disabled: "This account is disabled.",
|
|
failed: "Sign-in could not be completed. Ask an administrator if it keeps happening.",
|
|
};
|
|
|
|
/** Read the fixed error code the SSO callback leaves in the URL, then remove it. */
|
|
function useSsoError() {
|
|
const [code] = useState(() => new URLSearchParams(window.location.search).get("auth_error"));
|
|
useEffect(() => {
|
|
if (code) window.history.replaceState(null, "", window.location.pathname);
|
|
}, [code]);
|
|
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;
|
|
/** Holds at least one orbit permission (so the vault screens have something to show). */
|
|
orbits: boolean;
|
|
/** May start a refresh through at least one relation (administrators always may). */
|
|
refresh: boolean;
|
|
can: (permission: string, orbitId?: string) => boolean;
|
|
};
|
|
|
|
export function capsFrom(me: Me | undefined, admin: boolean): Caps {
|
|
return {
|
|
admin,
|
|
orbits: admin || (Array.isArray(me?.grants) && me.grants.length > 0),
|
|
// An old hub that sends no relations leaves this to the administrator flag.
|
|
refresh: admin || (Array.isArray(me?.refresh_relations) && me.refresh_relations.length > 0),
|
|
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>; caps: Caps }) => ReactNode;
|
|
}) {
|
|
const queryClient = useQueryClient();
|
|
const session = useQuery({
|
|
queryKey: ["operator-session"],
|
|
queryFn: ({ signal }) => fetchOperatorSession(signal),
|
|
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();
|
|
|
|
async function submit(event: FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
const form = event.currentTarget;
|
|
const password = new FormData(form).get("password");
|
|
if (pending || typeof password !== "string" || !password) return;
|
|
setPending(true);
|
|
setError(undefined);
|
|
form.reset();
|
|
await queryClient.cancelQueries({ queryKey: ["operator-session"] });
|
|
try {
|
|
const signedIn = await loginOperator(password);
|
|
queryClient.setQueryData(["operator-session"], signedIn);
|
|
} catch {
|
|
setError("Could not sign in. Check the password or try again shortly.");
|
|
} finally {
|
|
setPending(false);
|
|
}
|
|
}
|
|
|
|
async function signOut() {
|
|
if (!session.isSuccess) return;
|
|
await queryClient.cancelQueries({ queryKey: ["operator-session"] });
|
|
await logoutOperator();
|
|
queryClient.setQueryData(["operator-session"], {
|
|
login_enabled: session.data.login_enabled, oidc_enabled: session.data.oidc_enabled,
|
|
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;
|
|
// 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 (
|
|
<main className="vault-app flex min-h-screen items-center justify-center p-5">
|
|
<section className="w-full max-w-sm rounded-2xl border border-space-700 bg-space-900 p-6 sm:p-8">
|
|
<p className="instrument-label mb-3">Tessera / Backup control</p>
|
|
<h1 className="text-2xl font-semibold text-star-100">Sign in</h1>
|
|
{session.isPending ? <p role="status" className="mt-4 text-star-300">Connecting to the hub…</p>
|
|
: session.isError ? (
|
|
<div className="mt-4 space-y-3">
|
|
<p role="alert" className="text-star-300">Could not reach the hub.</p>
|
|
<Button onClick={() => void session.refetch()}>Try again</Button>
|
|
</div>
|
|
) : session.data.actor ? (
|
|
<div className="mt-4 space-y-4">
|
|
<h2 className="text-lg font-semibold text-star-100">No access yet</h2>
|
|
<p role="status" className="text-star-300">
|
|
You are signed in as {session.data.actor}, but this account has not been granted access to Tessera.
|
|
Ask an administrator to add you, then sign in again.
|
|
</p>
|
|
<Button onClick={() => void signOut()}>Sign out</Button>
|
|
</div>
|
|
) : session.data.login_enabled || session.data.oidc_enabled ? (
|
|
<div className="mt-5 space-y-5">
|
|
{ssoError && <p role="alert" className="text-sm text-orbit-red">{ssoError}</p>}
|
|
{session.data.oidc_enabled && (
|
|
<a href="/api/v1/auth/oidc/login"
|
|
className="block w-full rounded-xl bg-star-100 px-4 py-2 text-center font-medium text-space-950">
|
|
Sign in with SSO
|
|
</a>
|
|
)}
|
|
{session.data.login_enabled && (
|
|
session.data.oidc_enabled ? (
|
|
<details className="group">
|
|
<summary className="cursor-pointer text-sm text-star-300">Emergency operator sign-in</summary>
|
|
<form onSubmit={submit} className="mt-3 space-y-4">
|
|
<label className="block text-sm text-star-300">
|
|
Operator password
|
|
<input type="password" name="password" autoComplete="current-password" required
|
|
maxLength={1024} className="field" />
|
|
</label>
|
|
{error && <p role="alert" className="text-sm text-orbit-red">{error}</p>}
|
|
<Button type="submit" variant="primary" className="w-full" disabled={pending}>
|
|
{pending ? "Signing in…" : "Sign in"}
|
|
</Button>
|
|
</form>
|
|
</details>
|
|
) : (
|
|
<form onSubmit={submit} className="mt-3 space-y-4">
|
|
<label className="block text-sm text-star-300">
|
|
Operator password
|
|
<input type="password" name="password" autoComplete="current-password" required
|
|
maxLength={1024} className="field" />
|
|
</label>
|
|
{error && <p role="alert" className="text-sm text-orbit-red">{error}</p>}
|
|
<Button type="submit" variant="primary" className="w-full" disabled={pending}>
|
|
{pending ? "Signing in…" : "Sign in"}
|
|
</Button>
|
|
</form>
|
|
)
|
|
)}
|
|
</div>
|
|
) : <p className="mt-4 text-star-300">Browser sign-in is disabled on this hub.</p>}
|
|
</section>
|
|
</main>
|
|
);
|
|
}
|