@htilabs/platform-common-models 0.21.0 → 0.23.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 (71) hide show
  1. package/dist/authz/index.cjs +539 -0
  2. package/dist/authz/index.cjs.map +1 -0
  3. package/dist/authz/index.d.cts +210 -0
  4. package/dist/authz/index.d.ts +210 -0
  5. package/dist/authz/index.js +507 -0
  6. package/dist/authz/index.js.map +1 -0
  7. package/dist/constants/index.d.cts +2 -1
  8. package/dist/constants/index.d.ts +2 -1
  9. package/dist/cvcs/index.cjs +936 -243
  10. package/dist/cvcs/index.cjs.map +1 -1
  11. package/dist/cvcs/index.d.cts +986 -254
  12. package/dist/cvcs/index.d.ts +986 -254
  13. package/dist/cvcs/index.js +936 -243
  14. package/dist/cvcs/index.js.map +1 -1
  15. package/dist/enums/index.cjs +37 -10
  16. package/dist/enums/index.cjs.map +1 -1
  17. package/dist/enums/index.d.cts +42 -15
  18. package/dist/enums/index.d.ts +42 -15
  19. package/dist/enums/index.js +37 -10
  20. package/dist/enums/index.js.map +1 -1
  21. package/dist/{platform-auth-CvAYFVhK.d.cts → ic-DpKrdgQP.d.cts} +1 -78
  22. package/dist/{platform-auth-CvAYFVhK.d.ts → ic-DpKrdgQP.d.ts} +1 -78
  23. package/dist/index.cjs +1328 -253
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +4 -2
  26. package/dist/index.d.ts +4 -2
  27. package/dist/index.js +1313 -253
  28. package/dist/index.js.map +1 -1
  29. package/dist/platform-auth-B49Ly57B.d.cts +78 -0
  30. package/dist/platform-auth-B49Ly57B.d.ts +78 -0
  31. package/dist/schemas/index.cjs +104 -0
  32. package/dist/schemas/index.cjs.map +1 -1
  33. package/dist/schemas/index.d.cts +240 -1
  34. package/dist/schemas/index.d.ts +240 -1
  35. package/dist/schemas/index.js +95 -0
  36. package/dist/schemas/index.js.map +1 -1
  37. package/dist/types/index.d.cts +2 -2
  38. package/dist/types/index.d.ts +2 -2
  39. package/package.json +6 -1
  40. package/src/__sot__/README.md +3 -0
  41. package/src/__sot__/adminRoles.pin.json +122 -0
  42. package/src/__sot__/adminRoles.published.json +77 -0
  43. package/src/__sot__/coreFunctionFields.ts +137 -0
  44. package/src/__sot__/coreFunctions.pin.json +1659 -0
  45. package/src/__sot__/coreFunctions.published.json +233 -0
  46. package/src/__sot__/roleFields.ts +137 -0
  47. package/src/__sot__/userRoles.pin.json +174 -0
  48. package/src/__sot__/userRoles.published.json +103 -0
  49. package/src/__tests__/__snapshots__/cvc-sot.snap +6 -6
  50. package/src/__tests__/admin-roles-canon.test.ts +80 -0
  51. package/src/__tests__/authz-resolve.test.ts +712 -0
  52. package/src/__tests__/core-functions-canon.test.ts +358 -24
  53. package/src/__tests__/cvc-sot-snapshot.test.ts +17 -6
  54. package/src/__tests__/cvc-status-parser.test.ts +2 -2
  55. package/src/__tests__/cvc-structural.test.ts +3 -3
  56. package/src/__tests__/organization-program.test.ts +254 -0
  57. package/src/__tests__/role-vocab-gate.ts +279 -0
  58. package/src/__tests__/user-roles-canon.test.ts +104 -0
  59. package/src/authz/index.ts +9 -0
  60. package/src/authz/resolveEffectiveFunctions.ts +454 -0
  61. package/src/cvcs/adminRoles.v2.0.0.json +197 -0
  62. package/src/cvcs/{coreFunctions.v1.1.0.json → coreFunctions.v1.3.0.json} +646 -90
  63. package/src/cvcs/index.ts +3 -3
  64. package/src/cvcs/userRoles.v2.0.0.json +296 -0
  65. package/src/generated/coreFunctionsEvaluable.ts +101 -0
  66. package/src/generated/cvc-enums.ts +42 -15
  67. package/src/index.ts +4 -0
  68. package/src/schemas/index.ts +18 -0
  69. package/src/schemas/organization-program.ts +297 -0
  70. package/src/cvcs/adminRoles.v1.0.0.json +0 -153
  71. package/src/cvcs/userRoles.v1.0.0.json +0 -203
