@pegasimed.com/pegasi-sail-connect-shared 0.2.0-dev.0 → 0.2.0-dev.10

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 (48) hide show
  1. package/README.md +273 -37
  2. package/dist/authorization/index.d.ts +1 -0
  3. package/dist/authorization/index.d.ts.map +1 -1
  4. package/dist/authorization/index.js +1 -0
  5. package/dist/authorization/index.js.map +1 -1
  6. package/dist/authorization/work-grants.d.ts +151 -0
  7. package/dist/authorization/work-grants.d.ts.map +1 -0
  8. package/dist/authorization/work-grants.js +306 -0
  9. package/dist/authorization/work-grants.js.map +1 -0
  10. package/dist/authorization-testing.d.ts +229 -0
  11. package/dist/authorization-testing.d.ts.map +1 -0
  12. package/dist/authorization-testing.js +744 -0
  13. package/dist/authorization-testing.js.map +1 -0
  14. package/dist/capabilities/canonical-json.d.ts +3 -0
  15. package/dist/capabilities/canonical-json.d.ts.map +1 -0
  16. package/dist/capabilities/canonical-json.js +83 -0
  17. package/dist/capabilities/canonical-json.js.map +1 -0
  18. package/dist/capabilities/catalog-data.d.ts +575 -291
  19. package/dist/capabilities/catalog-data.d.ts.map +1 -1
  20. package/dist/capabilities/catalog-data.js +604 -303
  21. package/dist/capabilities/catalog-data.js.map +1 -1
  22. package/dist/capabilities/catalog.d.ts.map +1 -1
  23. package/dist/capabilities/catalog.js +4 -4
  24. package/dist/capabilities/catalog.js.map +1 -1
  25. package/dist/capabilities/index.d.ts +4 -0
  26. package/dist/capabilities/index.d.ts.map +1 -1
  27. package/dist/capabilities/index.js +7 -0
  28. package/dist/capabilities/index.js.map +1 -1
  29. package/dist/capabilities/migration-data.d.ts +105 -190
  30. package/dist/capabilities/migration-data.d.ts.map +1 -1
  31. package/dist/capabilities/migration-data.js +83 -144
  32. package/dist/capabilities/migration-data.js.map +1 -1
  33. package/dist/capabilities/migration.d.ts +20 -20
  34. package/dist/capabilities/migration.d.ts.map +1 -1
  35. package/dist/capabilities/migration.js +25 -40
  36. package/dist/capabilities/migration.js.map +1 -1
  37. package/dist/capabilities/sha256.d.ts +18 -0
  38. package/dist/capabilities/sha256.d.ts.map +1 -0
  39. package/dist/capabilities/sha256.js +180 -0
  40. package/dist/capabilities/sha256.js.map +1 -0
  41. package/dist/capabilities/types.d.ts +3 -2
  42. package/dist/capabilities/types.d.ts.map +1 -1
  43. package/dist/worker-logger.d.ts +46 -4
  44. package/dist/worker-logger.d.ts.map +1 -1
  45. package/dist/worker-logger.js +33 -11
  46. package/dist/worker-logger.js.map +1 -1
  47. package/package.json +7 -3
  48. package/scripts/check-service-keys.mjs +30 -7
