feat: access console with a permission tree, grouped grants and effective access
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled

Backend: grants accept a list of permissions; PUT /access/grants edits or renews a set atomically; refusals carry a reason; the grant list includes refresh grants per relation and the administrator-only permissions; users keep their last groups and admin flag; the emergency operator cannot hold grants.

Frontend: the Access screen shows the grantable permissions as a checkbox tree with dependencies, rows grouped by person or group, orbit and end date, expiry and no-effect states, and what each person can do right now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 20:20:25 +07:00
parent 3bd0a1c9a3
commit c938afe1b5
15 changed files with 1412 additions and 223 deletions

109
web/scripts/access.test.mjs Normal file
View File

@@ -0,0 +1,109 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
branchState, expiryState, groupGrants, hasNoEffect, neededBy, personAccess, reasonText, roleLabel, seenGroups, setMany, setPermission,
} from "../src/lib/access.ts";
const roles = [
{ name: "viewer", permissions: ["orbit.read", "snapshot.read"] },
{ name: "capturer", permissions: ["orbit.read", "snapshot.read", "capture.run"] },
{ name: "downloader", permissions: ["orbit.read", "snapshot.read", "snapshot.download"] },
];
const NOW = 1_000_000;
const grant = (id, principal, permission, extra = {}) => ({
id, principal_type: "user", principal, permission, scope_type: "global", scope_id: null, expires_at: null, created_by: "t", created_at: 1, ...extra,
});
test("ticking a permission ticks what it needs; unticking removes what depends on it", () => {
const download = setPermission(new Set(), "snapshot.download", true);
assert.deepEqual([...download].sort(), ["orbit.read", "snapshot.download", "snapshot.read"]);
const noList = setPermission(download, "snapshot.read", false);
assert.deepEqual([...noList], ["orbit.read"], "download needs list, so it goes too");
assert.deepEqual(neededBy(new Set(["orbit.read", "capture.run"]), "orbit.read"), ["capture.run"]);
assert.deepEqual(neededBy(new Set(["orbit.read"]), "orbit.read"), []);
});
test("a branch reports all, some or none and ticks as a whole", () => {
const ids = ["snapshot.read", "snapshot.download"];
assert.equal(branchState(new Set(), ids), "none");
assert.equal(branchState(new Set(["snapshot.read"]), ids), "some");
const all = setMany(new Set(), ids, true);
assert.equal(branchState(all, ids), "all");
assert.ok(all.has("orbit.read"));
assert.equal(branchState(setMany(all, ids, false), ids), "none");
});
test("names a set of permissions from the hub's roles, never inventing one", () => {
assert.equal(roleLabel(["snapshot.read", "orbit.read"], roles), "Viewer");
assert.equal(roleLabel(["orbit.read", "snapshot.read", "capture.run"], roles), "Capturer");
assert.equal(roleLabel(["orbit.read", "snapshot.read", "capture.run", "snapshot.download"], roles), "Capturer + download");
assert.equal(roleLabel(["capture.run"], roles), "Custom");
assert.equal(roleLabel([], roles), "Custom");
assert.equal(roleLabel(["orbit.read"], []), "Custom", "no roles known: always custom");
});
test("one row per person, orbit and end date, with permissions in tree order", () => {
const rows = groupGrants([
grant("1", "u", "capture.run"), grant("2", "u", "orbit.read"), grant("3", "u", "snapshot.read"),
grant("4", "u", "orbit.read", { scope_type: "orbit", scope_id: "o1" }),
grant("5", "u", "snapshot.read", { expires_at: 5 }),
grant("6", "dev", "orbit.read", { principal_type: "group" }),
]);
assert.equal(rows.length, 4);
assert.deepEqual(rows[0].permissions, ["orbit.read", "snapshot.read", "capture.run"]);
assert.deepEqual(rows[0].ids, ["1", "2", "3"]);
});
test("expiry is none, soon (within two weeks) or expired", () => {
assert.equal(expiryState(null, NOW), "none");
assert.equal(expiryState(NOW, NOW), "expired", "expiry is exclusive, as on the hub");
assert.equal(expiryState(NOW + 86_400, NOW), "soon");
assert.equal(expiryState(NOW + 30 * 86_400, NOW), "none");
});
test("a grant without orbit.read has no effect, unless another grant of theirs supplies it", () => {
const all = [grant("1", "u", "capture.run", { scope_type: "orbit", scope_id: "o1" })];
const [row] = groupGrants(all);
assert.equal(hasNoEffect(row, all, [], NOW), true);
const withGlobal = [...all, grant("2", "u", "orbit.read")];
assert.equal(hasNoEffect(row, withGlobal, [], NOW), false, "a global orbit.read covers it");
const otherOrbit = [...all, grant("3", "u", "orbit.read", { scope_type: "orbit", scope_id: "o2" })];
assert.equal(hasNoEffect(row, otherOrbit, [], NOW), true, "another orbit does not");
const viaGroup = [...all, grant("4", "qa", "orbit.read", { principal_type: "group" })];
assert.equal(hasNoEffect(row, viaGroup, ["qa"], NOW), false, "a group of theirs supplies it");
assert.equal(hasNoEffect(row, viaGroup, [], NOW), true, "a group they are not in does not");
const expired = [grant("5", "u", "capture.run", { expires_at: NOW - 1 })];
assert.equal(hasNoEffect(groupGrants(expired)[0], expired, [], NOW), false, "an expired grant is shown as expired instead");
});
test("a person is an administrator, waiting, or described by everything that reaches them", () => {
const user = (extra) => ({ id: "u", issuer: "i", display_name: "U", active: true, created_at: 1, last_login_at: 1, is_emergency: false, admin: false, groups: [], ...extra });
assert.equal(personAccess(user({ admin: true }), [], [], roles, NOW).kind, "admin");
assert.equal(personAccess(user(), [], [], roles, NOW).kind, "waiting");
const viaGroup = personAccess(user({ groups: ["dev"] }), [grant("1", "dev", "orbit.read", { principal_type: "group" }), grant("2", "dev", "snapshot.read", { principal_type: "group" })], [], roles, NOW);
assert.deepEqual([viaGroup.kind, viaGroup.label, viaGroup.via], ["granted", "Viewer", ["dev"]]);
const refreshOnly = personAccess(
user(), [],
[{ id: "r", principal_type: "user", principal: "u", relation_id: "x", version: 1, active: true, source_name: "prod", target_name: "stg", expires_at: null, created_at: 1 }],
roles, NOW,
);
assert.deepEqual([refreshOnly.kind, refreshOnly.refresh], ["granted", ["prod → stg"]]);
const ended = personAccess(
user(), [],
[{ id: "r", principal_type: "user", principal: "u", relation_id: "x", version: 1, active: false, source_name: "prod", target_name: "stg", expires_at: null, created_at: 1 }],
roles, NOW,
);
assert.equal(ended.kind, "waiting", "a grant on an ended relation gives nothing");
assert.equal(personAccess(user(), [grant("1", "u", "capture.run")], [], roles, NOW).noEffect, true);
});
test("seen groups are counted once per person and sorted by size", () => {
const u = (groups) => ({ groups });
assert.deepEqual(seenGroups([u(["dev", "qa"]), u(["dev", "dev"]), u(undefined)]), [{ name: "dev", people: 2 }, { name: "qa", people: 1 }]);
});
test("refusal codes become sentences and unknown ones fall back", () => {
assert.match(reasonText("already_granted", "x"), /Already granted/);
assert.equal(reasonText("something_new", "fallback"), "fallback");
assert.equal(reasonText(undefined, "fallback"), "fallback");
});

