@pegasimed.com/pegasi-sail-connect-shared 0.2.0-dev.3 → 0.2.0-dev.31
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/README.md +1070 -32
- package/dist/authorization/internal-authorization.d.ts +61 -1
- package/dist/authorization/internal-authorization.d.ts.map +1 -1
- package/dist/authorization/internal-authorization.js +105 -2
- package/dist/authorization/internal-authorization.js.map +1 -1
- package/dist/authorization-testing.d.ts +246 -0
- package/dist/authorization-testing.d.ts.map +1 -0
- package/dist/authorization-testing.js +785 -0
- package/dist/authorization-testing.js.map +1 -0
- package/dist/capabilities/catalog-data.d.ts +3099 -805
- package/dist/capabilities/catalog-data.d.ts.map +1 -1
- package/dist/capabilities/catalog-data.js +3272 -885
- package/dist/capabilities/catalog-data.js.map +1 -1
- package/dist/capabilities/catalog.d.ts +1 -1
- package/dist/capabilities/catalog.d.ts.map +1 -1
- package/dist/capabilities/catalog.js +1 -1
- package/dist/capabilities/catalog.js.map +1 -1
- package/dist/capabilities/index.d.ts +4 -0
- package/dist/capabilities/index.d.ts.map +1 -1
- package/dist/capabilities/index.js +7 -0
- package/dist/capabilities/index.js.map +1 -1
- package/dist/capabilities/migration-data.d.ts +58 -165
- package/dist/capabilities/migration-data.d.ts.map +1 -1
- package/dist/capabilities/migration-data.js +30 -116
- package/dist/capabilities/migration-data.js.map +1 -1
- package/dist/capabilities/migration.d.ts +20 -20
- package/dist/capabilities/migration.d.ts.map +1 -1
- package/dist/capabilities/migration.js +22 -34
- package/dist/capabilities/migration.js.map +1 -1
- package/dist/capabilities/types.d.ts +9 -2
- package/dist/capabilities/types.d.ts.map +1 -1
- package/dist/capabilities/validate.d.ts +1 -1
- package/dist/capabilities/validate.d.ts.map +1 -1
- package/dist/capabilities/validate.js +9 -0
- package/dist/capabilities/validate.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/organization/index.d.ts +141 -0
- package/dist/organization/index.d.ts.map +1 -0
- package/dist/organization/index.js +93 -0
- package/dist/organization/index.js.map +1 -0
- package/package.json +9 -1
- package/scripts/check-service-keys.mjs +30 -7
|
@@ -0,0 +1,785 @@
|
|
|
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
|
+
// A JSON value of at most 3 levels (leaf, list or record), copied from own
|
|
329
|
+
// data descriptors; a non-finite number, an accessor, a symbol key, a function
|
|
330
|
+
// or a deeper value is refused as claim-invalid.
|
|
331
|
+
function copyJsonValue(value, depth) {
|
|
332
|
+
const invalid = () => reject("claim-invalid", { claim: "patientDataAccess" });
|
|
333
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") {
|
|
334
|
+
return value;
|
|
335
|
+
}
|
|
336
|
+
if (typeof value === "number") {
|
|
337
|
+
return isFinite(value) ? value : invalid();
|
|
338
|
+
}
|
|
339
|
+
if (depth >= 3) {
|
|
340
|
+
return invalid();
|
|
341
|
+
}
|
|
342
|
+
if (isArray(value)) {
|
|
343
|
+
const items = copyList(value, invalid);
|
|
344
|
+
const copy = [];
|
|
345
|
+
for (let index = 0; index < items.length; index += 1) {
|
|
346
|
+
appendOwn(copy, copyJsonValue(items[index], depth + 1));
|
|
347
|
+
}
|
|
348
|
+
return copy;
|
|
349
|
+
}
|
|
350
|
+
const fields = copyRecord(value, invalid);
|
|
351
|
+
const copy = createObject(null);
|
|
352
|
+
const keys = ownKeys(fields);
|
|
353
|
+
for (let index = 0; index < keys.length; index += 1) {
|
|
354
|
+
const key = keys[index];
|
|
355
|
+
setField(copy, key, copyJsonValue(ownValue(getOwnDescriptor(fields, key), "value"), depth + 1));
|
|
356
|
+
}
|
|
357
|
+
return copy;
|
|
358
|
+
}
|
|
359
|
+
function copyFixture(input) {
|
|
360
|
+
const options = copyRecord(input, () => reject("input-invalid"));
|
|
361
|
+
const nowSeconds = readClock(options.nowSeconds);
|
|
362
|
+
const claims = copyRecord(options.claims, (claim) => (claim === undefined ? reject("input-invalid", { claim: "claims" }) : reject("claim-invalid", { claim })));
|
|
363
|
+
const listOf = (field, reason) => claims[field] === undefined ? undefined : copyList(claims[field], () => reject(reason, { claim: field }));
|
|
364
|
+
const levels = listOf("permissionLevels", "permission-levels-invalid");
|
|
365
|
+
let permissionLevels;
|
|
366
|
+
if (levels !== undefined) {
|
|
367
|
+
permissionLevels = [];
|
|
368
|
+
for (let index = 0; index < levels.length; index += 1) {
|
|
369
|
+
appendOwn(permissionLevels, copyRecord(levels[index], () => reject("permission-levels-invalid", { claim: "permissionLevels" })));
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const practitionerLink = claims.practitionerLink === undefined ? undefined : copyRecord(claims.practitionerLink, () => reject("practitioner-link-invalid", { claim: "practitionerLink" }));
|
|
373
|
+
const money = claims.money === undefined ? undefined : copyRecord(claims.money, () => reject("money-invalid", { claim: "money" }));
|
|
374
|
+
const enabledCurrencies = money === undefined ? undefined : copyList(money.enabledCurrencies, () => reject("money-invalid", { claim: "money" }));
|
|
375
|
+
return {
|
|
376
|
+
secret: options.secret,
|
|
377
|
+
nowSeconds,
|
|
378
|
+
ttlSeconds: options.ttlSeconds,
|
|
379
|
+
claims,
|
|
380
|
+
enabledProducts: listOf("enabledProducts", "products-invalid"),
|
|
381
|
+
permissions: listOf("permissions", "permissions-invalid"),
|
|
382
|
+
permissionLevels,
|
|
383
|
+
workGrants: copyWorkGrants(claims.workGrants),
|
|
384
|
+
practitionerLink,
|
|
385
|
+
money,
|
|
386
|
+
enabledCurrencies,
|
|
387
|
+
patientDataAccess: claims.patientDataAccess === undefined ? undefined : copyJsonValue(claims.patientDataAccess, 0)
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
// ---------------------------------------------------------------------------
|
|
391
|
+
// Phase 2: validate the copy (built-ins verified intact, no input code runs).
|
|
392
|
+
// ---------------------------------------------------------------------------
|
|
393
|
+
const ALLOWED_CLAIMS = new Set([
|
|
394
|
+
"tokenUse",
|
|
395
|
+
"schemaVersion",
|
|
396
|
+
"iss",
|
|
397
|
+
"aud",
|
|
398
|
+
"sub",
|
|
399
|
+
"tenantId",
|
|
400
|
+
"licenseKey",
|
|
401
|
+
"sid",
|
|
402
|
+
"authorizationVersion",
|
|
403
|
+
"licenseStatus",
|
|
404
|
+
"username",
|
|
405
|
+
"role",
|
|
406
|
+
"enabledProducts",
|
|
407
|
+
"permissions",
|
|
408
|
+
"capabilityCatalogVersion",
|
|
409
|
+
"permissionLevels",
|
|
410
|
+
"workGrants",
|
|
411
|
+
"practitionerLink",
|
|
412
|
+
"money",
|
|
413
|
+
"patientDataAccess"
|
|
414
|
+
]);
|
|
415
|
+
// Rejections of readInternalAuthorization on the built payload, as reasons of
|
|
416
|
+
// this helper. The payload is a plain object built here and the permissions
|
|
417
|
+
// are checked before, so AUTHORIZATION_PAYLOAD_INVALID and
|
|
418
|
+
// AUTHORIZATION_KEY_UNKNOWN cannot occur; they map to input-invalid and
|
|
419
|
+
// permission-unknown.
|
|
420
|
+
const READER_REASONS = {
|
|
421
|
+
AUTHORIZATION_PAYLOAD_INVALID: "input-invalid",
|
|
422
|
+
AUTHORIZATION_TOKEN_USE_INVALID: "token-use-invalid",
|
|
423
|
+
AUTHORIZATION_SCHEMA_UNSUPPORTED: "schema-version-invalid",
|
|
424
|
+
AUTHORIZATION_VERSION_INVALID: "authorization-version-invalid",
|
|
425
|
+
AUTHORIZATION_KEY_UNKNOWN: "permission-unknown",
|
|
426
|
+
AUTHORIZATION_CLAIM_INVALID: "claim-invalid"
|
|
427
|
+
};
|
|
428
|
+
// AUTHORIZATION_CLAIM_INVALID of a list or of the catalog version: a reason of its own.
|
|
429
|
+
const CLAIM_REASONS = {
|
|
430
|
+
enabledProducts: "products-invalid",
|
|
431
|
+
permissions: "permissions-invalid",
|
|
432
|
+
capabilityCatalogVersion: "catalog-version-invalid",
|
|
433
|
+
permissionLevels: "permission-levels-invalid"
|
|
434
|
+
};
|
|
435
|
+
const LEVEL_FIELDS = ["module", "feature", "level"];
|
|
436
|
+
const CURRENCY = /^[A-Z]{3}$/;
|
|
437
|
+
const MAX_CURRENCIES = 32;
|
|
438
|
+
// Field order of a signed work grant (access-domain.ts:91-92, as in the PKG-08 example).
|
|
439
|
+
const WORK_GRANT_FIELD_ORDER = ["domain", "resourceId", "relation", "parentResource", "grantVersion", "notBefore", "expiresAt"];
|
|
440
|
+
function hasDuplicates(values) {
|
|
441
|
+
return new Set(values).size !== values.length;
|
|
442
|
+
}
|
|
443
|
+
function strings(values) {
|
|
444
|
+
return values.every((value) => typeof value === "string");
|
|
445
|
+
}
|
|
446
|
+
function checkSecret(secret) {
|
|
447
|
+
if (typeof secret !== "string" || byteLength(utf8(secret)) < MIN_TEST_SECRET_BYTES) {
|
|
448
|
+
return reject("secret-invalid");
|
|
449
|
+
}
|
|
450
|
+
return secret;
|
|
451
|
+
}
|
|
452
|
+
// nowSeconds is the given value or the clock read once by the copy (readClock).
|
|
453
|
+
function checkTime(nowSeconds, ttlSeconds) {
|
|
454
|
+
if (typeof nowSeconds !== "number" || !isSafeInteger(nowSeconds) || nowSeconds < 0) {
|
|
455
|
+
return reject("time-invalid");
|
|
456
|
+
}
|
|
457
|
+
const ttl = ttlSeconds === undefined ? MAX_INTERNAL_AUTHORIZATION_TTL_SECONDS : ttlSeconds;
|
|
458
|
+
if (typeof ttl !== "number" || !isSafeInteger(ttl) || ttl < MIN_INTERNAL_AUTHORIZATION_TTL_SECONDS || ttl > MAX_INTERNAL_AUTHORIZATION_TTL_SECONDS) {
|
|
459
|
+
return reject("ttl-invalid");
|
|
460
|
+
}
|
|
461
|
+
return { iat: nowSeconds, exp: nowSeconds + ttl };
|
|
462
|
+
}
|
|
463
|
+
function checkProducts(products) {
|
|
464
|
+
if (products !== undefined && (!strings(products) || hasDuplicates(products))) {
|
|
465
|
+
return reject("products-invalid", { claim: "enabledProducts" });
|
|
466
|
+
}
|
|
467
|
+
return products;
|
|
468
|
+
}
|
|
469
|
+
// Wildcards and unknown keys first (['*', '*'] is permission-wildcard), then duplicates.
|
|
470
|
+
function checkPermissions(permissions) {
|
|
471
|
+
if (permissions === undefined) {
|
|
472
|
+
return undefined;
|
|
473
|
+
}
|
|
474
|
+
if (!strings(permissions)) {
|
|
475
|
+
return reject("permissions-invalid", { claim: "permissions" });
|
|
476
|
+
}
|
|
477
|
+
const unknownKeys = findUnknownPermissionKeys(permissions);
|
|
478
|
+
if (unknownKeys.length > 0) {
|
|
479
|
+
reject(unknownKeys.some((key) => key.includes("*")) ? "permission-wildcard" : "permission-unknown", { claim: "permissions", unknownKeys });
|
|
480
|
+
}
|
|
481
|
+
return hasDuplicates(permissions) ? reject("permissions-invalid", { claim: "permissions" }) : permissions;
|
|
482
|
+
}
|
|
483
|
+
// Access signs { module, feature, level } only (access-domain.ts:53-57): the
|
|
484
|
+
// reader ignores other fields, the helper refuses them. The reader checks the values.
|
|
485
|
+
function checkPermissionLevels(levels) {
|
|
486
|
+
if (levels === undefined) {
|
|
487
|
+
return undefined;
|
|
488
|
+
}
|
|
489
|
+
const result = [];
|
|
490
|
+
for (const fields of levels) {
|
|
491
|
+
if (Object.keys(fields).some((field) => !LEVEL_FIELDS.includes(field))) {
|
|
492
|
+
reject("permission-levels-invalid", { claim: "permissionLevels" });
|
|
493
|
+
}
|
|
494
|
+
const level = {};
|
|
495
|
+
for (const field of LEVEL_FIELDS) {
|
|
496
|
+
if (hasOwn(fields, field)) {
|
|
497
|
+
setField(level, field, fields[field]);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
appendOwn(result, level);
|
|
501
|
+
}
|
|
502
|
+
return result;
|
|
503
|
+
}
|
|
504
|
+
function checkPractitionerLink(fields) {
|
|
505
|
+
if (fields === undefined) {
|
|
506
|
+
return undefined;
|
|
507
|
+
}
|
|
508
|
+
const practitionerId = fields.practitionerId;
|
|
509
|
+
if (Object.keys(fields).length !== 1 || typeof practitionerId !== "string" || practitionerId.length === 0) {
|
|
510
|
+
return reject("practitioner-link-invalid", { claim: "practitionerLink" });
|
|
511
|
+
}
|
|
512
|
+
const link = {};
|
|
513
|
+
setField(link, "practitionerId", practitionerId);
|
|
514
|
+
return link;
|
|
515
|
+
}
|
|
516
|
+
// enabledCurrencies is copied (phase 1) whenever money is present.
|
|
517
|
+
function checkMoney(fields, currencies) {
|
|
518
|
+
if (fields === undefined) {
|
|
519
|
+
return undefined;
|
|
520
|
+
}
|
|
521
|
+
const enabledCurrencies = currencies;
|
|
522
|
+
const defaultCurrency = fields.defaultCurrency;
|
|
523
|
+
if (Object.keys(fields).length !== 2 ||
|
|
524
|
+
typeof defaultCurrency !== "string" ||
|
|
525
|
+
!strings(enabledCurrencies) ||
|
|
526
|
+
enabledCurrencies.length === 0 ||
|
|
527
|
+
enabledCurrencies.length > MAX_CURRENCIES ||
|
|
528
|
+
enabledCurrencies.some((currency) => !CURRENCY.test(currency)) ||
|
|
529
|
+
hasDuplicates(enabledCurrencies) ||
|
|
530
|
+
!enabledCurrencies.includes(defaultCurrency)) {
|
|
531
|
+
return reject("money-invalid", { claim: "money" });
|
|
532
|
+
}
|
|
533
|
+
const money = {};
|
|
534
|
+
setField(money, "defaultCurrency", defaultCurrency);
|
|
535
|
+
setField(money, "enabledCurrencies", enabledCurrencies);
|
|
536
|
+
return money;
|
|
537
|
+
}
|
|
538
|
+
// One work grant to sign: the given fields in Access's order, the id first
|
|
539
|
+
// (computed with workGrantId when absent; when the identity fields are not
|
|
540
|
+
// strings it stays absent and validateWorkGrantsV2 refuses the grant with its
|
|
541
|
+
// own rule). Unknown fields are kept so that the validator refuses them.
|
|
542
|
+
function workGrantToSign(fields, tenantId, sub) {
|
|
543
|
+
const body = {};
|
|
544
|
+
for (const field of WORK_GRANT_FIELD_ORDER) {
|
|
545
|
+
if (hasOwn(fields, field)) {
|
|
546
|
+
setField(body, field, field === "parentResource" ? { ...fields[field] } : fields[field]);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
for (const field of Object.keys(fields)) {
|
|
550
|
+
if (field !== "id" && !WORK_GRANT_FIELD_ORDER.includes(field)) {
|
|
551
|
+
setField(body, field, fields[field]);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
let id = fields.id;
|
|
555
|
+
if (id === undefined && typeof tenantId === "string" && typeof sub === "string") {
|
|
556
|
+
try {
|
|
557
|
+
id = workGrantId(tenantId, sub, body);
|
|
558
|
+
}
|
|
559
|
+
catch {
|
|
560
|
+
id = undefined;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
if (id === undefined) {
|
|
564
|
+
return body;
|
|
565
|
+
}
|
|
566
|
+
const grant = {};
|
|
567
|
+
setField(grant, "id", id);
|
|
568
|
+
for (const field of Object.keys(body)) {
|
|
569
|
+
setField(grant, field, body[field]);
|
|
570
|
+
}
|
|
571
|
+
return grant;
|
|
572
|
+
}
|
|
573
|
+
function workGrantsToSign(grants, tenantId, sub) {
|
|
574
|
+
const result = [];
|
|
575
|
+
for (const fields of grants) {
|
|
576
|
+
appendOwn(result, workGrantToSign(fields, tenantId, sub));
|
|
577
|
+
}
|
|
578
|
+
// Access sorts the signed list by id (access-domain.ts:339-341).
|
|
579
|
+
const idOf = (grant) => (typeof grant.id === "string" ? grant.id : "");
|
|
580
|
+
return result.sort((left, right) => (idOf(left) < idOf(right) ? -1 : idOf(left) > idOf(right) ? 1 : 0));
|
|
581
|
+
}
|
|
582
|
+
// ---------------------------------------------------------------------------
|
|
583
|
+
// Phase 3: serialize, check and sign (primordials only).
|
|
584
|
+
// ---------------------------------------------------------------------------
|
|
585
|
+
// JSON of the validated payload, in the order of its own keys. Only strings
|
|
586
|
+
// (JSON.stringify of a primitive string never looks up toJSON), safe integers
|
|
587
|
+
// (validated), arrays and records the helper built are ever serialized.
|
|
588
|
+
function serialize(value) {
|
|
589
|
+
if (typeof value === "string") {
|
|
590
|
+
return jsonStringify(value);
|
|
591
|
+
}
|
|
592
|
+
if (typeof value === "number") {
|
|
593
|
+
return `${value}`;
|
|
594
|
+
}
|
|
595
|
+
// Leaves of a test patientDataAccess claim (copyJsonValue admits only these).
|
|
596
|
+
if (value === null) {
|
|
597
|
+
return "null";
|
|
598
|
+
}
|
|
599
|
+
if (typeof value === "boolean") {
|
|
600
|
+
return value ? "true" : "false";
|
|
601
|
+
}
|
|
602
|
+
let text = "";
|
|
603
|
+
if (isArray(value)) {
|
|
604
|
+
const length = ownValue(value, "length");
|
|
605
|
+
for (let index = 0; index < length; index += 1) {
|
|
606
|
+
text = `${text}${index === 0 ? "" : ","}${serialize(ownValue(value, `${index}`))}`;
|
|
607
|
+
}
|
|
608
|
+
return `[${text}]`;
|
|
609
|
+
}
|
|
610
|
+
const keys = ownKeys(value);
|
|
611
|
+
for (let index = 0; index < keys.length; index += 1) {
|
|
612
|
+
const key = keys[index];
|
|
613
|
+
text = `${text}${index === 0 ? "" : ","}${jsonStringify(key)}:${serialize(ownValue(value, key))}`;
|
|
614
|
+
}
|
|
615
|
+
return `{${text}}`;
|
|
616
|
+
}
|
|
617
|
+
const BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
618
|
+
function base64Url(bytes) {
|
|
619
|
+
const length = byteLength(bytes);
|
|
620
|
+
const digit = (value) => BASE64URL[value & 63];
|
|
621
|
+
let text = "";
|
|
622
|
+
let index = 0;
|
|
623
|
+
for (; index + 2 < length; index += 3) {
|
|
624
|
+
const chunk = (bytes[index] << 16) | (bytes[index + 1] << 8) | bytes[index + 2];
|
|
625
|
+
text = `${text}${digit(chunk >> 18)}${digit(chunk >> 12)}${digit(chunk >> 6)}${digit(chunk)}`;
|
|
626
|
+
}
|
|
627
|
+
const rest = length - index;
|
|
628
|
+
if (rest > 0) {
|
|
629
|
+
const chunk = (bytes[index] << 16) | (rest === 2 ? bytes[index + 1] << 8 : 0);
|
|
630
|
+
text = `${text}${digit(chunk >> 18)}${digit(chunk >> 12)}${rest === 2 ? digit(chunk >> 6) : ""}`;
|
|
631
|
+
}
|
|
632
|
+
return text;
|
|
633
|
+
}
|
|
634
|
+
function deepFreeze(value) {
|
|
635
|
+
if (typeof value === "object" && value !== null && !isFrozen(value)) {
|
|
636
|
+
const keys = ownKeys(value);
|
|
637
|
+
for (let index = 0; index < keys.length; index += 1) {
|
|
638
|
+
deepFreeze(ownValue(value, keys[index]));
|
|
639
|
+
}
|
|
640
|
+
freeze(value);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
const HEADER = base64Url(utf8(serialize({ alg: "HS256", typ: "JWT" })));
|
|
644
|
+
/**
|
|
645
|
+
* Signs an internal authorization token v2 for tests and smokes (Node only:
|
|
646
|
+
* HS256 with node:crypto). It reads nothing from the environment: the secret,
|
|
647
|
+
* the time and every claim come from `input` (Date.now() is read once, by the
|
|
648
|
+
* copy, only when nowSeconds is absent). The test runtime is trusted; a cheap
|
|
649
|
+
* structural check refuses (`builtins-tampered`, nothing signed) a polluted
|
|
650
|
+
* Object.prototype/Array.prototype or a toJSON on a prototype (see the threat
|
|
651
|
+
* model at the top of the module). Before signing it
|
|
652
|
+
* validates the fixture as PKG-08 section 5 defines it and throws
|
|
653
|
+
* TestInternalAuthorizationInvalidError (nothing signed) when:
|
|
654
|
+
*
|
|
655
|
+
* - the secret is shorter than MIN_TEST_SECRET_BYTES (empty included);
|
|
656
|
+
* - the input, the claims or a nested record (a work grant, its parent,
|
|
657
|
+
* practitionerLink, money, a permission level) is not a plain record, has a
|
|
658
|
+
* symbol key or an accessor, or throws any value when read; a list
|
|
659
|
+
* (enabledProducts, permissions, permissionLevels, workGrants,
|
|
660
|
+
* money.enabledCurrencies) is not a dense array: a hole, an undefined or
|
|
661
|
+
* accessor element, an accessor length or a throwing proxy is refused.
|
|
662
|
+
* Everything is read once from own data descriptors (no getter runs) into
|
|
663
|
+
* copies, and only the copies are checked, signed and frozen;
|
|
664
|
+
* - nowSeconds (or the clock, when absent: a finite primitive number, never
|
|
665
|
+
* converted) is not a safe integer >= 0, or ttlSeconds is outside
|
|
666
|
+
* [MIN_, MAX_INTERNAL_AUTHORIZATION_TTL_SECONDS] (1 to 60: exp - iat <= 60);
|
|
667
|
+
* - a claim is not one the token carries (iat and exp included);
|
|
668
|
+
* - tokenUse, schemaVersion, iss or aud is given with another value than
|
|
669
|
+
* `internal-forward-auth`, `sail-work-authorization.v2`,
|
|
670
|
+
* INTERNAL_AUTHORIZATION_ISSUER or INTERNAL_AUTHORIZATION_AUDIENCE;
|
|
671
|
+
* - readInternalAuthorization of this package refuses the payload: required
|
|
672
|
+
* strings (sub, tenantId, licenseKey, sid, licenseStatus), optional
|
|
673
|
+
* non-empty role and username, authorizationVersion >= 1, enabledProducts
|
|
674
|
+
* only sail/connect, permissions only explicit catalog keys (any `*` is
|
|
675
|
+
* permission-wildcard, any other unknown key permission-unknown; checked
|
|
676
|
+
* before duplicates), capabilityCatalogVersion and permissionLevels shapes;
|
|
677
|
+
* - a permission is a serviceToService key (permission-service-only): the
|
|
678
|
+
* internal token is a user's token, and those keys are presented only by a
|
|
679
|
+
* service identity (not tenant-assignable, omitted by migrateGrants, E1);
|
|
680
|
+
* - enabledProducts or permissions repeat a value;
|
|
681
|
+
* - validateWorkGrantsV2 refuses the signed workGrants (ids computed with
|
|
682
|
+
* workGrantId from the tenantId and sub claims; a given id must be that one,
|
|
683
|
+
* so a legacy `|` id is refused; warehouse needs grantVersion; no
|
|
684
|
+
* duplicates; parentResource only on agenda and warehouse);
|
|
685
|
+
* - practitionerLink or money does not have the exact shape Access signs.
|
|
686
|
+
*
|
|
687
|
+
* Optional claims follow Access: enabledProducts and permissions are omitted
|
|
688
|
+
* when absent or empty, role and username when absent; permissionLevels is
|
|
689
|
+
* signed only when given; workGrants is always signed (sorted by id).
|
|
690
|
+
* Returns the token and the frozen payload exactly as signed.
|
|
691
|
+
*/
|
|
692
|
+
export function signTestInternalAuthorization(input) {
|
|
693
|
+
assertBuiltinsIntact();
|
|
694
|
+
// Phase 1: the only step in which input code (traps) can run.
|
|
695
|
+
const copy = copyFixture(input);
|
|
696
|
+
// A trap or the clock may have polluted a prototype while it ran. After this
|
|
697
|
+
// point no external code runs: only the copies are read.
|
|
698
|
+
assertBuiltinsIntact();
|
|
699
|
+
// Phase 2.
|
|
700
|
+
const secret = checkSecret(copy.secret);
|
|
701
|
+
const { iat, exp } = checkTime(copy.nowSeconds, copy.ttlSeconds);
|
|
702
|
+
const claims = copy.claims;
|
|
703
|
+
const extra = Object.keys(claims)
|
|
704
|
+
.filter((claim) => !ALLOWED_CLAIMS.has(claim))
|
|
705
|
+
.sort();
|
|
706
|
+
if (extra.length > 0) {
|
|
707
|
+
reject("claim-not-allowed", { claim: extra[0] });
|
|
708
|
+
}
|
|
709
|
+
if (claims.iss !== undefined && claims.iss !== INTERNAL_AUTHORIZATION_ISSUER) {
|
|
710
|
+
reject("issuer-invalid", { claim: "iss" });
|
|
711
|
+
}
|
|
712
|
+
if (claims.aud !== undefined && claims.aud !== INTERNAL_AUTHORIZATION_AUDIENCE) {
|
|
713
|
+
reject("audience-invalid", { claim: "aud" });
|
|
714
|
+
}
|
|
715
|
+
const enabledProducts = checkProducts(copy.enabledProducts);
|
|
716
|
+
const permissions = checkPermissions(copy.permissions);
|
|
717
|
+
const permissionLevels = checkPermissionLevels(copy.permissionLevels);
|
|
718
|
+
const workGrants = workGrantsToSign(copy.workGrants, claims.tenantId, claims.sub);
|
|
719
|
+
const practitionerLink = checkPractitionerLink(copy.practitionerLink);
|
|
720
|
+
const money = checkMoney(copy.money, copy.enabledCurrencies);
|
|
721
|
+
// Claim order of signInternalAuthorizationToken (seed-auth.ts:613-634), with
|
|
722
|
+
// capabilityCatalogVersion after permissions as in PKG-08 section 4.1.
|
|
723
|
+
const payload = {};
|
|
724
|
+
const put = (claim, value) => {
|
|
725
|
+
if (value !== undefined) {
|
|
726
|
+
setField(payload, claim, value);
|
|
727
|
+
}
|
|
728
|
+
};
|
|
729
|
+
const nonEmpty = (list) => (list !== undefined && list.length > 0 ? list : undefined);
|
|
730
|
+
put("tokenUse", claims.tokenUse === undefined ? INTERNAL_AUTHORIZATION_TOKEN_USE : claims.tokenUse);
|
|
731
|
+
put("iss", INTERNAL_AUTHORIZATION_ISSUER);
|
|
732
|
+
put("aud", INTERNAL_AUTHORIZATION_AUDIENCE);
|
|
733
|
+
put("sub", claims.sub);
|
|
734
|
+
put("tenantId", claims.tenantId);
|
|
735
|
+
put("licenseKey", claims.licenseKey);
|
|
736
|
+
put("sid", claims.sid);
|
|
737
|
+
put("iat", iat);
|
|
738
|
+
put("exp", exp);
|
|
739
|
+
put("schemaVersion", claims.schemaVersion === undefined ? AUTHORIZATION_SCHEMA_VERSION : claims.schemaVersion);
|
|
740
|
+
put("licenseStatus", claims.licenseStatus);
|
|
741
|
+
put("username", claims.username);
|
|
742
|
+
put("role", claims.role);
|
|
743
|
+
put("enabledProducts", nonEmpty(enabledProducts));
|
|
744
|
+
put("permissions", nonEmpty(permissions));
|
|
745
|
+
put("capabilityCatalogVersion", claims.capabilityCatalogVersion === undefined ? CAPABILITY_CATALOG_VERSION : claims.capabilityCatalogVersion);
|
|
746
|
+
put("permissionLevels", permissionLevels);
|
|
747
|
+
put("workGrants", workGrants);
|
|
748
|
+
put("practitionerLink", practitionerLink);
|
|
749
|
+
put("authorizationVersion", claims.authorizationVersion);
|
|
750
|
+
put("money", money);
|
|
751
|
+
put("patientDataAccess", copy.patientDataAccess);
|
|
752
|
+
const read = readInternalAuthorization(payload);
|
|
753
|
+
if (!read.ok) {
|
|
754
|
+
const claim = read.claim;
|
|
755
|
+
const reason = read.code === "AUTHORIZATION_CLAIM_INVALID" && claim !== undefined ? (CLAIM_REASONS[claim] ?? "claim-invalid") : READER_REASONS[read.code];
|
|
756
|
+
reject(reason, { claim });
|
|
757
|
+
}
|
|
758
|
+
// The internal token is a user's token: serviceToService keys are never
|
|
759
|
+
// granted to users (not tenant-assignable, omitted by migrateGrants, E1).
|
|
760
|
+
const serviceKeys = read.authorization.permissions.filter((key) => getCapability(key)?.serviceToService === true);
|
|
761
|
+
if (serviceKeys.length > 0) {
|
|
762
|
+
reject("permission-service-only", { claim: "permissions", unknownKeys: serviceKeys });
|
|
763
|
+
}
|
|
764
|
+
try {
|
|
765
|
+
validateWorkGrantsV2(workGrants, { tenantId: read.authorization.tenantId, sub: read.authorization.sub });
|
|
766
|
+
}
|
|
767
|
+
catch (error) {
|
|
768
|
+
// validateWorkGrantsV2 only throws WorkGrantsInvalidError.
|
|
769
|
+
const invalid = error;
|
|
770
|
+
reject("work-grants-invalid", { claim: "workGrants", workGrantsReason: invalid.reason, index: invalid.index });
|
|
771
|
+
}
|
|
772
|
+
// Phase 3: the bytes signed must be the validated copy.
|
|
773
|
+
assertBuiltinsIntact();
|
|
774
|
+
const json = serialize(payload);
|
|
775
|
+
if (serialize(jsonParse(json)) !== json) {
|
|
776
|
+
reject("builtins-tampered");
|
|
777
|
+
}
|
|
778
|
+
const body = `${HEADER}.${base64Url(utf8(json))}`;
|
|
779
|
+
const hmac = createHmac("sha256", secret);
|
|
780
|
+
apply(hmacUpdate, hmac, [body]);
|
|
781
|
+
const signature = apply(hmacDigest, hmac, ["base64url"]);
|
|
782
|
+
deepFreeze(payload);
|
|
783
|
+
return freeze({ token: `${body}.${signature}`, payload: payload });
|
|
784
|
+
}
|
|
785
|
+
//# sourceMappingURL=authorization-testing.js.map
|