@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.
- package/dist/authz/index.cjs +539 -0
- package/dist/authz/index.cjs.map +1 -0
- package/dist/authz/index.d.cts +210 -0
- package/dist/authz/index.d.ts +210 -0
- package/dist/authz/index.js +507 -0
- package/dist/authz/index.js.map +1 -0
- package/dist/constants/index.d.cts +2 -1
- package/dist/constants/index.d.ts +2 -1
- package/dist/cvcs/index.cjs +936 -243
- package/dist/cvcs/index.cjs.map +1 -1
- package/dist/cvcs/index.d.cts +986 -254
- package/dist/cvcs/index.d.ts +986 -254
- package/dist/cvcs/index.js +936 -243
- package/dist/cvcs/index.js.map +1 -1
- package/dist/enums/index.cjs +37 -10
- package/dist/enums/index.cjs.map +1 -1
- package/dist/enums/index.d.cts +42 -15
- package/dist/enums/index.d.ts +42 -15
- package/dist/enums/index.js +37 -10
- package/dist/enums/index.js.map +1 -1
- package/dist/{platform-auth-CvAYFVhK.d.cts → ic-DpKrdgQP.d.cts} +1 -78
- package/dist/{platform-auth-CvAYFVhK.d.ts → ic-DpKrdgQP.d.ts} +1 -78
- package/dist/index.cjs +1328 -253
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +1313 -253
- package/dist/index.js.map +1 -1
- package/dist/platform-auth-B49Ly57B.d.cts +78 -0
- package/dist/platform-auth-B49Ly57B.d.ts +78 -0
- package/dist/schemas/index.cjs +104 -0
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +240 -1
- package/dist/schemas/index.d.ts +240 -1
- package/dist/schemas/index.js +95 -0
- package/dist/schemas/index.js.map +1 -1
- package/dist/types/index.d.cts +2 -2
- package/dist/types/index.d.ts +2 -2
- package/package.json +6 -1
- package/src/__sot__/README.md +3 -0
- package/src/__sot__/adminRoles.pin.json +122 -0
- package/src/__sot__/adminRoles.published.json +77 -0
- package/src/__sot__/coreFunctionFields.ts +137 -0
- package/src/__sot__/coreFunctions.pin.json +1659 -0
- package/src/__sot__/coreFunctions.published.json +233 -0
- package/src/__sot__/roleFields.ts +137 -0
- package/src/__sot__/userRoles.pin.json +174 -0
- package/src/__sot__/userRoles.published.json +103 -0
- package/src/__tests__/__snapshots__/cvc-sot.snap +6 -6
- package/src/__tests__/admin-roles-canon.test.ts +80 -0
- package/src/__tests__/authz-resolve.test.ts +712 -0
- package/src/__tests__/core-functions-canon.test.ts +358 -24
- package/src/__tests__/cvc-sot-snapshot.test.ts +17 -6
- package/src/__tests__/cvc-status-parser.test.ts +2 -2
- package/src/__tests__/cvc-structural.test.ts +3 -3
- package/src/__tests__/organization-program.test.ts +254 -0
- package/src/__tests__/role-vocab-gate.ts +279 -0
- package/src/__tests__/user-roles-canon.test.ts +104 -0
- package/src/authz/index.ts +9 -0
- package/src/authz/resolveEffectiveFunctions.ts +454 -0
- package/src/cvcs/adminRoles.v2.0.0.json +197 -0
- package/src/cvcs/{coreFunctions.v1.1.0.json → coreFunctions.v1.3.0.json} +646 -90
- package/src/cvcs/index.ts +3 -3
- package/src/cvcs/userRoles.v2.0.0.json +296 -0
- package/src/generated/coreFunctionsEvaluable.ts +101 -0
- package/src/generated/cvc-enums.ts +42 -15
- package/src/index.ts +4 -0
- package/src/schemas/index.ts +18 -0
- package/src/schemas/organization-program.ts +297 -0
- package/src/cvcs/adminRoles.v1.0.0.json +0 -153
- package/src/cvcs/userRoles.v1.0.0.json +0 -203
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Organization program fragment (`schemas/organization-program.ts`) — the ONE
|
|
3
|
+
* definition of `organizations.programs[]` both apps read (PAVE 2.0 writes it).
|
|
4
|
+
*
|
|
5
|
+
* Pins: the review-status vocabulary is the UDD Program object's three words;
|
|
6
|
+
* the mounted field is absent until written (no implicit `[]`); a row with a
|
|
7
|
+
* review status outside the vocabulary fails validation; the live-row rule
|
|
8
|
+
* excludes retired and rejected programs.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import mongoose, { Schema } from "mongoose";
|
|
12
|
+
import { describe, it, expect, vi } from "vitest";
|
|
13
|
+
|
|
14
|
+
import { applyRunValidatorsIfUnset } from "../schemas/agency.js";
|
|
15
|
+
import {
|
|
16
|
+
type OrganizationProgram,
|
|
17
|
+
ORGANIZATION_PROGRAM_VALIDATED_UPDATE_OPS,
|
|
18
|
+
PROGRAM_REVIEW_STATUS,
|
|
19
|
+
PROGRAM_REVIEW_STATUS_VALUES,
|
|
20
|
+
addOrganizationProgramsField,
|
|
21
|
+
buildOrganizationProgramSchema,
|
|
22
|
+
isLiveOrganizationProgram,
|
|
23
|
+
isProgramReviewStatus,
|
|
24
|
+
} from "../schemas/organization-program.js";
|
|
25
|
+
|
|
26
|
+
function modelWithPrograms(name: string, select?: boolean) {
|
|
27
|
+
const schema = new Schema({ id: String, name: String });
|
|
28
|
+
addOrganizationProgramsField(schema, select === undefined ? {} : { select });
|
|
29
|
+
return mongoose.model(name, schema);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe("review status vocabulary", () => {
|
|
33
|
+
it("is the UDD Program object's three words", () => {
|
|
34
|
+
expect([...PROGRAM_REVIEW_STATUS_VALUES]).toEqual([
|
|
35
|
+
"pending",
|
|
36
|
+
"confirmed",
|
|
37
|
+
"rejected",
|
|
38
|
+
]);
|
|
39
|
+
expect(PROGRAM_REVIEW_STATUS.PENDING).toBe("pending");
|
|
40
|
+
expect(isProgramReviewStatus("confirmed")).toBe(true);
|
|
41
|
+
// The lane's words never reach the stored row.
|
|
42
|
+
expect(isProgramReviewStatus("pending_steward")).toBe(false);
|
|
43
|
+
expect(isProgramReviewStatus("declined")).toBe(false);
|
|
44
|
+
expect(isProgramReviewStatus(null)).toBe(false);
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
describe("the mounted programs[] field", () => {
|
|
49
|
+
it("is absent until written — no implicit empty array on a fresh document", () => {
|
|
50
|
+
const Org = modelWithPrograms("OrgProgFragmentAbsent");
|
|
51
|
+
const doc = new Org({ id: "org-1", name: "Willow Bend" });
|
|
52
|
+
expect(doc.get("programs")).toBeUndefined();
|
|
53
|
+
expect(doc.toObject()).not.toHaveProperty("programs");
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("carries a program row with identity, label and the arrival facts, with no _id", () => {
|
|
57
|
+
const Org = modelWithPrograms("OrgProgFragmentRow");
|
|
58
|
+
const doc = new Org({
|
|
59
|
+
id: "org-1",
|
|
60
|
+
name: "Willow Bend",
|
|
61
|
+
programs: [
|
|
62
|
+
{
|
|
63
|
+
programId: "prog-1",
|
|
64
|
+
name: "Night Intake Unit",
|
|
65
|
+
status: "active",
|
|
66
|
+
reviewStatus: "pending",
|
|
67
|
+
addedBy: "user-1",
|
|
68
|
+
addedInApp: "pave",
|
|
69
|
+
addedInSession: "sess-1",
|
|
70
|
+
},
|
|
71
|
+
],
|
|
72
|
+
});
|
|
73
|
+
expect(doc.validateSync()).toBeUndefined();
|
|
74
|
+
const row = (
|
|
75
|
+
doc.toObject() as unknown as { programs: Record<string, unknown>[] }
|
|
76
|
+
).programs[0];
|
|
77
|
+
expect(row).toMatchObject({
|
|
78
|
+
programId: "prog-1",
|
|
79
|
+
name: "Night Intake Unit",
|
|
80
|
+
reviewStatus: "pending",
|
|
81
|
+
addedInApp: "pave",
|
|
82
|
+
});
|
|
83
|
+
expect(row).not.toHaveProperty("_id");
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("refuses a review status outside the vocabulary and a row with no identity", () => {
|
|
87
|
+
const Org = modelWithPrograms("OrgProgFragmentInvalid");
|
|
88
|
+
const bad = new Org({
|
|
89
|
+
id: "org-1",
|
|
90
|
+
programs: [{ programId: "p", name: "X", reviewStatus: "declined" }],
|
|
91
|
+
});
|
|
92
|
+
expect(bad.validateSync()?.errors["programs.0.reviewStatus"]).toBeDefined();
|
|
93
|
+
const noId = new Org({ id: "org-1", programs: [{ name: "X" }] });
|
|
94
|
+
expect(noId.validateSync()?.errors["programs.0.programId"]).toBeDefined();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("the steward's own copy carries no review status (optional, not defaulted)", () => {
|
|
98
|
+
const Org = modelWithPrograms("OrgProgFragmentSteward");
|
|
99
|
+
const doc = new Org({
|
|
100
|
+
id: "org-1",
|
|
101
|
+
programs: [{ programId: "prog-s", name: "Steward Row" }],
|
|
102
|
+
});
|
|
103
|
+
expect(doc.validateSync()).toBeUndefined();
|
|
104
|
+
const row = (
|
|
105
|
+
doc.toObject() as unknown as { programs: Record<string, unknown>[] }
|
|
106
|
+
).programs[0];
|
|
107
|
+
expect(row).not.toHaveProperty("reviewStatus");
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it("honours a consumer's `select: false` (Thread's read posture)", () => {
|
|
111
|
+
const Org = modelWithPrograms("OrgProgFragmentSelect", false);
|
|
112
|
+
expect(Org.schema.path("programs").options.select).toBe(false);
|
|
113
|
+
const sub = buildOrganizationProgramSchema();
|
|
114
|
+
expect(sub.path("programId")).toBeDefined();
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
describe("the OrganizationProgram type", () => {
|
|
119
|
+
it("represents a steward row (id + name only) and a named row; carries no _id", () => {
|
|
120
|
+
// Type-level: these assignments compile only if the inferred type has
|
|
121
|
+
// programId/name required, everything else optional, and no `_id`.
|
|
122
|
+
const steward: OrganizationProgram = { programId: "p-s", name: "Steward Row" };
|
|
123
|
+
const named: OrganizationProgram = {
|
|
124
|
+
programId: "p-n",
|
|
125
|
+
name: "Night Intake Unit",
|
|
126
|
+
reviewStatus: "pending",
|
|
127
|
+
addedBy: "user-1",
|
|
128
|
+
addedInApp: "pave",
|
|
129
|
+
addedInSession: null,
|
|
130
|
+
};
|
|
131
|
+
// @ts-expect-error — a word outside the vocabulary is not a review status
|
|
132
|
+
const bad: OrganizationProgram = { programId: "p", name: "X", reviewStatus: "approved" };
|
|
133
|
+
expect(steward.programId).toBe("p-s");
|
|
134
|
+
expect(named.reviewStatus).toBe("pending");
|
|
135
|
+
expect(bad.programId).toBe("p");
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
describe("addOrganizationProgramsField on a schema that already declares programs", () => {
|
|
140
|
+
it("replaces the path with the shared fragment and warns", () => {
|
|
141
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
142
|
+
const schema = new Schema({
|
|
143
|
+
id: String,
|
|
144
|
+
programs: { type: [new Schema({ programId: String, legacy: String })], select: false },
|
|
145
|
+
});
|
|
146
|
+
addOrganizationProgramsField(schema, { select: false });
|
|
147
|
+
expect(warn).toHaveBeenCalledTimes(1);
|
|
148
|
+
expect(schema.path("programs").options.select).toBe(false);
|
|
149
|
+
const Org = mongoose.model("OrgProgFragmentReplaced", schema);
|
|
150
|
+
const doc = new Org({ id: "o", programs: [{ programId: "p", name: "N", legacy: "x" }] });
|
|
151
|
+
expect(doc.validateSync()).toBeUndefined();
|
|
152
|
+
const row = (doc.toObject() as unknown as { programs: Record<string, unknown>[] }).programs[0];
|
|
153
|
+
expect(row).not.toHaveProperty("legacy");
|
|
154
|
+
warn.mockRestore();
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it("drops the consumer's own select:false when options are omitted — the hazard the warning names", () => {
|
|
158
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
159
|
+
const schema = new Schema({
|
|
160
|
+
id: String,
|
|
161
|
+
programs: { type: [new Schema({ programId: String })], select: false },
|
|
162
|
+
});
|
|
163
|
+
addOrganizationProgramsField(schema);
|
|
164
|
+
expect(warn).toHaveBeenCalledTimes(1);
|
|
165
|
+
expect(schema.path("programs").options.select).toBeUndefined();
|
|
166
|
+
warn.mockRestore();
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("honours select:true as well as select:false", () => {
|
|
170
|
+
const schema = addOrganizationProgramsField(new Schema({ id: String }), {
|
|
171
|
+
select: true,
|
|
172
|
+
});
|
|
173
|
+
expect(schema.path("programs").options.select).toBe(true);
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
describe("each mount gets its own sub-schema instance", () => {
|
|
178
|
+
it("a hook, virtual or index one consumer adds to its rows does not reach another consumer", () => {
|
|
179
|
+
const a = addOrganizationProgramsField(new Schema({ id: String }));
|
|
180
|
+
const b = addOrganizationProgramsField(new Schema({ id: String }));
|
|
181
|
+
const subA = a.path("programs").schema as Schema;
|
|
182
|
+
const subB = b.path("programs").schema as Schema;
|
|
183
|
+
expect(subA).not.toBe(subB);
|
|
184
|
+
subA.index({ name: 1 });
|
|
185
|
+
subA.virtual("shout").get(function (this: { name: string }) {
|
|
186
|
+
return this.name.toUpperCase();
|
|
187
|
+
});
|
|
188
|
+
expect(subB.indexes()).toHaveLength(0);
|
|
189
|
+
expect(subB.virtualpath("shout")).toBeFalsy();
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
describe("validators on the update paths", () => {
|
|
194
|
+
it("installs runValidators on updateOne / updateMany / findOneAndUpdate by default; opt-out installs nothing", () => {
|
|
195
|
+
type Hooked = { s: { hooks: { hasHooks: (n: string) => boolean } } };
|
|
196
|
+
const hooksOf = (schema: Schema) => (schema as unknown as Hooked).s.hooks;
|
|
197
|
+
const on = hooksOf(addOrganizationProgramsField(new Schema({ id: String })));
|
|
198
|
+
for (const op of ORGANIZATION_PROGRAM_VALIDATED_UPDATE_OPS)
|
|
199
|
+
expect(on.hasHooks(op), op).toBe(true);
|
|
200
|
+
expect(on.hasHooks("save")).toBe(false);
|
|
201
|
+
const off = hooksOf(
|
|
202
|
+
addOrganizationProgramsField(new Schema({ id: String }), {
|
|
203
|
+
validateOnUpdate: false,
|
|
204
|
+
}),
|
|
205
|
+
);
|
|
206
|
+
for (const op of ORGANIZATION_PROGRAM_VALIDATED_UPDATE_OPS)
|
|
207
|
+
expect(off.hasHooks(op), op).toBe(false);
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
it("the hook body sets runValidators unless the caller already decided (shared with agency.ts)", () => {
|
|
211
|
+
const q = (initial: Record<string, unknown>) => {
|
|
212
|
+
let opts = { ...initial };
|
|
213
|
+
const self = {
|
|
214
|
+
getOptions: () => opts,
|
|
215
|
+
setOptions: (o: Record<string, unknown>) => {
|
|
216
|
+
opts = { ...opts, ...o };
|
|
217
|
+
return self;
|
|
218
|
+
},
|
|
219
|
+
};
|
|
220
|
+
return self;
|
|
221
|
+
};
|
|
222
|
+
const a = q({});
|
|
223
|
+
applyRunValidatorsIfUnset(a as never);
|
|
224
|
+
expect(a.getOptions().runValidators).toBe(true);
|
|
225
|
+
const b = q({ runValidators: false });
|
|
226
|
+
applyRunValidatorsIfUnset(b as never);
|
|
227
|
+
expect(b.getOptions().runValidators).toBe(false);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it("with runValidators on, a $push row outside the vocabulary or without an id is refused by the array validator", () => {
|
|
231
|
+
// What the hook buys on a real update: Mongoose's update validator casts
|
|
232
|
+
// the $push payload against the sub-schema when runValidators is set.
|
|
233
|
+
// Exercised without a connection through the sub-schema's own validation,
|
|
234
|
+
// which is what the update validator runs for an array-of-subdoc path.
|
|
235
|
+
const Org = mongoose.model(
|
|
236
|
+
"OrgProgFragmentUpdateValidate",
|
|
237
|
+
addOrganizationProgramsField(new Schema({ id: String })),
|
|
238
|
+
);
|
|
239
|
+
const bad = new Org({ id: "o", programs: [{ programId: "p", name: "X", reviewStatus: "declined" }] });
|
|
240
|
+
expect(bad.validateSync()?.errors["programs.0.reviewStatus"]).toBeDefined();
|
|
241
|
+
const noId = new Org({ id: "o", programs: [{ name: "X" }] });
|
|
242
|
+
expect(noId.validateSync()?.errors["programs.0.programId"]).toBeDefined();
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
describe("isLiveOrganizationProgram", () => {
|
|
247
|
+
it("offers active / confirmed / pending rows, never retired or rejected ones", () => {
|
|
248
|
+
expect(isLiveOrganizationProgram({ status: "active" })).toBe(true);
|
|
249
|
+
expect(isLiveOrganizationProgram({ reviewStatus: "pending" })).toBe(true);
|
|
250
|
+
expect(isLiveOrganizationProgram({})).toBe(true);
|
|
251
|
+
expect(isLiveOrganizationProgram({ status: "retired" })).toBe(false);
|
|
252
|
+
expect(isLiveOrganizationProgram({ reviewStatus: "rejected" })).toBe(false);
|
|
253
|
+
});
|
|
254
|
+
});
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared body of GATE J (CVC-135 user roles) and GATE K (CVC-134 admin roles):
|
|
3
|
+
* the generated SOT restates its canon pin, whole.
|
|
4
|
+
*
|
|
5
|
+
* Both SOTs are generated by `scripts/role_vocab.py` (via `gen-user-roles.py` /
|
|
6
|
+
* `gen-admin-roles.py`), so both gates assert the same contract; each gate's own
|
|
7
|
+
* file adds the vocabulary-specific checks. Not a test file itself (no
|
|
8
|
+
* `.test.ts` suffix): vitest collects only the two callers.
|
|
9
|
+
*/
|
|
10
|
+
import { readFileSync } from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { describe, it, expect } from "vitest";
|
|
14
|
+
|
|
15
|
+
import { sotFieldName } from "../__sot__/roleFields.js";
|
|
16
|
+
|
|
17
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
18
|
+
export const cvcDir = path.join(here, "..", "cvcs");
|
|
19
|
+
const sotDir = path.join(here, "..", "__sot__");
|
|
20
|
+
|
|
21
|
+
export interface RoleEntry {
|
|
22
|
+
code: string;
|
|
23
|
+
key: string;
|
|
24
|
+
title: string;
|
|
25
|
+
selectable: boolean;
|
|
26
|
+
parentCode: string | null;
|
|
27
|
+
childCodes: string[];
|
|
28
|
+
definition: string | null;
|
|
29
|
+
canonicalCode?: string;
|
|
30
|
+
definitionNote?: string;
|
|
31
|
+
[extra: string]: unknown;
|
|
32
|
+
}
|
|
33
|
+
export interface RoleEnvelope {
|
|
34
|
+
domain: string;
|
|
35
|
+
version: string;
|
|
36
|
+
_status: string;
|
|
37
|
+
_source: string;
|
|
38
|
+
_supersedes: {
|
|
39
|
+
version: string;
|
|
40
|
+
keyMap: Record<string, string | null>;
|
|
41
|
+
retiredCodes: { code: string; key: string; successor: null; reason: string }[];
|
|
42
|
+
notes: Record<string, string>;
|
|
43
|
+
appended: string[];
|
|
44
|
+
refreshed: string[];
|
|
45
|
+
tombstoned: string[];
|
|
46
|
+
};
|
|
47
|
+
levels: Record<string, string>;
|
|
48
|
+
entries: RoleEntry[];
|
|
49
|
+
}
|
|
50
|
+
export interface RolePin {
|
|
51
|
+
sourceRepo: string;
|
|
52
|
+
sourceFile: string;
|
|
53
|
+
sourceSha: string;
|
|
54
|
+
codes: string[];
|
|
55
|
+
roleFields: Record<string, Record<string, unknown>>;
|
|
56
|
+
legacyCodes: Record<string, string>;
|
|
57
|
+
}
|
|
58
|
+
export interface RoleLedger {
|
|
59
|
+
prefixes: Record<string, number>;
|
|
60
|
+
since: Record<string, string>;
|
|
61
|
+
renamed: Record<string, { to: string; prefix: number; version: string }>;
|
|
62
|
+
aliases: Record<string, { to: string; canonical: string; version: string }>;
|
|
63
|
+
retired: Record<string, { code: string; successor: null; reason: string; version: string }>;
|
|
64
|
+
supersededKeys: string[];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface RoleGateConfig {
|
|
68
|
+
gate: string;
|
|
69
|
+
domain: string;
|
|
70
|
+
/** Segment-0 CVC prefix, e.g. "135". */
|
|
71
|
+
prefix: string;
|
|
72
|
+
/** `userRoles` / `adminRoles`. */
|
|
73
|
+
stem: string;
|
|
74
|
+
version: string;
|
|
75
|
+
supersededVersion: string;
|
|
76
|
+
canonFile: string;
|
|
77
|
+
roleCount: number;
|
|
78
|
+
/** Canon code -> package key. */
|
|
79
|
+
keyOf: (canonCode: string) => string;
|
|
80
|
+
/** The generated enum for this domain. */
|
|
81
|
+
keys: Readonly<Record<string, string>>;
|
|
82
|
+
/** The barrel export for this domain. */
|
|
83
|
+
barrel: unknown;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const BASE_FIELDS = new Set([
|
|
87
|
+
"code",
|
|
88
|
+
"key",
|
|
89
|
+
"title",
|
|
90
|
+
"selectable",
|
|
91
|
+
"parentCode",
|
|
92
|
+
"childCodes",
|
|
93
|
+
"definition",
|
|
94
|
+
"canonicalCode",
|
|
95
|
+
"definitionNote",
|
|
96
|
+
]);
|
|
97
|
+
const MISSINGNESS_KEYS = ["missingness_root", "unknown", "anonymous", "data_not_collected"];
|
|
98
|
+
|
|
99
|
+
export function loadRoleVocab(cfg: RoleGateConfig): {
|
|
100
|
+
sot: RoleEnvelope;
|
|
101
|
+
pin: RolePin;
|
|
102
|
+
ledger: RoleLedger;
|
|
103
|
+
} {
|
|
104
|
+
const read = <T>(p: string): T => JSON.parse(readFileSync(p, "utf8")) as T;
|
|
105
|
+
return {
|
|
106
|
+
sot: read<RoleEnvelope>(path.join(cvcDir, `${cfg.stem}.v${cfg.version}.json`)),
|
|
107
|
+
pin: read<RolePin>(path.join(sotDir, `${cfg.stem}.pin.json`)),
|
|
108
|
+
ledger: read<RoleLedger>(path.join(sotDir, `${cfg.stem}.published.json`)),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* How a consumer resolves a stored role value: a live key, else `_supersedes.keyMap` (null = withdrawn).
|
|
114
|
+
* The keyMap is KEY-SPACE (the package convention), so a value stored in canon's spelling
|
|
115
|
+
* (`ACCT-ADM`, `MEM-ADM`) is first normalised with the codeset's key rule (`cfg.keyOf`).
|
|
116
|
+
*/
|
|
117
|
+
export function resolveStoredKey(cfg: RoleGateConfig, stored: string): string | undefined {
|
|
118
|
+
const key = stored in cfg.keys || stored in (cfg.barrel as RoleEnvelope)._supersedes.keyMap
|
|
119
|
+
? stored
|
|
120
|
+
: cfg.keyOf(stored);
|
|
121
|
+
if (key in cfg.keys) return cfg.keys[key];
|
|
122
|
+
const live = (cfg.barrel as RoleEnvelope)._supersedes.keyMap[key];
|
|
123
|
+
return live ? cfg.keys[live] : undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function describeRoleVocabGate(cfg: RoleGateConfig): void {
|
|
127
|
+
const { sot, pin, ledger } = loadRoleVocab(cfg);
|
|
128
|
+
const flatRe = new RegExp(`^${cfg.prefix}-(\\d{3})-000-000-000-000-000$`);
|
|
129
|
+
const codeOf = (n: number): string => `${cfg.prefix}-${String(n).padStart(3, "0")}-000-000-000-000-000`;
|
|
130
|
+
const byKey = new Map(sot.entries.map((e) => [e.key, e] as const));
|
|
131
|
+
|
|
132
|
+
describe(`${cfg.domain} — ${cfg.gate}: the SOT restates canon (${pin.sourceFile} @ the pin)`, () => {
|
|
133
|
+
it(`is the generated file, at ${cfg.version}, superseding ${cfg.supersededVersion} (which is gone)`, () => {
|
|
134
|
+
expect(sot.domain).toBe(cfg.domain);
|
|
135
|
+
expect(sot.version).toBe(cfg.version);
|
|
136
|
+
expect(sot._status).toMatch(/^CANONICAL — /);
|
|
137
|
+
expect(sot._status).toContain("GENERATED");
|
|
138
|
+
expect(sot._source).toContain(pin.sourceFile);
|
|
139
|
+
expect(sot._supersedes.version).toBe(cfg.supersededVersion);
|
|
140
|
+
expect(() => readFileSync(path.join(cvcDir, `${cfg.stem}.v${cfg.supersededVersion}.json`))).toThrow();
|
|
141
|
+
expect((cfg.barrel as RoleEnvelope).version, "the barrel exports THIS file").toBe(cfg.version);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("pins canon's codeset", () => {
|
|
145
|
+
expect(pin.sourceRepo).toBe("htilabstech/prototype");
|
|
146
|
+
expect(pin.sourceFile).toBe(cfg.canonFile);
|
|
147
|
+
expect(Object.keys(pin.roleFields).sort()).toEqual(pin.codes);
|
|
148
|
+
expect(pin.codes).toHaveLength(cfg.roleCount);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it("carries EVERY canon role and NOTHING canon does not; canonicalCode is canon's code", () => {
|
|
152
|
+
expect([...byKey.keys()].sort(), "SOT keys vs canon codes").toEqual(pin.codes.map(cfg.keyOf).sort());
|
|
153
|
+
expect(sot.entries).toHaveLength(pin.codes.length);
|
|
154
|
+
for (const code of pin.codes) {
|
|
155
|
+
expect(byKey.get(cfg.keyOf(code))?.canonicalCode, code).toBe(code);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it("restates every projected canon field verbatim, and invents none", () => {
|
|
160
|
+
const bad: string[] = [];
|
|
161
|
+
for (const code of pin.codes) {
|
|
162
|
+
const f = pin.roleFields[code]!;
|
|
163
|
+
const e = byKey.get(cfg.keyOf(code))!;
|
|
164
|
+
if (!e.selectable) bad.push(`${code}: live canon role is not selectable`);
|
|
165
|
+
if (e.title !== f["label"]) bad.push(`${code}: title ${JSON.stringify(e.title)} != canon label`);
|
|
166
|
+
// A canon definition's trailing NOTE paragraph rides as definitionNote; the join is canon's text.
|
|
167
|
+
const joined = e.definitionNote === undefined ? e.definition : `${e.definition} ${e.definitionNote}`;
|
|
168
|
+
if (joined !== f["definition"]) bad.push(`${code}: definition (+ definitionNote) != canon`);
|
|
169
|
+
if (e.definitionNote !== undefined && !e.definitionNote.startsWith("NOTE: "))
|
|
170
|
+
bad.push(`${code}: definitionNote is not canon's NOTE paragraph`);
|
|
171
|
+
if (e.definitionNote === undefined && (f["definition"] as string).includes(" NOTE: "))
|
|
172
|
+
bad.push(`${code}: canon's NOTE paragraph was left in the definition`);
|
|
173
|
+
for (const [field, value] of Object.entries(f)) {
|
|
174
|
+
if (field === "label" || field === "definition") continue;
|
|
175
|
+
const sotName = sotFieldName(field);
|
|
176
|
+
if (value === null) {
|
|
177
|
+
if (sotName in e) bad.push(`${code}: carries ${sotName}, canon has no ${field}`);
|
|
178
|
+
} else if (JSON.stringify(e[sotName]) !== JSON.stringify(value)) {
|
|
179
|
+
bad.push(`${code}: ${sotName} ${JSON.stringify(e[sotName])} != canon ${field} ${JSON.stringify(value)}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const allowed = new Set([...BASE_FIELDS, ...Object.keys(f).map(sotFieldName)]);
|
|
183
|
+
for (const k of Object.keys(e)) if (!allowed.has(k)) bad.push(`${code}: field ${k} is not canon's`);
|
|
184
|
+
}
|
|
185
|
+
expect(bad).toEqual([]);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it("is flat and append-only: every role at a flat code, contiguous from 001", () => {
|
|
189
|
+
const prefixes = sot.entries.map((e) => {
|
|
190
|
+
const m = flatRe.exec(e.code);
|
|
191
|
+
expect(m, `${e.key} at ${e.code} is not a flat segment-1 code`).not.toBeNull();
|
|
192
|
+
expect(e.parentCode).toBeNull();
|
|
193
|
+
expect(e.childCodes).toEqual([]);
|
|
194
|
+
return Number(m![1]);
|
|
195
|
+
});
|
|
196
|
+
expect(prefixes).toEqual(prefixes.map((_, i) => i + 1));
|
|
197
|
+
expect(sot.levels).toEqual({ "1": expect.any(String) });
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("keeps every published code where it was — the ledger, pair by pair (consumers gate on the key)", () => {
|
|
201
|
+
const bad: string[] = [];
|
|
202
|
+
for (const [key, prefix] of Object.entries(ledger.prefixes)) {
|
|
203
|
+
const e = byKey.get(key);
|
|
204
|
+
if (!e) bad.push(`${key}: published at ${codeOf(prefix)} but absent from the SOT`);
|
|
205
|
+
else if (e.code !== codeOf(prefix)) bad.push(`${key}: published at ${codeOf(prefix)}, SOT has ${e.code}`);
|
|
206
|
+
if (cfg.keys[key] !== codeOf(prefix)) bad.push(`${key}: generated enum != ${codeOf(prefix)}`);
|
|
207
|
+
}
|
|
208
|
+
for (const e of sot.entries) if (!(e.key in ledger.prefixes)) bad.push(`${e.key}: in the SOT but not in the ledger`);
|
|
209
|
+
expect(bad).toEqual([]);
|
|
210
|
+
expect(Object.keys(cfg.keys).sort()).toEqual(Object.keys(ledger.prefixes).sort());
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it("carries NO missingness: the quadruplet is withdrawn as retirements, never reused", () => {
|
|
214
|
+
expect(sot.entries.filter((e) => e.code.startsWith(`${cfg.prefix}-000-`))).toEqual([]);
|
|
215
|
+
// Version-agnostic: the ledger's `retired` set is enforced on every version; the per-version
|
|
216
|
+
// record (`retiredCodes`, the missingness note) only in the version the retirement happened.
|
|
217
|
+
for (const k of MISSINGNESS_KEYS) expect(k in ledger.retired, `${k} is retired in the ledger`).toBe(true);
|
|
218
|
+
const live = new Set(sot.entries.map((e) => e.code));
|
|
219
|
+
for (const [key, r] of Object.entries(ledger.retired)) {
|
|
220
|
+
expect(r.code.startsWith(`${cfg.prefix}-000-`), key).toBe(true);
|
|
221
|
+
expect(live.has(r.code), `${key}'s code ${r.code} is reused`).toBe(false);
|
|
222
|
+
expect(key in cfg.keys, `${key} is still in the enum`).toBe(false);
|
|
223
|
+
expect(sot._supersedes.keyMap[key], `${key} keyMap`).toBeNull();
|
|
224
|
+
expect(resolveStoredKey(cfg, key), `a stored ${key}`).toBeUndefined();
|
|
225
|
+
}
|
|
226
|
+
const retiredNow = Object.entries(ledger.retired).filter(
|
|
227
|
+
([, r]) => r.version === cfg.version,
|
|
228
|
+
);
|
|
229
|
+
expect(sot._supersedes.retiredCodes).toEqual(
|
|
230
|
+
retiredNow.map(([key, r]) => ({ code: r.code, key, successor: null, reason: r.reason })),
|
|
231
|
+
);
|
|
232
|
+
if (retiredNow.length > 0) {
|
|
233
|
+
expect(sot._supersedes.retiredCodes.length).toBeGreaterThan(0);
|
|
234
|
+
expect(sot._supersedes.notes["missingness"]).toMatch(/^WITHDRAWN: /);
|
|
235
|
+
} else {
|
|
236
|
+
expect(sot._supersedes.notes["missingness"]).toBeUndefined();
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it("every canon legacy_codes line resolves: a published old key re-keyed in place, the rest aliased", () => {
|
|
241
|
+
const canonLegacy = Object.entries(pin.legacyCodes).map(
|
|
242
|
+
([o, n]) => [cfg.keyOf(o), cfg.keyOf(n)] as const,
|
|
243
|
+
);
|
|
244
|
+
const recorded = {
|
|
245
|
+
...Object.fromEntries(Object.entries(ledger.renamed).map(([o, r]) => [o, r.to])),
|
|
246
|
+
...Object.fromEntries(Object.entries(ledger.aliases).map(([o, a]) => [o, a.to])),
|
|
247
|
+
};
|
|
248
|
+
expect(recorded, "ledger renamed + aliases == canon legacy_codes").toEqual(Object.fromEntries(canonLegacy));
|
|
249
|
+
for (const [old, r] of Object.entries(ledger.renamed)) {
|
|
250
|
+
expect(ledger.prefixes[r.to], `${r.to} took ${old}'s prefix`).toBe(r.prefix);
|
|
251
|
+
expect(old in ledger.prefixes, `${old} no longer holds a prefix`).toBe(false);
|
|
252
|
+
expect(sot._supersedes.notes[old]).toMatch(/^RE-KEYED IN PLACE in \d+\.\d+\.\d+: /);
|
|
253
|
+
}
|
|
254
|
+
for (const [old, a] of Object.entries(ledger.aliases)) {
|
|
255
|
+
expect(old in ledger.prefixes || old in ledger.retired, `${old} was never published`).toBe(false);
|
|
256
|
+
expect(cfg.keyOf(a.canonical)).toBe(old);
|
|
257
|
+
expect(sot._supersedes.notes[old]).toMatch(/^LEGACY ALIAS \(since \d+\.\d+\.\d+\): /);
|
|
258
|
+
expect(resolveStoredKey(cfg, a.canonical), `canon's spelling ${a.canonical}`).toBe(cfg.keys[a.to]);
|
|
259
|
+
}
|
|
260
|
+
for (const [old, live] of canonLegacy) {
|
|
261
|
+
expect(old in cfg.keys, `${old} is not a live key`).toBe(false);
|
|
262
|
+
expect(resolveStoredKey(cfg, old), `a stored ${old}`).toBe(cfg.keys[live]);
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it(`_supersedes.keyMap is CUMULATIVE: every ${cfg.supersededVersion} key, plus every re-key, alias and retirement the ledger has ever recorded`, () => {
|
|
267
|
+
const expected: Record<string, string | null> = {};
|
|
268
|
+
for (const k of ledger.supersededKeys) {
|
|
269
|
+
expected[k] = k in ledger.retired ? null : (ledger.renamed[k]?.to ?? k);
|
|
270
|
+
}
|
|
271
|
+
for (const [old, r] of Object.entries(ledger.renamed)) expected[old] = r.to;
|
|
272
|
+
for (const [old, a] of Object.entries(ledger.aliases)) expected[old] = a.to;
|
|
273
|
+
for (const k of Object.keys(ledger.retired)) expected[k] = null;
|
|
274
|
+
expect(sot._supersedes.keyMap).toEqual(expected);
|
|
275
|
+
expect(sot._supersedes.appended).toEqual([]);
|
|
276
|
+
expect(sot._supersedes.tombstoned).toEqual([]);
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* USER ROLES (CVC-135) — GATE J: the SOT restates canon, whole
|
|
3
|
+
* =============================================================
|
|
4
|
+
*
|
|
5
|
+
* `src/cvcs/userRoles.v2.0.0.json` is GENERATED from the canonical CVC-135
|
|
6
|
+
* codeset (`htilabstech/prototype` `data/cvcs/core_user_role.yaml`) by
|
|
7
|
+
* `scripts/gen-user-roles.py`. This test is the hermetic enforcer: it asserts
|
|
8
|
+
* the shipped SOT conforms to `src/__sot__/userRoles.pin.json` (the canon
|
|
9
|
+
* snapshot `scripts/sot-pins.ts` takes at a SHA), on every PR, with no
|
|
10
|
+
* cross-repo auth. `npm run sot:pins:check` is the detector that notices when
|
|
11
|
+
* canon itself has moved. The shared contract lives in `role-vocab-gate.ts`
|
|
12
|
+
* (GATE K, CVC-134 admin roles, asserts the same one); this file adds the
|
|
13
|
+
* CVC-135 specifics.
|
|
14
|
+
*
|
|
15
|
+
* History it closes: the 1.0.0 file was hand-imported in 0.8.13 from the June
|
|
16
|
+
* Notion export and validated against itself. Canon re-keyed the Crisis
|
|
17
|
+
* Response role `hotline_op` -> `crisis_response` (yaml `legacy_codes`, roster
|
|
18
|
+
* re-keyed 2026-08-14) and changed 6 published titles (5 plus the re-keyed
|
|
19
|
+
* Crisis Response's own) and 13 definitions on 2026-09-06
|
|
20
|
+
* (CVC134-135-AUDIT); nothing failed, while canon CVC-133 bounds named
|
|
21
|
+
* `crisis_response` on 35 functions the package could not resolve.
|
|
22
|
+
*/
|
|
23
|
+
import { describe, it, expect } from "vitest";
|
|
24
|
+
|
|
25
|
+
import { UserRoleKeys } from "../generated/cvc-enums.js";
|
|
26
|
+
import { userRolesSot } from "../cvcs/index.js";
|
|
27
|
+
import { describeRoleVocabGate, loadRoleVocab, resolveStoredKey, type RoleGateConfig } from "./role-vocab-gate.js";
|
|
28
|
+
|
|
29
|
+
const cfg: RoleGateConfig = {
|
|
30
|
+
gate: "GATE J",
|
|
31
|
+
domain: "user_roles",
|
|
32
|
+
prefix: "135",
|
|
33
|
+
stem: "userRoles",
|
|
34
|
+
version: "2.0.0",
|
|
35
|
+
supersededVersion: "1.0.0",
|
|
36
|
+
canonFile: "data/cvcs/core_user_role.yaml",
|
|
37
|
+
roleCount: 15,
|
|
38
|
+
keyOf: (code) => code,
|
|
39
|
+
keys: UserRoleKeys,
|
|
40
|
+
barrel: userRolesSot,
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
describeRoleVocabGate(cfg);
|
|
44
|
+
|
|
45
|
+
describe("user_roles — GATE J: CVC-135 specifics", () => {
|
|
46
|
+
const { sot, ledger } = loadRoleVocab(cfg);
|
|
47
|
+
const CRISIS_CODE = "135-004-000-000-000-000-000";
|
|
48
|
+
|
|
49
|
+
it("every published code is frozen: the 1.0.0 key -> code table, hotline_op's slot now crisis_response", () => {
|
|
50
|
+
// Literal, NOT derived from the ledger: the 1.0.0 file is deleted, so this table is the only record
|
|
51
|
+
// independent of userRoles.published.json. A ledger edit that moves a published key fails here.
|
|
52
|
+
expect(Object.entries(UserRoleKeys)).toEqual(
|
|
53
|
+
[
|
|
54
|
+
"case_nav",
|
|
55
|
+
"healthcare_provider_medical",
|
|
56
|
+
"behavioral_health_provider",
|
|
57
|
+
"crisis_response", // 1.0.0 `hotline_op`, re-keyed in place
|
|
58
|
+
"intel_analyst",
|
|
59
|
+
"investigator",
|
|
60
|
+
"le_liaison_vsp",
|
|
61
|
+
"legal_advocate",
|
|
62
|
+
"mandatory_reporter",
|
|
63
|
+
"mdt_participant",
|
|
64
|
+
"prosecutor_review",
|
|
65
|
+
"public_reporter",
|
|
66
|
+
"research_analytics",
|
|
67
|
+
"screener",
|
|
68
|
+
"volunteer",
|
|
69
|
+
].map((k, i) => [k, `135-${String(i + 1).padStart(3, "0")}-000-000-000-000-000`]),
|
|
70
|
+
);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("re-keys hotline_op -> crisis_response at 135-004, and a stored hotline_op still resolves", () => {
|
|
74
|
+
expect(UserRoleKeys.crisis_response).toBe(CRISIS_CODE);
|
|
75
|
+
expect(sot.entries.find((e) => e.key === "crisis_response")?.title).toBe("Crisis Response");
|
|
76
|
+
expect(ledger.renamed).toEqual({ hotline_op: { to: "crisis_response", prefix: 4, version: "2.0.0" } });
|
|
77
|
+
expect(sot._supersedes.keyMap["hotline_op"]).toBe("crisis_response");
|
|
78
|
+
expect(resolveStoredKey(cfg, "hotline_op")).toBe(CRISIS_CODE);
|
|
79
|
+
expect(resolveStoredKey(cfg, "crisis_response")).toBe(CRISIS_CODE);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("aliases canon's never-published legacy codes case_advocate and leads_investigator", () => {
|
|
83
|
+
expect(Object.keys(ledger.aliases).sort()).toEqual(["case_advocate", "leads_investigator"]);
|
|
84
|
+
expect(resolveStoredKey(cfg, "case_advocate")).toBe(UserRoleKeys.case_nav);
|
|
85
|
+
expect(resolveStoredKey(cfg, "leads_investigator")).toBe(UserRoleKeys.investigator);
|
|
86
|
+
// Canon's retired_never_canonical strings are deliberately NOT aliased: they must fail, not resolve.
|
|
87
|
+
for (const never of ["platform_admin", "case_navigator", "advocate"]) {
|
|
88
|
+
expect(resolveStoredKey(cfg, never), never).toBeUndefined();
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("_supersedes.refreshed (2.0.0 over 1.0.0) names exactly the roles whose title or definition canon changed", () => {
|
|
93
|
+
if (sot._supersedes.version !== "1.0.0") return; // a per-bump record; re-derived for each bump
|
|
94
|
+
expect(sot._supersedes.refreshed).toHaveLength(14);
|
|
95
|
+
expect(sot._supersedes.refreshed).not.toContain("intel_analyst");
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it("carries canon's platform_tools on every role and the HTI-only flag on research_analytics", () => {
|
|
99
|
+
for (const e of sot.entries) expect(Array.isArray(e["platformTools"]), e.key).toBe(true);
|
|
100
|
+
expect(sot.entries.filter((e) => "flags" in e).map((e) => [e.key, e["flags"]])).toEqual([
|
|
101
|
+
["research_analytics", ["HTI-only"]],
|
|
102
|
+
]);
|
|
103
|
+
});
|
|
104
|
+
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @htilabs/platform-common-models/authz
|
|
3
|
+
*
|
|
4
|
+
* Browser-safe entry for the shared CVC-133 authorization resolver: pure
|
|
5
|
+
* TypeScript, no mongoose, no I/O. Also re-exported from the package root
|
|
6
|
+
* (which loads mongoose-backed models and services).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export * from "./resolveEffectiveFunctions.js";
|