@@ -0,0 +1,744 @@
1
+ // Node-only test helper of the `./authorization/testing` subpath (PKG-09).
2
+ //
3
+ // Signs an Access internal authorization token v2 (HS256) for fixtures and
4
+ // smokes of the services, with exactly the shape Access signs
5
+ // (signInternalAuthorizationToken, access-api src/seed-auth.ts:596-635, plus
6
+ // the capabilityCatalogVersion claim of the cut), and refuses to sign any
7
+ // claim set that this package's own reader and work-grant validator, or the
8
+ // Access signer, would refuse. It uses node:crypto, so it is not part of the
9
+ // browser-safe subpaths (`./capabilities`, `./authorization`) nor of the root
10
+ // export, and nothing in those imports it.
11
+ //
12
+ // Threat model. This is a TEST helper: the test process and its runtime are
13
+ // trusted (code that can alter the built-ins, the clock or proxies inside the
14
+ // process can already sign anything with the test secret). What the helper
15
+ // guarantees is that no hostile or malformed INPUT VALUE produces signed bytes
16
+ // other than the ones it validated:
17
+ //
18
+ // 1. Hostile input values (DEFENDED): holes, undefined or accessor elements and
19
+ // accessor lengths in lists, getters and setters, inherited fields, records
20
+ // whose prototype is not Object.prototype or null, symbol keys, a toJSON of
21
+ // the input, proxies whose traps lie or throw any value (a revoked proxy
22
+ // included). The copy step reads the whole input once, through primordials
23
+ // captured when this module loads, into null-prototype records and own
24
+ // dense arrays built with Object.defineProperty, and also reads Date.now()
25
+ // once when nowSeconds is absent (a finite primitive number, used as data).
26
+ // Everything after it reads only the copies: no external code (input traps,
27
+ // getters, valueOf/toString, Date.now) runs after the copy.
28
+ // 2. Defence in depth: the payload is serialized by a serializer of its own
29
+ // (JSON.stringify only ever receives a primitive string, which never looks
30
+ // up toJSON), in Access's field order, then parsed back and serialized
31
+ // again; base64url is computed here and the HMAC methods were captured at
32
+ // load. Internal rejections are recognised by identity (a module WeakSet),
33
+ // never with instanceof on a thrown value.
34
+ // 3. Built-ins: TRUSTED, with a cheap structural fail-closed check (belt and
35
+ // braces, not a security boundary): before and after the copy and before
36
+ // signing, `builtins-tampered` if Object.prototype or Array.prototype has an
37
+ // index key or an accessor other than __proto__, or if the Object, Array,
38
+ // String, Number, Boolean, BigInt, Symbol or Function prototype has toJSON.
39
+ // Nothing else is compared, so spies (vi.spyOn(JSON, "stringify")),
40
+ // polyfills and methods added to the built-ins do not make it refuse.
41
+ import { createHmac } from "node:crypto";
42
+ import { AUTHORIZATION_SCHEMA_VERSION, INTERNAL_AUTHORIZATION_TOKEN_USE, readInternalAuthorization } from "./authorization/internal-authorization.js";
43
+ import { validateWorkGrantsV2, workGrantId } from "./authorization/work-grants.js";
44
+ import { CAPABILITY_CATALOG_VERSION } from "./capabilities/catalog-data.js";
45
+ import { findUnknownPermissionKeys, getCapability } from "./capabilities/catalog.js";
46
+ import { MAX_LIST_LENGTH } from "./capabilities/list.js";
47
+ /** `iss` of the internal authorization token (access-api src/seed-config.ts:656-658, default of INTERNAL_AUTHORIZATION_ISSUER). */
48
+ export const INTERNAL_AUTHORIZATION_ISSUER = "sail-connect-access-api";
49
+ /** `aud` of the internal authorization token (access-api src/seed-config.ts:656-658, default of INTERNAL_AUTHORIZATION_AUDIENCE). */
50
+ export const INTERNAL_AUTHORIZATION_AUDIENCE = "pegasi-internal-upstreams";
51
+ /**
52
+ * Shortest lifetime of a token Access signs. INTERNAL_AUTHORIZATION_TTL_SECONDS
53
+ * is clamped to [5, 60] (seed-config.ts:451-456), but exp = min(session
54
+ * absoluteExpiresAt, now + ttl) (seed-auth.ts:603), so a token of a session
55
+ * about to end lives from 1 s up: the only rule is exp > iat.
56
+ */
57
+ export const MIN_INTERNAL_AUTHORIZATION_TTL_SECONDS = 1;
58
+ /** Longest lifetime Access signs and accepts (exp - iat <= 60). Also the default. */
59
+ export const MAX_INTERNAL_AUTHORIZATION_TTL_SECONDS = 60;
60
+ /** Shortest HS256 secret, in UTF-8 bytes (the default minimum of verifyHs256Jwt in ./jwt). */
61
+ export const MIN_TEST_SECRET_BYTES = 32;
62
+ /** Stable code of TestInternalAuthorizationInvalidError. */
63
+ export const TEST_INTERNAL_AUTHORIZATION_INVALID = "TEST_INTERNAL_AUTHORIZATION_INVALID";
64
+ const getOwnDescriptor = Object.getOwnPropertyDescriptor;
65
+ const defineProperty = Object.defineProperty;
66
+ const getPrototypeOf = Object.getPrototypeOf;
67
+ const createObject = Object.create;
68
+ const freeze = Object.freeze;
69
+ const isFrozen = Object.isFrozen;
70
+ const hasOwn = Object.hasOwn;
71
+ const ownKeys = Reflect.ownKeys;
72
+ const apply = Reflect.apply;
73
+ const isArray = Array.isArray;
74
+ const isSafeInteger = Number.isSafeInteger;
75
+ const jsonStringify = JSON.stringify;
76
+ const jsonParse = JSON.parse;
77
+ const floor = Math.floor;
78
+ const isFinite = Number.isFinite;
79
+ // The own data value of `key` (never inherited, never a getter run): undefined when absent or an accessor.
80
+ function ownValue(target, key) {
81
+ const descriptor = getOwnDescriptor(target, key);
82
+ return descriptor !== undefined && hasOwn(descriptor, "value") ? getOwnDescriptor(descriptor, "value").value : undefined;
83
+ }
84
+ // A method found on `target` or its prototype chain at load time.
85
+ function method(target, key) {
86
+ for (let current = target; current !== null; current = getPrototypeOf(current)) {
87
+ const value = ownValue(current, key);
88
+ if (typeof value === "function") {
89
+ return value;
90
+ }
91
+ }
92
+ throw new TypeError(`Missing built-in method ${String(key)}.`);
93
+ }
94
+ // A data descriptor with a null prototype: Object.defineProperty never reads
95
+ // an inherited `get`, `set` or `value` from Object.prototype.
96
+ function dataDescriptor(value) {
97
+ const descriptor = createObject(null);
98
+ descriptor.value = value;
99
+ descriptor.writable = true;
100
+ descriptor.enumerable = true;
101
+ descriptor.configurable = true;
102
+ return descriptor;
103
+ }
104
+ // Defines an own data property (a key such as "__proto__" is a field like any
105
+ // other; no inherited setter, index setter included, runs).
106
+ function setField(target, key, value) {
107
+ defineProperty(target, key, dataDescriptor(value));
108
+ }
109
+ // Appends to an array this module owns, with an own data property.
110
+ function appendOwn(target, value) {
111
+ setField(target, target.length, value);
112
+ }
113
+ const weakSetAdd = method(WeakSet.prototype, "add");
114
+ const weakSetHas = method(WeakSet.prototype, "has");
115
+ const textEncoder = new TextEncoder();
116
+ const textEncode = method(TextEncoder.prototype, "encode");
117
+ const typedArrayLength = ownValue(getOwnDescriptor(getPrototypeOf(Uint8Array.prototype), "length"), "get");
118
+ const HMAC_PROBE = createHmac("sha256", "primordial-probe");
119
+ const hmacUpdate = method(HMAC_PROBE, "update");
120
+ const hmacDigest = method(HMAC_PROBE, "digest");
121
+ function utf8(text) {
122
+ return apply(textEncode, textEncoder, [text]);
123
+ }
124
+ function byteLength(bytes) {
125
+ return apply(typedArrayLength, bytes, []);
126
+ }
127
+ // ---------------------------------------------------------------------------
128
+ // Rejections: recognised by identity (never instanceof on a thrown value).
129
+ // ---------------------------------------------------------------------------
130
+ const REJECTIONS = new WeakSet();
131
+ /** Thrown by signTestInternalAuthorization: the fixture is invalid (or the built-ins are tampered) and nothing was signed. */
132
+ export class TestInternalAuthorizationInvalidError extends Error {
133
+ code = TEST_INTERNAL_AUTHORIZATION_INVALID;
134
+ reason;
135
+ /** The claim at fault, when one is. */
136
+ claim;
137
+ /** For permission-wildcard, permission-unknown and permission-service-only: the offending permissions, sorted. */
138
+ unknownKeys;
139
+ /** For work-grants-invalid: the rule (of validateWorkGrantsV2 or of the copy) and the index of the entry. */
140
+ workGrantsReason;
141
+ index;
142
+ // Built with primordials only: it may run while the built-ins are tampered.
143
+ constructor(reason, details = {}) {
144
+ let where = "";
145
+ const add = (part) => {
146
+ where = where === "" ? part : `${where}, ${part}`;
147
+ };
148
+ if (details.claim !== undefined)
149
+ add(`claim ${details.claim}`);
150
+ if (details.workGrantsReason !== undefined)
151
+ add(`work grants ${details.workGrantsReason}`);
152
+ if (details.index !== undefined)
153
+ add(`index ${details.index}`);
154
+ super(`Test internal authorization is invalid: ${reason}${where === "" ? "" : ` (${where})`}.`);
155
+ this.name = "TestInternalAuthorizationInvalidError";
156
+ this.reason = reason;
157
+ this.claim = details.claim;
158
+ const keys = details.unknownKeys;
159
+ let copy;
160
+ if (keys !== undefined) {
161
+ copy = [];
162
+ for (let index = 0; index < keys.length; index += 1) {
163
+ appendOwn(copy, keys[index]);
164
+ }
165
+ freeze(copy);
166
+ }
167
+ this.unknownKeys = copy;
168
+ this.workGrantsReason = details.workGrantsReason;
169
+ this.index = details.index;
170
+ }
171
+ }
172
+ function reject(reason, details) {
173
+ const error = new TestInternalAuthorizationInvalidError(reason, details);
174
+ apply(weakSetAdd, REJECTIONS, [error]);
175
+ throw error;
176
+ }
177
+ function isRejection(value) {
178
+ return apply(weakSetHas, REJECTIONS, [value]) === true;
179
+ }
180
+ // ---------------------------------------------------------------------------
181
+ // Structural fail-closed check of the built-ins (belt and braces, NOT a
182
+ // security boundary: the test runtime is trusted, see the threat model).
183
+ // ---------------------------------------------------------------------------
184
+ // Prototypes that must never carry toJSON (JSON.stringify would call it).
185
+ const NO_TO_JSON = [
186
+ Object.prototype,
187
+ Array.prototype,
188
+ String.prototype,
189
+ Number.prototype,
190
+ Boolean.prototype,
191
+ BigInt.prototype,
192
+ Symbol.prototype,
193
+ Function.prototype
194
+ ];
195
+ const OBJECT_PROTOTYPE = Object.prototype;
196
+ const DATA_ONLY_PROTOTYPES = [Object.prototype, Array.prototype];
197
+ // Cheap rules with no false positive in a normal process (spies, polyfills and
198
+ // methods added to the built-ins pass): an index key or an accessor (other
199
+ // than __proto__) on Object.prototype or Array.prototype, or a toJSON on the
200
+ // prototypes JSON.stringify would consult. Nothing else is compared.
201
+ function structuralRulesHold() {
202
+ let holds = true;
203
+ for (let index = 0; index < NO_TO_JSON.length; index += 1) {
204
+ if (getOwnDescriptor(NO_TO_JSON[index], "toJSON") !== undefined) {
205
+ holds = false;
206
+ }
207
+ }
208
+ for (let index = 0; index < DATA_ONLY_PROTOTYPES.length; index += 1) {
209
+ const prototype = DATA_ONLY_PROTOTYPES[index];
210
+ const keys = ownKeys(prototype);
211
+ for (let position = 0; position < keys.length; position += 1) {
212
+ const key = keys[position];
213
+ const accessor = !hasOwn(getOwnDescriptor(prototype, key), "value");
214
+ const indexKey = typeof key === "string" && key.length > 0 && key[0] !== undefined && key[0] >= "0" && key[0] <= "9";
215
+ if (indexKey || (accessor && !(prototype === OBJECT_PROTOTYPE && key === "__proto__"))) {
216
+ holds = false;
217
+ }
218
+ }
219
+ }
220
+ return holds;
221
+ }
222
+ function assertBuiltinsIntact() {
223
+ if (!structuralRulesHold()) {
224
+ reject("builtins-tampered");
225
+ }
226
+ }
227
+ function isPlainRecord(value) {
228
+ if (typeof value !== "object" || value === null || isArray(value)) {
229
+ return false;
230
+ }
231
+ const prototype = getPrototypeOf(value);
232
+ return prototype === OBJECT_PROTOTYPE || prototype === null;
233
+ }
234
+ // A null-prototype copy of a plain record: string keys and data properties
235
+ // only, read from own descriptors; undefined fields are left out. `invalid`
236
+ // gets the key at fault (none for a value that is not a plain record, a symbol
237
+ // key or a read that throws any value).
238
+ function copyRecord(value, invalid) {
239
+ const fields = createObject(null);
240
+ try {
241
+ if (!isPlainRecord(value)) {
242
+ return invalid();
243
+ }
244
+ const keys = ownKeys(value);
245
+ for (let index = 0; index < keys.length; index += 1) {
246
+ const key = keys[index];
247
+ if (typeof key !== "string") {
248
+ return invalid();
249
+ }
250
+ const descriptor = getOwnDescriptor(value, key);
251
+ if (descriptor === undefined || !hasOwn(descriptor, "value")) {
252
+ return invalid(key);
253
+ }
254
+ const field = ownValue(descriptor, "value");
255
+ if (field !== undefined) {
256
+ setField(fields, key, field);
257
+ }
258
+ }
259
+ }
260
+ catch (error) {
261
+ if (isRejection(error)) {
262
+ throw error;
263
+ }
264
+ return invalid();
265
+ }
266
+ return fields;
267
+ }
268
+ // An own dense copy of an array: a hole, an undefined or accessor element
269
+ // (`entry` with the index), an accessor or out-of-range length or a read that
270
+ // throws (`unreadable`), or a value that is not an array (`not-array`) is refused.
271
+ function copyList(value, invalid) {
272
+ const items = [];
273
+ try {
274
+ if (!isArray(value)) {
275
+ return invalid("not-array");
276
+ }
277
+ const length = ownValue(value, "length");
278
+ if (typeof length !== "number" || !isSafeInteger(length) || length < 0 || length > MAX_LIST_LENGTH) {
279
+ return invalid("unreadable");
280
+ }
281
+ for (let index = 0; index < length; index += 1) {
282
+ const item = ownValue(value, `${index}`);
283
+ if (item === undefined) {
284
+ return invalid("entry", index);
285
+ }
286
+ appendOwn(items, item);
287
+ }
288
+ }
289
+ catch (error) {
290
+ if (isRejection(error)) {
291
+ throw error;
292
+ }
293
+ return invalid("unreadable");
294
+ }
295
+ return items;
296
+ }
297
+ function copyWorkGrants(value) {
298
+ const grants = [];
299
+ if (value === undefined) {
300
+ return grants;
301
+ }
302
+ const invalid = (workGrantsReason, index) => reject("work-grants-invalid", { claim: "workGrants", workGrantsReason, index });
303
+ const entries = copyList(value, (fault, index) => invalid(fault === "entry" ? "entry-invalid" : fault, index));
304
+ for (let index = 0; index < entries.length; index += 1) {
305
+ const entry = copyRecord(entries[index], () => invalid("entry-invalid", index));
306
+ const parent = entry.parentResource;
307
+ if (parent !== undefined) {
308
+ // A parent of any kind (a revoked proxy included) goes through the same copy and catch boundary.
309
+ setField(entry, "parentResource", copyRecord(parent, () => invalid("parent-invalid", index)));
310
+ }
311
+ appendOwn(grants, entry);
312
+ }
313
+ return grants;
314
+ }
315
+ // Date.now() is external code (tests replace it): it runs once, here, before
316
+ // any validation, and only a finite primitive number is used, as data; any
317
+ // other value is refused without converting it (no valueOf or toString runs).
318
+ function readClock(nowSeconds) {
319
+ if (nowSeconds !== undefined) {
320
+ return nowSeconds;
321
+ }
322
+ const now = Date.now();
323
+ if (typeof now !== "number" || !isFinite(now)) {
324
+ return reject("time-invalid");
325
+ }
326
+ return floor(now / 1000);
327
+ }
328
+ function copyFixture(input) {
329
+ const options = copyRecord(input, () => reject("input-invalid"));
330
+ const nowSeconds = readClock(options.nowSeconds);
331
+ const claims = copyRecord(options.claims, (claim) => (claim === undefined ? reject("input-invalid", { claim: "claims" }) : reject("claim-invalid", { claim })));
332
+ const listOf = (field, reason) => claims[field] === undefined ? undefined : copyList(claims[field], () => reject(reason, { claim: field }));
333
+ const levels = listOf("permissionLevels", "permission-levels-invalid");
334
+ let permissionLevels;
335
+ if (levels !== undefined) {
336
+ permissionLevels = [];
337
+ for (let index = 0; index < levels.length; index += 1) {
338
+ appendOwn(permissionLevels, copyRecord(levels[index], () => reject("permission-levels-invalid", { claim: "permissionLevels" })));
339
+ }
340
+ }
341
+ const practitionerLink = claims.practitionerLink === undefined ? undefined : copyRecord(claims.practitionerLink, () => reject("practitioner-link-invalid", { claim: "practitionerLink" }));
342
+ const money = claims.money === undefined ? undefined : copyRecord(claims.money, () => reject("money-invalid", { claim: "money" }));
343
+ const enabledCurrencies = money === undefined ? undefined : copyList(money.enabledCurrencies, () => reject("money-invalid", { claim: "money" }));
344
+ return {
345
+ secret: options.secret,
346
+ nowSeconds,
347
+ ttlSeconds: options.ttlSeconds,
348
+ claims,
349
+ enabledProducts: listOf("enabledProducts", "products-invalid"),
350
+ permissions: listOf("permissions", "permissions-invalid"),
351
+ permissionLevels,
352
+ workGrants: copyWorkGrants(claims.workGrants),
353
+ practitionerLink,
354
+ money,
355
+ enabledCurrencies
356
+ };
357
+ }
358
+ // ---------------------------------------------------------------------------
359
+ // Phase 2: validate the copy (built-ins verified intact, no input code runs).
360
+ // ---------------------------------------------------------------------------
361
+ const ALLOWED_CLAIMS = new Set([
362
+ "tokenUse",
363
+ "schemaVersion",
364
+ "iss",
365
+ "aud",
366
+ "sub",
367
+ "tenantId",
368
+ "licenseKey",
369
+ "sid",
370
+ "authorizationVersion",
371
+ "licenseStatus",
372
+ "username",
373
+ "role",
374
+ "enabledProducts",
375
+ "permissions",
376
+ "capabilityCatalogVersion",
377
+ "permissionLevels",
378
+ "workGrants",
379
+ "practitionerLink",
380
+ "money"
381
+ ]);
382
+ // Rejections of readInternalAuthorization on the built payload, as reasons of
383
+ // this helper. The payload is a plain object built here and the permissions
384
+ // are checked before, so AUTHORIZATION_PAYLOAD_INVALID and
385
+ // AUTHORIZATION_KEY_UNKNOWN cannot occur; they map to input-invalid and
386
+ // permission-unknown.
387
+ const READER_REASONS = {
388
+ AUTHORIZATION_PAYLOAD_INVALID: "input-invalid",
389
+ AUTHORIZATION_TOKEN_USE_INVALID: "token-use-invalid",
390
+ AUTHORIZATION_SCHEMA_UNSUPPORTED: "schema-version-invalid",
391
+ AUTHORIZATION_VERSION_INVALID: "authorization-version-invalid",
392
+ AUTHORIZATION_KEY_UNKNOWN: "permission-unknown",
393
+ AUTHORIZATION_CLAIM_INVALID: "claim-invalid"
394
+ };
395
+ // AUTHORIZATION_CLAIM_INVALID of a list or of the catalog version: a reason of its own.
396
+ const CLAIM_REASONS = {
397
+ enabledProducts: "products-invalid",
398
+ permissions: "permissions-invalid",
399
+ capabilityCatalogVersion: "catalog-version-invalid",
400
+ permissionLevels: "permission-levels-invalid"
401
+ };
402
+ const LEVEL_FIELDS = ["module", "feature", "level"];
403
+ const CURRENCY = /^[A-Z]{3}$/;
404
+ const MAX_CURRENCIES = 32;
405
+ // Field order of a signed work grant (access-domain.ts:91-92, as in the PKG-08 example).
406
+ const WORK_GRANT_FIELD_ORDER = ["domain", "resourceId", "relation", "parentResource", "grantVersion", "notBefore", "expiresAt"];
407
+ function hasDuplicates(values) {
408
+ return new Set(values).size !== values.length;
409
+ }
410
+ function strings(values) {
411
+ return values.every((value) => typeof value === "string");
412
+ }
413
+ function checkSecret(secret) {
414
+ if (typeof secret !== "string" || byteLength(utf8(secret)) < MIN_TEST_SECRET_BYTES) {
415
+ return reject("secret-invalid");
416
+ }
417
+ return secret;
418
+ }
419
+ // nowSeconds is the given value or the clock read once by the copy (readClock).
420
+ function checkTime(nowSeconds, ttlSeconds) {
421
+ if (typeof nowSeconds !== "number" || !isSafeInteger(nowSeconds) || nowSeconds < 0) {
422
+ return reject("time-invalid");
423
+ }
424
+ const ttl = ttlSeconds === undefined ? MAX_INTERNAL_AUTHORIZATION_TTL_SECONDS : ttlSeconds;
425
+ if (typeof ttl !== "number" || !isSafeInteger(ttl) || ttl < MIN_INTERNAL_AUTHORIZATION_TTL_SECONDS || ttl > MAX_INTERNAL_AUTHORIZATION_TTL_SECONDS) {
426
+ return reject("ttl-invalid");
427
+ }
428
+ return { iat: nowSeconds, exp: nowSeconds + ttl };
429
+ }
430
+ function checkProducts(products) {
431
+ if (products !== undefined && (!strings(products) || hasDuplicates(products))) {
432
+ return reject("products-invalid", { claim: "enabledProducts" });
433
+ }
434
+ return products;
435
+ }
436
+ // Wildcards and unknown keys first (['*', '*'] is permission-wildcard), then duplicates.
437
+ function checkPermissions(permissions) {
438
+ if (permissions === undefined) {
439
+ return undefined;
440
+ }
441
+ if (!strings(permissions)) {
442
+ return reject("permissions-invalid", { claim: "permissions" });
443
+ }
444
+ const unknownKeys = findUnknownPermissionKeys(permissions);
445
+ if (unknownKeys.length > 0) {
446
+ reject(unknownKeys.some((key) => key.includes("*")) ? "permission-wildcard" : "permission-unknown", { claim: "permissions", unknownKeys });
447
+ }
448
+ return hasDuplicates(permissions) ? reject("permissions-invalid", { claim: "permissions" }) : permissions;
449
+ }
450
+ // Access signs { module, feature, level } only (access-domain.ts:53-57): the
451
+ // reader ignores other fields, the helper refuses them. The reader checks the values.
452
+ function checkPermissionLevels(levels) {
453
+ if (levels === undefined) {
454
+ return undefined;
455
+ }
456
+ const result = [];
457
+ for (const fields of levels) {
458
+ if (Object.keys(fields).some((field) => !LEVEL_FIELDS.includes(field))) {
459
+ reject("permission-levels-invalid", { claim: "permissionLevels" });
460
+ }
461
+ const level = {};
462
+ for (const field of LEVEL_FIELDS) {
463
+ if (hasOwn(fields, field)) {
464
+ setField(level, field, fields[field]);
465
+ }
466
+ }
467
+ appendOwn(result, level);
468
+ }
469
+ return result;
470
+ }
471
+ function checkPractitionerLink(fields) {
472
+ if (fields === undefined) {
473
+ return undefined;
474
+ }
475
+ const practitionerId = fields.practitionerId;
476
+ if (Object.keys(fields).length !== 1 || typeof practitionerId !== "string" || practitionerId.length === 0) {
477
+ return reject("practitioner-link-invalid", { claim: "practitionerLink" });
478
+ }
479
+ const link = {};
480
+ setField(link, "practitionerId", practitionerId);
481
+ return link;
482
+ }
483
+ // enabledCurrencies is copied (phase 1) whenever money is present.
484
+ function checkMoney(fields, currencies) {
485
+ if (fields === undefined) {
486
+ return undefined;
487
+ }
488
+ const enabledCurrencies = currencies;
489
+ const defaultCurrency = fields.defaultCurrency;
490
+ if (Object.keys(fields).length !== 2 ||
491
+ typeof defaultCurrency !== "string" ||
492
+ !strings(enabledCurrencies) ||
493
+ enabledCurrencies.length === 0 ||
494
+ enabledCurrencies.length > MAX_CURRENCIES ||
495
+ enabledCurrencies.some((currency) => !CURRENCY.test(currency)) ||
496
+ hasDuplicates(enabledCurrencies) ||
497
+ !enabledCurrencies.includes(defaultCurrency)) {
498
+ return reject("money-invalid", { claim: "money" });
499
+ }
500
+ const money = {};
501
+ setField(money, "defaultCurrency", defaultCurrency);
502
+ setField(money, "enabledCurrencies", enabledCurrencies);
503
+ return money;
504
+ }
505
+ // One work grant to sign: the given fields in Access's order, the id first
506
+ // (computed with workGrantId when absent; when the identity fields are not
507
+ // strings it stays absent and validateWorkGrantsV2 refuses the grant with its
508
+ // own rule). Unknown fields are kept so that the validator refuses them.
509
+ function workGrantToSign(fields, tenantId, sub) {
510
+ const body = {};
511
+ for (const field of WORK_GRANT_FIELD_ORDER) {
512
+ if (hasOwn(fields, field)) {
513
+ setField(body, field, field === "parentResource" ? { ...fields[field] } : fields[field]);
514
+ }
515
+ }
516
+ for (const field of Object.keys(fields)) {
517
+ if (field !== "id" && !WORK_GRANT_FIELD_ORDER.includes(field)) {
518
+ setField(body, field, fields[field]);
519
+ }
520
+ }
521
+ let id = fields.id;
522
+ if (id === undefined && typeof tenantId === "string" && typeof sub === "string") {
523
+ try {
524
+ id = workGrantId(tenantId, sub, body);
525
+ }
526
+ catch {
527
+ id = undefined;
528
+ }
529
+ }
530
+ if (id === undefined) {
531
+ return body;
532
+ }
533
+ const grant = {};
534
+ setField(grant, "id", id);
535
+ for (const field of Object.keys(body)) {
536
+ setField(grant, field, body[field]);
537
+ }
538
+ return grant;
539
+ }
540
+ function workGrantsToSign(grants, tenantId, sub) {
541
+ const result = [];
542
+ for (const fields of grants) {
543
+ appendOwn(result, workGrantToSign(fields, tenantId, sub));
544
+ }
545
+ // Access sorts the signed list by id (access-domain.ts:339-341).
546
+ const idOf = (grant) => (typeof grant.id === "string" ? grant.id : "");
547
+ return result.sort((left, right) => (idOf(left) < idOf(right) ? -1 : idOf(left) > idOf(right) ? 1 : 0));
548
+ }
549
+ // ---------------------------------------------------------------------------
550
+ // Phase 3: serialize, check and sign (primordials only).
551
+ // ---------------------------------------------------------------------------
552
+ // JSON of the validated payload, in the order of its own keys. Only strings
553
+ // (JSON.stringify of a primitive string never looks up toJSON), safe integers
554
+ // (validated), arrays and records the helper built are ever serialized.
555
+ function serialize(value) {
556
+ if (typeof value === "string") {
557
+ return jsonStringify(value);
558
+ }
559
+ if (typeof value === "number") {
560
+ return `${value}`;
561
+ }
562
+ let text = "";
563
+ if (isArray(value)) {
564
+ const length = ownValue(value, "length");
565
+ for (let index = 0; index < length; index += 1) {
566
+ text = `${text}${index === 0 ? "" : ","}${serialize(ownValue(value, `${index}`))}`;
567
+ }
568
+ return `[${text}]`;
569
+ }
570
+ const keys = ownKeys(value);
571
+ for (let index = 0; index < keys.length; index += 1) {
572
+ const key = keys[index];
573
+ text = `${text}${index === 0 ? "" : ","}${jsonStringify(key)}:${serialize(ownValue(value, key))}`;
574
+ }
575
+ return `{${text}}`;
576
+ }
577
+ const BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
578
+ function base64Url(bytes) {
579
+ const length = byteLength(bytes);
580
+ const digit = (value) => BASE64URL[value & 63];
581
+ let text = "";
582
+ let index = 0;
583
+ for (; index + 2 < length; index += 3) {
584
+ const chunk = (bytes[index] << 16) | (bytes[index + 1] << 8) | bytes[index + 2];
585
+ text = `${text}${digit(chunk >> 18)}${digit(chunk >> 12)}${digit(chunk >> 6)}${digit(chunk)}`;
586
+ }
587
+ const rest = length - index;
588
+ if (rest > 0) {
589
+ const chunk = (bytes[index] << 16) | (rest === 2 ? bytes[index + 1] << 8 : 0);
590
+ text = `${text}${digit(chunk >> 18)}${digit(chunk >> 12)}${rest === 2 ? digit(chunk >> 6) : ""}`;
591
+ }
592
+ return text;
593
+ }
594
+ function deepFreeze(value) {
595
+ if (typeof value === "object" && value !== null && !isFrozen(value)) {
596
+ const keys = ownKeys(value);
597
+ for (let index = 0; index < keys.length; index += 1) {
598
+ deepFreeze(ownValue(value, keys[index]));
599
+ }
600
+ freeze(value);
601
+ }
602
+ }
603
+ const HEADER = base64Url(utf8(serialize({ alg: "HS256", typ: "JWT" })));
604
+ /**
605
+ * Signs an internal authorization token v2 for tests and smokes (Node only:
606
+ * HS256 with node:crypto). It reads nothing from the environment: the secret,
607
+ * the time and every claim come from `input` (Date.now() is read once, by the
608
+ * copy, only when nowSeconds is absent). The test runtime is trusted; a cheap
609
+ * structural check refuses (`builtins-tampered`, nothing signed) a polluted
610
+ * Object.prototype/Array.prototype or a toJSON on a prototype (see the threat
611
+ * model at the top of the module). Before signing it
612
+ * validates the fixture as PKG-08 section 5 defines it and throws
613
+ * TestInternalAuthorizationInvalidError (nothing signed) when:
614
+ *
615
+ * - the secret is shorter than MIN_TEST_SECRET_BYTES (empty included);
616
+ * - the input, the claims or a nested record (a work grant, its parent,
617
+ * practitionerLink, money, a permission level) is not a plain record, has a
618
+ * symbol key or an accessor, or throws any value when read; a list
619
+ * (enabledProducts, permissions, permissionLevels, workGrants,
620
+ * money.enabledCurrencies) is not a dense array: a hole, an undefined or
621
+ * accessor element, an accessor length or a throwing proxy is refused.
622
+ * Everything is read once from own data descriptors (no getter runs) into
623
+ * copies, and only the copies are checked, signed and frozen;
624
+ * - nowSeconds (or the clock, when absent: a finite primitive number, never
625
+ * converted) is not a safe integer >= 0, or ttlSeconds is outside
626
+ * [MIN_, MAX_INTERNAL_AUTHORIZATION_TTL_SECONDS] (1 to 60: exp - iat <= 60);
627
+ * - a claim is not one the token carries (iat and exp included);
628
+ * - tokenUse, schemaVersion, iss or aud is given with another value than
629
+ * `internal-forward-auth`, `sail-work-authorization.v2`,
630
+ * INTERNAL_AUTHORIZATION_ISSUER or INTERNAL_AUTHORIZATION_AUDIENCE;
631
+ * - readInternalAuthorization of this package refuses the payload: required
632
+ * strings (sub, tenantId, licenseKey, sid, licenseStatus), optional
633
+ * non-empty role and username, authorizationVersion >= 1, enabledProducts
634
+ * only sail/connect, permissions only explicit catalog keys (any `*` is
635
+ * permission-wildcard, any other unknown key permission-unknown; checked
636
+ * before duplicates), capabilityCatalogVersion and permissionLevels shapes;
637
+ * - a permission is a serviceToService key (permission-service-only): the
638
+ * internal token is a user's token, and those keys are presented only by a
639
+ * service identity (not tenant-assignable, omitted by migrateGrants, E1);
640
+ * - enabledProducts or permissions repeat a value;
641
+ * - validateWorkGrantsV2 refuses the signed workGrants (ids computed with
642
+ * workGrantId from the tenantId and sub claims; a given id must be that one,
643
+ * so a legacy `|` id is refused; warehouse needs grantVersion; no
644
+ * duplicates; parentResource only on agenda and warehouse);
645
+ * - practitionerLink or money does not have the exact shape Access signs.
646
+ *
647
+ * Optional claims follow Access: enabledProducts and permissions are omitted
648
+ * when absent or empty, role and username when absent; permissionLevels is
649
+ * signed only when given; workGrants is always signed (sorted by id).
650
+ * Returns the token and the frozen payload exactly as signed.
651
+ */
652
+ export function signTestInternalAuthorization(input) {
653
+ assertBuiltinsIntact();
654
+ // Phase 1: the only step in which input code (traps) can run.
655
+ const copy = copyFixture(input);
656
+ // A trap or the clock may have polluted a prototype while it ran. After this
657
+ // point no external code runs: only the copies are read.
658
+ assertBuiltinsIntact();
659
+ // Phase 2.
660
+ const secret = checkSecret(copy.secret);
661
+ const { iat, exp } = checkTime(copy.nowSeconds, copy.ttlSeconds);
662
+ const claims = copy.claims;
663
+ const extra = Object.keys(claims)
664
+ .filter((claim) => !ALLOWED_CLAIMS.has(claim))
665
+ .sort();
666
+ if (extra.length > 0) {
667
+ reject("claim-not-allowed", { claim: extra[0] });
668
+ }
669
+ if (claims.iss !== undefined && claims.iss !== INTERNAL_AUTHORIZATION_ISSUER) {
670
+ reject("issuer-invalid", { claim: "iss" });
671
+ }
672
+ if (claims.aud !== undefined && claims.aud !== INTERNAL_AUTHORIZATION_AUDIENCE) {
673
+ reject("audience-invalid", { claim: "aud" });
674
+ }
675
+ const enabledProducts = checkProducts(copy.enabledProducts);
676
+ const permissions = checkPermissions(copy.permissions);
677
+ const permissionLevels = checkPermissionLevels(copy.permissionLevels);
678
+ const workGrants = workGrantsToSign(copy.workGrants, claims.tenantId, claims.sub);
679
+ const practitionerLink = checkPractitionerLink(copy.practitionerLink);
680
+ const money = checkMoney(copy.money, copy.enabledCurrencies);
681
+ // Claim order of signInternalAuthorizationToken (seed-auth.ts:613-634), with
682
+ // capabilityCatalogVersion after permissions as in PKG-08 section 4.1.
683
+ const payload = {};
684
+ const put = (claim, value) => {
685
+ if (value !== undefined) {
686
+ setField(payload, claim, value);
687
+ }
688
+ };
689
+ const nonEmpty = (list) => (list !== undefined && list.length > 0 ? list : undefined);
690
+ put("tokenUse", claims.tokenUse === undefined ? INTERNAL_AUTHORIZATION_TOKEN_USE : claims.tokenUse);
691
+ put("iss", INTERNAL_AUTHORIZATION_ISSUER);
692
+ put("aud", INTERNAL_AUTHORIZATION_AUDIENCE);
693
+ put("sub", claims.sub);
694
+ put("tenantId", claims.tenantId);
695
+ put("licenseKey", claims.licenseKey);
696
+ put("sid", claims.sid);
697
+ put("iat", iat);
698
+ put("exp", exp);
699
+ put("schemaVersion", claims.schemaVersion === undefined ? AUTHORIZATION_SCHEMA_VERSION : claims.schemaVersion);
700
+ put("licenseStatus", claims.licenseStatus);
701
+ put("username", claims.username);
702
+ put("role", claims.role);
703
+ put("enabledProducts", nonEmpty(enabledProducts));
704
+ put("permissions", nonEmpty(permissions));
705
+ put("capabilityCatalogVersion", claims.capabilityCatalogVersion === undefined ? CAPABILITY_CATALOG_VERSION : claims.capabilityCatalogVersion);
706
+ put("permissionLevels", permissionLevels);
707
+ put("workGrants", workGrants);
708
+ put("practitionerLink", practitionerLink);
709
+ put("authorizationVersion", claims.authorizationVersion);
710
+ put("money", money);
711
+ const read = readInternalAuthorization(payload);
712
+ if (!read.ok) {
713
+ const claim = read.claim;
714
+ const reason = read.code === "AUTHORIZATION_CLAIM_INVALID" && claim !== undefined ? (CLAIM_REASONS[claim] ?? "claim-invalid") : READER_REASONS[read.code];
715
+ reject(reason, { claim });
716
+ }
717
+ // The internal token is a user's token: serviceToService keys are never
718
+ // granted to users (not tenant-assignable, omitted by migrateGrants, E1).
719
+ const serviceKeys = read.authorization.permissions.filter((key) => getCapability(key)?.serviceToService === true);
720
+ if (serviceKeys.length > 0) {
721
+ reject("permission-service-only", { claim: "permissions", unknownKeys: serviceKeys });
722
+ }
723
+ try {
724
+ validateWorkGrantsV2(workGrants, { tenantId: read.authorization.tenantId, sub: read.authorization.sub });
725
+ }
726
+ catch (error) {
727
+ // validateWorkGrantsV2 only throws WorkGrantsInvalidError.
728
+ const invalid = error;
729
+ reject("work-grants-invalid", { claim: "workGrants", workGrantsReason: invalid.reason, index: invalid.index });
730
+ }
731
+ // Phase 3: the bytes signed must be the validated copy.
732
+ assertBuiltinsIntact();
733
+ const json = serialize(payload);
734
+ if (serialize(jsonParse(json)) !== json) {
735
+ reject("builtins-tampered");
736
+ }
737
+ const body = `${HEADER}.${base64Url(utf8(json))}`;
738
+ const hmac = createHmac("sha256", secret);
739
+ apply(hmacUpdate, hmac, [body]);
740
+ const signature = apply(hmacDigest, hmac, ["base64url"]);
741
+ deepFreeze(payload);
742
+ return freeze({ token: `${body}.${signature}`, payload: payload });
743
+ }
744
+ //# sourceMappingURL=authorization-testing.js.map