View File

@@ -177,7 +177,28 @@ export type Grant = {
created_by: string;
created_at: number;
};
export type GrantList = { grants: Grant[]; roles: { name: string; permissions: string[] }[]; grantable: string[] };
/** A refresh grant: one relation (a source orbit and the staging target it overwrites), not an orbit scope. */
export type RelationGrantRow = {
id: string;
principal_type: "user" | "group";
principal: string;
relation_id: string;
version: number;
/** An ended relation grants nothing. */
active: boolean;
source_name: string;
target_name: string;
expires_at: number | null;
created_at: number;
};
export type GrantList = {
grants: Grant[];
relation_grants?: RelationGrantRow[];
roles: { name: string; permissions: string[] }[];
grantable: string[];
/** Permissions only administrators hold. */
admin_only?: string[];
};
export type AccessUser = {
id: string;
issuer: string;
@@ -186,11 +207,16 @@ export type AccessUser = {
created_at: number;
last_login_at: number | null;
is_emergency: boolean;
/** Administrator at the last sign-in. Absent on a hub older than this field. */
admin?: boolean;
/** Groups the identity provider reported at the last sign-in. */
groups?: string[];
};
export type NewGrant = {
principal_type: "user" | "group";
principal: string;
role?: string;
permissions?: string[];
orbit_id?: string;
expires_at?: string;
};
@@ -199,6 +225,9 @@ 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) });
/** Edit or renew in one step: `replaces` are the grants of the same person or group and orbit being swapped for the new set. */
export const replaceGrants = (grant: NewGrant & { replaces: string[] }) =>
api<Grant[]>("/api/v1/access/grants", { method: "PUT", 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 }) });

View File

