@terpjs/react-core 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,210 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import { buildModuleRows } from "./accessModel";
4
+ import type { AccessModel } from "./accessModel";
5
+
6
+ /** A model shaped like the server's, with the rungs deliberately out of rank order. */
7
+ function model(overrides: Partial<AccessModel> = {}): AccessModel {
8
+ return {
9
+ roles: [
10
+ { name: "admin", rank: 30 },
11
+ { name: "viewer", rank: 10 },
12
+ { name: "editor", rank: 20 },
13
+ ],
14
+ permissions: [{ name: "notes.delete", min_role: "editor", label: "Delete a note" }],
15
+ modules: [],
16
+ ...overrides,
17
+ } as AccessModel;
18
+ }
19
+
20
+ function endpoint(
21
+ methods: string[],
22
+ label: string | null,
23
+ allowed: Record<string, boolean>,
24
+ extra: string[] = [],
25
+ ) {
26
+ return {
27
+ path: `/api/v1/notes/${label ?? "x"}`,
28
+ methods,
29
+ requirement: "role:viewer",
30
+ extra_permissions: extra,
31
+ name: "handler",
32
+ operation: label === null ? null : { id: "notes.op", label },
33
+ by_role: Object.entries(allowed).map(([role, ok]) => ({
34
+ role,
35
+ allowed: ok,
36
+ reason: ok ? "allowed" : "rank",
37
+ })),
38
+ };
39
+ }
40
+
41
+ describe("buildModuleRows", () => {
42
+ it("orders the rungs by rank even when the payload does not", () => {
43
+ // Both the endpoint and the hook sort, so a pre-sorted fixture observes neither. The
44
+ // fixture above is scrambled on purpose — a ladder rendered out of order destroys the whole
45
+ // legibility of a strip, whose point is authority reading left to right.
46
+ const [row] = buildModuleRows(
47
+ model({
48
+ modules: [
49
+ {
50
+ name: "notes",
51
+ prefix: "/api/v1/notes",
52
+ policy: null,
53
+ permissions: [],
54
+ access: { assignable: true, label: "Notes", platform_reason: null },
55
+ endpoints: [],
56
+ },
57
+ ],
58
+ } as Partial<AccessModel>),
59
+ );
60
+ expect(row.rungs.map((rung) => rung.role)).toEqual(["viewer", "editor", "admin"]);
61
+ });
62
+
63
+ it("reports what each rung ADDS, split by kind", () => {
64
+ // "Everything below, plus…" is the only framing in which two rungs can be compared at a
65
+ // glance, and the split matters because "may delete three things" is a different decision
66
+ // from "may read thirty" — a mixed list buries the destructive half in the harmless one.
67
+ const [row] = buildModuleRows(
68
+ model({
69
+ modules: [
70
+ {
71
+ name: "notes",
72
+ prefix: "/api/v1/notes",
73
+ policy: null,
74
+ permissions: ["notes.delete"],
75
+ access: { assignable: true, label: "Notes", platform_reason: null },
76
+ endpoints: [
77
+ endpoint(["GET"], "View a note", { viewer: true, editor: true, admin: true }),
78
+ endpoint(["POST"], "Write a note", { viewer: false, editor: true, admin: true }),
79
+ endpoint(["DELETE"], "Delete a note", { viewer: false, editor: false, admin: true }),
80
+ ],
81
+ },
82
+ ],
83
+ } as Partial<AccessModel>),
84
+ );
85
+ const [viewer, editor, admin] = row.rungs;
86
+
87
+ expect(viewer.added.read.map((o) => o.label)).toEqual(["View a note"]);
88
+ expect(viewer.added.write).toEqual([]);
89
+
90
+ // The editor rung adds only the write — the read it inherits is not repeated.
91
+ expect(editor.added.write.map((o) => o.label)).toEqual(["Write a note"]);
92
+ expect(editor.added.read).toEqual([]);
93
+
94
+ expect(admin.added.delete.map((o) => o.label)).toEqual(["Delete a note"]);
95
+ expect(admin.added.write).toEqual([]);
96
+ // And the cumulative set is still available, because the ladder is inclusive.
97
+ expect(admin.reachable).toHaveLength(3);
98
+ });
99
+
100
+ it("says plainly when a rung adds nothing", () => {
101
+ // A module whose policy only separates read from write has an `admin` rung that buys
102
+ // nothing, and an administrator assigning it expecting more has made a mistake the pane
103
+ // could have prevented. ADR 0121's second open question, answered by telling the truth
104
+ // rather than hiding the rung.
105
+ const [row] = buildModuleRows(
106
+ model({
107
+ modules: [
108
+ {
109
+ name: "notes",
110
+ prefix: "/api/v1/notes",
111
+ policy: null,
112
+ permissions: [],
113
+ access: { assignable: true, label: "Notes", platform_reason: null },
114
+ endpoints: [
115
+ endpoint(["GET"], "View a note", { viewer: true, editor: true, admin: true }),
116
+ endpoint(["POST"], "Write a note", { viewer: false, editor: true, admin: true }),
117
+ ],
118
+ },
119
+ ],
120
+ } as Partial<AccessModel>),
121
+ );
122
+ expect(row.rungs.map((rung) => rung.addsNothing)).toEqual([false, false, true]);
123
+ });
124
+
125
+ it("keeps a module that refuses assignment, with its reason", () => {
126
+ // Filtering it out leaves a question an administrator cannot stop asking. Present, with
127
+ // "administering grants hands out every other authority", answers it — which is why the
128
+ // declaration requires a reason at all.
129
+ const rows = buildModuleRows(
130
+ model({
131
+ modules: [
132
+ {
133
+ name: "access",
134
+ prefix: "/api/v1/access",
135
+ policy: null,
136
+ permissions: [],
137
+ access: {
138
+ assignable: false,
139
+ label: null,
140
+ platform_reason: "administering grants hands out every other authority",
141
+ },
142
+ endpoints: [],
143
+ },
144
+ { name: "silent", prefix: null, policy: null, permissions: [], access: null, endpoints: [] },
145
+ ],
146
+ } as Partial<AccessModel>),
147
+ );
148
+ expect(rows.map((r) => [r.name, r.assignable, r.platformReason !== null])).toEqual([
149
+ ["access", false, true],
150
+ ["silent", false, false],
151
+ ]);
152
+ // A module with no declaration falls back to its own identifier rather than rendering blank.
153
+ expect(rows[1].label).toBe("silent");
154
+ });
155
+
156
+ it("counts routes that declared no operation instead of guessing a label", () => {
157
+ // The pane has to be able to say the module is not fully explained. Presenting a partial
158
+ // list as complete is the failure `OperationCoverage.STRICT` exists to end.
159
+ const [row] = buildModuleRows(
160
+ model({
161
+ modules: [
162
+ {
163
+ name: "notes",
164
+ prefix: "/api/v1/notes",
165
+ policy: null,
166
+ permissions: [],
167
+ access: { assignable: true, label: "Notes", platform_reason: null },
168
+ endpoints: [
169
+ endpoint(["GET"], null, { viewer: true, editor: true, admin: true }),
170
+ endpoint(["POST"], "Write a note", { viewer: false, editor: true, admin: true }),
171
+ ],
172
+ },
173
+ ],
174
+ } as Partial<AccessModel>),
175
+ );
176
+ expect(row.unexplainedRoutes).toBe(1);
177
+ expect(row.rungs[0].added.read[0]).toMatchObject({ label: "handler", unexplained: true });
178
+ });
179
+
180
+ it("never re-derives an allowance from rank", () => {
181
+ // The load-bearing property of this file. `by_role` is the kernel guard's own answer, so a
182
+ // rung the server says is refused stays refused here even when its rank would suggest
183
+ // otherwise — a client that compared ranks would be a second implementation of the
184
+ // decision, and the copy that drifts is the one an administrator is shown.
185
+ const [row] = buildModuleRows(
186
+ model({
187
+ modules: [
188
+ {
189
+ name: "notes",
190
+ prefix: "/api/v1/notes",
191
+ policy: null,
192
+ permissions: ["notes.delete"],
193
+ access: { assignable: true, label: "Notes", platform_reason: null },
194
+ endpoints: [
195
+ // An admin is refused (the route needs a grant the server cannot assume), while a
196
+ // viewer is allowed. Nonsense by rank, and exactly what the server reports for a
197
+ // route-level `require_permission`.
198
+ endpoint(["DELETE"], "Delete a note", {
199
+ viewer: true,
200
+ editor: false,
201
+ admin: false,
202
+ }),
203
+ ],
204
+ },
205
+ ],
206
+ } as Partial<AccessModel>),
207
+ );
208
+ expect(row.rungs.map((rung) => rung.reachable.length)).toEqual([1, 0, 0]);
209
+ });
210
+ });
@@ -0,0 +1,165 @@
1
+ import type { components } from "@terpjs/contract";
2
+
3
+ export type AccessModel = components["schemas"]["AccessModelRead"];
4
+ type AccessModule = components["schemas"]["AccessModuleRead"];
5
+ type AccessEndpoint = components["schemas"]["AccessEndpointRead"];
6
+
7
+ /**
8
+ * Pure derivation of the access pane's rows from one `/model` payload — no React, no fetching,
9
+ * so the part that decides what a reader is told stays independently readable and testable.
10
+ *
11
+ * Everything here is a *rearrangement* of what the server already said. No allowance is
12
+ * recomputed: `by_role` carries the outcome the kernel guard itself produced for each rung
13
+ * (ADR 0121 §4), so this file groups and diffs those answers and never forms an opinion about
14
+ * them. That is the whole reason the server projects per-rung outcomes rather than raw policy —
15
+ * a client that re-derived allowance from rank comparisons would be a second implementation of
16
+ * the decision, and the copy that drifts is the one an administrator is shown.
17
+ */
18
+
19
+ /** What kind of thing an operation does, which is what makes a delta worth reading. */
20
+ export type OperationKind = "read" | "write" | "delete";
21
+
22
+ /** One operation a rung can reach, named in the source language where the route declared one. */
23
+ export interface ReachableOperation {
24
+ kind: OperationKind;
25
+ /** The declared operation label, or the route's own name when it declared none. */
26
+ label: string;
27
+ /** True when no operation was declared, so the pane can say "unexplained" rather than guess. */
28
+ unexplained: boolean;
29
+ }
30
+
31
+ /** One rung of a module's ladder, with what it adds over the rung below. */
32
+ export interface ModuleRung {
33
+ role: string;
34
+ rank: number;
35
+ /** Everything reachable at this rung, cumulative — the ladder is inclusive. */
36
+ reachable: ReachableOperation[];
37
+ /**
38
+ * What moving *to* this rung hands over that the rung below did not.
39
+ *
40
+ * The tile shows this rather than the cumulative set, because "everything below, plus…" is
41
+ * the only framing in which two rungs can be compared at a glance. Split by kind for the
42
+ * reason the reference application split it: "may delete three things" is a different
43
+ * decision from "may read thirty", and a mixed list buries the destructive half in the
44
+ * middle of the harmless one.
45
+ */
46
+ added: Record<OperationKind, ReachableOperation[]>;
47
+ /**
48
+ * True when this rung adds nothing at all over the one below.
49
+ *
50
+ * Common and worth saying out loud: a module whose `Policy` only distinguishes read from
51
+ * write has an `admin` rung that buys nothing, and an administrator who assigns it expecting
52
+ * more has made a mistake the pane could have prevented. This is ADR 0121's second open
53
+ * question, answered in the direction of telling the truth rather than hiding the rung.
54
+ */
55
+ addsNothing: boolean;
56
+ }
57
+
58
+ /** One module's row in the pane. */
59
+ export interface ModuleRow {
60
+ name: string;
61
+ /** What to call it: the declared label, falling back to the module's own identifier. */
62
+ label: string;
63
+ /** Whether a rung here can be assigned at all. */
64
+ assignable: boolean;
65
+ /** Why not, when a module refuses outright — the justification it declared. */
66
+ platformReason: string | null;
67
+ rungs: ModuleRung[];
68
+ /** The permissions this module claims, by name. */
69
+ permissions: string[];
70
+ /**
71
+ * Routes that declared no operation, so the pane can say the module is not fully explained
72
+ * rather than presenting a partial list as complete. Empty is the good state.
73
+ */
74
+ unexplainedRoutes: number;
75
+ }
76
+
77
+ function kindOf(endpoint: AccessEndpoint): OperationKind {
78
+ // Derived from the methods the server reported, not from a second opinion about the verb.
79
+ // A WebSocket reports no method and is guarded at the write tier, which is what the guard
80
+ // does with a connection that has no method after the upgrade.
81
+ const methods = endpoint.methods ?? [];
82
+ if (methods.includes("DELETE")) return "delete";
83
+ if (methods.length === 0) return "write";
84
+ if (methods.some((method) => method !== "GET" && method !== "HEAD" && method !== "OPTIONS")) {
85
+ return "write";
86
+ }
87
+ return "read";
88
+ }
89
+
90
+ function describe(endpoint: AccessEndpoint): ReachableOperation {
91
+ const declared = endpoint.operation?.label;
92
+ return {
93
+ kind: kindOf(endpoint),
94
+ label: declared ?? endpoint.name,
95
+ unexplained: declared === undefined || declared === null,
96
+ };
97
+ }
98
+
99
+ /** Whether a rung may reach an endpoint, as the *server* answered it. */
100
+ function allowedAt(endpoint: AccessEndpoint, role: string): boolean {
101
+ return endpoint.by_role?.some((row) => row.role === role && row.allowed) ?? false;
102
+ }
103
+
104
+ const EMPTY_ADDED: () => Record<OperationKind, ReachableOperation[]> = () => ({
105
+ read: [],
106
+ write: [],
107
+ delete: [],
108
+ });
109
+
110
+ function buildRungs(module: AccessModule, ladder: AccessModel["roles"]): ModuleRung[] {
111
+ const endpoints = module.endpoints ?? [];
112
+ let below: ReadonlySet<string> = new Set();
113
+ return ladder.map((role) => {
114
+ const reachable = endpoints
115
+ .filter((endpoint) => allowedAt(endpoint, role.name))
116
+ .map(describe);
117
+ const keys = new Set(reachable.map((operation) => `${operation.kind}:${operation.label}`));
118
+ const added = EMPTY_ADDED();
119
+ for (const operation of reachable) {
120
+ if (!below.has(`${operation.kind}:${operation.label}`)) added[operation.kind].push(operation);
121
+ }
122
+ below = keys;
123
+ return {
124
+ role: role.name,
125
+ rank: role.rank,
126
+ reachable,
127
+ added,
128
+ addsNothing:
129
+ added.read.length === 0 && added.write.length === 0 && added.delete.length === 0,
130
+ };
131
+ });
132
+ }
133
+
134
+ /**
135
+ * The pane's rows, in ladder order, for every module the model describes.
136
+ *
137
+ * Modules that refuse assignment are **kept**, not filtered. A module missing from the pane is
138
+ * a question an administrator cannot stop asking; one that is present and says "never
139
+ * assignable, because administering grants hands out every other authority" answers it. The
140
+ * reason is the useful part, which is why the declaration requires one.
141
+ */
142
+ export function buildModuleRows(model: AccessModel): ModuleRow[] {
143
+ const ladder = [...model.roles].sort((a, b) => a.rank - b.rank);
144
+ return model.modules.map((module) => ({
145
+ name: module.name,
146
+ label: module.access?.label ?? module.name,
147
+ assignable: module.access?.assignable ?? false,
148
+ platformReason: module.access?.platform_reason ?? null,
149
+ rungs: buildRungs(module, ladder),
150
+ permissions: module.permissions ?? [],
151
+ unexplainedRoutes: (module.endpoints ?? []).filter(
152
+ (endpoint) => endpoint.operation === null || endpoint.operation === undefined,
153
+ ).length,
154
+ }));
155
+ }
156
+
157
+ /**
158
+ * The value of the "no access" tile, which is a real tile rather than an option buried in a
159
+ * menu — so revoking is exactly as reachable as granting, and the strip biases downward
160
+ * instead of upward.
161
+ *
162
+ * The empty string, deliberately: no declared rung can carry it, so it cannot collide with a
163
+ * role name, and `value === NO_ACCESS` is the same test as "no rung selected".
164
+ */
165
+ export const NO_ACCESS = "";
@@ -0,0 +1,65 @@
1
+ import { NO_ACCESS } from "./accessModel";
2
+ import type { ModuleRow, ModuleRung, OperationKind } from "./accessModel";
3
+ import type { Tile } from "../ui/TileGroup";
4
+ import type { TerpStrings } from "../uiText";
5
+
6
+ /**
7
+ * One module's ladder as tiles — shared by the screen that *explains* the model and the panel
8
+ * that *assigns* from it.
9
+ *
10
+ * Shared deliberately rather than written twice. The two surfaces answer the same question in
11
+ * different moods — "what does editor get here?" and "should this person be editor here?" — and
12
+ * a reader who compared them would be entitled to expect the same answer. Two copies of this
13
+ * mapping is exactly how they would stop matching.
14
+ */
15
+
16
+ /** What each rung of a module hands over, as the tile body. */
17
+ export function RungBody({ rung, strings }: { rung: ModuleRung; strings: TerpStrings }) {
18
+ if (rung.addsNothing) {
19
+ // Said out loud rather than shown as an empty tile. A module whose policy only separates
20
+ // read from write has an `admin` rung that buys nothing, and an administrator assigning it
21
+ // expecting more has made a mistake this line prevents.
22
+ return <span data-terp="tile-note">{strings.accessAddsNothing}</span>;
23
+ }
24
+ const kinds: [OperationKind, string][] = [
25
+ ["read", strings.accessKindRead],
26
+ ["write", strings.accessKindWrite],
27
+ ["delete", strings.accessKindDelete],
28
+ ];
29
+ return (
30
+ <>
31
+ {kinds.map(([kind, label]) =>
32
+ rung.added[kind].length === 0 ? null : (
33
+ <span key={kind} data-terp="tile-delta">
34
+ {/* Split by kind, because "may delete three things" is a different decision from
35
+ "may read thirty" and a mixed list buries the destructive half in the middle of
36
+ the harmless one. The destructive kind is last and carries its own tone. */}
37
+ <strong>{label}:</strong> {rung.added[kind].map((o) => o.label).join(", ")}
38
+ </span>
39
+ ),
40
+ )}
41
+ </>
42
+ );
43
+ }
44
+
45
+ /** The module's rungs as tiles, with a real "no access" tile first. */
46
+ export function tilesFor(row: ModuleRow, strings: TerpStrings): Tile[] {
47
+ return [
48
+ // A real tile, so revoking is exactly as reachable as granting.
49
+ { value: NO_ACCESS, label: strings.accessNoRung },
50
+ ...row.rungs.map((rung, index) => ({
51
+ value: rung.role,
52
+ label: rung.role,
53
+ body: <RungBody rung={rung} strings={strings} />,
54
+ // The most privileged rung carries the destructive framing. Deliberately inverted from a
55
+ // plan picker, which highlights its top tier to move you up: this screen exists to help
56
+ // someone choose the smallest tier that works.
57
+ tone: index === row.rungs.length - 1 ? ("danger" as const) : ("neutral" as const),
58
+ })),
59
+ ];
60
+ }
61
+
62
+ /** The rung that is the top of the ladder, whose assignment is the one worth confirming. */
63
+ export function topRung(row: ModuleRow): string | null {
64
+ return row.rungs.length === 0 ? null : row.rungs[row.rungs.length - 1].role;
65
+ }
@@ -104,7 +104,7 @@ describe("withAdminArea", () => {
104
104
  // Omitted flags default to true: an empty object is the full area.
105
105
  const full = withAdminArea(appManifests(), appViews(), {});
106
106
  const fullAdmin = full.manifests.find((manifest) => manifest.name === "terp-admin");
107
- expect(fullAdmin?.routes).toHaveLength(8);
107
+ expect(fullAdmin?.routes).toHaveLength(9);
108
108
  expect(full.views.TerpAdminHub).toBe(withAdminArea(appManifests(), appViews(), true).views.TerpAdminHub);
109
109
  });
