@forgezero/access 0.1.1 → 0.1.3

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.
@@ -0,0 +1,548 @@
1
+ // src/index.ts
2
+ var SCHEMA_VERSION = 1;
3
+ function assertReadable(document, what) {
4
+ const version = document.version ?? 1;
5
+ if (version > SCHEMA_VERSION) {
6
+ throw new AccessError("ACCESS_VERSION_TOO_NEW", `${what} is version ${version}; this build reads ${SCHEMA_VERSION}. Upgrade @forgezero/access.`);
7
+ }
8
+ }
9
+
10
+ class AccessError extends Error {
11
+ code;
12
+ constructor(code, message) {
13
+ super(message);
14
+ this.code = code;
15
+ this.name = "AccessError";
16
+ }
17
+ }
18
+
19
+ class Refusal extends Error {
20
+ status;
21
+ code;
22
+ details;
23
+ retryable;
24
+ refusal = true;
25
+ constructor(status, code, message, details = {}, retryable = false) {
26
+ super(message);
27
+ this.status = status;
28
+ this.code = code;
29
+ this.details = details;
30
+ this.retryable = retryable;
31
+ this.name = "Refusal";
32
+ }
33
+ }
34
+ function isRefusal(error) {
35
+ return typeof error === "object" && error !== null && error.refusal === true;
36
+ }
37
+
38
+ class Settled extends Error {
39
+ value;
40
+ status;
41
+ headers;
42
+ settled = true;
43
+ constructor(value, status = 200, headers = {}) {
44
+ super("Already settled.");
45
+ this.value = value;
46
+ this.status = status;
47
+ this.headers = headers;
48
+ this.name = "Settled";
49
+ }
50
+ }
51
+ function isSettled(error) {
52
+ return typeof error === "object" && error !== null && error.settled === true;
53
+ }
54
+ function defineFactors(factors) {
55
+ for (const [id, factor] of Object.entries(factors)) {
56
+ if (factor.status === "shipped" && !(factor.tests?.length ?? 0)) {
57
+ throw new AccessError("FACTOR_UNTESTED", `Factor "${id}" is marked shipped with no tests. A method nobody exercises is a claim.`);
58
+ }
59
+ }
60
+ return factors;
61
+ }
62
+ function page(label, options = {}) {
63
+ return { kind: "page", label, accessGroup: "default", ...options };
64
+ }
65
+ function action(label, method, options = {}) {
66
+ return { kind: "action", label, method, accessGroup: "default", ...options };
67
+ }
68
+ function defineRoutes(routes) {
69
+ for (const [key, route] of Object.entries(routes)) {
70
+ if (!/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/.test(route.accessGroup)) {
71
+ throw new AccessError("ROUTE_ACCESS_INVALID", `"${key}": accessGroup must be a bounded name.`);
72
+ }
73
+ const isApi = key.startsWith("api/");
74
+ if (isApi !== (route.kind === "action")) {
75
+ throw new AccessError("ROUTE_KIND_MISMATCH", `"${key}": routes under api/ must be actions, and actions must be under api/.`);
76
+ }
77
+ if (route.kind === "action" && route.page && !(route.page in routes)) {
78
+ throw new AccessError("ROUTE_DANGLING_PAGE", `"${key}" names page "${route.page}", which does not exist.`);
79
+ }
80
+ if (route.kind === "action" && route.response) {
81
+ for (const status of Object.keys(route.response)) {
82
+ if (!route.response[Number(status)]) {
83
+ throw new AccessError("ROUTE_EMPTY_RESPONSE", `"${key}" declares status ${status} with no schema.`);
84
+ }
85
+ }
86
+ }
87
+ }
88
+ return routes;
89
+ }
90
+ function codePolicy(config) {
91
+ return {
92
+ roles: async () => config.roles,
93
+ enabledFactors: async () => config.enabledFactors
94
+ };
95
+ }
96
+ function externalPolicy(reader) {
97
+ return {
98
+ async roles() {
99
+ const roles = await reader.roles();
100
+ for (const role of roles)
101
+ assertReadable(role, `role "${role.roleKey}"`);
102
+ return roles;
103
+ },
104
+ enabledFactors: () => reader.enabledFactors()
105
+ };
106
+ }
107
+ function stemOf(routeKey, strip) {
108
+ const withoutApi = routeKey.startsWith("api/") ? routeKey.slice(4) : routeKey;
109
+ return strip ? withoutApi.replace(strip, "") : withoutApi;
110
+ }
111
+ function grantsRoute(grants, routeKey, options = {}) {
112
+ const { mode = "inherit", sharesGrantWith, strip } = options;
113
+ const stem = stemOf(routeKey, strip);
114
+ const shared = sharesGrantWith ? stemOf(sharesGrantWith, strip) : undefined;
115
+ return grants.some((grant) => {
116
+ const granted = stemOf(grant, strip);
117
+ if (stem === granted || granted === routeKey)
118
+ return true;
119
+ if (shared !== undefined && (granted === shared || granted === sharesGrantWith))
120
+ return true;
121
+ return mode === "inherit" && stem.startsWith(granted + "/");
122
+ });
123
+ }
124
+ function fulfilledActionFactors() {
125
+ return [];
126
+ }
127
+ function defineAccessControl(config) {
128
+ assertReadable(config, "access control");
129
+ const routeKeys = new Set(Object.keys(config.routes));
130
+ const actionKeys = Object.entries(config.routes).filter(([, route]) => route.kind === "action").map(([key]) => key);
131
+ const checkKeys = (listName, name, keys) => {
132
+ if (keys.length === 0) {
133
+ throw new AccessError("POLICY_ORPHANED", `${listName} "${name}" binds no routes.`);
134
+ }
135
+ for (const key of keys) {
136
+ if (!routeKeys.has(key)) {
137
+ throw new AccessError("POLICY_UNKNOWN_ROUTE", `${listName} "${name}" names "${key}", which is not a route.`);
138
+ }
139
+ }
140
+ };
141
+ const sessionOf = new Map;
142
+ for (const [name, policy] of Object.entries(config.sessionPolicies)) {
143
+ checkKeys("Session policy", name, policy.routes);
144
+ for (const key of policy.routes) {
145
+ if (sessionOf.has(key)) {
146
+ throw new AccessError("SESSION_DUPLICATE", `"${key}" is in more than one session policy.`);
147
+ }
148
+ sessionOf.set(key, policy);
149
+ }
150
+ for (const factor of policy.factors) {
151
+ const spec = config.factors[factor];
152
+ if (!spec)
153
+ throw new AccessError("FACTOR_UNKNOWN", `Session policy "${name}" names unknown factor "${factor}".`);
154
+ if (spec.kind === "action") {
155
+ throw new AccessError("FACTOR_WRONG_KIND", `"${factor}" is action-only and cannot establish a session.`);
156
+ }
157
+ }
158
+ }
159
+ const unclassified = [...routeKeys].filter((key) => !sessionOf.has(key));
160
+ if (unclassified.length > 0) {
161
+ throw new AccessError("SESSION_INCOMPLETE", `No session policy covers: ${unclassified.join(", ")}. Every route needs exactly one.`);
162
+ }
163
+ const actionOf = new Map;
164
+ for (const [name, policy] of Object.entries(config.actionPolicies ?? {})) {
165
+ checkKeys("Action policy", name, policy.routes);
166
+ if (policy.required < 1 || policy.required > policy.factors.length) {
167
+ throw new AccessError("ACTION_UNSATISFIABLE", `Action policy "${name}" requires ${policy.required} of ${policy.factors.length} factors.`);
168
+ }
169
+ for (const factor of policy.factors) {
170
+ const spec = config.factors[factor];
171
+ if (!spec)
172
+ throw new AccessError("FACTOR_UNKNOWN", `Action policy "${name}" names unknown factor "${factor}".`);
173
+ if (spec.kind === "session") {
174
+ throw new AccessError("FACTOR_WRONG_KIND", `"${factor}" is session-only and cannot authorise an action.`);
175
+ }
176
+ }
177
+ for (const key of policy.routes) {
178
+ if (actionOf.has(key)) {
179
+ throw new AccessError("ACTION_DUPLICATE", `"${key}" is in more than one action policy.`);
180
+ }
181
+ actionOf.set(key, policy);
182
+ }
183
+ }
184
+ const rateOf = new Map;
185
+ const rateLists = Object.entries(config.ratePolicies ?? {});
186
+ for (const [name, policy] of rateLists) {
187
+ checkKeys("Rate policy", name, policy.routes);
188
+ for (const key of policy.routes) {
189
+ if (rateOf.has(key)) {
190
+ throw new AccessError("RATE_DUPLICATE", `"${key}" is in more than one rate policy.`);
191
+ }
192
+ rateOf.set(key, policy);
193
+ }
194
+ }
195
+ if (rateLists.length > 0) {
196
+ const unrated = actionKeys.filter((key) => !rateOf.has(key));
197
+ if (unrated.length > 0) {
198
+ throw new AccessError("RATE_INCOMPLETE", `No rate policy covers: ${unrated.join(", ")}. Declaring any means declaring all.`);
199
+ }
200
+ }
201
+ const beforeOf = new Map;
202
+ for (const [name, handler] of Object.entries(config.beforeHandlers ?? {})) {
203
+ checkKeys("Before handler", name, handler.routes);
204
+ for (const key of handler.routes) {
205
+ beforeOf.set(key, [...beforeOf.get(key) ?? [], handler]);
206
+ }
207
+ }
208
+ const afterOf = new Map;
209
+ for (const [name, handler] of Object.entries(config.afterHandlers ?? {})) {
210
+ checkKeys("After handler", name, handler.routes);
211
+ for (const key of handler.routes) {
212
+ afterOf.set(key, [...afterOf.get(key) ?? [], handler]);
213
+ }
214
+ }
215
+ const features = config.features ?? [];
216
+ return {
217
+ version: config.version ?? SCHEMA_VERSION,
218
+ routes: config.routes,
219
+ features,
220
+ source: config.source,
221
+ keys: () => Object.keys(config.routes),
222
+ get: (key) => config.routes[key],
223
+ exists(key, context) {
224
+ const route = config.routes[key];
225
+ if (!route)
226
+ return false;
227
+ if (route.feature && !features.includes(route.feature))
228
+ return false;
229
+ if (context?.stage && route.stages && !route.stages.includes(context.stage))
230
+ return false;
231
+ if (context?.realm && route.realms && !route.realms.includes(context.realm))
232
+ return false;
233
+ return true;
234
+ },
235
+ sessionPolicyFor: (key) => sessionOf.get(key),
236
+ actionPolicyFor: (key) => actionOf.get(key),
237
+ ratePolicyFor: (key) => rateOf.get(key),
238
+ beforeFor: (key) => beforeOf.get(key) ?? [],
239
+ afterFor: (key) => afterOf.get(key) ?? []
240
+ };
241
+ }
242
+ function authorise(args) {
243
+ const { access, routeKey, stage, realm, session, roles } = args;
244
+ if (!access.exists(routeKey, { stage, realm })) {
245
+ return { allow: false, status: 404, code: "NOT_FOUND" };
246
+ }
247
+ const policy = access.sessionPolicyFor(routeKey);
248
+ if ((policy?.factors.length ?? 0) === 0)
249
+ return { allow: true };
250
+ if (!session)
251
+ return { allow: false, status: 401, code: "AUTH_REQUIRED" };
252
+ const missing = (policy?.factors ?? []).filter((factor) => !session.factors.includes(factor));
253
+ if (missing.length > 0) {
254
+ return { allow: false, status: 428, code: "SECURITY_REQUIRED", missing };
255
+ }
256
+ const grants = roles.filter((role) => session.roleKeys.includes(role.roleKey)).flatMap((role) => role.grants);
257
+ if (!grantsRoute(grants, routeKey)) {
258
+ return { allow: false, status: 403, code: "ACCESS_DENIED" };
259
+ }
260
+ return { allow: true };
261
+ }
262
+ function resolveActionFactors(policy, enabled) {
263
+ const available = policy.factors.filter((factor) => enabled.includes(factor));
264
+ return { available, required: policy.required, satisfiable: available.length >= policy.required };
265
+ }
266
+ function impactOfDisabling(access, enabledAfter) {
267
+ const broken = [];
268
+ for (const key of access.keys()) {
269
+ const policy = access.actionPolicyFor(key);
270
+ if (!policy)
271
+ continue;
272
+ const { available, required, satisfiable } = resolveActionFactors(policy, enabledAfter);
273
+ if (!satisfiable)
274
+ broken.push({ route: key, available: available.length, required });
275
+ }
276
+ return broken;
277
+ }
278
+ var VERSION = "0.1.0";
279
+
280
+ // src/security.ts
281
+ var HEX = Array.from({ length: 256 }, (_, index) => index.toString(16).padStart(2, "0"));
282
+ function toHex(bytes) {
283
+ let out = "";
284
+ for (const byte of bytes)
285
+ out += HEX[byte];
286
+ return out;
287
+ }
288
+ function fromHex(hex) {
289
+ if (hex.length % 2 !== 0)
290
+ throw new Error("Hex string must have an even length.");
291
+ const bytes = new Uint8Array(hex.length / 2);
292
+ for (let index = 0;index < bytes.length; index += 1) {
293
+ bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);
294
+ }
295
+ return bytes;
296
+ }
297
+ function toBase64Url(bytes) {
298
+ let binary = "";
299
+ for (const byte of bytes)
300
+ binary += String.fromCharCode(byte);
301
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
302
+ }
303
+ function fromBase64Url(value) {
304
+ const padded = value.replace(/-/g, "+").replace(/_/g, "/");
305
+ const binary = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
306
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
307
+ }
308
+ function timingSafeEqual(a, b) {
309
+ if (a.length !== b.length)
310
+ return false;
311
+ let difference = 0;
312
+ for (let index = 0;index < a.length; index += 1) {
313
+ difference |= a.charCodeAt(index) ^ b.charCodeAt(index);
314
+ }
315
+ return difference === 0;
316
+ }
317
+ function randomToken(bytes = 32) {
318
+ const buffer = new Uint8Array(bytes);
319
+ crypto.getRandomValues(buffer);
320
+ return toBase64Url(buffer);
321
+ }
322
+ function randomHex(bytes = 32) {
323
+ const buffer = new Uint8Array(bytes);
324
+ crypto.getRandomValues(buffer);
325
+ return toHex(buffer);
326
+ }
327
+ function randomDigits(length = 6) {
328
+ let digits = "";
329
+ for (let index = 0;index < length; index += 1)
330
+ digits += randomInt(10).toString();
331
+ return digits;
332
+ }
333
+ function randomInt(max) {
334
+ if (max <= 0 || max > 256)
335
+ throw new Error("randomInt supports 1..256.");
336
+ const limit = Math.floor(256 / max) * max;
337
+ const buffer = new Uint8Array(1);
338
+ for (;; ) {
339
+ crypto.getRandomValues(buffer);
340
+ if (buffer[0] < limit)
341
+ return buffer[0] % max;
342
+ }
343
+ }
344
+ async function sha256(input) {
345
+ const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
346
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
347
+ return toHex(new Uint8Array(digest));
348
+ }
349
+ var hashToken = sha256;
350
+ async function hmacSha256(key, message) {
351
+ const keyBytes = typeof key === "string" ? new TextEncoder().encode(key) : key;
352
+ const imported = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
353
+ const signature = await crypto.subtle.sign("HMAC", imported, new TextEncoder().encode(message));
354
+ return toHex(new Uint8Array(signature));
355
+ }
356
+ async function verifyHmac(key, message, signature) {
357
+ return timingSafeEqual(await hmacSha256(key, message), signature);
358
+ }
359
+ async function hkdf(secret, info, length = 32, salt = new Uint8Array(32)) {
360
+ const key = await crypto.subtle.importKey("raw", secret, "HKDF", false, ["deriveBits"]);
361
+ const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: new TextEncoder().encode(info) }, key, length * 8);
362
+ return new Uint8Array(bits);
363
+ }
364
+ async function seal(key, plaintext, aad) {
365
+ const iv = new Uint8Array(12);
366
+ crypto.getRandomValues(iv);
367
+ const imported = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]);
368
+ const ciphertext = await crypto.subtle.encrypt({
369
+ name: "AES-GCM",
370
+ iv,
371
+ ...aad ? { additionalData: new TextEncoder().encode(aad) } : {}
372
+ }, imported, new TextEncoder().encode(plaintext));
373
+ return { iv: toBase64Url(iv), ciphertext: toBase64Url(new Uint8Array(ciphertext)) };
374
+ }
375
+ async function open(key, sealed, aad) {
376
+ const imported = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
377
+ const plaintext = await crypto.subtle.decrypt({
378
+ name: "AES-GCM",
379
+ iv: fromBase64Url(sealed.iv),
380
+ ...aad ? { additionalData: new TextEncoder().encode(aad) } : {}
381
+ }, imported, fromBase64Url(sealed.ciphertext));
382
+ return new TextDecoder().decode(plaintext);
383
+ }
384
+ var nowSeconds = () => Math.floor(Date.now() / 1000);
385
+ var isLive = (expiresAtSec, at = nowSeconds()) => expiresAtSec > at;
386
+ var SECRET_NAME = /token|secret|password|passphrase|credential|authorization|cookie|apikey|api_key|private/i;
387
+ function redact(value) {
388
+ const out = {};
389
+ for (const [name, entry] of Object.entries(value)) {
390
+ if (SECRET_NAME.test(name))
391
+ out[name] = "[redacted]";
392
+ else if (entry && typeof entry === "object" && !Array.isArray(entry)) {
393
+ out[name] = redact(entry);
394
+ } else
395
+ out[name] = entry;
396
+ }
397
+ return out;
398
+ }
399
+ // src/principal.ts
400
+ var ATOM = /^[A-Za-z0-9][A-Za-z0-9_.:@/-]{0,255}$/;
401
+ var GROUP = /^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;
402
+ var METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
403
+ function uniqueAtoms(values, max, pattern = ATOM) {
404
+ return values.length <= max && new Set(values).size === values.length && values.every((value) => pattern.test(value));
405
+ }
406
+ function defineRbacPrincipal(principal) {
407
+ if (!ATOM.test(principal.kind) || !ATOM.test(principal.principalKey) || principal.assignments.length > 32) {
408
+ throw new AccessError("PRINCIPAL_INVALID", "The principal kind, key, or assignment count is invalid.");
409
+ }
410
+ const assignmentKeys = new Set;
411
+ for (const assignment of principal.assignments) {
412
+ if (!ATOM.test(assignment.assignmentKey) || assignmentKeys.has(assignment.assignmentKey) || !uniqueAtoms(assignment.roleKeys, 128) || !uniqueAtoms(assignment.accessGroups, 32, GROUP) || !uniqueAtoms(assignment.sessionFactors, 32) || assignment.methods.length === 0 || assignment.methods.length > METHODS.size || new Set(assignment.methods).size !== assignment.methods.length || assignment.methods.some((method) => !METHODS.has(method))) {
413
+ throw new AccessError("PRINCIPAL_ASSIGNMENT_INVALID", "A principal assignment is malformed, duplicate, or unbounded.");
414
+ }
415
+ if (assignment.idleTtlMs === undefined !== (assignment.lastActiveAtMs === undefined) || assignment.idleTtlMs !== undefined && (!Number.isSafeInteger(assignment.idleTtlMs) || assignment.idleTtlMs <= 0) || assignment.lastActiveAtMs !== undefined && (!Number.isSafeInteger(assignment.lastActiveAtMs) || assignment.lastActiveAtMs < 0) || assignment.absoluteExpiresAtMs !== undefined && (!Number.isSafeInteger(assignment.absoluteExpiresAtMs) || assignment.absoluteExpiresAtMs < 0)) {
416
+ throw new AccessError("PRINCIPAL_ASSIGNMENT_INVALID", "Assignment expiry coordinates are incomplete or invalid.");
417
+ }
418
+ if (assignment.delegatedBy && (!ATOM.test(assignment.delegatedBy.userKey) || !ATOM.test(assignment.delegatedBy.sessionKey) || !Number.isSafeInteger(assignment.delegatedBy.atMs))) {
419
+ throw new AccessError("PRINCIPAL_ASSIGNMENT_INVALID", "Assignment delegation binding is invalid.");
420
+ }
421
+ assignmentKeys.add(assignment.assignmentKey);
422
+ }
423
+ return principal;
424
+ }
425
+ function assignmentIsActive(assignment, now = Date.now()) {
426
+ if (assignment.absoluteExpiresAtMs !== undefined && now >= assignment.absoluteExpiresAtMs)
427
+ return false;
428
+ if (assignment.idleTtlMs !== undefined && assignment.lastActiveAtMs !== undefined && now >= assignment.lastActiveAtMs + assignment.idleTtlMs)
429
+ return false;
430
+ return true;
431
+ }
432
+ function touchPrincipalAssignment(assignment, now = Date.now()) {
433
+ if (!assignmentIsActive(assignment, now) || assignment.idleTtlMs === undefined)
434
+ return assignment;
435
+ return { ...assignment, lastActiveAtMs: now };
436
+ }
437
+ function decidePrincipalAccess(args) {
438
+ const route = args.access.get(args.routeKey);
439
+ if (!route || !args.access.exists(args.routeKey, { stage: args.stage, realm: args.realm }) || route.kind === "action" && args.method !== undefined && route.method !== args.method) {
440
+ return { allow: false, status: 404, code: "NOT_FOUND" };
441
+ }
442
+ if (route.accessGroup === "public")
443
+ return { allow: true, public: true };
444
+ if (!args.principal)
445
+ return { allow: false, status: 401, code: "AUTH_REQUIRED" };
446
+ const principal = defineRbacPrincipal(args.principal);
447
+ const policy = args.access.sessionPolicyFor(args.routeKey);
448
+ const requiredFactors = policy?.factors ?? [];
449
+ let missing;
450
+ for (const assignment of principal.assignments) {
451
+ if (!assignmentIsActive(assignment, args.now) || !assignment.accessGroups.includes(route.accessGroup) || route.kind === "action" && !assignment.methods.includes(route.method))
452
+ continue;
453
+ const absent = requiredFactors.filter((factor) => !assignment.sessionFactors.includes(factor));
454
+ if (absent.length > 0) {
455
+ missing = missing === undefined ? absent : [...new Set([...missing, ...absent])];
456
+ continue;
457
+ }
458
+ const grants = args.roles.filter((role) => assignment.roleKeys.includes(role.roleKey)).flatMap((role) => role.grants);
459
+ if (!grantsRoute(grants, args.routeKey, {
460
+ mode: route.grantMode,
461
+ sharesGrantWith: route.sharesGrantWith
462
+ }))
463
+ continue;
464
+ const action2 = args.access.actionPolicyFor(args.routeKey);
465
+ if (action2 && !args.actionProofSatisfied) {
466
+ return {
467
+ allow: false,
468
+ status: 428,
469
+ code: "ACTION_REQUIRED",
470
+ missing: action2.factors,
471
+ required: action2.required
472
+ };
473
+ }
474
+ return { allow: true, public: false, assignmentKey: assignment.assignmentKey };
475
+ }
476
+ if (missing?.length)
477
+ return { allow: false, status: 428, code: "SECURITY_REQUIRED", missing };
478
+ return { allow: false, status: 403, code: "ACCESS_DENIED" };
479
+ }
480
+
481
+ // src/principal-session.ts
482
+ var DEFAULT_PRINCIPAL_IDLE_TTL_MS = 30 * 60 * 1000;
483
+ var DEFAULT_PRINCIPAL_ABSOLUTE_TTL_MS = 8 * 60 * 60 * 1000;
484
+ var MAX_PRINCIPAL_IDLE_TTL_MS = 60 * 60 * 1000;
485
+ var MAX_PRINCIPAL_ABSOLUTE_TTL_MS = 24 * 60 * 60 * 1000;
486
+ function validTtl(value, maximum) {
487
+ return Number.isSafeInteger(value) && value > 0 && value <= maximum;
488
+ }
489
+ async function issuePrincipalSession(args) {
490
+ if (args.clientIdentity.length < 16 || args.clientIdentity.length > 256 || /[\0\r\n]/.test(args.clientIdentity)) {
491
+ throw new AccessError("PRINCIPAL_CLIENT_IDENTITY_INVALID", "Client identity must be a bounded opaque value.");
492
+ }
493
+ const idleTtlMs = args.idleTtlMs ?? DEFAULT_PRINCIPAL_IDLE_TTL_MS;
494
+ const absoluteTtlMs = args.absoluteTtlMs ?? DEFAULT_PRINCIPAL_ABSOLUTE_TTL_MS;
495
+ if (!validTtl(idleTtlMs, MAX_PRINCIPAL_IDLE_TTL_MS) || !validTtl(absoluteTtlMs, MAX_PRINCIPAL_ABSOLUTE_TTL_MS) || idleTtlMs > absoluteTtlMs) {
496
+ throw new AccessError("PRINCIPAL_SESSION_TTL_INVALID", "Principal session TTLs are invalid or exceed package limits.");
497
+ }
498
+ const principal = defineRbacPrincipal({
499
+ kind: args.kind,
500
+ principalKey: args.principalKey,
501
+ assignments: args.assignments ?? []
502
+ });
503
+ const credential = randomToken(32);
504
+ const now = args.now ?? Date.now();
505
+ return {
506
+ credential,
507
+ record: {
508
+ sessionKey: randomToken(24),
509
+ principalKey: principal.principalKey,
510
+ kind: principal.kind,
511
+ status: "active",
512
+ credentialHash: await hashToken(credential),
513
+ clientIdentityHash: await hashToken(args.clientIdentity),
514
+ assignments: principal.assignments,
515
+ createdAtMs: now,
516
+ lastActiveAtMs: now,
517
+ idleTtlMs,
518
+ absoluteExpiresAtMs: now + absoluteTtlMs
519
+ }
520
+ };
521
+ }
522
+ function principalSessionIsActive(record, now = Date.now()) {
523
+ return record.status === "active" && now < record.absoluteExpiresAtMs && now < record.lastActiveAtMs + record.idleTtlMs;
524
+ }
525
+ async function authenticatePrincipalSession(record, args) {
526
+ if (!principalSessionIsActive(record, args.now))
527
+ return;
528
+ if (!timingSafeEqual(await hashToken(args.credential), record.credentialHash) || !timingSafeEqual(await hashToken(args.clientIdentity), record.clientIdentityHash))
529
+ return;
530
+ return defineRbacPrincipal({
531
+ kind: record.kind,
532
+ principalKey: record.principalKey,
533
+ assignments: record.assignments
534
+ });
535
+ }
536
+ function touchPrincipalSession(record, now = Date.now()) {
537
+ return principalSessionIsActive(record, now) ? { ...record, lastActiveAtMs: now } : record;
538
+ }
539
+ export {
540
+ touchPrincipalSession,
541
+ principalSessionIsActive,
542
+ issuePrincipalSession,
543
+ authenticatePrincipalSession,
544
+ MAX_PRINCIPAL_IDLE_TTL_MS,
545
+ MAX_PRINCIPAL_ABSOLUTE_TTL_MS,
546
+ DEFAULT_PRINCIPAL_IDLE_TTL_MS,
547
+ DEFAULT_PRINCIPAL_ABSOLUTE_TTL_MS
548
+ };
@@ -0,0 +1,56 @@
1
+ import { type AccessControl, type Method, type Role, type RouteRegistry } from './index';
2
+ /** One independently revocable RBAC layer on a principal. */
3
+ export interface PrincipalAssignment {
4
+ assignmentKey: string;
5
+ roleKeys: readonly string[];
6
+ accessGroups: readonly string[];
7
+ methods: readonly Method[];
8
+ /** Session-level facts copied only by a trusted delegation issuer. */
9
+ sessionFactors: readonly string[];
10
+ /** Optional sliding-idle boundary. Omit for a persistent admin assignment. */
11
+ idleTtlMs?: number;
12
+ lastActiveAtMs?: number;
13
+ /** A sliding touch can never move this hard boundary. */
14
+ absoluteExpiresAtMs?: number;
15
+ delegatedBy?: {
16
+ userKey: string;
17
+ sessionKey: string;
18
+ atMs: number;
19
+ };
20
+ }
21
+ export interface RbacPrincipal {
22
+ kind: string;
23
+ principalKey: string;
24
+ assignments: readonly PrincipalAssignment[];
25
+ }
26
+ export type PrincipalAccessDecision = {
27
+ allow: true;
28
+ public: boolean;
29
+ assignmentKey?: string;
30
+ } | {
31
+ allow: false;
32
+ status: 401 | 403 | 404 | 428;
33
+ code: 'NOT_FOUND' | 'AUTH_REQUIRED' | 'ACCESS_DENIED' | 'SECURITY_REQUIRED' | 'ACTION_REQUIRED';
34
+ missing?: readonly string[];
35
+ required?: number;
36
+ };
37
+ /** Validate persisted/external principal data before it becomes authority. */
38
+ export declare function defineRbacPrincipal<T extends RbacPrincipal>(principal: T): T;
39
+ export declare function assignmentIsActive(assignment: PrincipalAssignment, now?: number): boolean;
40
+ /** Pure sliding-idle update; persistence and compare-and-swap remain host-owned. */
41
+ export declare function touchPrincipalAssignment(assignment: PrincipalAssignment, now?: number): PrincipalAssignment;
42
+ /**
43
+ * One authorization decision shared by browser-delegated and verified-header
44
+ * principals. Authentication is deliberately outside this function.
45
+ */
46
+ export declare function decidePrincipalAccess<R extends RouteRegistry>(args: {
47
+ access: AccessControl<R>;
48
+ routeKey: string;
49
+ method?: Method;
50
+ stage?: string;
51
+ realm?: string;
52
+ principal?: RbacPrincipal;
53
+ roles: readonly Role[];
54
+ actionProofSatisfied?: boolean;
55
+ now?: number;
56
+ }): PrincipalAccessDecision;