@@ -1,23 +1,59 @@
import { useState, type FormEvent } from "react";
import { useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
createGrant, deleteGrant, fetchAccessUsers, fetchGrants, fetchMe, revokeUserSessions, setUserActive,
type Grant, type NewGrant, type Orbit,
createGrant, deleteGrant, fetchAccessUsers, fetchGrants, fetchMe, fetchRelations, grantRelationAccess, refusalReason, replaceGrants,
revokeRelationAccess, revokeUserSessions, setUserActive, type AccessUser, type Orbit, type RelationGrantRow, type RelationView,
} from "../../api";
import {
ADMIN_LABELS, TREE, branchState, expiryState, groupGrants, hasNoEffect, neededBy, personAccess, reasonText, roleLabel,
seenGroups, setMany, setPermission, shortName, type AccessRow,
} from "../../lib/access";
import { Button } from "../ui/Button";
import { DatePicker } from "../ui/DatePicker";
import { Select } from "../ui/Select";
const field = "field";
const pad = (n: number) => String(n).padStart(2, "0");
const ymd = (date: Date) => `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
/** Today plus `days`, as `YYYY-MM-DD` in the viewer's own calendar (not UTC). */
const inDays = (days: number) => ymd(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + days));
const day = (seconds: number) => new Date(seconds * 1000).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
const when = (seconds: number | null) => (seconds ? new Date(seconds * 1000).toLocaleString() : "never");
const label = "text-[11px] font-mono uppercase tracking-[.14em] text-star-400";
/** 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")}`;
type Report = { added: number; skipped: number; failures: string[] };
type Who = "user" | "group";
/** A checkbox that can be fully, partly or not ticked, or locked. */
function Box({ state, name, disabled, onChange, small }: { state: "all" | "some" | "none"; name: string; disabled?: boolean; onChange: () => void; small?: boolean }) {
const on = state !== "none";
const size = small ? "h-5 w-5" : "h-[22px] w-[22px]";
return (
<button
type="button" role="checkbox" aria-checked={state === "some" ? "mixed" : on} aria-label={name} disabled={disabled} onClick={onChange}
className={`mt-0.5 flex ${size} shrink-0 items-center justify-center rounded-md border-[1.5px] disabled:cursor-not-allowed ${on ? "border-orbit-amber bg-orbit-amber" : "border-[#4a525b] bg-space-950"} ${disabled && on ? "opacity-70" : ""}`}
>
{state === "all" && <svg aria-hidden width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="#14110d" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 7.5l3 3 6-7" /></svg>}
{state === "some" && <svg aria-hidden width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="#14110d" strokeWidth="2.4" strokeLinecap="round"><path d="M3 7h8" /></svg>}
</button>
);
}
function when(seconds: number | null) {
return seconds ? new Date(seconds * 1000).toLocaleString() : "never";
function Chip({ active, onClick, children }: { active?: boolean; onClick: () => void; children: React.ReactNode }) {
return (
<button type="button" aria-pressed={active} onClick={onClick}
className={`rounded-full border px-3 py-1 text-[13px] ${active ? "border-[#f1bc90] bg-[#2a2119] text-[#f1bc90]" : "border-[#3a4149] text-star-200 hover:border-[#5a6068]"}`}>
{children}
</button>
);
}
function Badge({ tone, children }: { tone: "green" | "violet" | "amber" | "red" | "plain"; children: React.ReactNode }) {
const tones = {
green: "bg-[#1c2b27] text-orbit-green", violet: "bg-[#2a2640] text-wormhole-violet", amber: "bg-[#2a2119] text-orbit-amber",
red: "bg-[#3a1f1d] text-orbit-red", plain: "bg-[#26262a] text-star-200",
};
return <span className={`inline-block rounded-md px-2 py-0.5 text-[13px] font-medium ${tones[tone]}`}>{children}</span>;
}
/** Who may see and do what. Everything here is administrator-only and takes effect on the user's next request. */
@@ -25,165 +61,502 @@ 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 relations = useQuery({ queryKey: ["relations"], queryFn: fetchRelations, 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"] });
void qc.invalidateQueries({ queryKey: ["relation-access"] });
};
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 userList: AccessUser[] | undefined = Array.isArray(users.data) ? users.data : undefined;
const relationGrants: RelationGrantRow[] = Array.isArray(grantList?.relation_grants) ? grantList.relation_grants : [];
const activeRelations: RelationView[] = Array.isArray(relations.data?.relations) ? relations.data.relations.filter((r) => r.active) : [];
const roles = grantList?.roles ?? [];
const now = Math.floor(Date.now() / 1000);
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");
const groupsSeen = useMemo(() => seenGroups(userList ?? []), [userList]);
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() } : {}),
});
const formRef = useRef<HTMLElement>(null);
const [editing, setEditing] = useState<AccessRow | undefined>();
const [formKey, setFormKey] = useState(0);
const [prefill, setPrefill] = useState<{ perms: string[]; expires: string } | undefined>();
function startEdit(row: AccessRow, renew: boolean) {
setEditing(row);
setPrefill({ perms: row.permissions, expires: renew ? inDays(30) : row.expires_at ? ymd(new Date(row.expires_at * 1000)) : "" });
setFormKey((k) => k + 1);
formRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
}
function stopEdit() {
setEditing(undefined);
setPrefill(undefined);
setFormKey((k) => k + 1);
}
// 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),
);
const remove = useMutation({ mutationFn: async (ids: string[]) => { for (const id of ids) await deleteGrant(id); }, onSuccess: refresh });
const removeRefresh = useMutation({ mutationFn: ({ relation, id }: { relation: string; id: string }) => revokeRelationAccess(relation, id), onSuccess: refresh });
const fix = useMutation({
mutationFn: (row: AccessRow) => replaceGrants({
principal_type: row.principal_type, principal: row.principal, ...(row.scope_id ? { orbit_id: row.scope_id } : {}),
...(row.expires_at ? { expires_at: new Date(row.expires_at * 1000).toISOString() } : {}),
permissions: [...setPermission(new Set(row.permissions), "orbit.read", true)], replaces: row.ids,
}),
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 rows = useMemo(() => groupGrants(grantList?.grants ?? []), [grantList]);
const groupsOf = (row: AccessRow) => (row.principal_type === "user" ? userList?.find((u) => u.id === row.principal)?.groups ?? [] : []);
type Line = { key: string; sort: number; attention: boolean; soon: boolean; refresh: boolean; orbit?: AccessRow; relation?: RelationGrantRow };
const lines: Line[] = [
...rows.map((row): Line => {
const state = expiryState(row.expires_at, now);
const noEffect = hasNoEffect(row, grantList?.grants ?? [], groupsOf(row), now);
return { key: row.key, orbit: row, refresh: false, sort: state === "expired" ? 1 : 0, attention: state === "expired" || noEffect, soon: state === "soon" };
}),
...relationGrants.map((g): Line => {
const state = expiryState(g.expires_at, now);
return { key: g.id, relation: g, refresh: true, sort: state === "expired" || !g.active ? 1 : 0, attention: state === "expired" || !g.active, soon: state === "soon" };
}),
].sort((a, b) => a.sort - b.sort);
const [filter, setFilter] = useState<"all" | "attention" | "refresh" | "soon">("all");
const shown = lines.filter((l) => filter === "all" || (filter === "attention" && l.attention) || (filter === "refresh" && l.refresh) || (filter === "soon" && l.soon));
const count = (f: (l: Line) => boolean) => lines.filter(f).length;
const people = userList ?? [];
const failed = toggle.isError ? toggle.error : signOut.isError ? signOut.error : undefined;
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>
<div className="space-y-10 p-6">
<GiveAccess
key={formKey} sectionRef={formRef} orbits={orbits} users={people} roles={roles} relations={activeRelations} groupsSeen={groupsSeen}
editing={editing} prefill={prefill} adminOnly={grantList?.admin_only ?? Object.keys(ADMIN_LABELS)} onDone={() => { refresh(); void qc.invalidateQueries({ queryKey: ["relations"] }); if (editing) stopEdit(); }}
onCancelEdit={stopEdit} userName={userName}
/>
<section aria-labelledby="grants-heading">
<h3 id="grants-heading" className="text-lg font-semibold text-star-100">Current access</h3>
<div className="flex flex-wrap items-baseline justify-between gap-2">
<h3 id="grants-heading" className="text-lg font-semibold text-star-100">Current access</h3>
<p className="text-sm text-star-400">One row per person or group, orbit and end date. Refresh grants are listed here too.</p>
</div>
{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>
: lines.length === 0 ? (
<div className="mt-3 rounded-xl border border-dashed border-[#3a4149] p-6 text-center">
<p className="font-medium text-star-100">Nobody has been granted access yet</p>
<p className="mt-1 text-sm text-star-400">Administrators from SSO already see everything. Use the form above to let someone else in.</p>
</div>
) : (
<>
<div className="mt-3 flex flex-wrap gap-2" role="group" aria-label="Filter current access">
<Chip active={filter === "all"} onClick={() => setFilter("all")}>All · {lines.length}</Chip>
<Chip active={filter === "attention"} onClick={() => setFilter("attention")}>Needs attention · {count((l) => l.attention)}</Chip>
<Chip active={filter === "refresh"} onClick={() => setFilter("refresh")}>Refresh · {count((l) => l.refresh)}</Chip>
<Chip active={filter === "soon"} onClick={() => setFilter("soon")}>Ending soon · {count((l) => l.soon)}</Chip>
</div>
<div className="mt-3 overflow-x-auto rounded-xl border border-space-700">
<table className="w-full min-w-[820px] text-left text-sm">
<thead className="bg-[#0d1013] text-star-400"><tr className={label}>
<th className="px-4 py-3 font-normal">Who</th><th className="font-normal">Can do</th><th className="font-normal">Orbit</th><th className="font-normal">Ends</th><th />
</tr></thead>
<tbody>
{shown.map((line) => line.orbit
? <OrbitLine key={line.key} row={line.orbit} grants={grantList.grants} roles={roles} now={now} people={groupsSeen}
who={line.orbit.principal_type === "group" ? line.orbit.principal : userName(line.orbit.principal)}
orbit={orbitName(line.orbit.scope_id)} noEffect={hasNoEffect(line.orbit, grantList.grants, groupsOf(line.orbit), now)}
busy={remove.isPending || fix.isPending} onEdit={(renew) => startEdit(line.orbit as AccessRow, renew)}
onFix={() => fix.mutate(line.orbit as AccessRow)} onRemove={() => remove.mutate((line.orbit as AccessRow).ids)} />
: line.relation && <RefreshLine key={line.key} grant={line.relation} now={now} who={line.relation.principal_type === "group" ? line.relation.principal : userName(line.relation.principal)}
busy={removeRefresh.isPending} onRemove={() => removeRefresh.mutate({ relation: line.relation!.relation_id, id: line.relation!.id })} />)}
{shown.length === 0 && <tr><td colSpan={5} className="px-4 py-5 text-star-400">Nothing matches this filter.</td></tr>}
</tbody>
</table>
</div>
</>
)}
{(remove.isError || removeRefresh.isError || fix.isError) && <p role="alert" className="mt-3 text-sm text-orbit-red">That change was not saved. Reload the list and try again.</p>}
</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>
)}
<div className="flex flex-wrap items-baseline justify-between gap-2">
<h3 id="users-heading" className="text-lg font-semibold text-star-100">People who have signed in</h3>
<p className="text-sm text-star-400">Access is what each person can do right now, from every grant and group.</p>
</div>
{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>
<div className="mt-3 overflow-x-auto rounded-xl border border-space-700">
<table className="w-full min-w-[820px] text-left text-sm">
<thead className="bg-[#0d1013] text-star-400"><tr className={label}>
<th className="px-4 py-3 font-normal">Name</th><th className="font-normal">Last sign-in</th><th className="font-normal">Access</th><th className="font-normal">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>
))}
{people.map((u) => {
const self = `oidc:${u.id}` === me.data?.id;
const access = u.is_emergency ? undefined : personAccess(u, grantList?.grants ?? [], relationGrants, roles, now);
return (
<tr key={u.id} className="border-t border-space-700 align-middle text-star-100">
<td className="px-4 py-3">{u.is_emergency ? "Emergency operator" : u.display_name}{self && <span className="ml-2 rounded-md bg-[#26262a] px-2 py-0.5 text-xs text-star-200">You</span>}</td>
<td className="text-star-200">{when(u.last_login_at)}</td>
<td className="pr-3">
{u.is_emergency ? <><Badge tone="amber">Administrator</Badge> <span className="text-xs text-star-400">emergency password</span></>
: access?.kind === "admin" ? <><Badge tone="amber">Administrator</Badge> <span className="text-xs text-star-400">from SSO settings</span></>
: access?.kind === "waiting" ? <><span className="rounded-md border border-[#3a4149] px-2 py-0.5 text-[13px] text-star-200">Waiting</span> <span className="text-xs text-star-400">No access yet.</span></>
: access && (
<span className="text-[13px] text-star-200">
{access.label && <Badge tone="green">{access.label}</Badge>}
{access.via.length > 0 && <> via group {access.via.join(", ")}</>}
{access.refresh.length > 0 && <>{access.label ? " · " : ""}<Badge tone="violet">Refresh</Badge> {access.refresh.join(", ")}</>}
{access.noEffect && <span className="block text-xs text-orbit-amber">⚠ Cannot see any orbit yet: “See the orbit” is missing.</span>}
</span>
)}
</td>
<td className={u.active ? "" : "text-star-400"}>{u.active ? "Active" : "Disabled"}</td>
<td className="space-x-2 whitespace-nowrap px-4 text-right">
{!u.is_emergency && (
<>
<Button disabled={signOut.isPending} onClick={() => signOut.mutate(u.id)}>Sign out everywhere</Button>
{!self && <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>}
{failed && <p role="alert" className="mt-3 text-sm text-orbit-red">{reasonText(refusalReason(failed), "That change was refused.")}</p>}
</section>
</div>
);
}
function OrbitLine({ row, grants, roles, now, who, orbit, people, noEffect, busy, onEdit, onFix, onRemove }: {
row: AccessRow; grants: unknown; roles: { name: string; permissions: string[] }[]; now: number; who: string; orbit: string;
people: { name: string; people: number }[]; noEffect: boolean; busy: boolean; onEdit: (renew: boolean) => void; onFix: () => void; onRemove: () => void;
}) {
void grants;
const state = expiryState(row.expires_at, now);
const expired = state === "expired";
const members = row.principal_type === "group" ? people.find((p) => p.name === row.principal)?.people : undefined;
const role = roleLabel(row.permissions, roles);
return (
<tr className={`border-t border-space-700 align-top text-star-100 ${expired ? "bg-[#14110f]" : ""}`}>
<td className="px-4 py-3">
<span className={`font-medium ${expired ? "text-star-300" : ""}`}>{who}</span>
<span className="block font-mono text-xs text-star-400">{row.principal_type === "group" ? `group${members ? ` · ${members} ${members === 1 ? "person" : "people"}` : ""}` : "person"}</span>
</td>
<td className="pr-3">
<Badge tone={role === "Custom" ? "plain" : expired ? "plain" : "green"}>{role}</Badge>
<span className="ml-2 text-[13px] text-star-400">{row.permissions.map(shortName).join(" · ")}</span>
{noEffect && <span className="mt-1 block text-[13px] text-orbit-amber">⚠ Has no effect: this person cannot see the orbit. Add “See the orbit”.</span>}
</td>
<td className="pr-3">{orbit}</td>
<td className="pr-3">
{expired ? <Badge tone="red">Expired {day(row.expires_at!)}</Badge>
: row.expires_at ? <span className={state === "soon" ? "text-orbit-amber" : "text-star-200"}>{day(row.expires_at)}{state === "soon" ? " · ending soon" : ""}</span>
: <span className="text-star-300">No end</span>}
</td>
<td className="space-x-2 whitespace-nowrap px-4 text-right">
{noEffect && <Button disabled={busy} onClick={onFix}>Fix</Button>}
{expired ? <Button onClick={() => onEdit(true)}>Renew</Button> : <Button onClick={() => onEdit(false)} aria-label={`Edit access for ${who}`}>Edit</Button>}
<Button disabled={busy} onClick={onRemove} aria-label={`Remove all access of ${who} on ${orbit}`}>Remove</Button>
</td>
</tr>
);
}
function RefreshLine({ grant, now, who, busy, onRemove }: { grant: RelationGrantRow; now: number; who: string; busy: boolean; onRemove: () => void }) {
const state = expiryState(grant.expires_at, now);
const expired = state === "expired";
return (
<tr className={`border-t border-space-700 align-top text-star-100 ${expired || !grant.active ? "bg-[#14110f]" : ""}`}>
<td className="px-4 py-3">
<span className="font-medium">{who}</span>
<span className="block font-mono text-xs text-star-400">{grant.principal_type === "group" ? "group" : "person"}</span>
</td>
<td className="pr-3">
<Badge tone={grant.active ? "violet" : "plain"}>Refresh</Badge>
<span className="ml-2 text-[13px] text-star-400">{grant.source_name} → {grant.target_name} · v{grant.version}</span>
{!grant.active && <span className="mt-1 block text-[13px] text-orbit-amber">⚠ This relation has ended, so the grant does nothing. Allow them again on its new version.</span>}
</td>
<td className="pr-3 text-star-400">per relation</td>
<td className="pr-3">
{expired ? <Badge tone="red">Expired {day(grant.expires_at!)}</Badge>
: grant.expires_at ? <span className={state === "soon" ? "text-orbit-amber" : "text-star-200"}>{day(grant.expires_at)}{state === "soon" ? " · ending soon" : ""}</span>
: <span className="text-star-300">No end</span>}
</td>
<td className="whitespace-nowrap px-4 text-right"><Button disabled={busy} onClick={onRemove} aria-label={`Remove refresh access of ${who}`}>Remove</Button></td>
</tr>
);
}
function GiveAccess({ sectionRef, orbits, users, roles, relations, groupsSeen, adminOnly, editing, prefill, onDone, onCancelEdit, userName }: {
sectionRef: React.RefObject<HTMLElement | null>; orbits: Orbit[]; users: AccessUser[]; roles: { name: string; permissions: string[] }[];
relations: RelationView[]; groupsSeen: { name: string; people: number }[]; adminOnly: string[]; editing?: AccessRow;
prefill?: { perms: string[]; expires: string }; onDone: () => void; onCancelEdit: () => void; userName: (id: string) => string;
}) {
const [kind, setKind] = useState<Who>(editing?.principal_type ?? "user");
const [principal, setPrincipal] = useState(editing?.principal ?? "");
const [orbit, setOrbit] = useState(editing?.scope_id ?? "");
const [expires, setExpires] = useState(prefill?.expires ?? "");
const [perms, setPerms] = useState<Set<string>>(new Set(prefill?.perms ?? ["orbit.read", "snapshot.read"]));
const [rels, setRels] = useState<Set<string>>(new Set());
const [adminOpen, setAdminOpen] = useState(false);
const [report, setReport] = useState<Report | undefined>();
const candidates = users.filter((u) => !u.is_emergency && !u.admin && u.active);
const roleOf = (set: Set<string>) => roleLabel(set, roles);
const count = perms.size + rels.size;
const ready = count > 0 && principal.trim() !== "" && (!editing || perms.size > 0);
const submit = useMutation({
mutationFn: async (): Promise<Report> => {
const base = {
principal_type: kind, principal: principal.trim(),
...(orbit ? { orbit_id: orbit } : {}),
...(expires ? { expires_at: new Date(`${expires}T23:59:59`).toISOString() } : {}),
};
const out: Report = { added: 0, skipped: 0, failures: [] };
if (perms.size > 0) {
try {
const permissions = [...perms];
if (editing) {
await replaceGrants({ ...base, permissions, replaces: editing.ids });
out.added += permissions.length;
} else {
const created = await createGrant({ ...base, permissions });
out.added += created.length;
out.skipped += permissions.length - created.length;
}
} catch (error) {
out.failures.push(reasonText(refusalReason(error), "The permissions could not be saved."));
}
}
for (const id of rels) {
const relation = relations.find((r) => r.id === id);
const name = relation ? `${relation.source_name} → ${relation.target_name}` : "that relation";
try {
await grantRelationAccess(id, { principal_type: kind, principal: principal.trim(), ...(base.expires_at ? { expires_at: base.expires_at } : {}) });
out.added += 1;
} catch {
out.failures.push(`Refresh through ${name} was not added. It may already be allowed.`);
}
}
return out;
},
onSuccess: (result) => {
setReport(result);
if (result.failures.length === 0) {
if (editing) onDone();
else {
setPerms(new Set(["orbit.read", "snapshot.read"]));
setRels(new Set());
onDone();
}
} else onDone();
},
});
const preset = (name: string) => setPerms(new Set(roles.find((r) => r.name === name)?.permissions ?? []));
const presetActive = (name: string) => {
const role = roles.find((r) => r.name === name);
return !!role && role.permissions.length === perms.size && role.permissions.every((p) => perms.has(p));
};
const relKey = (id: string) => (rels.has(id) ? "all" : "none") as "all" | "none";
const refreshBranch = relations.map((r) => r.id);
const refreshState = branchState(rels, refreshBranch);
const summary = [
perms.size > 0 && `${[...perms].map(shortName).join(", ")} on ${orbit ? orbits.find((o) => o.id === orbit)?.name ?? "that orbit" : "all orbits"}`,
rels.size > 0 && `refresh through ${relations.filter((r) => rels.has(r.id)).map((r) => `${r.source_name} → ${r.target_name}`).join(", ")}`,
].filter(Boolean).join(" · ");
return (
<section ref={sectionRef} aria-labelledby="grant-heading">
<h3 id="grant-heading" className="text-lg font-semibold text-star-100">{editing ? `Edit access: ${editing.principal_type === "group" ? editing.principal : userName(editing.principal)}` : "Give access"}</h3>
<p className="mt-1 max-w-3xl text-sm text-star-300">
Administrators come from the SSO configuration. Everyone else sees only what you grant here. Choose who, then tick exactly what they may do.
Everything on a branch needs the orbit to be visible, so the tree ticks that for you.
</p>
<form className="mt-4 space-y-5" onSubmit={(e) => { e.preventDefault(); if (ready) submit.mutate(); }}>
<div className="grid gap-6 lg:grid-cols-[1.5fr_1fr_1fr]">
<div>
<p className={label}>1 · Who</p>
{editing ? <p className="mt-2 text-star-100">{editing.principal_type === "group" ? `Group ${editing.principal}` : userName(editing.principal)} <button type="button" className="ml-2 text-sm text-[#f1bc90] underline" onClick={onCancelEdit}>Cancel editing</button></p> : (
<>
<div className="mt-2 flex rounded-lg border border-[#2f343b] bg-space-950 p-1" role="group" aria-label="Grant to">
{(["user", "group"] as const).map((k) => (
<button key={k} type="button" aria-pressed={kind === k} onClick={() => { setKind(k); setPrincipal(""); }}
className={`h-9 flex-1 rounded-md text-sm font-medium ${kind === k ? "bg-[#2a2119] text-[#f1bc90]" : "text-star-200"}`}>
{k === "user" ? "A person" : "An identity-provider group"}
</button>
))}
</div>
{kind === "user" ? (
<label className="mt-3 block text-sm text-star-300">
Person
<Select value={principal} onChange={(e) => setPrincipal(e.target.value)} required aria-label="Person">
<option value="" disabled>Choose…</option>
{candidates.map((u) => <option key={u.id} value={u.id}>{u.display_name}</option>)}
</Select>
<span className="mt-1 block text-xs text-star-400">Only active people who have signed in. Administrators already have everything.</span>
</label>
) : (
<div className="mt-3">
<label className="block text-sm text-star-300">
Group name
<input value={principal} onChange={(e) => setPrincipal(e.target.value)} required maxLength={128} className={field} autoComplete="off" />
</label>
{groupsSeen.length > 0 && (
<>
<p className="mt-2 text-xs text-star-400">Seen at recent sign-ins. Names must match the token's groups claim exactly.</p>
<div className="mt-2 flex flex-wrap gap-2">
{groupsSeen.slice(0, 8).map((g) => (
<button key={g.name} type="button" onClick={() => setPrincipal(g.name)}
className="rounded-full border border-[#3a4149] px-3 py-1 font-mono text-xs text-star-100 hover:border-[#5a6068]">
{g.name} <span className="text-star-400">· {g.people}</span>
</button>
))}
</div>
</>
)}
</div>
)}
</>
)}
</div>
<div>
<p className={label}>2 · Where</p>
<div className="mt-2">
<Select value={orbit} onChange={(e) => setOrbit(e.target.value)} aria-label="Orbit" disabled={!!editing}>
<option value="">All orbits</option>
{orbits.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
</Select>
</div>
{rels.size > 0 && <p className="mt-2 text-xs text-orbit-amber">Refresh is granted per relation, not per orbit. This choice applies to the other ticked rows only.</p>}
</div>
<div>
<p className={label}>3 · Until</p>
<div className="mt-2 flex flex-wrap gap-2">
<Chip active={expires === ""} onClick={() => setExpires("")}>No end</Chip>
<Chip active={expires === inDays(30)} onClick={() => setExpires(inDays(30))}>30 days</Chip>
<Chip active={expires === inDays(90)} onClick={() => setExpires(inDays(90))}>90 days</Chip>
</div>
<div className="mt-2"><DatePicker aria-label="Ends on" placeholder="Or pick a date…" min={inDays(1)} value={expires} onChange={(v) => setExpires(v)} /></div>
<p className="mt-2 text-xs text-star-400">Grants can run for at most two years.</p>
</div>
</div>
<div className="rounded-2xl border border-space-700 bg-[#0d1013]">
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#22272d] px-5 py-3">
<p className={label}>4 · What they may do</p>
<div className="flex flex-wrap items-center gap-2">
<span className="text-[13px] text-star-400">Start from</span>
{roles.map((r) => <Chip key={r.name} active={presetActive(r.name)} onClick={() => preset(r.name)}>{r.name.charAt(0).toUpperCase() + r.name.slice(1)}</Chip>)}
<Chip onClick={() => { setPerms(new Set()); setRels(new Set()); }}>Clear</Chip>
</div>
</div>
<div className="columns-1 gap-4 px-5 pb-1 pt-4 md:columns-2">
{TREE.map((group) => {
const ids = group.items.map((i) => i.id);
const state = branchState(perms, ids);
return (
<div key={group.id} className="mb-4 break-inside-avoid overflow-hidden rounded-xl border border-[#22272d] bg-[#0f1216]">
<div className="flex items-start gap-3 bg-[#141920] px-4 py-3">
<Box state={state} name={group.label} onChange={() => setPerms(setMany(perms, ids, state !== "all"))} />
<div><p className="font-semibold text-star-100">{group.label}</p><p className="text-[13px] text-star-400">{group.note}</p></div>
</div>
{group.items.map((item) => {
const lockedBy = neededBy(perms, item.id);
const on = perms.has(item.id);
return (
<div key={item.id} className="flex items-start gap-3 border-t border-[#1b1f24] py-2.5 pl-[50px] pr-4">
<Box small state={on ? "all" : "none"} name={item.label} disabled={on && lockedBy.length > 0} onChange={() => setPerms(setPermission(perms, item.id, !on))} />
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-baseline justify-between gap-x-3">
<span className="text-star-100">{item.label}</span>
<code className="font-mono text-[11.5px] text-[#8a9097]">{item.id}</code>
</div>
{on && lockedBy.length > 0 ? <p className="text-[12.5px] text-star-400">Needed by {lockedBy.map(shortName).join(", ")}.</p>
: item.hint ? <p className="text-[12.5px] text-star-400">{item.hint}</p> : null}
</div>
</div>
);
})}
</div>
);
})}
<div className="mb-4 break-inside-avoid overflow-hidden rounded-xl border border-[#22272d] bg-[#0f1216]">
<div className="flex items-start gap-3 bg-[#141920] px-4 py-3">
<Box state={refreshState} name="Refresh staging" disabled={refreshBranch.length === 0}
onChange={() => setRels(new Set(refreshState === "all" ? [] : refreshBranch))} />
<div><p className="font-semibold text-star-100">Refresh staging</p><p className="text-[13px] text-star-400">Per relation, not per orbit. Does not need the orbit to be visible.</p></div>
</div>
{relations.length === 0 && <p className="border-t border-[#1b1f24] px-4 py-3 text-[13px] text-star-400">No active relations yet. Create one in Relations first.</p>}
{relations.map((r) => (
<div key={r.id} className="flex items-start gap-3 border-t border-[#1b1f24] py-2.5 pl-[50px] pr-4">
<Box small state={relKey(r.id)} name={`Refresh ${r.source_name} to ${r.target_name}`}
onChange={() => setRels((cur) => { const next = new Set(cur); if (next.has(r.id)) next.delete(r.id); else next.add(r.id); return next; })} />
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-baseline justify-between gap-x-3">
<span className="text-star-100">{r.source_name} → {r.target_name}</span>
<code className="font-mono text-[11.5px] text-[#8a9097]">refresh.run</code>
</div>
<p className="text-[12.5px] text-star-400">Version {r.version}{r.usable ? " · ready" : " · not usable right now"}</p>
</div>
</div>
))}
</div>
</div>
<div className="mx-5 mb-4 rounded-xl border border-[#22272d]">
<button type="button" aria-expanded={adminOpen} onClick={() => setAdminOpen((o) => !o)} className="flex w-full items-center gap-3 px-4 py-2.5 text-left text-sm text-star-200">
<svg aria-hidden width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="#9298a0" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="6.5" width="8" height="5.5" rx="1.3" /><path d="M5 6.5V4.8a2 2 0 014 0v1.7" /></svg>
<span className="flex-1">Administrators only · {adminOnly.length} permissions that are never delegated</span>
<span className="text-[13px] text-star-400">{adminOpen ? "Hide" : "Show"}</span>
</button>
{adminOpen && (
<div className="flex flex-wrap gap-2 px-4 pb-3">
{adminOnly.map((p) => <span key={p} className="rounded-full border border-dashed border-[#3a4149] px-3 py-1 text-[13px] text-star-400">{ADMIN_LABELS[p] ?? p} <code className="font-mono text-[11.5px] text-[#7d838a]">{p}</code></span>)}
</div>
)}
</div>
<div className="flex flex-wrap items-center justify-between gap-4 rounded-b-2xl border-t border-[#22272d] bg-[#111418] px-5 py-4">
<div className="min-w-0">
<p className="text-sm text-star-100" aria-live="polite">
{count === 0 ? "Nothing ticked yet" : `${editing ? "Will set" : "Will create"} ${count} grant${count > 1 ? "s" : ""}${perms.size ? ` · ${roleOf(perms)}` : ""}`}
</p>
<p className="mt-0.5 text-[13px] text-star-400">{count === 0 ? "Tick a row, or start from a role." : `${summary} · ${expires ? `until ${day(new Date(`${expires}T23:59:59`).getTime() / 1000)}` : "no end date"}`}</p>
</div>
<div className="flex gap-2">
{editing && <Button type="button" onClick={onCancelEdit}>Cancel</Button>}
<Button type="submit" variant="primary" disabled={!ready || submit.isPending}>{submit.isPending ? "Saving…" : editing ? "Save changes" : "Grant access"}</Button>
</div>
</div>
</div>
</form>
{report && report.failures.length === 0 && (report.added > 0 || report.skipped > 0) && (
<p role="status" className="mt-3 text-sm text-orbit-green">
{report.added > 0 ? `${report.added} added` : "Nothing new added"}{report.skipped > 0 ? `, ${report.skipped} ${report.skipped === 1 ? "was" : "were"} already there` : ""}.
</p>
)}
{report && report.failures.length > 0 && (
<div role="alert" className="mt-3 space-y-1 text-sm text-orbit-red">
{report.added > 0 && <p>{report.added} added.</p>}
{report.failures.map((f) => <p key={f}>{f}</p>)}
</div>
)}
</section>
);
}

View File

@@ -256,7 +256,14 @@ function RelationAccess({ relationId, onChange }: { relationId: string; onChange
<ul className="mt-1 space-y-1 text-sm text-star-100">
{list.map((g) => (
<li key={g.id} className="flex items-center justify-between gap-3">
<span>{g.principal_type === "group" ? `Group ${g.principal}` : nameOf(g.principal)}</span>
<span>
{g.principal_type === "group" ? `Group ${g.principal}` : nameOf(g.principal)}
{g.expires_at && (
<span className={`ml-2 text-xs ${g.expires_at * 1000 <= Date.now() ? "text-orbit-red" : "text-star-400"}`}>
{g.expires_at * 1000 <= Date.now() ? "expired " : "until "}{new Date(g.expires_at * 1000).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" })}
</span>
)}
</span>
<Button disabled={remove.isPending} onClick={() => remove.mutate(g.id)} aria-label={`Remove access for ${g.principal_type === "group" ? g.principal : nameOf(g.principal)}`}>Remove</Button>
</li>
))}

213
web/src/lib/access.ts Normal file
View File

@@ -0,0 +1,213 @@
// Pure rules behind the Access console: what the permission tree ticks together, how stored grants are
// grouped into rows, what a row or a person is called, and when a grant does nothing. No React, no fetching.
import type { AccessUser, Grant, RelationGrantRow } from "../api";
type Role = { name: string; permissions: string[] };
/** The permissions that can be granted, in the order the tree lists them. */
export const ORBIT_PERMISSIONS = ["orbit.read", "snapshot.read", "snapshot.download", "capture.run"] as const;
/** What a ticked permission needs ticked with it: without `orbit.read` the orbit answers 404. */
export const REQUIRES: Record<string, string[]> = {
"snapshot.read": ["orbit.read"],
"snapshot.download": ["orbit.read", "snapshot.read"],
"capture.run": ["orbit.read"],
};
export type TreeGroup = { id: string; label: string; note: string; items: { id: string; label: string; hint?: string }[] };
/** The grantable permissions as a tree. Refresh is not here: it is granted per relation, not per orbit. */
export const TREE: TreeGroup[] = [
{ id: "orbit", label: "Orbit", note: "Which orbits appear for this person", items: [{ id: "orbit.read", label: "See the orbit" }] },
{
id: "snapshots", label: "Snapshots", note: "Backups taken from the orbit",
items: [
{ id: "snapshot.read", label: "List and open snapshots" },
{ id: "snapshot.download", label: "Download a snapshot", hint: "Also ticks list and the orbit." },
],
},
{ id: "capture", label: "Capture", note: "Starting a backup", items: [{ id: "capture.run", label: "Run a capture now" }] },
];
/** Plain names for the permissions only administrators hold; an unknown one shows its code. */
export const ADMIN_LABELS: Record<string, string> = {
"orbit.manage": "Create and edit orbits",
"outpost.manage": "Manage Outposts",
"retention.manage": "Change retention",
"snapshot.delete": "Delete snapshots",
"recovery.manage": "Restore and recovery",
"relation.manage": "Environments and relations",
"access.manage": "Access",
};
/** Tick or untick one permission together with everything that depends on it. */
export function setPermission(current: ReadonlySet<string>, id: string, on: boolean): Set<string> {
const next = new Set(current);
if (on) {
next.add(id);
for (const needed of REQUIRES[id] ?? []) next.add(needed);
} else {
next.delete(id);
for (const [other, needs] of Object.entries(REQUIRES)) if (needs.includes(id)) next.delete(other);
}
return next;
}
/** Ticked permissions that need `id`, so it cannot be unticked underneath them. */
export function neededBy(current: ReadonlySet<string>, id: string): string[] {
return [...current].filter((other) => (REQUIRES[other] ?? []).includes(id));
}
/** Tick or untick a whole branch. */
export function setMany(current: ReadonlySet<string>, ids: string[], on: boolean): Set<string> {
return ids.reduce((set, id) => setPermission(set, id, on), new Set(current));
}
/** How many of `ids` are ticked: `all`, `some` or `none`. */
export function branchState(current: ReadonlySet<string>, ids: string[]): "all" | "some" | "none" {
const on = ids.filter((id) => current.has(id)).length;
return on === 0 ? "none" : on === ids.length ? "all" : "some";
}
const sameSet = (a: ReadonlySet<string>, b: ReadonlySet<string>) => a.size === b.size && [...a].every((x) => b.has(x));
/**
* A name for a set of permissions, from the roles the hub knows: the role it equals, a role plus the extras it has on top
* ("Capturer + Download"), or "Custom". The hub stores no role, only permissions, so this is only ever a label.
*/
export function roleLabel(permissions: Iterable<string>, roles: Role[]): string {
const have = new Set(permissions);
if (have.size === 0) return "Custom";
const named = (role: Role) => role.name.charAt(0).toUpperCase() + role.name.slice(1);
const exact = roles.find((role) => sameSet(new Set(role.permissions), have));
if (exact) return named(exact);
const within = roles
.filter((role) => role.permissions.every((p) => have.has(p)))
.sort((a, b) => b.permissions.length - a.permissions.length)[0];
if (within) {
const extra = [...have].filter((p) => !within.permissions.includes(p));
if (extra.length > 0 && extra.length <= 2) return `${named(within)} + ${extra.map(shortName).join(", ")}`;
}
return "Custom";
}
/** What a permission is called in running text. */
export function shortName(permission: string): string {
return {
"orbit.read": "see orbit",
"snapshot.read": "list snapshots",
"snapshot.download": "download",
"capture.run": "run capture",
}[permission] ?? permission;
}
const order = (permission: string) => {
const at = ORBIT_PERMISSIONS.indexOf(permission as (typeof ORBIT_PERMISSIONS)[number]);
return at < 0 ? ORBIT_PERMISSIONS.length : at;
};
export type AccessRow = {
key: string;
principal_type: "user" | "group";
principal: string;
scope_id: string | null;
expires_at: number | null;
permissions: string[];
ids: string[];
};
/** One row per person or group, orbit and end date; the permissions inside it are the grants it stands for. */
export function groupGrants(grants: Grant[]): AccessRow[] {
const rows = new Map<string, AccessRow>();
for (const grant of grants) {
const key = [grant.principal_type, grant.principal, grant.scope_id ?? "", grant.expires_at ?? ""].join("|");
const row = rows.get(key) ?? {
key, principal_type: grant.principal_type, principal: grant.principal, scope_id: grant.scope_id,
expires_at: grant.expires_at, permissions: [], ids: [],
};
row.permissions.push(grant.permission);
row.ids.push(grant.id);
rows.set(key, row);
}
for (const row of rows.values()) row.permissions.sort((a, b) => order(a) - order(b));
return [...rows.values()];
}
export type Expiry = "none" | "soon" | "expired";
const SOON_DAYS = 14;
/** `expires_at` is seconds since the epoch; `now` is too. */
export function expiryState(expiresAt: number | null, now: number): Expiry {
if (expiresAt === null) return "none";
if (expiresAt <= now) return "expired";
return expiresAt - now <= SOON_DAYS * 86_400 ? "soon" : "none";
}
export const live = (grant: { expires_at: number | null }, now: number) => grant.expires_at === null || grant.expires_at > now;
/**
* A grant that cannot be used because the person never gets to see the orbit. The row's own permissions are not the whole
* story: a global grant, another grant on the same orbit, or one of the person's groups may already give `orbit.read`.
*/
export function hasNoEffect(row: AccessRow, grants: Grant[], groupsOf: string[], now: number): boolean {
if (row.permissions.length === 0 || row.permissions.every((p) => p === "orbit.read")) return false;
if (!live(row, now)) return false;
const principals = new Set(row.principal_type === "user" ? [`user|${row.principal}`, ...groupsOf.map((g) => `group|${g}`)] : [`group|${row.principal}`]);
return !grants.some(
(g) => g.permission === "orbit.read" && live(g, now) && principals.has(`${g.principal_type}|${g.principal}`) &&
(g.scope_type === "global" || g.scope_id === row.scope_id),
);
}
export type PersonAccess = {
kind: "admin" | "waiting" | "granted";
/** Role-style name of everything they hold through grants (people and their groups together). */
label: string;
via: string[];
refresh: string[];
noEffect: boolean;
};
/** What a person can do right now, from every live grant of theirs and of the groups they came in with. */
export function personAccess(user: AccessUser, grants: Grant[], relationGrants: RelationGrantRow[], roles: Role[], now: number): PersonAccess {
const groups = user.groups ?? [];
if (user.admin) return { kind: "admin", label: "Administrator", via: [], refresh: [], noEffect: false };
const mine = grants.filter(
(g) => live(g, now) && ((g.principal_type === "user" && g.principal === user.id) || (g.principal_type === "group" && groups.includes(g.principal))),
);
const via = [...new Set(mine.filter((g) => g.principal_type === "group").map((g) => g.principal))];
const refresh = relationGrants
.filter((g) => g.active && live(g, now) && ((g.principal_type === "user" && g.principal === user.id) || (g.principal_type === "group" && groups.includes(g.principal))))
.map((g) => `${g.source_name} → ${g.target_name}`);
const permissions = new Set(mine.map((g) => g.permission));
if (permissions.size === 0 && refresh.length === 0) return { kind: "waiting", label: "Waiting", via: [], refresh: [], noEffect: false };
const noEffect = permissions.size > 0 && !permissions.has("orbit.read");
return { kind: "granted", label: permissions.size ? roleLabel(permissions, roles) : "", via, refresh: [...new Set(refresh)], noEffect };
}
/** Groups seen at recent sign-ins, most members first, so a name does not have to be typed from memory. */
export function seenGroups(users: AccessUser[]): { name: string; people: number }[] {
const counts = new Map<string, number>();
for (const user of users) for (const group of new Set(user.groups ?? [])) counts.set(group, (counts.get(group) ?? 0) + 1);
return [...counts].map(([name, people]) => ({ name, people })).sort((a, b) => b.people - a.people || a.name.localeCompare(b.name));
}
const REASONS: Record<string, string> = {
already_granted: "Already granted: this person or group already has everything you ticked here.",
unknown_user: "That person no longer exists. Reload the list and choose again.",
unknown_orbit: "That orbit no longer exists. Reload the list and choose again.",
emergency_operator: "The emergency operator is an administrator and never needs a grant.",
bad_end_date: "The end date must be in the future and within two years.",
bad_group: "Enter a group name of up to 128 characters, without control characters.",
bad_person: "Choose a person from the list.",
nothing_selected: "Tick at least one permission first.",
unknown_permission: "That permission cannot be granted.",
grant_mismatch: "Those grants belong to someone else or somewhere else. Reload and try again.",
cannot_disable_self: "You cannot disable yourself.",
cannot_disable_emergency: "The emergency operator cannot be disabled.",
};
/** A sentence for a refusal code the hub sent; `fallback` when it sent none or a code this screen does not know. */
export function reasonText(code: string | undefined, fallback: string): string {
return (code && REASONS[code]) || fallback;
}