110
110
 
@@ -115,7 +115,19 @@ describe("withAdminArea", () => {
115
115
  });
116
116
  const admin = manifests.find((manifest) => manifest.name === "terp-admin");
117
117
  expect(admin?.nav?.[0]?.label).toBe("Admin");
118
- expect(admin?.routes.map((route) => route.path)).toEqual(["/admin", "/admin/audit"]);
118
+ expect(admin?.routes.map((route) => route.path)).toEqual([
119
+ "/admin",
120
+ "/admin/audit",
121
+ "/admin/access",
122
+ ]);
123
+
124
+ // The access screen is section-gated too, and for a reason rather than for symmetry: it
125
+ // reads `GET /api/v1/access/model`, which exists only where the access capability is
126
+ // mounted, so an app without it would otherwise ship a nav entry leading to a 404.
127
+ const withoutAccess = withAdminArea(appManifests(), appViews(), { access: false });
128
+ const trimmed = withoutAccess.manifests.find((m) => m.name === "terp-admin");
129
+ expect(trimmed?.routes.map((route) => route.path)).not.toContain("/admin/access");
130
+ expect(withoutAccess.views.TerpAdminAccess).toBeUndefined();
119
131
  });
120
132
 
121
133
  it("refuses a view-id collision that claims no path (a silent drop would dead-link the hub)", () => {
@@ -156,6 +168,38 @@ function stubAdminFetch() {
156
168
  role_name: "admin",
157
169
  });
158
170
  }
