@stapel/workspaces-react 0.7.0 → 0.8.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/api/generated/schema.d.ts +390 -3
  3. package/dist/api/generated/schema.d.ts.map +1 -1
  4. package/dist/api/types.d.ts +84 -2
  5. package/dist/api/types.d.ts.map +1 -1
  6. package/dist/api/workspacesApi.d.ts +33 -1
  7. package/dist/api/workspacesApi.d.ts.map +1 -1
  8. package/dist/api/workspacesApi.js +19 -0
  9. package/dist/api/workspacesApi.js.map +1 -1
  10. package/dist/index.d.ts +7 -5
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/model/mutations.d.ts +85 -1
  15. package/dist/model/mutations.d.ts.map +1 -1
  16. package/dist/model/mutations.js +151 -0
  17. package/dist/model/mutations.js.map +1 -1
  18. package/dist/model/queries.d.ts +72 -2
  19. package/dist/model/queries.d.ts.map +1 -1
  20. package/dist/model/queries.js +90 -1
  21. package/dist/model/queries.js.map +1 -1
  22. package/dist/model/queryKeys.d.ts +10 -1
  23. package/dist/model/queryKeys.d.ts.map +1 -1
  24. package/dist/model/queryKeys.js +19 -0
  25. package/dist/model/queryKeys.js.map +1 -1
  26. package/dist/model/stepUp.d.ts +25 -0
  27. package/dist/model/stepUp.d.ts.map +1 -0
  28. package/dist/model/stepUp.js +79 -0
  29. package/dist/model/stepUp.js.map +1 -0
  30. package/llms.txt +11 -2
  31. package/manifest.json +123 -2
  32. package/package.json +4 -4
  33. package/src/analytics/generated/events.json +1 -1
  34. package/src/api/generated/schema.ts +390 -3
  35. package/src/api/types.ts +93 -2
  36. package/src/api/workspacesApi.ts +87 -0
  37. package/src/index.ts +29 -2
  38. package/src/model/mutations.ts +192 -0
  39. package/src/model/queries.ts +132 -2
  40. package/src/model/queryKeys.ts +35 -1
  41. package/src/model/stepUp.ts +96 -0
package/src/index.ts CHANGED
@@ -57,14 +57,27 @@ export {
57
57
  useWorkspaces,
58
58
  useWorkspace,
59
59
  useMembers,
60
+ useInvitations,
61
+ useInfiniteInvitations,
60
62
  useRoles,
61
63
  useInvitationPreview,
62
64
  useCapabilities,
65
+ useCapabilityGate,
63
66
  } from "./model/queries.js";
64
- export type { CapabilitiesResult } from "./model/queries.js";
67
+ export type { CapabilitiesResult, CapabilityGate } from "./model/queries.js";
65
68
 
66
69
  // ── model (capability matcher + email-mask ports — backend-synced utils) ─────
67
70
  export { capabilityMatches, hasCapability } from "./model/capabilities.js";
71
+ export {
72
+ BUILTIN_CAPABILITY_LEVELS,
73
+ SENSITIVE_SCOPE,
74
+ capabilityLevel,
75
+ readVerificationEnrollment,
76
+ } from "./model/stepUp.js";
77
+ export type {
78
+ CapabilityLevel,
79
+ VerificationEnrollment,
80
+ } from "./model/stepUp.js";
68
81
  export { maskEmail, emailMatchesMask } from "./model/emailMask.js";
69
82
 
70
83
  // ── model (write hooks) ──────────────────────────────────────────────────────
@@ -78,8 +91,15 @@ export {
78
91
  useAcceptInvitation,
79
92
  useClaimInvitation,
80
93
  useDeclineInvitation,
94
+ useRevokeInvitation,
95
+ useResendInvitation,
96
+ useResetMemberPassword,
97
+ useUpdateSecuritySettings,
98
+ } from "./model/mutations.js";
99
+ export type {
100
+ MemberRoleChange,
101
+ MemberPasswordResetVars,
81
102
  } from "./model/mutations.js";
82
- export type { MemberRoleChange } from "./model/mutations.js";
83
103
 
84
104
  // ── api (wire type aliases) ──────────────────────────────────────────────────
