endpoint-permissions-kit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,594 @@
1
+ // src/constants.ts
2
+ var METHODS = ["find", "update", "create", "remove"];
3
+ var GENERAL_ROLE = "general";
4
+ var GLOBAL_HOOK_OWNER = "*";
5
+ var ALL_FIELDS = "*";
6
+ var MODULE_SEPARATOR = ".";
7
+ var PERMISSION_ID_SEPARATOR = "::";
8
+
9
+ // src/state.ts
10
+ function getOrCreateState() {
11
+ const stateKey = Symbol.for("endpoint-permissions-kit");
12
+ const stateHost = globalThis;
13
+ if (stateHost[stateKey] === undefined) {
14
+ stateHost[stateKey] = { roles: new Set([GENERAL_ROLE]), modules: new Map, snapshot: null };
15
+ }
16
+ return stateHost[stateKey];
17
+ }
18
+
19
+ // src/errors.ts
20
+ function pkitError(code, message) {
21
+ return Object.assign(new Error(message), { name: "PkitError", code });
22
+ }
23
+
24
+ // src/resolve.ts
25
+ var DIRECT_AUTHORIZATION = Object.freeze({ direct: true, grantedBy: Object.freeze([]) });
26
+ var DISABLED_ACCESS = Object.freeze({ status: "disabled" });
27
+ var UNASSIGNED_ACCESS = Object.freeze({ status: "unassigned" });
28
+ function permissionIdOf(role, action, name) {
29
+ return [role, action, name].join(PERMISSION_ID_SEPARATOR);
30
+ }
31
+ function resolveAccess(nameEntry, permissionId, role, method, assigned) {
32
+ if (assigned.has(permissionId))
33
+ return resolveDirectAccess(nameEntry, role, method);
34
+ return resolveGrantedAccess(nameEntry, method, assigned);
35
+ }
36
+ function resolveDirectAccess(nameEntry, role, method) {
37
+ const definition = nameEntry.actions.get(role)?.[method];
38
+ if (!definition?.enabled)
39
+ return DISABLED_ACCESS;
40
+ return { status: "granted", properties: definition.properties, authorization: DIRECT_AUTHORIZATION };
41
+ }
42
+ function resolveGrantedAccess(nameEntry, method, assigned) {
43
+ const grantedBy = [];
44
+ const properties = new Set;
45
+ let reachable = false;
46
+ for (const [enablingId, grant] of nameEntry.grants) {
47
+ if (!assigned.has(enablingId))
48
+ continue;
49
+ reachable = true;
50
+ const definition = grant.actions[method];
51
+ if (!definition)
52
+ continue;
53
+ grantedBy.push(enablingId);
54
+ for (const field of definition.properties)
55
+ properties.add(field);
56
+ }
57
+ if (grantedBy.length === 0)
58
+ return reachable ? DISABLED_ACCESS : UNASSIGNED_ACCESS;
59
+ const authorization = Object.freeze({ direct: false, grantedBy: Object.freeze(grantedBy.sort()) });
60
+ return { status: "granted", properties: Object.freeze([...properties]), authorization };
61
+ }
62
+
63
+ // src/validators.ts
64
+ function validateObject(value, failure) {
65
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
66
+ throw pkitError(failure.code, failure.message);
67
+ }
68
+ }
69
+ function validateStrings(value, rules) {
70
+ if (!Array.isArray(value))
71
+ throw pkitError(rules.code, rules.message);
72
+ for (const field of value) {
73
+ if (typeof field !== "string" || field.length < rules.minimumLength) {
74
+ throw pkitError(rules.code, rules.message);
75
+ }
76
+ }
77
+ }
78
+ function validateContextKey(key) {
79
+ if (key !== "roles")
80
+ throw pkitError("INVALID_DEFINITION", `unknown context key: "${String(key)}"`);
81
+ }
82
+ function validateOpenRegistry(state) {
83
+ if (state.snapshot)
84
+ throw pkitError("SEALED", "pkit.seal() was already called: no more registrations allowed");
85
+ }
86
+ function validateSnapshot(snapshot) {
87
+ if (snapshot === null) {
88
+ throw pkitError("NOT_SEALED", "pkit.seal() has not been called: call it after importing every permission file");
89
+ }
90
+ }
91
+ function validateRole(role, roles, code) {
92
+ if (typeof role === "string" && roles.has(role))
93
+ return;
94
+ if (code === "ROLE_NOT_DECLARED") {
95
+ throw pkitError(code, `role "${String(role)}" is not declared. Available roles: ${[...roles].join(", ")}.
96
+ ` + "Is pkit.context.set('roles', [...]) missing from pkit.config.js, or was it imported after this file?");
97
+ }
98
+ throw pkitError(code, `role "${String(role)}" is not declared`);
99
+ }
100
+ function validateRoleCatalog(roles, state) {
101
+ validateOpenRegistry(state);
102
+ if (state.modules.size) {
103
+ throw pkitError("INVALID_DEFINITION", "roles must be declared before registering permissions: import pkit.config.js first");
104
+ }
105
+ validateStrings(roles, {
106
+ code: "INVALID_DEFINITION",
107
+ message: "roles must be an array of non-empty strings",
108
+ minimumLength: 1
109
+ });
110
+ if (roles.length === 0)
111
+ throw pkitError("INVALID_DEFINITION", "roles must declare at least one role");
112
+ for (const role of roles)
113
+ validateRoleSegment(role);
114
+ }
115
+ function isCleanSegment(value) {
116
+ return value.length > 0 && value.trim() === value && !value.includes(":");
117
+ }
118
+ function validateRoleSegment(role) {
119
+ if (typeof role === "string" && isCleanSegment(role) && role !== GLOBAL_HOOK_OWNER)
120
+ return;
121
+ throw pkitError("INVALID_DEFINITION", `invalid role: "${String(role)}" (non-empty string, no ":" or surrounding whitespace; "${GLOBAL_HOOK_OWNER}" is reserved for global hooks)`);
122
+ }
123
+ function validateModuleName(moduleName) {
124
+ if (typeof moduleName === "string" && isCleanSegment(moduleName) && !moduleName.includes(MODULE_SEPARATOR))
125
+ return;
126
+ throw pkitError("INVALID_DEFINITION", `invalid module name: "${String(moduleName)}" (non-empty string, no dots, no ":" or surrounding whitespace)`);
127
+ }
128
+ function validatePermissionName(name) {
129
+ if (typeof name === "string" && isCleanSegment(name) && name !== GLOBAL_HOOK_OWNER)
130
+ return;
131
+ throw pkitError("INVALID_DEFINITION", `invalid permission name: "${String(name)}" (non-empty string, no ":" or surrounding whitespace; "*" is reserved)`);
132
+ }
133
+ function parsePermissionId(value, failure) {
134
+ if (typeof value !== "string")
135
+ throw pkitError(failure.code, failure.message);
136
+ const parts = value.split(PERMISSION_ID_SEPARATOR);
137
+ const [role, action, name] = parts;
138
+ if (parts.length !== 3 || role === undefined || action === undefined || name === undefined) {
139
+ throw pkitError(failure.code, failure.message);
140
+ }
141
+ const isValidRole = isCleanSegment(role) && role !== GLOBAL_HOOK_OWNER;
142
+ const isValidName = isCleanSegment(name) && name !== GLOBAL_HOOK_OWNER;
143
+ const isValidAction = action.split(MODULE_SEPARATOR).every(isCleanSegment);
144
+ if (!isValidRole || !isValidName || !isValidAction)
145
+ throw pkitError(failure.code, failure.message);
146
+ return { role, action, name };
147
+ }
148
+ function validateMethod(method, failure) {
149
+ if (METHODS.includes(method))
150
+ return;
151
+ throw pkitError(failure.code, `${failure.message}: method "${String(method)}" does not exist. Methods: ${METHODS.join(", ")}`);
152
+ }
153
+ function readActionDefinition(definition, permissionPath) {
154
+ validateObject(definition, { code: "INVALID_DEFINITION", message: `${permissionPath}: must be an object` });
155
+ if (typeof definition.enabled !== "boolean") {
156
+ throw pkitError("INVALID_DEFINITION", `${permissionPath}: enabled must be a boolean`);
157
+ }
158
+ const { properties } = definition;
159
+ if (properties === ALL_FIELDS)
160
+ return Object.freeze({ enabled: definition.enabled, properties });
161
+ validateStrings(properties, {
162
+ code: "INVALID_DEFINITION",
163
+ message: `${permissionPath}: properties must be string[] or '*'`,
164
+ minimumLength: 1
165
+ });
166
+ if (properties.includes(ALL_FIELDS)) {
167
+ throw pkitError("INVALID_DEFINITION", `${permissionPath}: '${ALL_FIELDS}' is only allowed as the whole properties value`);
168
+ }
169
+ if (new Set(properties).size !== properties.length) {
170
+ throw pkitError("INVALID_DEFINITION", `${permissionPath}: properties contains duplicate fields`);
171
+ }
172
+ return Object.freeze({ enabled: definition.enabled, properties: Object.freeze([...properties]) });
173
+ }
174
+ function readActionDefinitions(actions, permissionPath) {
175
+ validateObject(actions, { code: "INVALID_DEFINITION", message: `${permissionPath}: registerActions expects an object` });
176
+ const registeredActions = Object.create(null);
177
+ for (const [method, definition] of Object.entries(actions)) {
178
+ validateMethod(method, { code: "INVALID_DEFINITION", message: permissionPath });
179
+ registeredActions[method] = readActionDefinition(definition, `${permissionPath}.${method}`);
180
+ }
181
+ return Object.freeze(registeredActions);
182
+ }
183
+ function validateActions(actions, registration, state) {
184
+ const { action, name, role } = registration;
185
+ validateOpenRegistry(state);
186
+ validateRole(role, state.roles, "ROLE_NOT_DECLARED");
187
+ if (state.modules.get(action)?.names.get(name)?.actions.has(role)) {
188
+ throw pkitError("DUPLICATE_REGISTRATION", `"${action}::${name}" already has actions registered for role "${role}"`);
189
+ }
190
+ return readActionDefinitions(actions, `${action}::${name} [${role}]`);
191
+ }
192
+ function validateGrantActions(actions, registration, state) {
193
+ const { action, name, permissionId } = registration;
194
+ validateOpenRegistry(state);
195
+ const source = parsePermissionId(permissionId, {
196
+ code: "INVALID_DEFINITION",
197
+ message: `"${action}::${name}": invalid grantTo identifier: "${String(permissionId)}" (format role::module::name)`
198
+ });
199
+ validateRole(source.role, state.roles, "ROLE_NOT_DECLARED");
200
+ if (source.action === action && source.name === name) {
201
+ throw pkitError("INVALID_DEFINITION", `"${permissionId}" cannot grant to itself`);
202
+ }
203
+ if (state.modules.get(action)?.names.get(name)?.grants.has(permissionId)) {
204
+ throw pkitError("DUPLICATE_REGISTRATION", `"${action}::${name}" already has a grant for "${permissionId}"`);
205
+ }
206
+ const permissionPath = `${action}::${name} [grantTo ${permissionId}]`;
207
+ const registeredActions = readActionDefinitions(actions, permissionPath);
208
+ for (const [method, definition] of Object.entries(registeredActions)) {
209
+ if (definition.enabled !== true) {
210
+ throw pkitError("INVALID_DEFINITION", `${permissionPath}.${method}: a grant does not allow enabled: false`);
211
+ }
212
+ if (definition.properties === ALL_FIELDS) {
213
+ throw pkitError("INVALID_DEFINITION", `${permissionPath}.${method}: a grant requires an explicit properties list`);
214
+ }
215
+ }
216
+ return { source, actions: registeredActions };
217
+ }
218
+ function validateHook(hook, registration, state) {
219
+ const { action, name, role, method } = registration;
220
+ validateOpenRegistry(state);
221
+ if (role !== undefined && role !== GLOBAL_HOOK_OWNER)
222
+ validateRole(role, state.roles, "ROLE_NOT_DECLARED");
223
+ const permissionPath = name === undefined ? action : `${action}::${name}`;
224
+ validateMethod(method, { code: "INVALID_DEFINITION", message: permissionPath });
225
+ if (typeof hook !== "function")
226
+ throw pkitError("INVALID_DEFINITION", `${permissionPath}: hook("${method}") expects a function`);
227
+ }
228
+ function declaresMethod(nameEntry, method) {
229
+ for (const actions of nameEntry.actions.values()) {
230
+ if (Object.hasOwn(actions, method))
231
+ return true;
232
+ }
233
+ return false;
234
+ }
235
+ function hasAccessPath(nameEntry, role, method) {
236
+ if (nameEntry.actions.get(role)?.[method])
237
+ return true;
238
+ for (const grant of nameEntry.grants.values()) {
239
+ if (grant.source.role === role && grant.actions[method])
240
+ return true;
241
+ }
242
+ return false;
243
+ }
244
+ function validateGrantReferences(permissionPath, nameEntry, modules) {
245
+ for (const [permissionId, grant] of nameEntry.grants) {
246
+ const sourceEntry = modules.get(grant.source.action)?.names.get(grant.source.name);
247
+ if (!sourceEntry?.actions.has(grant.source.role)) {
248
+ throw pkitError("INVALID_DEFINITION", `"${permissionPath}": grantTo "${permissionId}" references a permission with no registered actions`);
249
+ }
250
+ for (const method of Object.keys(grant.actions)) {
251
+ if (declaresMethod(nameEntry, method))
252
+ continue;
253
+ throw pkitError("INVALID_DEFINITION", `"${permissionPath}": grantTo "${permissionId}" grants "${method}", which no role declares on that permission`);
254
+ }
255
+ }
256
+ }
257
+ function validateRoleHooks(permissionPath, nameEntry) {
258
+ for (const [hookRole, methodHooks] of nameEntry.hooks) {
259
+ if (hookRole === GLOBAL_HOOK_OWNER)
260
+ continue;
261
+ for (const method of methodHooks.keys()) {
262
+ if (hasAccessPath(nameEntry, hookRole, method))
263
+ continue;
264
+ throw pkitError("INVALID_DEFINITION", `"${permissionPath}": hook for "${hookRole}" on "${method}" has no registered actions or grant for that role`);
265
+ }
266
+ }
267
+ }
268
+ function validateSealedRegistry(modules) {
269
+ for (const [action, registeredModule] of modules) {
270
+ if (registeredModule.names.size === 0) {
271
+ throw pkitError("INVALID_DEFINITION", `"${action}" has hooks but no name with registered actions`);
272
+ }
273
+ for (const [name, nameEntry] of registeredModule.names) {
274
+ const permissionPath = `${action}::${name}`;
275
+ if (nameEntry.actions.size === 0) {
276
+ throw pkitError("INVALID_DEFINITION", `"${permissionPath}" has no registered actions for any role`);
277
+ }
278
+ validateGrantReferences(permissionPath, nameEntry, modules);
279
+ validateRoleHooks(permissionPath, nameEntry);
280
+ }
281
+ }
282
+ }
283
+ function validateAssignments(permissions, role, assignable) {
284
+ validateStrings(permissions, { code: "INVALID_INPUT", message: "permissions must be an array of strings", minimumLength: 1 });
285
+ const assigned = new Set;
286
+ for (const permissionId of permissions) {
287
+ const reference = parsePermissionId(permissionId, {
288
+ code: "INVALID_INPUT",
289
+ message: `invalid permission identifier: "${permissionId}" (format role::module::name)`
290
+ });
291
+ if (reference.role !== role) {
292
+ throw pkitError("PERMISSION_ROLE_MISMATCH", `"${permissionId}" belongs to role "${reference.role}", not the authenticated role "${role}"`);
293
+ }
294
+ if (!assignable.has(permissionId)) {
295
+ throw pkitError("UNKNOWN_PERMISSION", `"${permissionId}" is not an assignable permission`);
296
+ }
297
+ assigned.add(permissionId);
298
+ }
299
+ return assigned;
300
+ }
301
+ function validateIdentity(assignments, state) {
302
+ validateSnapshot(state.snapshot);
303
+ const { role, permissions } = assignments;
304
+ if (typeof role !== "string")
305
+ throw pkitError("INVALID_INPUT", "role is required");
306
+ validateRole(role, state.roles, "UNKNOWN_ROLE");
307
+ return { role, assigned: validateAssignments(permissions, role, state.snapshot.assignable) };
308
+ }
309
+ function trimSelection(select, properties) {
310
+ validateStrings(select, { code: "INVALID_INPUT", message: "select must be an array of strings", minimumLength: 0 });
311
+ const selectedFields = [];
312
+ for (const field of select) {
313
+ if (properties.includes(field))
314
+ selectedFields.push(field);
315
+ }
316
+ return selectedFields;
317
+ }
318
+ function rejectForbiddenFields(data, properties, permissionPath) {
319
+ const forbiddenFields = [];
320
+ for (const field of Object.keys(data)) {
321
+ if (!properties.includes(field))
322
+ forbiddenFields.push(field);
323
+ }
324
+ if (forbiddenFields.length === 0)
325
+ return;
326
+ throw Object.assign(pkitError("PROPERTIES_NOT_ALLOWED", `fields not allowed in "${permissionPath}": ${forbiddenFields.join(", ")}`), { fields: forbiddenFields });
327
+ }
328
+ function validateRequest(input, state) {
329
+ validateSnapshot(state.snapshot);
330
+ const { action, name, method } = input;
331
+ validateMethod(method, { code: "INVALID_INPUT", message: "method is required" });
332
+ if (method !== "find" && Object.hasOwn(input, "select"))
333
+ throw pkitError("INVALID_INPUT", "select only applies to find");
334
+ if (typeof action !== "string" || typeof name !== "string")
335
+ throw pkitError("INVALID_INPUT", "action and name are required");
336
+ const { role, assigned } = validateIdentity(input, state);
337
+ const registeredModule = state.modules.get(action);
338
+ if (!registeredModule)
339
+ throw pkitError("UNKNOWN_ACTION", `module "${action}" is not registered`);
340
+ const nameEntry = registeredModule.names.get(name);
341
+ if (!nameEntry)
342
+ throw pkitError("UNKNOWN_PERMISSION", `permission "${action}::${name}" is not registered`);
343
+ const permissionId = permissionIdOf(role, action, name);
344
+ const access = resolveAccess(nameEntry, permissionId, role, method, assigned);
345
+ if (access.status === "unassigned") {
346
+ throw pkitError("PERMISSION_NOT_ASSIGNED", `"${permissionId}" is not assigned or granted by the user permissions`);
347
+ }
348
+ if (access.status === "disabled")
349
+ throw pkitError("METHOD_DISABLED", `"${permissionId}.${method}" is not enabled`);
350
+ const { data, context } = input;
351
+ if (context !== undefined)
352
+ validateObject(context, { code: "INVALID_INPUT", message: "context must be an object" });
353
+ const { properties, authorization } = access;
354
+ const permission = Object.freeze({ role, action, name, permissionId, method, enabled: true, properties, authorization });
355
+ const request = { registeredModule, nameEntry, permission, data, context };
356
+ if (method === "find") {
357
+ if (data !== undefined)
358
+ validateObject(data, { code: "INVALID_INPUT", message: "data must be an object" });
359
+ const { select } = input;
360
+ if (select === undefined)
361
+ return { ...request, result: properties };
362
+ if (properties === ALL_FIELDS) {
363
+ validateStrings(select, { code: "INVALID_INPUT", message: "select must be an array of strings", minimumLength: 0 });
364
+ return { ...request, result: select };
365
+ }
366
+ return { ...request, result: trimSelection(select, properties) };
367
+ }
368
+ validateObject(data, { code: "INVALID_INPUT", message: "data must be an object" });
369
+ if (properties !== ALL_FIELDS)
370
+ rejectForbiddenFields(data, properties, `${permissionId}.${method}`);
371
+ return { ...request, result: data };
372
+ }
373
+
374
+ // src/context.ts
375
+ function setRoles(key, roles) {
376
+ validateContextKey(key);
377
+ const state = getOrCreateState();
378
+ validateRoleCatalog(roles, state);
379
+ state.roles = new Set(roles);
380
+ }
381
+ function getRoles(key) {
382
+ validateContextKey(key);
383
+ return [...getOrCreateState().roles];
384
+ }
385
+ var context = Object.freeze({ set: setRoles, get: getRoles });
386
+
387
+ // src/registry.ts
388
+ function appendHook(methodHooks, method, hook) {
389
+ const hooks = methodHooks.get(method) ?? [];
390
+ methodHooks.set(method, hooks);
391
+ hooks.push(hook);
392
+ }
393
+ function registerActions(scope, actions) {
394
+ const state = getOrCreateState();
395
+ const registeredActions = validateActions(actions, scope, state);
396
+ ensureName(state, scope.action, scope.name).actions.set(scope.role, registeredActions);
397
+ return scope.builder;
398
+ }
399
+ function registerGrant(scope, actions) {
400
+ const state = getOrCreateState();
401
+ const grant = validateGrantActions(actions, scope, state);
402
+ ensureName(state, scope.action, scope.name).grants.set(scope.permissionId, grant);
403
+ return scope.builder;
404
+ }
405
+ function registerModuleHook(scope, method, hook) {
406
+ const state = getOrCreateState();
407
+ validateHook(hook, { action: scope.action, method }, state);
408
+ appendHook(ensureModule(state, scope.action).hooks, method, hook);
409
+ return scope.builder;
410
+ }
411
+ function registerNameHook(scope, method, hook) {
412
+ const state = getOrCreateState();
413
+ validateHook(hook, { ...scope, method }, state);
414
+ const nameEntry = ensureName(state, scope.action, scope.name);
415
+ const roleHooks = nameEntry.hooks.get(scope.role) ?? new Map;
416
+ nameEntry.hooks.set(scope.role, roleHooks);
417
+ appendHook(roleHooks, method, hook);
418
+ return scope.builder;
419
+ }
420
+ function createRoleBuilder(action, name, role) {
421
+ validateRoleSegment(role);
422
+ const builder = {};
423
+ const scope = { action, name, role, builder };
424
+ return Object.assign(builder, {
425
+ registerActions: registerActions.bind(null, scope),
426
+ hook: registerNameHook.bind(null, scope)
427
+ });
428
+ }
429
+ function createGrantBuilder(action, name, permissionId) {
430
+ const builder = {};
431
+ const scope = { action, name, permissionId, builder };
432
+ return Object.assign(builder, { registerActions: registerGrant.bind(null, scope) });
433
+ }
434
+ function createNameBuilder(action, name) {
435
+ validatePermissionName(name);
436
+ const builder = {};
437
+ const scope = { action, name, role: GLOBAL_HOOK_OWNER, builder };
438
+ return Object.assign(builder, {
439
+ role: createRoleBuilder.bind(null, action, name),
440
+ grantTo: createGrantBuilder.bind(null, action, name),
441
+ hook: registerNameHook.bind(null, scope)
442
+ });
443
+ }
444
+ function createModuleBuilder(action) {
445
+ const builder = {};
446
+ const scope = { action, builder };
447
+ return Object.assign(builder, {
448
+ module: appendModule.bind(null, action),
449
+ name: createNameBuilder.bind(null, action),
450
+ hook: registerModuleHook.bind(null, scope)
451
+ });
452
+ }
453
+ function appendModule(parentAction, segment) {
454
+ validateModuleName(segment);
455
+ return createModuleBuilder(`${parentAction}${MODULE_SEPARATOR}${segment}`);
456
+ }
457
+ function defineModule(segment) {
458
+ validateModuleName(segment);
459
+ return createModuleBuilder(segment);
460
+ }
461
+ function ensureModule(state, action) {
462
+ const registeredModule = state.modules.get(action);
463
+ if (registeredModule)
464
+ return registeredModule;
465
+ const newModule = { names: new Map, hooks: new Map };
466
+ state.modules.set(action, newModule);
467
+ return newModule;
468
+ }
469
+ function ensureName(state, action, name) {
470
+ const registeredModule = ensureModule(state, action);
471
+ const registeredName = registeredModule.names.get(name);
472
+ if (registeredName)
473
+ return registeredName;
474
+ const newName = { actions: new Map, grants: new Map, hooks: new Map };
475
+ registeredModule.names.set(name, newName);
476
+ return newName;
477
+ }
478
+
479
+ // src/seal.ts
480
+ function seal() {
481
+ const state = getOrCreateState();
482
+ if (state.snapshot)
483
+ return;
484
+ validateSealedRegistry(state.modules);
485
+ const named = Object.create(null);
486
+ for (const [action, registeredModule] of state.modules) {
487
+ for (const [name, nameEntry] of registeredModule.names) {
488
+ for (const [role, actions] of nameEntry.actions) {
489
+ named[permissionIdOf(role, action, name)] = actions;
490
+ }
491
+ }
492
+ }
493
+ state.snapshot = { named: Object.freeze(named), assignable: new Set(Object.keys(named)) };
494
+ }
495
+
496
+ // src/permissions.ts
497
+ function getNamedCatalog() {
498
+ const { snapshot } = getOrCreateState();
499
+ validateSnapshot(snapshot);
500
+ return snapshot.named;
501
+ }
502
+ function resolveMethodAccess(nameEntry, permissionId, role, assigned) {
503
+ const methodAccess = Object.create(null);
504
+ let reachable = false;
505
+ for (const method of METHODS) {
506
+ const access = resolveAccess(nameEntry, permissionId, role, method, assigned);
507
+ methodAccess[method] = access.status === "granted";
508
+ if (access.status !== "unassigned")
509
+ reachable = true;
510
+ }
511
+ return reachable ? Object.freeze(methodAccess) : undefined;
512
+ }
513
+ function forUser(assignments) {
514
+ const state = getOrCreateState();
515
+ const { role, assigned } = validateIdentity(assignments, state);
516
+ const access = Object.create(null);
517
+ for (const [action, registeredModule] of state.modules) {
518
+ for (const [name, nameEntry] of registeredModule.names) {
519
+ const permissionId = permissionIdOf(role, action, name);
520
+ const methodAccess = resolveMethodAccess(nameEntry, permissionId, role, assigned);
521
+ if (methodAccess)
522
+ access[permissionId] = methodAccess;
523
+ }
524
+ }
525
+ return Object.freeze(access);
526
+ }
527
+ var permissions = Object.freeze(Object.defineProperty({ forUser }, "named", { get: getNamedCatalog, enumerable: true, configurable: false }));
528
+
529
+ // src/validate.ts
530
+ async function invokeHook(hook, request) {
531
+ return hook(request.data, request.context, request.permission);
532
+ }
533
+ function describeHookFailure(reason) {
534
+ try {
535
+ return reason instanceof Error ? reason.message : String(reason);
536
+ } catch {
537
+ return "the hook threw a value that cannot be described";
538
+ }
539
+ }
540
+ async function validate(input) {
541
+ try {
542
+ const request = validateRequest(input, getOrCreateState());
543
+ const { registeredModule, nameEntry, permission, result } = request;
544
+ const { method, role } = permission;
545
+ const hookGroups = [
546
+ registeredModule.hooks.get(method),
547
+ nameEntry.hooks.get(GLOBAL_HOOK_OWNER)?.get(method),
548
+ nameEntry.hooks.get(role)?.get(method)
549
+ ];
550
+ const hookCalls = [];
551
+ for (const hooks of hookGroups) {
552
+ if (!hooks)
553
+ continue;
554
+ for (const hook of hooks)
555
+ hookCalls.push(invokeHook(hook, request));
556
+ }
557
+ const hookResults = await Promise.allSettled(hookCalls);
558
+ const errors = [];
559
+ for (const hookResult of hookResults) {
560
+ if (hookResult.status === "fulfilled")
561
+ continue;
562
+ const hookCause = hookResult.reason;
563
+ errors.push({ code: "HOOK_ERROR", message: describeHookFailure(hookCause), cause: hookCause });
564
+ }
565
+ if (errors.length)
566
+ return { result: null, errors: Object.freeze(errors) };
567
+ return { result, errors: Object.freeze([]) };
568
+ } catch (cause) {
569
+ if (cause instanceof Error && cause.name === "PkitError") {
570
+ const permissionError = cause;
571
+ const error = permissionError.code === "PROPERTIES_NOT_ALLOWED" ? { code: permissionError.code, message: permissionError.message, fields: permissionError.fields } : { code: permissionError.code, message: permissionError.message };
572
+ return { result: null, errors: Object.freeze([error]) };
573
+ }
574
+ return {
575
+ result: null,
576
+ errors: Object.freeze([{ code: "VALIDATION_ERROR", message: "permission could not be validated", cause }])
577
+ };
578
+ }
579
+ }
580
+ // src/index.ts
581
+ var pkit = Object.freeze({ context, module: defineModule, seal, permissions, validate });
582
+ var src_default = pkit;
583
+ export {
584
+ METHODS,
585
+ context,
586
+ src_default as default,
587
+ defineModule as module,
588
+ permissions,
589
+ pkit,
590
+ seal,
591
+ validate
592
+ };
593
+
594
+ //# debugId=60F9871502AF5BAC64756E2164756E21