171
+ if (path.endsWith("/api/v1/access/model")) {
172
+ // The admin screens read the role ladder from the access model rather than from three
173
+ // literals in `roles.ts`, so the mock has to answer it. Declaring a fourth rung here is
174
+ // deliberate: it is what proves the screens render the ladder the *app* declares, which
175
+ // a viewer/editor/admin fixture could never observe.
176
+ return jsonResponse({
177
+ // Deliberately NOT in rank order. The endpoint sorts, and the hook sorts again — so a
178
+ // pre-sorted fixture cannot observe either, and removing the hook's sort broke no test
179
+ // at all until this fixture was scrambled. A ladder rendered out of order is a real
180
+ // defect: the strip's whole legibility comes from authority reading left to right.
181
+ roles: [
182
+ { name: "admin", rank: 30 },
183
+ { name: "viewer", rank: 10 },
184
+ { name: "approver", rank: 25 },
185
+ { name: "editor", rank: 20 },
186
+ ],
187
+ permissions: [],
188
+ modules: [],
189
+ });
190
+ }
191
+ if (path.includes("/api/v1/access/subjects/")) {
192
+ // The assignment panel on every detail screen reads this. Answered with a real, empty
193
+ // payload rather than left to the page fallback: the panel treats a failed read as
194
+ // "the rungs are unknown" and refuses to render its strips, which is correct behaviour
195
+ // and would otherwise turn every detail-screen test into a test of that error path.
196
+ return jsonResponse({
197
+ subject_id: path.split("/").pop(),
198
+ via: [],
199
+ permissions: [],
200
+ module_roles: [],
201
+ });
202
+ }
159
203
  if (path.endsWith("/api/v1/users/u1")) {
160
204
  if (request.method === "PATCH") {
161
205
  return jsonResponse({
@@ -461,6 +505,51 @@ describe("the packaged admin area", () => {
461
505
  })).toBe(true);
462
506
  });
463
507
 
508
+ it("offers the ladder the app declares, not the three ranks the framework ships", async () => {
509
+ // `roles.ts` used to return ranks 10/20/30 as literals, so an app that declared a fourth
510
+ // rung got a three-rung admin UI while ADR 0022 promised the role model was the app's.
511
+ // The ladder now comes from `GET /api/v1/access/model`, and the fixture declares
512
+ // `approver` at 25 precisely so this can observe it: a viewer/editor/admin fixture would
513
+ // pass against the old literals too.
514
+ const { fetchMock } = renderAdminApp("/admin/users/new");
515
+ await screen.findByRole("heading", { level: 1, name: "Provision user" });
516
+
517
+ // Waited on the rung itself, not the heading: the heading resolves before the model
518
+ // fetch settles, and asserting then would have been asserting on an empty ladder.
519
+ await screen.findByRole("option", { name: "approver" });
520
+ const select = screen.getByLabelText("Role") as HTMLSelectElement;
521
+ const offered = [...select.options].map((option) => [option.value, option.textContent]);
522
+ expect(offered).toEqual([
523
+ ["10", "Viewer"],
524
+ ["20", "Editor"],
525
+ // No framework translation exists for a rung the app invented, so it renders under the
526
+ // name its author gave it — which beats the `rank 25` the old rank-only fallback showed.
527
+ ["25", "approver"],
528
+ ["30", "Administrator"],
529
+ ]);
530
+
531
+ // And the form starts on the least privileged *declared* rung. Asserted through the
532
+ // request body rather than `select.value`, which cannot observe it: with no option
533
+ // matching the state, HTML's own selectedness algorithm shows the first one anyway, so a
534
+ // value assertion passed even against a default of 99. The posted rank is the thing that
535
+ // decides what the account actually gets.
536
+ fireEvent.change(screen.getByLabelText("Email"), {
537
+ target: { value: "new.account@example.com" },
538
+ });
539
+ fireEvent.change(screen.getByLabelText("Password"), {
540
+ target: { value: "strong-password" },
541
+ });
542
+ fireEvent.click(screen.getByRole("button", { name: "Provision user" }));
543
+ await screen.findByRole("heading", { level: 1, name: "new.account@example.com" });
544
+
545
+ const posted = fetchMock.mock.calls.find(([input]) => {
546
+ const request = input as Request;
547
+ return request.method === "POST" && request.url.endsWith("/api/v1/users/");
548
+ });
549
+ const body = (await (posted![0] as Request).json()) as { role: number };
550
+ expect(body.role).toBe(10);
551
+ });
552
+
464
553
  it("puts a 422's reason under the field it names instead of floating it in a toast", async () => {
465
554
  // The failure path had no test at all, which is how the framework shipped `Field.error` with
466
555
  // no production consumer for two releases: the rendering half was gated, the producing half
@@ -705,7 +794,10 @@ describe("the packaged admin area", () => {
705
794
  renderAdminApp("/admin/groups/g1");
706
795
  const headings = await waitFor(() => {
707
796
  const found = document.querySelectorAll('[data-terp="admin-section-title"]');
708
- expect(found.length).toBe(2);
797
+ // Access per module, members, granted permissions. The count is here so the loop below
798
+ // cannot pass by finding nothing, and naming them is what keeps it from being a magic
799
+ // number the next section silently invalidates.
800
+ expect(found.length).toBe(3);
709
801
  return found;
710
802
  });
711
803
  for (const heading of headings) {
@@ -2,6 +2,7 @@ import { defineModuleManifest } from "@terpjs/contract";
2
2
 
3
3
  import type { TerpModule } from "../bootstrap";
4
4
 
5
+ import { AccessAdmin } from "./AccessAdmin";
5
6
  import { AdminHub } from "./AdminHub";
6
7
  import { AuditLogAdmin } from "./AuditLogAdmin";
7
8
  import { GroupDetail } from "./GroupDetail";
@@ -35,6 +36,7 @@ export const adminModule: TerpModule = {
35
36
  { path: "/admin/groups/new", view: "TerpAdminGroupCreate", role: "admin" },
36
37
  { path: "/admin/groups/$groupId", view: "TerpAdminGroupDetail", role: "admin" },
37
38
  { path: "/admin/audit", view: "TerpAdminAudit", role: "admin" },
39
+ { path: "/admin/access", view: "TerpAdminAccess", role: "admin" },
38
40
  ],
39
41
  nav: [{ label: "Admin", to: "/admin", icon: "shield", role: "admin" }],
40
42
  }),
@@ -47,5 +49,6 @@ export const adminModule: TerpModule = {
47
49
  TerpAdminGroupCreate: GroupCreate,
48
50
  TerpAdminGroupDetail: GroupDetail,
49
51
  TerpAdminAudit: AuditLogAdmin,
52
+ TerpAdminAccess: AccessAdmin,
50
53
  },
51
54
  };
@@ -1,19 +1,33 @@
1
- import type { TerpStrings } from "../uiText";
1
+ import type { AdminRoleOption } from "./useAccessLadder";
2
2
 
3
- export interface AdminRoleOption {
4
- rank: number;
5
- label: string;
6
- }
3
+ export type { AdminRoleOption } from "./useAccessLadder";
7
4
 
8
- /** The packaged role ladder, localized through the active framework catalog. */
9
- export function adminRoleOptions(strings: TerpStrings): AdminRoleOption[] {
10
- return [
11
- { rank: 10, label: strings.roleViewer },
12
- { rank: 20, label: strings.roleEditor },
13
- { rank: 30, label: strings.roleAdmin },
14
- ];
5
+ /**
6
+ * Resolve a rank to the label of the rung that carries it.
7
+ *
8
+ * The ladder is passed in rather than known here. This function used to build the ladder
9
+ * itself, returning ranks `10 / 20 / 30` as literals — so an app that declared a fourth rung
10
+ * got a three-rung admin UI, and one that re-ranked a tier got the wrong label, while ADR 0022
11
+ * promised the role model belonged to the app rather than the framework. The rungs now come
12
+ * from `useAccessLadder`, which reads them from the access model.
13
+ *
14
+ * A rank no declared rung carries still falls back to `rank N`: it means the record holds a
15
+ * rank the app no longer declares, which is a real thing to say rather than a gap to paper
16
+ * over — the same reasoning `terp grant list` uses when it marks a stale grant instead of
17
+ * hiding it.
18
+ */
19
+ export function adminRoleLabel(rungs: readonly AdminRoleOption[], rank: number): string {
20
+ return rungs.find((option) => option.rank === rank)?.label ?? `rank ${rank}`;
15
21
  }
16
22
 
17
- export function adminRoleLabel(strings: TerpStrings, rank: number): string {
18
- return adminRoleOptions(strings).find((option) => option.rank === rank)?.label ?? `rank ${rank}`;
19
- }
23
+ /**
24
+ * The rank a new-account form should start on: the least privileged rung the app declares.
25
+ *
26
+ * `null` while the ladder is still loading, which is what stops a form from defaulting to a
27
+ * rank the app may not declare at all. The literal `10` it replaced was the packaged viewer
28
+ * rank, and an app whose lowest rung is `5` would have been provisioning accounts one tier
29
+ * above its own floor.
30
+ */
31
+ export function lowestRank(rungs: readonly AdminRoleOption[]): number | null {
32
+ return rungs.length === 0 ? null : rungs[0].rank;
33
+ }