@@ -0,0 +1,712 @@
1
+ /**
2
+ * Shared CVC-133 authorization resolver — behavioral contract (co-zo3).
3
+ *
4
+ * Part 1 ports Thread's 12 resolver tests (thread branch
5
+ * `fix/effective-functions-multirole-tier3` @ ed1bebf,
6
+ * `apps/api/tests/effectiveFunctions.resolver.unit.test.ts`) onto pure input:
7
+ * the fake platform-db connection is gone, so each loader-shaped test is
8
+ * restated as the pure invariant it was guarding. One Thread test asserted a
9
+ * team PREF_YES LIFT, which the ruled model forbids (kickoff § 3 rule 4); it is
10
+ * ported inverted and says so.
11
+ *
12
+ * Part 2 adds the kickoff § 4.1 extras; part 3 the viewing level.
13
+ */
14
+ import { readFileSync, readdirSync } from "node:fs";
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { describe, expect, it } from "vitest";
18
+ import coreFunctionsSot from "../cvcs/coreFunctions.v1.3.0.json" with { type: "json" };
19
+ import { CoreFunctionsKeys } from "../generated/cvc-enums.js";
20
+ import * as authzSubpath from "../authz/index.js";
21
+ import {
22
+ isCanonEvaluableFunction,
23
+ resolveEffectiveFunctions,
24
+ resolveEffectiveViewingLevel,
25
+ selectActingTeamId,
26
+ viewingLevelFromFunctions,
27
+ type AuthzTeamPolicy,
28
+ type ResolveEffectiveFunctionsInput,
29
+ } from "../index.js";
30
+
31
+ // Thread's fixture: three Thread-scoped functions. `case_edit` is ALWAYS for
32
+ // SUP and NEVER for CIRO; `usr_manage` is MEM-ADM only; `session_create` is
33
+ // PREF_NO for SUP and PREF_YES for CIRO.
34
+ const functions = [
35
+ { code: "case_edit", tools: ["THREAD"] },
36
+ { code: "usr_manage", tools: ["THREAD"] },
37
+ { code: "session_create", tools: ["THREAD"] },
38
+ ];
39
+ const roles = [
40
+ { code: "SUP", tools: ["THREAD"], functions: { case_edit: "ALWAYS", session_create: "PREF_NO" } },
41
+ { code: "CIRO", tools: ["THREAD"], functions: { case_edit: "NEVER", session_create: "PREF_YES" } },
42
+ { code: "MEM-ADM", tools: ["THREAD"], functions: { usr_manage: "ALWAYS" } },
43
+ ] as const;
44
+
45
+ const input = (
46
+ over: Partial<ResolveEffectiveFunctionsInput> = {},
47
+ ): ResolveEffectiveFunctionsInput => ({
48
+ roles,
49
+ functions,
50
+ assignedRoleCodes: ["MEM-ADM", "CIRO", "SUP"],
51
+ unknownFunctionPolicy: "deny",
52
+ ...over,
53
+ });
54
+ const resolve = (over: Partial<ResolveEffectiveFunctionsInput> = {}) =>
55
+ resolveEffectiveFunctions(input(over));
56
+
57
+ // ─── Part 1 — Thread's 12, on pure input ────────────────────────────────────
58
+
59
+ describe("multi-role rule: roles stack, NEVER is local (rule 2)", () => {
60
+ it("[thread 1] MEM-ADM + CIRO + SUP gets case_edit: SUP's ALWAYS stands, CIRO's NEVER is local to CIRO", () => {
61
+ const fns = resolve();
62
+ expect(fns).toContain("case_edit");
63
+ expect(fns).toContain("usr_manage");
64
+ expect(fns).toContain("session_create"); // CIRO's PREF_YES
65
+ });
66
+
67
+ it("[thread 2] still denies a function every assigned role denies", () => {
68
+ expect(resolve({ assignedRoleCodes: ["CIRO"] })).toEqual(["session_create"]);
69
+ });
70
+ });
71
+
72
+ describe("team layer (rules 3, 4, 5)", () => {
73
+ it("[thread 3, inverted] the acting team's policy applies — as a restriction; its PREF_YES never lifts", () => {
74
+ // Thread asserted that a team PREF_YES turned SUP's PREF_NO on. Rule 4
75
+ // (team restrict-only) refutes that premise; the policy's effect is shown
76
+ // by the restriction it carries instead.
77
+ const restrict: AuthzTeamPolicy = {
78
+ roles: [{ roleCode: "CIRO", overrides: { session_create: "PREF_NO" } }],
79
+ };
80
+ expect(resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: restrict })).toEqual([]);
81
+ const lift: AuthzTeamPolicy = {
82
+ roles: [{ roleCode: "SUP", overrides: { session_create: "PREF_YES" } }],
83
+ };
84
+ expect(resolve({ assignedRoleCodes: ["SUP"], teamPolicy: lift })).not.toContain(
85
+ "session_create",
86
+ );
87
+ });
88
+
89
+ it("[thread 4] the team layer reads only the passed policy's entries: another role's role-grain entry does not touch this role", () => {
90
+ // Thread's test pinned the loader join (teams.teamAccessPolicyId, never an
91
+ // id collision). On pure input the equivalent is that only what the
92
+ // acting team's policy says about THIS role (or about every role, via the
93
+ // flat map) can narrow it.
94
+ const policy: AuthzTeamPolicy = {
95
+ roles: [{ roleCode: "SUP", overrides: { session_create: "PREF_NO" } }],
96
+ };
97
+ expect(resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: policy })).toEqual([
98
+ "session_create",
99
+ ]);
100
+ });
101
+
102
+ it("[thread 5] with no verified acting team, only the seat's own primary team is ever selected", () => {
103
+ // Thread: a policy from another agency / a team the user is not on is
104
+ // ignored. Verifying a claimed team is the loader's job (rule 5); on pure
105
+ // input the helper never reaches outside the seat's own list unprompted.
106
+ expect(selectActingTeamId(["team-a"])).toBe("team-a");
107
+ expect(selectActingTeamId(["team-a"], null)).toBe("team-a");
108
+ expect(selectActingTeamId([])).toBeNull();
109
+ });
110
+
111
+ it("[thread 6] the team cannot lift a lock: Tier-1 ALWAYS survives a team PREF_NO, agency NEVER survives a team PREF_YES", () => {
112
+ const fns = resolve({
113
+ assignedRoleCodes: ["SUP"],
114
+ agencyOverrides: { SUP: { session_create: "NEVER" } },
115
+ teamPolicy: { functions: { session_create: "PREF_YES", case_edit: "PREF_NO" } },
116
+ });
117
+ expect(fns).toEqual(["case_edit"]);
118
+ });
119
+
120
+ it("[thread 7] a team ALWAYS is ignored (the team tier cannot grant or lock)", () => {
121
+ const fns = resolve({
122
+ assignedRoleCodes: ["SUP"],
123
+ teamPolicy: { functions: { session_create: "ALWAYS" } },
124
+ });
125
+ expect(fns).not.toContain("session_create");
126
+ });
127
+
128
+ it("[thread 8] ONE team resolves — the primary (teamIds[0]); other teams are visibility scope, not policy input", () => {
129
+ const policies: Record<string, AuthzTeamPolicy> = {
130
+ "team-a": { functions: { session_create: "PREF_NO" } },
131
+ "team-b": { functions: { session_create: "PREF_YES" } },
132
+ };
133
+ const forSeat = (teamIds: string[]) => {
134
+ const acting = selectActingTeamId(teamIds);
135
+ return resolve({
136
+ assignedRoleCodes: ["CIRO"],
137
+ teamPolicy: acting ? policies[acting] : null,
138
+ });
139
+ };
140
+ expect(forSeat(["team-a", "team-b"])).not.toContain("session_create");
141
+ expect(forSeat(["team-b", "team-a"])).toContain("session_create");
142
+ });
143
+
144
+ it("[thread 9] a primary team with no policy, or a seat with no team, passes the team layer through (ruling 3c)", () => {
145
+ expect(resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: null })).toContain("session_create");
146
+ expect(resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: {} })).toContain("session_create");
147
+ expect(resolve({ assignedRoleCodes: ["CIRO"] })).toContain("session_create");
148
+ });
149
+ });
150
+
151
+ describe("fail-closed edges (rule 8)", () => {
152
+ it("[thread 10] nothing loaded (Thread: platform-db not connected) resolves to []", () => {
153
+ expect(resolve({ roles: [], functions: [] })).toEqual([]);
154
+ });
155
+ it("[thread 11] a seat with no roles resolves to []", () => {
156
+ expect(resolve({ assignedRoleCodes: [] })).toEqual([]);
157
+ });
158
+ it("[thread 12] an assigned code with no role row (Thread: an invalid id) contributes nothing", () => {
159
+ expect(resolve({ assignedRoleCodes: ["nope"] })).toEqual([]);
160
+ expect(resolve({ assignedRoleCodes: ["nope", "CIRO"] })).toEqual(["session_create"]);
161
+ });
162
+ });
163
+
164
+ // ─── Part 2 — kickoff § 4.1 extras ──────────────────────────────────────────
165
+
166
+ describe("§ 4.1 extras", () => {
167
+ it("rule 4: a team PREF_YES cannot lift an agency PREF_NO", () => {
168
+ const fns = resolve({
169
+ assignedRoleCodes: ["CIRO"],
170
+ agencyOverrides: { CIRO: { session_create: "PREF_NO" } },
171
+ teamPolicy: {
172
+ functions: { session_create: "PREF_YES" },
173
+ roles: [{ roleCode: "CIRO", overrides: { session_create: "PREF_YES" } }],
174
+ },
175
+ });
176
+ expect(fns).toEqual([]);
177
+ });
178
+
179
+ it("rule 4: either team map switching a function off is enough (role-grain PREF_YES does not undo a flat PREF_NO)", () => {
180
+ const fns = resolve({
181
+ assignedRoleCodes: ["CIRO"],
182
+ teamPolicy: {
183
+ functions: { session_create: "PREF_NO" },
184
+ roles: [{ roleCode: "CIRO", overrides: { session_create: "PREF_YES" } }],
185
+ },
186
+ });
187
+ expect(fns).toEqual([]);
188
+ });
189
+
190
+ it("rule 3: Required — platform ALWAYS or agency-escalated ALWAYS — is immune to the team gate", () => {
191
+ const off: AuthzTeamPolicy = {
192
+ functions: { case_edit: "PREF_NO", session_create: "PREF_NO" },
193
+ };
194
+ // platform ALWAYS (SUP case_edit)
195
+ expect(resolve({ assignedRoleCodes: ["SUP"], teamPolicy: off })).toEqual(["case_edit"]);
196
+ // agency-escalated ALWAYS (SUP session_create: PREF_NO → ALWAYS)
197
+ expect(
198
+ resolve({
199
+ assignedRoleCodes: ["SUP"],
200
+ agencyOverrides: { SUP: { session_create: "ALWAYS" } },
201
+ teamPolicy: off,
202
+ }),
203
+ ).toEqual(["case_edit", "session_create"]);
204
+ // an agency PREF_YES lift is NOT Required — the team still gates it
205
+ expect(
206
+ resolve({
207
+ assignedRoleCodes: ["SUP"],
208
+ agencyOverrides: { SUP: { session_create: "PREF_YES" } },
209
+ teamPolicy: off,
210
+ }),
211
+ ).toEqual(["case_edit"]);
212
+ });
213
+
214
+ it("rule 3: Tier-1 ALWAYS / NEVER ignore the agency layer", () => {
215
+ const fns = resolve({
216
+ assignedRoleCodes: ["SUP", "CIRO"],
217
+ agencyOverrides: {
218
+ SUP: { case_edit: "PREF_NO" },
219
+ CIRO: { case_edit: "PREF_YES" },
220
+ },
221
+ });
222
+ expect(fns).toContain("case_edit"); // SUP's platform ALWAYS stands
223
+ expect(resolve({ assignedRoleCodes: ["CIRO"], agencyOverrides: { CIRO: { case_edit: "ALWAYS" } } }))
224
+ .not.toContain("case_edit"); // CIRO's platform NEVER stands
225
+ });
226
+
227
+ it("rule 1: the agency may switch a Default-Off function on for a role (and it stays team-gated)", () => {
228
+ expect(
229
+ resolve({ assignedRoleCodes: ["SUP"], agencyOverrides: { SUP: { session_create: "PREF_YES" } } }),
230
+ ).toContain("session_create");
231
+ });
232
+
233
+ it("rule 5: a verified acting team overrides the primary team", () => {
234
+ const policies: Record<string, AuthzTeamPolicy> = {
235
+ "team-a": {},
236
+ "team-b": { functions: { session_create: "PREF_NO" } },
237
+ };
238
+ const seat = ["team-a", "team-b"];
239
+ const run = (acting?: string) =>
240
+ resolve({
241
+ assignedRoleCodes: ["CIRO"],
242
+ teamPolicy: policies[selectActingTeamId(seat, acting) ?? ""] ?? null,
243
+ });
244
+ expect(selectActingTeamId(seat)).toBe("team-a");
245
+ expect(run()).toContain("session_create");
246
+ expect(selectActingTeamId(seat, "team-b")).toBe("team-b");
247
+ expect(run("team-b")).not.toContain("session_create");
248
+ });
249
+
250
+ it("rule 5: a verified acting team is used as is, even when the seat's own team list lacks it (the caller verified it)", () => {
251
+ // pave-2.0 verifies through teams.members[]; users.teams is not kept in
252
+ // step with it, so the helper must not re-check against seatTeamIds.
253
+ expect(selectActingTeamId(["team-a"], "team-verified-elsewhere")).toBe(
254
+ "team-verified-elsewhere",
255
+ );
256
+ expect(selectActingTeamId([], "team-verified-elsewhere")).toBe("team-verified-elsewhere");
257
+ });
258
+
259
+ it("rule 8: a canon-unknown code is denied even when the caller's catalog lists it with a v1-looking row", () => {
260
+ // ida_conduct is in the platform seed (cvcRoles.js) but not in CVC-133.
261
+ const fns = resolve({
262
+ functions: [...functions, { code: "ida_conduct", tools: ["THREAD"] }],
263
+ roles: [{ code: "SUP", tools: ["THREAD"], functions: { ida_conduct: "ALWAYS", case_edit: "ALWAYS" } }],
264
+ assignedRoleCodes: ["SUP"],
265
+ });
266
+ expect(isCanonEvaluableFunction("ida_conduct")).toBe(false);
267
+ expect(fns).toEqual(["case_edit"]);
268
+ });
269
+
270
+ it("rule 8: canon not-v1 codes are denied even with no status on the caller's row (break_glass, thread_share_send, share_approve)", () => {
271
+ const notV1 = ["break_glass", "thread_share_send", "share_approve"];
272
+ const fns = resolve({
273
+ functions: notV1.map((code) => ({ code, tools: ["PLATFORM"] })),
274
+ roles: [
275
+ {
276
+ code: "PLT-ADM",
277
+ tools: ["PLATFORM"],
278
+ functions: { break_glass: "ALWAYS", thread_share_send: "ALWAYS", share_approve: "ALWAYS" },
279
+ },
280
+ ],
281
+ assignedRoleCodes: ["PLT-ADM"],
282
+ });
283
+ for (const code of notV1) expect(isCanonEvaluableFunction(code), code).toBe(false);
284
+ expect(fns).toEqual([]);
285
+ });
286
+
287
+ it("rule 8: a canon-v1 code is still granted when the caller's stored row carries a stale not-v1 status (no PLT-ADM lockout)", () => {
288
+ // platform's seed stores platform_perm_modify as "Future function (not v1)";
289
+ // canon says v1. The caller's status is not read.
290
+ const staleRow = {
291
+ code: "platform_perm_modify",
292
+ tools: ["PLATFORM"],
293
+ status: "Future function (not v1)",
294
+ };
295
+ const fns = resolve({
296
+ functions: [staleRow],
297
+ roles: [{ code: "PLT-ADM", tools: ["PLATFORM"], functions: { platform_perm_modify: "ALWAYS" } }],
298
+ assignedRoleCodes: ["PLT-ADM"],
299
+ });
300
+ expect(fns).toEqual(["platform_perm_modify"]);
301
+ });
302
+
303
+ it("rule 8: a retired function is denied — the caller's retired flag can only further deny", () => {
304
+ // Canon carries 0 retired rows at f4356aa4, so the canon half is asserted on
305
+ // the SOT itself (every entry with retired: true is never evaluable).
306
+ const fns = resolve({
307
+ functions: [
308
+ { code: "case_edit", tools: ["THREAD"], retired: true },
309
+ { code: "session_create", tools: ["THREAD"], retired: false },
310
+ ],
311
+ assignedRoleCodes: ["SUP", "CIRO"],
312
+ });
313
+ expect(fns).toEqual(["session_create"]);
314
+ for (const e of coreFunctionsSot.entries.filter((x) => x.retired))
315
+ expect(isCanonEvaluableFunction(e.key), e.key).toBe(false);
316
+ });
317
+
318
+ it("rule 8: the missingness sentinels are never evaluable functions", () => {
319
+ for (const k of ["missingness_root", "unknown", "anonymous", "data_not_collected"])
320
+ expect(isCanonEvaluableFunction(k), k).toBe(false);
321
+ expect(
322
+ resolve({
323
+ functions: [{ code: "unknown", tools: ["THREAD"] }],
324
+ roles: [{ code: "SUP", tools: ["THREAD"], functions: { unknown: "ALWAYS" } }],
325
+ assignedRoleCodes: ["SUP"],
326
+ }),
327
+ ).toEqual([]);
328
+ });
329
+
330
+ it("rule 8: canon's evaluable set is exactly the SOT's v1 && !retired keys, all in CoreFunctionsKeys", () => {
331
+ const expected = coreFunctionsSot.entries.filter((e) => e.v1 && !e.retired).map((e) => e.key);
332
+ expect(expected).toHaveLength(86);
333
+ for (const k of expected) {
334
+ expect(Object.hasOwn(CoreFunctionsKeys, k), k).toBe(true);
335
+ expect(isCanonEvaluableFunction(k), k).toBe(true);
336
+ }
337
+ });
338
+
339
+ it("tier 1: an unlisted function defaults to PREF_NO when it shares a tool, NEVER when it does not", () => {
340
+ const fns = resolve({
341
+ functions: [...functions, { code: "lead_create", tools: ["LEADS"] }],
342
+ roles: [{ code: "SUP", tools: ["THREAD"], functions: {} }],
343
+ assignedRoleCodes: ["SUP"],
344
+ agencyOverrides: { SUP: { session_create: "PREF_YES", lead_create: "PREF_YES" } },
345
+ });
346
+ expect(fns).toEqual(["session_create"]); // lead_create is N/A for SUP: NEVER, locked
347
+ });
348
+
349
+ it("malformed Tier-1 state fails closed: a bad stored value is NEVER for that role", () => {
350
+ const fns = resolve({
351
+ roles: [{ code: "SUP", tools: ["THREAD"], functions: { case_edit: "yes" as never } }],
352
+ assignedRoleCodes: ["SUP"],
353
+ });
354
+ expect(fns).toEqual([]);
355
+ });
356
+
357
+ it("malformed agency override fails closed: it is NEVER for that role, never the platform default", () => {
358
+ // Dangerous direction: CIRO's platform PREF_YES must not survive a garbage
359
+ // agency value (it would if the override were ignored).
360
+ expect(
361
+ resolve({ assignedRoleCodes: ["CIRO"], agencyOverrides: { CIRO: { session_create: "on" as never } } }),
362
+ ).toEqual([]);
363
+ // ...and a garbage value never lifts a Default-Off.
364
+ expect(
365
+ resolve({ assignedRoleCodes: ["SUP"], agencyOverrides: { SUP: { session_create: "yes" as never } } }),
366
+ ).not.toContain("session_create");
367
+ // null / undefined mean "not set": the platform default stands.
368
+ expect(
369
+ resolve({ assignedRoleCodes: ["CIRO"], agencyOverrides: { CIRO: { session_create: null as never } } }),
370
+ ).toEqual(["session_create"]);
371
+ });
372
+
373
+ it("malformed team value fails closed: it restricts (Required stays immune)", () => {
374
+ // Dangerous direction: a garbage team value must not pass the grant through.
375
+ expect(
376
+ resolve({
377
+ assignedRoleCodes: ["CIRO"],
378
+ teamPolicy: { functions: { session_create: "off" as never } },
379
+ }),
380
+ ).toEqual([]);
381
+ expect(
382
+ resolve({
383
+ assignedRoleCodes: ["CIRO"],
384
+ teamPolicy: { roles: [{ roleCode: "CIRO", overrides: { session_create: 0 as never } }] },
385
+ }),
386
+ ).toEqual([]);
387
+ // Required (SUP's platform ALWAYS case_edit) is still immune to the team gate.
388
+ expect(
389
+ resolve({ assignedRoleCodes: ["SUP"], teamPolicy: { functions: { case_edit: "off" as never } } }),
390
+ ).toEqual(["case_edit"]);
391
+ // null means "not set": pass-through.
392
+ expect(
393
+ resolve({
394
+ assignedRoleCodes: ["CIRO"],
395
+ teamPolicy: { functions: { session_create: null as never } },
396
+ }),
397
+ ).toEqual(["session_create"]);
398
+ });
399
+
400
+ it("the ./authz subpath exposes the same surface as the root and imports nothing mongoose-backed", () => {
401
+ expect(authzSubpath.resolveEffectiveFunctions).toBe(resolveEffectiveFunctions);
402
+ expect(authzSubpath.selectActingTeamId).toBe(selectActingTeamId);
403
+ expect(authzSubpath.viewingLevelFromFunctions).toBe(viewingLevelFromFunctions);
404
+ const dir = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "authz");
405
+ const specifiers = readdirSync(dir)
406
+ .filter((f) => f.endsWith(".ts"))
407
+ .flatMap((f) => [...readFileSync(path.join(dir, f), "utf8").matchAll(/from\s+"([^"]+)"/g)].map((m) => m[1]!));
408
+ expect(new Set(specifiers)).toEqual(
409
+ new Set([
410
+ "./resolveEffectiveFunctions.js",
411
+ "../constants/platform-auth.js",
412
+ "../generated/cvc-enums.js",
413
+ "../generated/coreFunctionsEvaluable.js",
414
+ ]),
415
+ );
416
+ });
417
+
418
+ it("malformed team containers fail closed: a non-plain-object functions / overrides / policy restricts every team-gated grant it could govern; Required stays immune", () => {
419
+ const bad: unknown[] = [["session_create"], "PREF_YES", new Map([["session_create", "PREF_YES"]]), 7];
420
+ for (const container of bad) {
421
+ // the flat map governs every role
422
+ expect(
423
+ resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: { functions: container as never } }),
424
+ `functions = ${String(container)}`,
425
+ ).toEqual([]);
426
+ // one role's overrides govern that role only: CIRO's grant is withdrawn,
427
+ // SUP's (team-gated, agency-lifted) grant of the same function stands
428
+ expect(
429
+ resolve({
430
+ assignedRoleCodes: ["CIRO"],
431
+ teamPolicy: { roles: [{ roleCode: "CIRO", overrides: container as never }] },
432
+ }),
433
+ `overrides = ${String(container)}`,
434
+ ).toEqual([]);
435
+ expect(
436
+ resolve({
437
+ assignedRoleCodes: ["CIRO", "SUP"],
438
+ agencyOverrides: { SUP: { session_create: "PREF_YES" } },
439
+ teamPolicy: { roles: [{ roleCode: "CIRO", overrides: container as never }] },
440
+ }),
441
+ `overrides = ${String(container)} (other role)`,
442
+ ).toEqual(["case_edit", "session_create"]);
443
+ // the whole policy document
444
+ expect(
445
+ resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: container as never }),
446
+ `teamPolicy = ${String(container)}`,
447
+ ).toEqual([]);
448
+ }
449
+ // a non-array roles list restricts every team-gated grant
450
+ expect(
451
+ resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: { roles: { CIRO: {} } as never } }),
452
+ ).toEqual([]);
453
+ // Required (platform ALWAYS) is immune to all of it
454
+ expect(
455
+ resolve({ assignedRoleCodes: ["SUP"], teamPolicy: { functions: ["x"] as never } }),
456
+ ).toEqual(["case_edit"]);
457
+ expect(resolve({ assignedRoleCodes: ["SUP"], teamPolicy: "garbage" as never })).toEqual([
458
+ "case_edit",
459
+ ]);
460
+ });
461
+
462
+ it("duplicate teamPolicy.roles entries for one role are unioned: any PREF_NO / NEVER wins", () => {
463
+ const entries = [
464
+ { roleCode: "CIRO", overrides: { session_create: "PREF_YES" as const } },
465
+ { roleCode: "CIRO", overrides: { session_create: "PREF_NO" as const } },
466
+ ];
467
+ expect(resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: { roles: entries } })).toEqual([]);
468
+ expect(
469
+ resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: { roles: [...entries].reverse() } }),
470
+ ).toEqual([]);
471
+ });
472
+
473
+ it("a null or malformed teamPolicy.roles entry never throws and fails closed", () => {
474
+ // An entry with no readable roleCode cannot be attributed to a role, so
475
+ // it restricts every role's team-gated grants.
476
+ for (const entry of [null, undefined, "CIRO", 3, { overrides: { x: "PREF_NO" } }, { roleCode: 9 }]) {
477
+ expect(
478
+ () => resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: { roles: [entry as never] } }),
479
+ `entry = ${JSON.stringify(entry)}`,
480
+ ).not.toThrow();
481
+ expect(
482
+ resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: { roles: [entry as never] } }),
483
+ `entry = ${JSON.stringify(entry)}`,
484
+ ).toEqual([]);
485
+ }
486
+ // An entry for a role with no overrides narrows nothing.
487
+ expect(
488
+ resolve({ assignedRoleCodes: ["CIRO"], teamPolicy: { roles: [{ roleCode: "CIRO" }] } }),
489
+ ).toEqual(["session_create"]);
490
+ // Required stays immune.
491
+ expect(
492
+ resolve({ assignedRoleCodes: ["SUP"], teamPolicy: { roles: [null as never] } }),
493
+ ).toEqual(["case_edit"]);
494
+ });
495
+
496
+ it("a catalog row keeps a function only when `retired` is absent or exactly false", () => {
497
+ for (const retired of ["true", "false", 1, 0, null, {}]) {
498
+ expect(
499
+ resolve({
500
+ functions: [{ code: "session_create", tools: ["THREAD"], retired: retired as never }],
501
+ assignedRoleCodes: ["CIRO"],
502
+ }),
503
+ `retired = ${JSON.stringify(retired)}`,
504
+ ).toEqual([]);
505
+ }
506
+ expect(
507
+ resolve({ functions: [{ code: "session_create", tools: ["THREAD"], retired: false }], assignedRoleCodes: ["CIRO"] }),
508
+ ).toEqual(["session_create"]);
509
+ expect(
510
+ resolve({ functions: [{ code: "session_create", tools: ["THREAD"] }], assignedRoleCodes: ["CIRO"] }),
511
+ ).toEqual(["session_create"]);
512
+ });
513
+
514
+ it("malformed rows elsewhere never throw: bad role rows, catalog rows, role / agency containers fail closed", () => {
515
+ expect(
516
+ resolve({
517
+ roles: [null as never, "SUP" as never, ...roles],
518
+ functions: [null as never, { code: 5 } as never, ...functions],
519
+ assignedRoleCodes: ["CIRO", 3 as never],
520
+ }),
521
+ ).toEqual(["session_create"]);
522
+ // a role whose stored functions container is malformed grants nothing
523
+ expect(
524
+ resolve({
525
+ roles: [{ code: "CIRO", tools: ["THREAD"], functions: ["session_create"] as never }],
526
+ assignedRoleCodes: ["CIRO"],
527
+ }),
528
+ ).toEqual([]);
529
+ // a malformed agency container (whole map, or one role's entry) is NEVER for unlocked states
530
+ expect(resolve({ assignedRoleCodes: ["CIRO"], agencyOverrides: [] as never })).toEqual([]);
531
+ expect(
532
+ resolve({ assignedRoleCodes: ["CIRO"], agencyOverrides: { CIRO: "PREF_YES" as never } }),
533
+ ).toEqual([]);
534
+ // ...but locked Tier-1 states ignore it
535
+ expect(resolve({ assignedRoleCodes: ["SUP"], agencyOverrides: [] as never })).toEqual([
536
+ "case_edit",
537
+ ]);
538
+ });
539
+
540
+ it("non-array top-level inputs resolve to [] without throwing; a string is never split into characters", () => {
541
+ for (const bad of [null, undefined, 7, "CIRO", { CIRO: true }]) {
542
+ for (const field of ["roles", "functions", "assignedRoleCodes"] as const) {
543
+ const call = () => resolve({ [field]: bad as never });
544
+ expect(call, `${field} = ${JSON.stringify(bad)}`).not.toThrow();
545
+ expect(call(), `${field} = ${JSON.stringify(bad)}`).toEqual([]);
546
+ }
547
+ }
548
+ // "CIRO" as assignedRoleCodes must not become ["C","I","R","O"]: with role
549
+ // rows coded "C" / "I" a split string would grant session_create.
550
+ expect(
551
+ resolve({
552
+ roles: [
553
+ { code: "C", tools: ["THREAD"], functions: { session_create: "ALWAYS" } },
554
+ { code: "I", tools: ["THREAD"], functions: { session_create: "ALWAYS" } },
555
+ ],
556
+ assignedRoleCodes: "CIRO" as never,
557
+ }),
558
+ ).toEqual([]);
559
+ for (const input of [null, undefined, "x", 3, []]) {
560
+ expect(() => resolveEffectiveFunctions(input as never)).not.toThrow();
561
+ expect(resolveEffectiveFunctions(input as never)).toEqual([]);
562
+ }
563
+ });
564
+
565
+ it("Required from an agency escalation to ALWAYS stays immune under a malformed team policy", () => {
566
+ // SUP's session_create is platform PREF_NO; the agency escalates it to ALWAYS.
567
+ for (const junk of ["junk", ["x"], 0, new Map()]) {
568
+ expect(
569
+ resolve({
570
+ assignedRoleCodes: ["SUP"],
571
+ agencyOverrides: { SUP: { session_create: "ALWAYS" } },
572
+ teamPolicy: junk as never,
573
+ }),
574
+ `teamPolicy = ${String(junk)}`,
575
+ ).toEqual(["case_edit", "session_create"]);
576
+ }
577
+ // ...while a plain agency PREF_YES lift is still team-gated by the junk policy.
578
+ expect(
579
+ resolve({
580
+ assignedRoleCodes: ["SUP"],
581
+ agencyOverrides: { SUP: { session_create: "PREF_YES" } },
582
+ teamPolicy: "junk" as never,
583
+ }),
584
+ ).toEqual(["case_edit"]);
585
+ });
586
+
587
+ it("a malformed agency entry for role A leaves a grant from another held role B intact", () => {
588
+ // CIRO's agency entry is malformed (NEVER for CIRO's unlocked states); SUP's
589
+ // agency-lifted session_create still grants it.
590
+ expect(
591
+ resolve({
592
+ assignedRoleCodes: ["CIRO", "SUP"],
593
+ agencyOverrides: { CIRO: ["junk"] as never, SUP: { session_create: "PREF_YES" } },
594
+ }),
595
+ ).toEqual(["case_edit", "session_create"]);
596
+ // Without SUP's lift, CIRO alone loses session_create.
597
+ expect(
598
+ resolve({ assignedRoleCodes: ["CIRO"], agencyOverrides: { CIRO: ["junk"] as never } }),
599
+ ).toEqual([]);
600
+ });
601
+
602
+ it("returns a sorted, de-duplicated list", () => {
603
+ const fns = resolve({ assignedRoleCodes: ["SUP", "SUP", "MEM-ADM", "CIRO"] });
604
+ expect(fns).toEqual(["case_edit", "session_create", "usr_manage"]);
605
+ });
606
+ });
607
+
608
+ // ─── Part 3 — effective internal viewing level ──────────────────────────────
609
+
610
+ describe("effective viewing level (CVC-133 viewing_level_1/2/3 logic_notes)", () => {
611
+ const vFunctions = [
612
+ { code: "viewing_level_1_search", tools: ["PAVE"] },
613
+ { code: "viewing_level_2_autocomplete", tools: ["PAVE"] },
614
+ { code: "viewing_level_3_components", tools: ["PAVE"] },
615
+ ];
616
+ // Bounds excerpt from canon (records data/cvcs/core_functions.yaml @ f4356aa4):
617
+ // case_nav L1/L2 Always, L3 Default-On; legal_advocate L1 Default-On, L2/L3
618
+ // Default-Off; volunteer L1 Default-Off, L2/L3 Never.
619
+ const vRoles = [
620
+ {
621
+ code: "case_nav",
622
+ tools: ["PAVE"],
623
+ functions: {
624
+ viewing_level_1_search: "ALWAYS",
625
+ viewing_level_2_autocomplete: "ALWAYS",
626
+ viewing_level_3_components: "PREF_YES",
627
+ },
628
+ },
629
+ {
630
+ code: "legal_advocate",
631
+ tools: ["PAVE"],
632
+ functions: {
633
+ viewing_level_1_search: "PREF_YES",
634
+ viewing_level_2_autocomplete: "PREF_NO",
635
+ viewing_level_3_components: "PREF_NO",
636
+ },
637
+ },
638
+ {
639
+ code: "volunteer",
640
+ tools: ["PAVE"],
641
+ functions: {
642
+ viewing_level_1_search: "PREF_NO",
643
+ viewing_level_2_autocomplete: "NEVER",
644
+ viewing_level_3_components: "NEVER",
645
+ },
646
+ },
647
+ ] as const;
648
+ const v = (over: Partial<ResolveEffectiveFunctionsInput>): ResolveEffectiveFunctionsInput => ({
649
+ roles: vRoles,
650
+ functions: vFunctions,
651
+ assignedRoleCodes: [],
652
+ unknownFunctionPolicy: "deny",
653
+ ...over,
654
+ });
655
+
656
+ it("is the highest level function the seat resolves to", () => {
657
+ expect(resolveEffectiveViewingLevel(v({ assignedRoleCodes: ["case_nav"] }))).toBe(3);
658
+ expect(resolveEffectiveViewingLevel(v({ assignedRoleCodes: ["legal_advocate"] }))).toBe(1);
659
+ });
660
+
661
+ it("absence of all three is Level 0", () => {
662
+ expect(resolveEffectiveViewingLevel(v({ assignedRoleCodes: ["volunteer"] }))).toBe(0);
663
+ expect(resolveEffectiveViewingLevel(v({ assignedRoleCodes: [] }))).toBe(0);
664
+ });
665
+
666
+ it("roles union: the highest level any held role resolves to wins (a NEVER on one role does not cap another)", () => {
667
+ expect(
668
+ resolveEffectiveViewingLevel(v({ assignedRoleCodes: ["volunteer", "case_nav"] })),
669
+ ).toBe(3);
670
+ });
671
+
672
+ it("Default-Off counts once the agency enables it", () => {
673
+ expect(
674
+ resolveEffectiveViewingLevel(
675
+ v({
676
+ assignedRoleCodes: ["volunteer"],
677
+ agencyOverrides: { volunteer: { viewing_level_1_search: "PREF_YES" } },
678
+ }),
679
+ ),
680
+ ).toBe(1);
681
+ });
682
+
683
+ it("the team-set level clamps down, never up", () => {
684
+ const nav = v({ assignedRoleCodes: ["case_nav"] });
685
+ expect(resolveEffectiveViewingLevel(nav, 2)).toBe(2);
686
+ expect(resolveEffectiveViewingLevel(nav, null)).toBe(3);
687
+ const adv = v({ assignedRoleCodes: ["legal_advocate"] });
688
+ expect(resolveEffectiveViewingLevel(adv, 3)).toBe(1);
689
+ });
690
+
691
+ it("rides the same resolution: a team switching a level function off narrows it, Required levels stay", () => {
692
+ expect(
693
+ resolveEffectiveViewingLevel(
694
+ v({
695
+ assignedRoleCodes: ["case_nav"],
696
+ teamPolicy: {
697
+ functions: {
698
+ viewing_level_3_components: "PREF_NO",
699
+ viewing_level_2_autocomplete: "PREF_NO",
700
+ },
701
+ },
702
+ }),
703
+ ),
704
+ ).toBe(2); // L3 (Default-On) gated off; L2 is Always for case_nav, immune
705
+ });
706
+
707
+ it("viewingLevelFromFunctions reads an already-resolved set", () => {
708
+ expect(viewingLevelFromFunctions(["case_view", "viewing_level_2_autocomplete"])).toBe(2);
709
+ expect(viewingLevelFromFunctions(new Set<string>())).toBe(0);
710
+ expect(viewingLevelFromFunctions(["viewing_level_3_components"], 1)).toBe(1);
711
+ });
712
+ });