85
105
  export type {
@@ -94,9 +114,16 @@ export type {
94
114
  MemberInviteResult,
95
115
  MemberRoleUpdate,
96
116
  Invitation,
117
+ InvitationPage as InvitationListData,
118
+ InvitationsParams,
119
+ InvitationStatusFilter,
97
120
  InvitationAccept,
98
121
  InvitationPreview,
99
122
  InvitationClaim,
123
+ MemberPasswordReset,
124
+ MemberPasswordResetResult,
125
+ ProvisionedUserPolicy,
126
+ WorkspaceSecuritySettings,
100
127
  RoleInfo,
101
128
  RoleList,
102
129
  WorkspaceRole,
@@ -5,13 +5,17 @@ import type {
5
5
  } from "@tanstack/react-query";
6
6
  import type { StapelApiError } from "@stapel/core";
7
7
  import type {
8
+ Invitation,
8
9
  Member,
9
10
  MemberInvite,
10
11
  MemberInviteResult,
12
+ MemberPasswordReset,
13
+ MemberPasswordResetResult,
11
14
  InvitationAccept,
12
15
  InvitationClaim,
13
16
  Workspace,
14
17
  WorkspaceCreate,
18
+ WorkspaceSecuritySettings,
15
19
  WorkspaceUpdate,
16
20
  } from "../api/types.js";
17
21
  import { useWorkspacesApi } from "./context.js";
@@ -175,6 +179,194 @@ export function useRemoveMember(
175
179
  return useMutation(options);
176
180
  }
177
181
 
182
+ /**
183
+ * Withdraw a live invitation (POST /{id}/invitations/{invitationId}/revoke,
184
+ * #109). The variable is the invitation id; the reply is the UPDATED row, so
185
+ * it is written straight into the page cache the table reads — a revoke is
186
+ * the mirror of the invitee's decline and both must stay distinguishable in
187
+ * `status`, which a blind refetch-and-hope would blur. Only a `pending`
188
+ * invitation is revocable: the backend answers
189
+ * `error.400.invitation_already_used` / `_revoked` / `_expired` otherwise
190
+ * (each its own key, not a shrug). Also refreshes the member list — the seat
191
+ * the invitation reserved is freed on commit.
192
+ */
193
+ export function useRevokeInvitation(
194
+ workspaceId: string
195
+ ): UseMutationResult<Invitation, StapelApiError, string> {
196
+ const api = useWorkspacesApi();
197
+ const queryClient = useQueryClient();
198
+ const options: UseMutationOptions<Invitation, StapelApiError, string> = {
199
+ mutationFn: (invitationId) =>
200
+ api.revokeInvitation(workspaceId, invitationId),
201
+ onSuccess: () => {
202
+ void queryClient.invalidateQueries({
203
+ queryKey: workspacesQueryKeys.invitations(workspaceId),
204
+ });
205
+ void queryClient.invalidateQueries({
206
+ queryKey: workspacesQueryKeys.members(workspaceId),
207
+ });
208
+ },
209
+ };
210
+ return useMutation(options);
211
+ }
212
+
213
+ /**
214
+ * Send the invitation email again (POST /{id}/invitations/{invitationId}/resend,
215
+ * #109). The variable is the invitation id.
216
+ *
217
+ * This is NOT an idempotent "poke": the backend rotates the token and
218
+ * restarts the TTL, so every earlier link — including the one already in the
219
+ * invitee's inbox — stops working, and the row's `expires_at` moves. Hence
220
+ * the invalidation: a table still showing the old expiry would be lying about
221
+ * a live credential. An EXPIRED invitation is accepted on purpose (a dead TTL
222
+ * is the commonest reason to resend); reviving it re-reserves a seat, so a
223
+ * plan ceiling can answer 402 here.
224
+ */
225
+ export function useResendInvitation(
226
+ workspaceId: string
227
+ ): UseMutationResult<Invitation, StapelApiError, string> {
228
+ const api = useWorkspacesApi();
229
+ const queryClient = useQueryClient();
230
+ const options: UseMutationOptions<Invitation, StapelApiError, string> = {
231
+ mutationFn: (invitationId) =>
232
+ api.resendInvitation(workspaceId, invitationId),
233
+ onSuccess: () => {
234
+ void queryClient.invalidateQueries({
235
+ queryKey: workspacesQueryKeys.invitations(workspaceId),
236
+ });
237
+ },
238
+ };
239
+ return useMutation(options);
240
+ }
241
+
242
+ /** The variable for {@link useResetMemberPassword}: whose password, and the
243
+ * (optional) body — omit `password` to have the server generate one. */
244
+ export interface MemberPasswordResetVars {
245
+ readonly userId: string;
246
+ readonly body?: MemberPasswordReset;
247
+ }
248
+
249
+ /**
250
+ * Reset a member's password on the organization's order
251
+ * (POST /{id}/members/{userId}/password/reset, #110).
252
+ *
253
+ * **Step-up before the button.** Capability `members.password.reset` is
254
+ * declared `high`, so the backend wraps the endpoint in
255
+ * `requires_verification(scope="sensitive")`. Ask
256
+ * {@link "./queries.js".useCapabilityGate}(workspaceId,
257
+ * "members.password.reset") BEFORE offering the affordance: it answers both
258
+ * "may this caller" and "will a step-up be demanded". A step-up CHALLENGE is
259
+ * then driven by core's client and replayed transparently; the one case that
260
+ * is not transparent is the ENROLLMENT demand (the caller holds no factor to
261
+ * challenge) — read it off `error` with
262
+ * {@link "./stepUp.js".readVerificationEnrollment} and route to enrollment.
263
+ *
264
+ * **The one-shot credential.** `generated_password` comes back exactly once,
265
+ * only when the request omitted `password`, and can never be re-fetched. It
266
+ * is therefore deliberately kept OUT of the query cache: nothing here writes
267
+ * the response with `setQueryData`, and `gcTime: 0` drops the mutation result
268
+ * the moment the screen showing it unmounts. Writing it to a query would
269
+ * mean writing a live credential into every devtools panel AND into
270
+ * `localStorage`, because core's query runtime persists the whole per-user
271
+ * query cache (`createStapelQueryClient`). Hand it to the member out of band.
272
+ *
273
+ * Refreshes the member list (the reset moves the member's first-login state);
274
+ * a target that is not a resettable member of THIS workspace answers one
275
+ * byte-identical 404, never an existence oracle.
276
+ */
277
+ export function useResetMemberPassword(
278
+ workspaceId: string
279
+ ): UseMutationResult<
280
+ MemberPasswordResetResult,
281
+ StapelApiError,
282
+ MemberPasswordResetVars
283
+ > {
284
+ const api = useWorkspacesApi();
285
+ const queryClient = useQueryClient();
286
+ const options: UseMutationOptions<
287
+ MemberPasswordResetResult,
288
+ StapelApiError,
289
+ MemberPasswordResetVars
290
+ > = {
291
+ mutationFn: ({ userId, body }) =>
292
+ api.resetMemberPassword(workspaceId, userId, body),
293
+ // The result carries a live credential: never retained past the screen
294
+ // that displays it, and never persisted.
295
+ gcTime: 0,
296
+ onSuccess: () => {
297
+ void queryClient.invalidateQueries({
298
+ queryKey: workspacesQueryKeys.members(workspaceId),
299
+ });
300
+ },
301
+ };
302
+ return useMutation(options);
303
+ }
304
+
305
+ /**
306
+ * Update a workspace's SECURITY settings (the `security` block of
307
+ * `PATCH /{id}`, org-program §C3) — `require_mfa` and the first-login
308
+ * `provisioned_user_policies`.
309
+ *
310
+ * Separate from {@link useUpdateWorkspace} because the backend treats this
311
+ * block as a different endpoint in all but the URL: an extra capability
312
+ * (`workspace.security.manage`, declared `high`) plus a step-up on the same
313
+ * `sensitive` scope as the password reset, and turning `require_mfa` on
314
+ * sweeps the current members. See {@link useResetMemberPassword} for how to
315
+ * wire that in front of the control.
316
+ *
317
+ * `provisioned_user_policies` is a LIST since stapel-workspaces 0.13.0 (#90)
318
+ * — independent checkboxes, not alternatives. An explicit `[]` is a
319
+ * deliberate, auditable choice ("demand nothing"), so it is sent as such and
320
+ * never dropped as "empty means unset".
321
+ *
322
+ * MERGES, because the backend does not: `PATCH` assigns `settings` wholesale
323
+ * (`ws.settings = data.settings`), so sending a bare `{security: …}` would
324
+ * silently drop every other key the workspace holds. The merge reads the
325
+ * workspace fresh rather than trusting the detail cache — a stale snapshot
326
+ * here would resurrect settings somebody else has since removed.
327
+ */
328
+ export function useUpdateSecuritySettings(
329
+ workspaceId: string
330
+ ): UseMutationResult<Workspace, StapelApiError, WorkspaceSecuritySettings> {
331
+ const api = useWorkspacesApi();
332
+ const queryClient = useQueryClient();
333
+ const options: UseMutationOptions<
334
+ Workspace,
335
+ StapelApiError,
336
+ WorkspaceSecuritySettings
337
+ > = {
338
+ mutationFn: async (patch) => {
339
+ const current = await api.getWorkspace(workspaceId);
340
+ const settings = (current.settings ?? {}) as Record<string, unknown>;
341
+ const security = (settings["security"] ?? {}) as Record<string, unknown>;
342
+ // `policies_configured` is derived and read-only on the wire — never
343
+ // sent back, whatever a caller spread into the patch.
344
+ const { policies_configured: _derived, ...writable } = {
345
+ ...security,
346
+ ...patch,
347
+ };
348
+ return api.updateWorkspace(workspaceId, {
349
+ settings: { ...settings, security: writable },
350
+ });
351
+ },
352
+ onSuccess: (updated) => {
353
+ queryClient.setQueryData(
354
+ workspacesQueryKeys.detail(workspaceId),
355
+ updated
356
+ );
357
+ void queryClient.invalidateQueries({
358
+ queryKey: workspacesQueryKeys.list(),
359
+ });
360
+ // require_mfa ON suspends members without a strong factor; OFF lifts
361
+ // those suspensions. Either way the roster just moved.
362
+ void queryClient.invalidateQueries({
363
+ queryKey: workspacesQueryKeys.members(workspaceId),
364
+ });
365
+ },
366
+ };
367
+ return useMutation(options);
368
+ }
369
+
178
370
  /**
179
371
  * Accept an invitation by its token — the caller joins the workspace. A dead
180
372
  * token surfaces a localizable `StapelApiError` (`error.400.invitation_expired`
@@ -1,9 +1,15 @@
1
- import { useQuery } from "@tanstack/react-query";
2
- import type { UseQueryResult } from "@tanstack/react-query";
1
+ import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
2
+ import type {
3
+ InfiniteData,
4
+ UseInfiniteQueryResult,
5
+ UseQueryResult,
6
+ } from "@tanstack/react-query";
3
7
  import { useActiveSessionReady } from "@stapel/core";
4
8
  import type { StapelApiError } from "@stapel/core";
5
9
  import type {
10
+ InvitationPage,
6
11
  InvitationPreview,
12
+ InvitationsParams,
7
13
  MemberPage,
8
14
  MembersParams,
9
15
  RoleInfo,
@@ -13,6 +19,8 @@ import type {
13
19
  import { useWorkspacesApi } from "./context.js";
14
20
  import { workspacesQueryKeys } from "./queryKeys.js";
15
21
  import { hasCapability } from "./capabilities.js";
22
+ import { SENSITIVE_SCOPE, capabilityLevel } from "./stepUp.js";
23
+ import type { CapabilityLevel } from "./stepUp.js";
16
24
 
17
25
  /**
18
26
  * Read hooks over the workspaces API. Staleness follows core's query defaults;
@@ -81,6 +89,70 @@ export function useMembers(
81
89
  });
82
90
  }
83
91
 
92
+ /**
93
+ * One page of a workspace's invitations (GET /{id}/invitations, #109) — the
94
+ * admin's "who has not accepted yet" table. Disabled until a `workspaceId` is
95
+ * given (and the session is ready — see {@link useWorkspace}).
96
+ *
97
+ * ANCHOR pagination, exactly like {@link useMembers}: pass a page's
98
+ * `next_anchor` as `anchor` to walk forward. There is no page NUMBER — an
99
+ * offset would skew the moment an invitation is revoked or accepted while the
100
+ * admin is reading, which on this screen is the normal case, not the edge one.
101
+ * For scroll-to-load-more use {@link useInfiniteInvitations}.
102
+ *
103
+ * `status` defaults to the backend's `pending` (live, seat-reserving
104
+ * invitations); pass `never_accepted` to include declined/revoked/expired, or
105
+ * `all` for the full history.
106
+ */
107
+ export function useInvitations(
108
+ workspaceId: string | null,
109
+ params?: InvitationsParams
110
+ ): UseQueryResult<InvitationPage, StapelApiError> {
111
+ const api = useWorkspacesApi();
112
+ const sessionReady = useActiveSessionReady();
113
+ const p = params ?? {};
114
+ return useQuery({
115
+ queryKey: workspacesQueryKeys.invitationsPage(workspaceId ?? "", p),
116
+ queryFn: () => api.listInvitations(workspaceId as string, p),
117
+ enabled: sessionReady && workspaceId !== null && workspaceId !== "",
118
+ });
119
+ }
120
+
121
+ /**
122
+ * A workspace's invitations as an infinite (load-more) list. Follows the
123
+ * backend's ANCHOR pagination and nothing else: the page param IS the
124
+ * previous page's `next_anchor`, and the walk stops when `has_next` goes
125
+ * false. `data.pages.flatMap(p => p.items)` is the flat row list.
126
+ *
127
+ * `filters` (`status` / `search` / `limit`) are part of the query key, so
128
+ * flipping the status tab starts a fresh anchor walk rather than appending
129
+ * rows of one filter to the pages of another.
130
+ */
131
+ export function useInfiniteInvitations(
132
+ workspaceId: string | null,
133
+ filters?: Omit<InvitationsParams, "anchor" | "direction">
134
+ ): UseInfiniteQueryResult<
135
+ InfiniteData<InvitationPage, string | undefined>,
136
+ StapelApiError
137
+ > {
138
+ const api = useWorkspacesApi();
139
+ const sessionReady = useActiveSessionReady();
140
+ const f = filters ?? {};
141
+ return useInfiniteQuery({
142
+ queryKey: workspacesQueryKeys.invitationsInfinite(workspaceId ?? "", f),
143
+ queryFn: ({ pageParam }) =>
144
+ api.listInvitations(workspaceId as string, {
145
+ ...f,
146
+ direction: "next",
147
+ ...(pageParam !== undefined ? { anchor: pageParam } : {}),
148
+ }),
149
+ initialPageParam: undefined as string | undefined,
150
+ getNextPageParam: (last) =>
151
+ last.has_next ? (last.next_anchor ?? undefined) : undefined,
152
+ enabled: sessionReady && workspaceId !== null && workspaceId !== "",
153
+ });
154
+ }
155
+
84
156
  /**
85
157
  * The effective role registry (GET /roles, org-program §A2): builtin four +
86
158
  * the deployment's `STAPEL_WORKSPACES["ROLES"]` overlay, capability strings
@@ -150,3 +222,61 @@ export function useCapabilities(workspaceId: string | null): CapabilitiesResult
150
222
  error: query.error ?? null,
151
223
  };
152
224
  }
225
+
226
+ /** What {@link useCapabilityGate} answers about ONE capability, BEFORE the
227
+ * operation is attempted. */
228
+ export interface CapabilityGate {
229
+ /** The capability asked about, verbatim. */
230
+ readonly capability: string;
231
+ /** Does the caller's role carry it? Deny-by-default while loading. */
232
+ readonly allowed: boolean;
233
+ /** Its declared step-up level (ported registry — see `./stepUp.js`). */
234
+ readonly level: CapabilityLevel;
235
+ /** True when `level === "high"`: the backend ALSO demands a fresh
236
+ * verification (scope {@link SENSITIVE_SCOPE}) on top of the capability. */
237
+ readonly requiresStepUp: boolean;
238
+ /** The verification scope of that demand, or `null` at `standard`. */
239
+ readonly stepUpScope: string | null;
240
+ readonly isLoading: boolean;
241
+ }
242
+
243
+ /**
244
+ * Ask about one capability BEFORE offering the operation (org-program §A3).
245
+ *
246
+ * Two different answers, both needed in front of the button rather than
247
+ * behind it:
248
+ *
249
+ * * `allowed` — the caller's role carries the mandate. UI convenience only,
250
+ * deny-by-default; the backend re-checks. This is what replaces guessing
251
+ * access from the ROLE NAME: a deployment role like `secretary` can hold
252
+ * `members.invite` and would still fail a `role === "admin"` test forever,
253
+ * no matter what the registry says.
254
+ * * `requiresStepUp` — the operation is declared `high`, so a fresh step-up
255
+ * verification is demanded on top. Knowing this up front is what lets a
256
+ * screen say "you'll be asked to confirm" (or pre-drive enrollment)
257
+ * instead of showing a button that answers 403.
258
+ *
259
+ * Example — the administrative password reset:
260
+ * ```tsx
261
+ * const gate = useCapabilityGate(workspaceId, "members.password.reset");
262
+ * // gate.allowed === false → do not render the button at all
263
+ * // gate.requiresStepUp → render it with the "we will ask you to
264
+ * // confirm" affordance, wired to the app's
265
+ * // verification controller
266
+ * ```
267
+ */
268
+ export function useCapabilityGate(
269
+ workspaceId: string | null,
270
+ capability: string
271
+ ): CapabilityGate {
272
+ const { can, isLoading } = useCapabilities(workspaceId);
273
+ const level = capabilityLevel(capability);
274
+ return {
275
+ capability,
276
+ allowed: can(capability),
277
+ level,
278
+ requiresStepUp: level === "high",
279
+ stepUpScope: level === "high" ? SENSITIVE_SCOPE : null,
280
+ isLoading,
281
+ };
282
+ }
@@ -1,4 +1,4 @@
1
- import type { MembersParams } from "../api/types.js";
1
+ import type { InvitationsParams, MembersParams } from "../api/types.js";
2
2
 
3
3
  /**
4
4
  * Namespaced TanStack Query keys (frontend-standard §2 — "ключи неймспейснуты").
@@ -18,6 +18,21 @@ export const workspacesQueryKeys: {
18
18
  workspaceId: string,
19
19
  params: MembersParams
20
20
  ): readonly ["workspaces", "members", string, MembersParams];
21
+ invitations(workspaceId: string): readonly ["workspaces", "invitations", string];
22
+ invitationsPage(
23
+ workspaceId: string,
24
+ params: InvitationsParams
25
+ ): readonly ["workspaces", "invitations", string, InvitationsParams];
26
+ invitationsInfinite(
27
+ workspaceId: string,
28
+ filters: InvitationsParams
29
+ ): readonly [
30
+ "workspaces",
31
+ "invitations",
32
+ string,
33
+ "infinite",
34
+ InvitationsParams,
35
+ ];
21
36
  roles(): readonly ["workspaces", "roles"];
22
37
  invitationPreview(
23
38
  token: string
@@ -30,6 +45,25 @@ export const workspacesQueryKeys: {
30
45
  // invalidating `members(workspaceId)` (mutations.ts) drops every page.
31
46
  members: (workspaceId) => [ROOT, "members", workspaceId],
32
47
  membersPage: (workspaceId, params) => [ROOT, "members", workspaceId, params],
48
+ // Same prefix trick as `members`: the bare 3-tuple invalidates every page
49
+ // (and the infinite list, which keys on it) after a revoke / resend.
50
+ invitations: (workspaceId) => [ROOT, "invitations", workspaceId],
51
+ invitationsPage: (workspaceId, params) => [
52
+ ROOT,
53
+ "invitations",
54
+ workspaceId,
55
+ params,
56
+ ],
57
+ // The infinite list carries its own marker segment: its cached value is an
58
+ // `InfiniteData` envelope, not a page, so it must never collide with a
59
+ // single-page key that happens to hold the same filters.
60
+ invitationsInfinite: (workspaceId, filters) => [
61
+ ROOT,
62
+ "invitations",
63
+ workspaceId,
64
+ "infinite",
65
+ filters,
66
+ ],
33
67
  roles: () => [ROOT, "roles"],
34
68
  // NOTE: the key carries the invite TOKEN (a secret). Core's query persist
35
69
  // scope is per-user and the preview response is already public-by-design
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Step-up ahead of the button, not behind it (org-program §A3).
3
+ *
4
+ * Some workspace operations are declared **high**: the backend gates them
5
+ * with `stapel_core`'s `@requires_verification(scope="sensitive")` on top of
6
+ * the capability check, so an ambient cookie is never enough. A client that
7
+ * only learns this from the 403 shows the admin a button, a spinner and a
8
+ * refusal; this module lets it know BEFORE the click.
9
+ *
10
+ * Two things travel from the backend, and they are not the same thing:
11
+ *
12
+ * 1. **A step-up CHALLENGE** — `verification.challenge_id` is present. This
13
+ * one nobody has to handle here: `@stapel/core`'s client intercepts it,
14
+ * hands it to the app's verification controller (auth-react's factor
15
+ * machines) and replays the original request with
16
+ * `X-Verification-Token`. It is a detour, not a failure.
17
+ * 2. **An ENROLLMENT demand** — `verification.enroll === true` and there is
18
+ * NO challenge id, because the user holds no factor that could be
19
+ * challenged. Core deliberately does not intercept this one (there is
20
+ * nothing to drive), so it surfaces as a plain 403 and the app must send
21
+ * the user to factor enrollment first. {@link readVerificationEnrollment}
22
+ * is how a hook says "this is that, and these are the factors".
23
+ *
24
+ * KEEP IN SYNC with stapel-workspaces `capabilities.BUILTIN_CAPABILITY_LEVELS`
25
+ * — a PORT for the same reason `capabilityMatches` is one: `GET /roles`
26
+ * publishes each role's capabilities but not their levels, so the level map
27
+ * cannot be read off the wire. A deployment may raise further capabilities via
28
+ * `STAPEL_WORKSPACES["CAPABILITY_LEVELS"]`; those are additive, so treating an
29
+ * unlisted capability as `standard` can only ever under-promise (the backend
30
+ * still challenges, and core still drives it).
31
+ */
32
+ import { isStapelApiError } from "@stapel/core";
33
+
34
+ /** The verification scope every `high` workspace capability is gated under. */
35
+ export const SENSITIVE_SCOPE = "sensitive";
36
+
37
+ /** Step-up level of a capability. */
38
+ export type CapabilityLevel = "standard" | "high";
39
+
40
+ /** PORT of `BUILTIN_CAPABILITY_LEVELS` — everything unlisted is `standard`. */
41
+ export const BUILTIN_CAPABILITY_LEVELS: Readonly<Record<string, "high">> = {
42
+ "members.provision": "high",
43
+ "members.password.reset": "high",
44
+ "workspace.security.manage": "high",
45
+ };
46
+
47
+ /** The declared step-up level of one capability string. */
48
+ export function capabilityLevel(capability: string): CapabilityLevel {
49
+ return BUILTIN_CAPABILITY_LEVELS[capability] ?? "standard";
50
+ }
51
+
52
+ /**
53
+ * The 403 ENROLLMENT envelope: the caller must first enroll one of `factors`
54
+ * — there is no challenge to complete, so core cannot drive it.
55
+ */
56
+ export interface VerificationEnrollment {
57
+ /** What the demand protects — `"sensitive"` for every `high` capability. */
58
+ readonly scope: string;
59
+ /** Interchangeable factors, any ONE of which unblocks the operation. */
60
+ readonly factors: readonly string[];
61
+ }
62
+
63
+ function asRecord(value: unknown): Record<string, unknown> | null {
64
+ return typeof value === "object" && value !== null && !Array.isArray(value)
65
+ ? (value as Record<string, unknown>)
66
+ : null;
67
+ }
68
+
69
+ /**
70
+ * Read the enrollment demand out of a rejected request, or `null` when the
71
+ * error is anything else (including a step-up CHALLENGE, which carries a
72
+ * `challenge_id` and is core's business, not the consumer's).
73
+ */
74
+ export function readVerificationEnrollment(
75
+ error: unknown
76
+ ): VerificationEnrollment | null {
77
+ // Both dialects, narrowed through the imported predicate (never through a
78
+ // shape this call site invented): the typed error carries the parsed body,
79
+ // a rethrown raw envelope IS the body.
80
+ const body = asRecord(isStapelApiError(error) ? error.body : error);
81
+ if (body === null) return null;
82
+ const verification = asRecord(body["verification"]);
83
+ if (verification === null) return null;
84
+ if (verification["enroll"] !== true) return null;
85
+ if (typeof verification["challenge_id"] === "string") return null;
86
+ const factors = verification["factors"];
87
+ return {
88
+ scope:
89
+ typeof verification["scope"] === "string"
90
+ ? verification["scope"]
91
+ : SENSITIVE_SCOPE,
92
+ factors: Array.isArray(factors)
93
+ ? factors.filter((f): f is string => typeof f === "string")
94
+ : [],
95
+ };
96
+ }