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 = { 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; 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; 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(); const ssoError = useSsoError(); async function submit(event: FormEvent) { 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

Loading your access…

; } return children({ actor, onLogout: actor ? signOut : undefined, caps: capsFrom(me.data, admin) }); } return (

Tessera / Backup control

Sign in

{session.isPending ?

Connecting to the hub…

: session.isError ? (

Could not reach the hub.

) : session.data.actor ? (

No access yet

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.

) : session.data.login_enabled || session.data.oidc_enabled ? (
{ssoError &&

{ssoError}

} {session.data.oidc_enabled && ( Sign in with SSO )} {session.data.login_enabled && (
{session.data.oidc_enabled && ( Emergency operator sign-in )}
{error &&

{error}

}
)}
) :

Browser sign-in is disabled on this hub.

}
); }