endpoint-permissions-kit 0.1.0 → 0.2.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.
@@ -39,11 +39,11 @@ var __export = (target, all) => {
39
39
  // src/index.ts
40
40
  var exports_src = {};
41
41
  __export(exports_src, {
42
- METHODS: () => METHODS,
43
- context: () => context,
42
+ METHODS: () => METHODS2,
43
+ context: () => context_default,
44
44
  default: () => src_default,
45
45
  module: () => defineModule,
46
- permissions: () => permissions,
46
+ permissions: () => permissions_default,
47
47
  pkit: () => pkit,
48
48
  seal: () => seal,
49
49
  validate: () => validate
@@ -51,426 +51,567 @@ __export(exports_src, {
51
51
  module.exports = __toCommonJS(exports_src);
52
52
 
53
53
  // src/constants.ts
54
- var METHODS = ["find", "update", "create", "remove"];
55
- var GENERAL_ROLE = "general";
56
- var GLOBAL_HOOK_OWNER = "*";
57
- var ALL_FIELDS = "*";
58
- var MODULE_SEPARATOR = ".";
59
- var PERMISSION_ID_SEPARATOR = "::";
54
+ var constants = {
55
+ METHODS: Object.freeze(["find", "update", "create", "remove"]),
56
+ GENERAL_ROLE: "general",
57
+ GLOBAL_HOOK_OWNER: "*",
58
+ ALL_FIELDS: "*",
59
+ MODULE_SEPARATOR: ".",
60
+ PERMISSION_ID_SEPARATOR: "::"
61
+ };
62
+ var constants_default = constants;
60
63
 
61
- // src/state.ts
62
- function getOrCreateState() {
63
- const stateKey = Symbol.for("endpoint-permissions-kit");
64
- const stateHost = globalThis;
65
- if (stateHost[stateKey] === undefined) {
66
- stateHost[stateKey] = { roles: new Set([GENERAL_ROLE]), modules: new Map, snapshot: null };
64
+ // src/errors.ts
65
+ var errors = {
66
+ create(code, message) {
67
+ return Object.assign(new Error(message), { name: "PkitError", code });
68
+ },
69
+ describe(value) {
70
+ try {
71
+ return String(value);
72
+ } catch {
73
+ return typeof value;
74
+ }
67
75
  }
68
- return stateHost[stateKey];
76
+ };
77
+ var errors_default = errors;
78
+
79
+ // src/identifiers.ts
80
+ var identifiers = {
81
+ build(role, action, name) {
82
+ return `${role}${constants_default.PERMISSION_ID_SEPARATOR}${action}${constants_default.PERMISSION_ID_SEPARATOR}${name}`;
83
+ },
84
+ parse(value, code, subject) {
85
+ if (typeof value !== "string")
86
+ throw invalidIdentifier(value, code, subject);
87
+ const parts = value.split(constants_default.PERMISSION_ID_SEPARATOR);
88
+ const [role, action, name] = parts;
89
+ if (parts.length !== 3 || role === undefined || action === undefined || name === undefined) {
90
+ throw invalidIdentifier(value, code, subject);
91
+ }
92
+ const isValidRole = isCleanSegment(role) && role !== constants_default.GLOBAL_HOOK_OWNER;
93
+ const isValidName = isCleanSegment(name) && name !== constants_default.GLOBAL_HOOK_OWNER;
94
+ const isValidAction = action.split(constants_default.MODULE_SEPARATOR).every(isCleanSegment);
95
+ if (!isValidRole || !isValidName || !isValidAction)
96
+ throw invalidIdentifier(value, code, subject);
97
+ return { role, action, name };
98
+ },
99
+ checkRole(role) {
100
+ if (typeof role === "string" && isCleanSegment(role) && role !== constants_default.GLOBAL_HOOK_OWNER)
101
+ return;
102
+ throw errors_default.create("INVALID_DEFINITION", `invalid role: "${errors_default.describe(role)}" (non-empty string, no ":" or surrounding whitespace; "${constants_default.GLOBAL_HOOK_OWNER}" is reserved for global hooks)`);
103
+ },
104
+ checkModuleSegment(segment) {
105
+ if (typeof segment === "string" && isCleanSegment(segment) && !segment.includes(constants_default.MODULE_SEPARATOR))
106
+ return;
107
+ throw errors_default.create("INVALID_DEFINITION", `invalid module name: "${errors_default.describe(segment)}" (non-empty string, no dots, no ":" or surrounding whitespace)`);
108
+ },
109
+ checkName(name) {
110
+ if (typeof name === "string" && isCleanSegment(name) && name !== constants_default.GLOBAL_HOOK_OWNER)
111
+ return;
112
+ throw errors_default.create("INVALID_DEFINITION", `invalid permission name: "${errors_default.describe(name)}" (non-empty string, no ":" or surrounding whitespace; "*" is reserved)`);
113
+ }
114
+ };
115
+ function isCleanSegment(value) {
116
+ return value.length > 0 && value.trim() === value && !value.includes(":");
117
+ }
118
+ function invalidIdentifier(value, code, subject) {
119
+ return errors_default.create(code, `${subject}: "${errors_default.describe(value)}" (format role::module::name)`);
69
120
  }
121
+ var identifiers_default = identifiers;
70
122
 
71
- // src/errors.ts
72
- function pkitError(code, message) {
73
- return Object.assign(new Error(message), { name: "PkitError", code });
123
+ // src/state.ts
124
+ var STATE_KEY = Symbol.for("endpoint-permissions-kit");
125
+ var state = {
126
+ getOrCreate() {
127
+ const stateHost = globalThis;
128
+ if (stateHost[STATE_KEY] === undefined) {
129
+ stateHost[STATE_KEY] = { roles: new Set([constants_default.GENERAL_ROLE]), cropper: false, modules: new Map, snapshot: null };
130
+ }
131
+ return stateHost[STATE_KEY];
132
+ },
133
+ requireOpen(currentState) {
134
+ if (currentState.snapshot)
135
+ throw errors_default.create("SEALED", "pkit.seal() was already called: no more registrations allowed");
136
+ },
137
+ requireSnapshot(currentState) {
138
+ if (currentState.snapshot === null) {
139
+ throw errors_default.create("NOT_SEALED", "pkit.seal() has not been called: call it after importing every permission file");
140
+ }
141
+ return currentState.snapshot;
142
+ }
143
+ };
144
+ var state_default = state;
145
+
146
+ // src/context.ts
147
+ var context = Object.freeze({
148
+ set(key, value) {
149
+ const contextKey = checkKey(key);
150
+ const currentState = state_default.getOrCreate();
151
+ state_default.requireOpen(currentState);
152
+ if (contextKey === "cropper") {
153
+ if (typeof value !== "boolean")
154
+ throw errors_default.create("INVALID_DEFINITION", "cropper must be a boolean");
155
+ currentState.cropper = value;
156
+ return;
157
+ }
158
+ currentState.roles = new Set(readRoleCatalog(value, currentState.modules.size));
159
+ },
160
+ get(key) {
161
+ const contextKey = checkKey(key);
162
+ const currentState = state_default.getOrCreate();
163
+ return contextKey === "cropper" ? currentState.cropper : [...currentState.roles];
164
+ }
165
+ });
166
+ function checkKey(key) {
167
+ if (key === "roles" || key === "cropper")
168
+ return key;
169
+ throw errors_default.create("INVALID_DEFINITION", `unknown context key: "${errors_default.describe(key)}"`);
170
+ }
171
+ function readRoleCatalog(value, registeredModuleCount) {
172
+ if (registeredModuleCount > 0) {
173
+ throw errors_default.create("INVALID_DEFINITION", "roles must be declared before registering permissions: import pkit.config.js first");
174
+ }
175
+ if (!Array.isArray(value))
176
+ throw errors_default.create("INVALID_DEFINITION", "roles must be an array of non-empty strings");
177
+ for (const role of value) {
178
+ if (typeof role !== "string" || role.length === 0) {
179
+ throw errors_default.create("INVALID_DEFINITION", "roles must be an array of non-empty strings");
180
+ }
181
+ }
182
+ const catalog = value;
183
+ if (catalog.length === 0)
184
+ throw errors_default.create("INVALID_DEFINITION", "roles must declare at least one role");
185
+ for (const role of catalog)
186
+ identifiers_default.checkRole(role);
187
+ return catalog;
74
188
  }
189
+ var context_default = context;
75
190
 
76
191
  // src/resolve.ts
77
- var DIRECT_AUTHORIZATION = Object.freeze({ direct: true, grantedBy: Object.freeze([]) });
78
192
  var DISABLED_ACCESS = Object.freeze({ status: "disabled" });
79
193
  var UNASSIGNED_ACCESS = Object.freeze({ status: "unassigned" });
80
- function permissionIdOf(role, action, name) {
81
- return [role, action, name].join(PERMISSION_ID_SEPARATOR);
82
- }
83
- function resolveAccess(nameEntry, permissionId, role, method, assigned) {
84
- if (assigned.has(permissionId))
85
- return resolveDirectAccess(nameEntry, role, method);
86
- return resolveGrantedAccess(nameEntry, method, assigned);
87
- }
88
- function resolveDirectAccess(nameEntry, role, method) {
89
- const definition = nameEntry.actions.get(role)?.[method];
90
- if (!definition?.enabled)
91
- return DISABLED_ACCESS;
92
- return { status: "granted", properties: definition.properties, authorization: DIRECT_AUTHORIZATION };
93
- }
94
- function resolveGrantedAccess(nameEntry, method, assigned) {
95
- const grantedBy = [];
96
- const properties = new Set;
97
- let reachable = false;
194
+ var resolve = {
195
+ identity(assignments, snapshot, roles) {
196
+ if (assignments === null || typeof assignments !== "object")
197
+ throw errors_default.create("INVALID_INPUT", "assignments must be an object");
198
+ const { role, permissions } = assignments;
199
+ if (typeof role !== "string")
200
+ throw errors_default.create("INVALID_INPUT", "role is required");
201
+ if (!roles.has(role))
202
+ throw errors_default.create("UNKNOWN_ROLE", `role "${role}" is not declared`);
203
+ if (!Array.isArray(permissions))
204
+ throw errors_default.create("INVALID_INPUT", "permissions must be an array of strings");
205
+ const assigned = new Set;
206
+ const names = new Map;
207
+ for (const permissionId of permissions) {
208
+ const reference = identifiers_default.parse(permissionId, "INVALID_INPUT", "invalid permission identifier");
209
+ if (reference.role !== role) {
210
+ throw errors_default.create("PERMISSION_ROLE_MISMATCH", `"${permissionId}" belongs to role "${reference.role}", not the authenticated role "${role}"`);
211
+ }
212
+ if (!snapshot.assignable.has(permissionId)) {
213
+ throw errors_default.create("UNKNOWN_PERMISSION", `"${permissionId}" is not an assignable permission`);
214
+ }
215
+ const assignedName = names.get(reference.action);
216
+ if (assignedName !== undefined && assignedName !== reference.name) {
217
+ throw errors_default.create("AMBIGUOUS_PERMISSION", `"${permissionId}" and "${identifiers_default.build(role, reference.action, assignedName)}" are both assigned: a request names no permission name, so module "${reference.action}" cannot be resolved`);
218
+ }
219
+ assigned.add(permissionId);
220
+ names.set(reference.action, reference.name);
221
+ }
222
+ return { role, assigned, names };
223
+ },
224
+ permission(registeredModule, action, identity) {
225
+ const assignedName = identity.names.get(action);
226
+ if (assignedName !== undefined) {
227
+ const assignedEntry = registeredModule.names.get(assignedName);
228
+ if (assignedEntry === undefined)
229
+ return;
230
+ return { permissionId: identifiers_default.build(identity.role, action, assignedName), entry: assignedEntry };
231
+ }
232
+ let chosen;
233
+ for (const [name, nameEntry] of registeredModule.names) {
234
+ const permissionId = identifiers_default.build(identity.role, action, name);
235
+ if (resolve.methodAccess(nameEntry, permissionId, identity.role, identity.assigned) === undefined)
236
+ continue;
237
+ if (chosen !== undefined) {
238
+ throw errors_default.create("AMBIGUOUS_PERMISSION", `grants reach "${chosen.permissionId}" and "${permissionId}": a request names no permission name, so module "${action}" cannot be resolved`);
239
+ }
240
+ chosen = { permissionId, entry: nameEntry };
241
+ }
242
+ return chosen;
243
+ },
244
+ access(nameEntry, permissionId, role, method, assigned) {
245
+ if (!assigned.has(permissionId))
246
+ return grantedAccess(nameEntry, method, assigned);
247
+ const definition = nameEntry.actions.get(role)?.[method];
248
+ if (!definition?.enabled)
249
+ return DISABLED_ACCESS;
250
+ return { status: "granted", properties: definition.properties };
251
+ },
252
+ methodAccess(nameEntry, permissionId, role, assigned) {
253
+ const methodAccess = Object.create(null);
254
+ if (assigned.has(permissionId)) {
255
+ const actions = nameEntry.actions.get(role);
256
+ for (const method of constants_default.METHODS)
257
+ methodAccess[method] = actions?.[method]?.enabled === true;
258
+ return Object.freeze(methodAccess);
259
+ }
260
+ const grantedMethods = new Set;
261
+ let isReachable = false;
262
+ for (const [enablingId, grant] of nameEntry.grants) {
263
+ if (!assigned.has(enablingId))
264
+ continue;
265
+ isReachable = true;
266
+ for (const method of Object.keys(grant.actions))
267
+ grantedMethods.add(method);
268
+ }
269
+ if (!isReachable)
270
+ return;
271
+ for (const method of constants_default.METHODS)
272
+ methodAccess[method] = grantedMethods.has(method);
273
+ return Object.freeze(methodAccess);
274
+ }
275
+ };
276
+ function grantedAccess(nameEntry, method, assigned) {
277
+ const fields = new Set;
278
+ let isGranted = false;
279
+ let isReachable = false;
98
280
  for (const [enablingId, grant] of nameEntry.grants) {
99
281
  if (!assigned.has(enablingId))
100
282
  continue;
101
- reachable = true;
283
+ isReachable = true;
102
284
  const definition = grant.actions[method];
103
285
  if (!definition)
104
286
  continue;
105
- grantedBy.push(enablingId);
287
+ isGranted = true;
106
288
  for (const field of definition.properties)
107
- properties.add(field);
289
+ fields.add(field);
108
290
  }
109
- if (grantedBy.length === 0)
110
- return reachable ? DISABLED_ACCESS : UNASSIGNED_ACCESS;
111
- const authorization = Object.freeze({ direct: false, grantedBy: Object.freeze(grantedBy.sort()) });
112
- return { status: "granted", properties: Object.freeze([...properties]), authorization };
291
+ if (!isGranted)
292
+ return isReachable ? DISABLED_ACCESS : UNASSIGNED_ACCESS;
293
+ return { status: "granted", properties: Object.freeze([...fields]) };
113
294
  }
295
+ var resolve_default = resolve;
114
296
 
115
- // src/validators.ts
116
- function validateObject(value, failure) {
117
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
118
- throw pkitError(failure.code, failure.message);
119
- }
120
- }
121
- function validateStrings(value, rules) {
122
- if (!Array.isArray(value))
123
- throw pkitError(rules.code, rules.message);
124
- for (const field of value) {
125
- if (typeof field !== "string" || field.length < rules.minimumLength) {
126
- throw pkitError(rules.code, rules.message);
297
+ // src/permissions.ts
298
+ var permissions = Object.freeze({
299
+ forUser(assignments) {
300
+ const currentState = state_default.getOrCreate();
301
+ const snapshot = state_default.requireSnapshot(currentState);
302
+ const identity = resolve_default.identity(assignments, snapshot, currentState.roles);
303
+ const access = Object.create(null);
304
+ for (const [action, registeredModule] of currentState.modules) {
305
+ const chosen = resolve_default.permission(registeredModule, action, identity);
306
+ if (!chosen)
307
+ continue;
308
+ const methodAccess = resolve_default.methodAccess(chosen.entry, chosen.permissionId, identity.role, identity.assigned);
309
+ if (methodAccess)
310
+ access[chosen.permissionId] = methodAccess;
127
311
  }
312
+ return Object.freeze(access);
313
+ },
314
+ get named() {
315
+ return state_default.requireSnapshot(state_default.getOrCreate()).named;
128
316
  }
129
- }
130
- function validateContextKey(key) {
131
- if (key !== "roles")
132
- throw pkitError("INVALID_DEFINITION", `unknown context key: "${String(key)}"`);
133
- }
134
- function validateOpenRegistry(state) {
135
- if (state.snapshot)
136
- throw pkitError("SEALED", "pkit.seal() was already called: no more registrations allowed");
137
- }
138
- function validateSnapshot(snapshot) {
139
- if (snapshot === null) {
140
- throw pkitError("NOT_SEALED", "pkit.seal() has not been called: call it after importing every permission file");
317
+ });
318
+ var permissions_default = permissions;
319
+
320
+ // src/properties.ts
321
+ var PRUNED = Symbol("pruned");
322
+ var MAX_DEPTH = 1000;
323
+ var properties = {
324
+ checkDeclaredPath(property, permissionPath) {
325
+ if (property.includes("[") || property.includes("]")) {
326
+ throw errors_default.create("INVALID_DEFINITION", `${permissionPath}: array indexes are not allowed in properties: "${property}"`);
327
+ }
328
+ const segments = segmentsOf(property);
329
+ for (const segment of segments) {
330
+ if (segment.length === 0)
331
+ throw errors_default.create("INVALID_DEFINITION", `${permissionPath}: empty segment in property path: "${property}"`);
332
+ }
333
+ if (segments[0] === constants_default.ALL_FIELDS) {
334
+ throw errors_default.create("INVALID_DEFINITION", `${permissionPath}: a property path cannot start with "${constants_default.ALL_FIELDS}": "${property}"`);
335
+ }
336
+ },
337
+ resolve(data, allowed, cropper) {
338
+ if (allowed === constants_default.ALL_FIELDS)
339
+ return data;
340
+ const patterns = [];
341
+ for (const pattern of allowed)
342
+ patterns.push(segmentsOf(pattern));
343
+ const walk = { patterns, segments: [], ancestors: new Set([data]) };
344
+ if (cropper)
345
+ return cropData(data, walk);
346
+ rejectForbiddenPaths(data, walk);
347
+ return data;
141
348
  }
142
- }
143
- function validateRole(role, roles, code) {
144
- if (typeof role === "string" && roles.has(role))
145
- return;
146
- if (code === "ROLE_NOT_DECLARED") {
147
- throw pkitError(code, `role "${String(role)}" is not declared. Available roles: ${[...roles].join(", ")}.
148
- ` + "Is pkit.context.set('roles', [...]) missing from pkit.config.js, or was it imported after this file?");
349
+ };
350
+ function segmentsOf(path) {
351
+ const segments = [];
352
+ let segment = "";
353
+ let index = 0;
354
+ while (index < path.length) {
355
+ const character = path[index];
356
+ if (character === "\\") {
357
+ segment += path[index + 1] ?? "";
358
+ index += 2;
359
+ continue;
360
+ }
361
+ if (character === ".") {
362
+ segments.push(segment);
363
+ segment = "";
364
+ index += 1;
365
+ continue;
366
+ }
367
+ segment += character;
368
+ index += 1;
149
369
  }
150
- throw pkitError(code, `role "${String(role)}" is not declared`);
370
+ segments.push(segment);
371
+ return segments;
151
372
  }
152
- function validateRoleCatalog(roles, state) {
153
- validateOpenRegistry(state);
154
- if (state.modules.size) {
155
- throw pkitError("INVALID_DEFINITION", "roles must be declared before registering permissions: import pkit.config.js first");
373
+ function isAllowedPath(segments, patterns) {
374
+ for (const pattern of patterns) {
375
+ if (pattern.length !== segments.length)
376
+ continue;
377
+ let isMatch = true;
378
+ for (let index = 0;index < segments.length; index += 1) {
379
+ const patternSegment = pattern[index];
380
+ if (patternSegment === constants_default.ALL_FIELDS)
381
+ continue;
382
+ if (patternSegment === segments[index])
383
+ continue;
384
+ isMatch = false;
385
+ break;
386
+ }
387
+ if (isMatch)
388
+ return true;
156
389
  }
157
- validateStrings(roles, {
158
- code: "INVALID_DEFINITION",
159
- message: "roles must be an array of non-empty strings",
160
- minimumLength: 1
161
- });
162
- if (roles.length === 0)
163
- throw pkitError("INVALID_DEFINITION", "roles must declare at least one role");
164
- for (const role of roles)
165
- validateRoleSegment(role);
166
- }
167
- function isCleanSegment(value) {
168
- return value.length > 0 && value.trim() === value && !value.includes(":");
390
+ return false;
169
391
  }
170
- function validateRoleSegment(role) {
171
- if (typeof role === "string" && isCleanSegment(role) && role !== GLOBAL_HOOK_OWNER)
172
- return;
173
- throw pkitError("INVALID_DEFINITION", `invalid role: "${String(role)}" (non-empty string, no ":" or surrounding whitespace; "${GLOBAL_HOOK_OWNER}" is reserved for global hooks)`);
392
+ function isPlainObject(value) {
393
+ if (value === null || typeof value !== "object" || Array.isArray(value))
394
+ return false;
395
+ const prototype = Object.getPrototypeOf(value);
396
+ return prototype === Object.prototype || prototype === null;
174
397
  }
175
- function validateModuleName(moduleName) {
176
- if (typeof moduleName === "string" && isCleanSegment(moduleName) && !moduleName.includes(MODULE_SEPARATOR))
398
+ function requireDepth(walk) {
399
+ if (walk.ancestors.size < MAX_DEPTH)
177
400
  return;
178
- throw pkitError("INVALID_DEFINITION", `invalid module name: "${String(moduleName)}" (non-empty string, no dots, no ":" or surrounding whitespace)`);
401
+ throw new RangeError(`data is nested deeper than ${MAX_DEPTH} levels`);
179
402
  }
180
- function validatePermissionName(name) {
181
- if (typeof name === "string" && isCleanSegment(name) && name !== GLOBAL_HOOK_OWNER)
182
- return;
183
- throw pkitError("INVALID_DEFINITION", `invalid permission name: "${String(name)}" (non-empty string, no ":" or surrounding whitespace; "*" is reserved)`);
184
- }
185
- function parsePermissionId(value, failure) {
186
- if (typeof value !== "string")
187
- throw pkitError(failure.code, failure.message);
188
- const parts = value.split(PERMISSION_ID_SEPARATOR);
189
- const [role, action, name] = parts;
190
- if (parts.length !== 3 || role === undefined || action === undefined || name === undefined) {
191
- throw pkitError(failure.code, failure.message);
192
- }
193
- const isValidRole = isCleanSegment(role) && role !== GLOBAL_HOOK_OWNER;
194
- const isValidName = isCleanSegment(name) && name !== GLOBAL_HOOK_OWNER;
195
- const isValidAction = action.split(MODULE_SEPARATOR).every(isCleanSegment);
196
- if (!isValidRole || !isValidName || !isValidAction)
197
- throw pkitError(failure.code, failure.message);
198
- return { role, action, name };
199
- }
200
- function validateMethod(method, failure) {
201
- if (METHODS.includes(method))
403
+ function setField(target, key, value) {
404
+ if (key === "__proto__") {
405
+ Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
202
406
  return;
203
- throw pkitError(failure.code, `${failure.message}: method "${String(method)}" does not exist. Methods: ${METHODS.join(", ")}`);
204
- }
205
- function readActionDefinition(definition, permissionPath) {
206
- validateObject(definition, { code: "INVALID_DEFINITION", message: `${permissionPath}: must be an object` });
207
- if (typeof definition.enabled !== "boolean") {
208
- throw pkitError("INVALID_DEFINITION", `${permissionPath}: enabled must be a boolean`);
209
- }
210
- const { properties } = definition;
211
- if (properties === ALL_FIELDS)
212
- return Object.freeze({ enabled: definition.enabled, properties });
213
- validateStrings(properties, {
214
- code: "INVALID_DEFINITION",
215
- message: `${permissionPath}: properties must be string[] or '*'`,
216
- minimumLength: 1
217
- });
218
- if (properties.includes(ALL_FIELDS)) {
219
- throw pkitError("INVALID_DEFINITION", `${permissionPath}: '${ALL_FIELDS}' is only allowed as the whole properties value`);
220
- }
221
- if (new Set(properties).size !== properties.length) {
222
- throw pkitError("INVALID_DEFINITION", `${permissionPath}: properties contains duplicate fields`);
223
- }
224
- return Object.freeze({ enabled: definition.enabled, properties: Object.freeze([...properties]) });
225
- }
226
- function readActionDefinitions(actions, permissionPath) {
227
- validateObject(actions, { code: "INVALID_DEFINITION", message: `${permissionPath}: registerActions expects an object` });
228
- const registeredActions = Object.create(null);
229
- for (const [method, definition] of Object.entries(actions)) {
230
- validateMethod(method, { code: "INVALID_DEFINITION", message: permissionPath });
231
- registeredActions[method] = readActionDefinition(definition, `${permissionPath}.${method}`);
232
- }
233
- return Object.freeze(registeredActions);
234
- }
235
- function validateActions(actions, registration, state) {
236
- const { action, name, role } = registration;
237
- validateOpenRegistry(state);
238
- validateRole(role, state.roles, "ROLE_NOT_DECLARED");
239
- if (state.modules.get(action)?.names.get(name)?.actions.has(role)) {
240
- throw pkitError("DUPLICATE_REGISTRATION", `"${action}::${name}" already has actions registered for role "${role}"`);
241
- }
242
- return readActionDefinitions(actions, `${action}::${name} [${role}]`);
243
- }
244
- function validateGrantActions(actions, registration, state) {
245
- const { action, name, permissionId } = registration;
246
- validateOpenRegistry(state);
247
- const source = parsePermissionId(permissionId, {
248
- code: "INVALID_DEFINITION",
249
- message: `"${action}::${name}": invalid grantTo identifier: "${String(permissionId)}" (format role::module::name)`
250
- });
251
- validateRole(source.role, state.roles, "ROLE_NOT_DECLARED");
252
- if (source.action === action && source.name === name) {
253
- throw pkitError("INVALID_DEFINITION", `"${permissionId}" cannot grant to itself`);
254
407
  }
255
- if (state.modules.get(action)?.names.get(name)?.grants.has(permissionId)) {
256
- throw pkitError("DUPLICATE_REGISTRATION", `"${action}::${name}" already has a grant for "${permissionId}"`);
257
- }
258
- const permissionPath = `${action}::${name} [grantTo ${permissionId}]`;
259
- const registeredActions = readActionDefinitions(actions, permissionPath);
260
- for (const [method, definition] of Object.entries(registeredActions)) {
261
- if (definition.enabled !== true) {
262
- throw pkitError("INVALID_DEFINITION", `${permissionPath}.${method}: a grant does not allow enabled: false`);
408
+ target[key] = value;
409
+ }
410
+ function cropValue(value, walk) {
411
+ if (Array.isArray(value)) {
412
+ if (value.length === 0)
413
+ return isAllowedPath(walk.segments, walk.patterns) ? [] : PRUNED;
414
+ if (walk.ancestors.has(value))
415
+ throw new RangeError("data contains a circular reference");
416
+ requireDepth(walk);
417
+ walk.ancestors.add(value);
418
+ const items = [];
419
+ for (const item of value) {
420
+ const croppedItem = cropValue(item, walk);
421
+ if (croppedItem === PRUNED)
422
+ continue;
423
+ items.push(croppedItem);
263
424
  }
264
- if (definition.properties === ALL_FIELDS) {
265
- throw pkitError("INVALID_DEFINITION", `${permissionPath}.${method}: a grant requires an explicit properties list`);
425
+ walk.ancestors.delete(value);
426
+ return items.length === 0 ? PRUNED : items;
427
+ }
428
+ if (isPlainObject(value)) {
429
+ const container = value;
430
+ const keys = Object.keys(container);
431
+ if (keys.length === 0)
432
+ return isAllowedPath(walk.segments, walk.patterns) ? {} : PRUNED;
433
+ if (walk.ancestors.has(container))
434
+ throw new RangeError("data contains a circular reference");
435
+ requireDepth(walk);
436
+ walk.ancestors.add(container);
437
+ const cropped = {};
438
+ let keptCount = 0;
439
+ for (const key of keys) {
440
+ walk.segments.push(key);
441
+ const croppedValue = cropValue(container[key], walk);
442
+ walk.segments.pop();
443
+ if (croppedValue === PRUNED)
444
+ continue;
445
+ setField(cropped, key, croppedValue);
446
+ keptCount += 1;
266
447
  }
448
+ walk.ancestors.delete(container);
449
+ return keptCount === 0 ? PRUNED : cropped;
450
+ }
451
+ return isAllowedPath(walk.segments, walk.patterns) ? value : PRUNED;
452
+ }
453
+ function cropData(data, walk) {
454
+ const cropped = {};
455
+ for (const key of Object.keys(data)) {
456
+ walk.segments.push(key);
457
+ const croppedValue = cropValue(data[key], walk);
458
+ walk.segments.pop();
459
+ if (croppedValue === PRUNED)
460
+ continue;
461
+ setField(cropped, key, croppedValue);
267
462
  }
268
- return { source, actions: registeredActions };
269
- }
270
- function validateHook(hook, registration, state) {
271
- const { action, name, role, method } = registration;
272
- validateOpenRegistry(state);
273
- if (role !== undefined && role !== GLOBAL_HOOK_OWNER)
274
- validateRole(role, state.roles, "ROLE_NOT_DECLARED");
275
- const permissionPath = name === undefined ? action : `${action}::${name}`;
276
- validateMethod(method, { code: "INVALID_DEFINITION", message: permissionPath });
277
- if (typeof hook !== "function")
278
- throw pkitError("INVALID_DEFINITION", `${permissionPath}: hook("${method}") expects a function`);
279
- }
280
- function declaresMethod(nameEntry, method) {
281
- for (const actions of nameEntry.actions.values()) {
282
- if (Object.hasOwn(actions, method))
283
- return true;
284
- }
285
- return false;
463
+ return cropped;
286
464
  }
287
- function hasAccessPath(nameEntry, role, method) {
288
- if (nameEntry.actions.get(role)?.[method])
289
- return true;
290
- for (const grant of nameEntry.grants.values()) {
291
- if (grant.source.role === role && grant.actions[method])
292
- return true;
465
+ function collectForbiddenPaths(value, walk, forbidden) {
466
+ if (Array.isArray(value)) {
467
+ if (value.length === 0 || walk.ancestors.has(value)) {
468
+ reportPath(walk, forbidden);
469
+ return;
470
+ }
471
+ requireDepth(walk);
472
+ walk.ancestors.add(value);
473
+ for (const item of value)
474
+ collectForbiddenPaths(item, walk, forbidden);
475
+ walk.ancestors.delete(value);
476
+ return;
293
477
  }
294
- return false;
295
- }
296
- function validateGrantReferences(permissionPath, nameEntry, modules) {
297
- for (const [permissionId, grant] of nameEntry.grants) {
298
- const sourceEntry = modules.get(grant.source.action)?.names.get(grant.source.name);
299
- if (!sourceEntry?.actions.has(grant.source.role)) {
300
- throw pkitError("INVALID_DEFINITION", `"${permissionPath}": grantTo "${permissionId}" references a permission with no registered actions`);
478
+ if (isPlainObject(value)) {
479
+ const container = value;
480
+ const keys = Object.keys(container);
481
+ if (keys.length === 0 || walk.ancestors.has(container)) {
482
+ reportPath(walk, forbidden);
483
+ return;
301
484
  }
302
- for (const method of Object.keys(grant.actions)) {
303
- if (declaresMethod(nameEntry, method))
304
- continue;
305
- throw pkitError("INVALID_DEFINITION", `"${permissionPath}": grantTo "${permissionId}" grants "${method}", which no role declares on that permission`);
485
+ requireDepth(walk);
486
+ walk.ancestors.add(container);
487
+ for (const key of keys) {
488
+ walk.segments.push(key);
489
+ collectForbiddenPaths(container[key], walk, forbidden);
490
+ walk.segments.pop();
306
491
  }
492
+ walk.ancestors.delete(container);
493
+ return;
307
494
  }
495
+ reportPath(walk, forbidden);
308
496
  }
309
- function validateRoleHooks(permissionPath, nameEntry) {
310
- for (const [hookRole, methodHooks] of nameEntry.hooks) {
311
- if (hookRole === GLOBAL_HOOK_OWNER)
312
- continue;
313
- for (const method of methodHooks.keys()) {
314
- if (hasAccessPath(nameEntry, hookRole, method))
315
- continue;
316
- throw pkitError("INVALID_DEFINITION", `"${permissionPath}": hook for "${hookRole}" on "${method}" has no registered actions or grant for that role`);
317
- }
497
+ function reportPath(walk, forbidden) {
498
+ if (isAllowedPath(walk.segments, walk.patterns))
499
+ return;
500
+ forbidden.add(walk.segments.join("."));
501
+ }
502
+ function rejectForbiddenPaths(data, walk) {
503
+ const forbidden = new Set;
504
+ for (const key of Object.keys(data)) {
505
+ walk.segments.push(key);
506
+ collectForbiddenPaths(data[key], walk, forbidden);
507
+ walk.segments.pop();
318
508
  }
509
+ if (forbidden.size === 0)
510
+ return;
511
+ const fields = [...forbidden];
512
+ throw Object.assign(errors_default.create("PROPERTIES_NOT_ALLOWED", `fields not allowed: ${fields.join(", ")}`), { fields });
319
513
  }
320
- function validateSealedRegistry(modules) {
321
- for (const [action, registeredModule] of modules) {
322
- if (registeredModule.names.size === 0) {
323
- throw pkitError("INVALID_DEFINITION", `"${action}" has hooks but no name with registered actions`);
514
+ var properties_default = properties;
515
+
516
+ // src/definitions.ts
517
+ var METHODS = new Set(constants_default.METHODS);
518
+ var definitions = {
519
+ checkMethod(method, code, subject) {
520
+ if (typeof method === "string" && METHODS.has(method))
521
+ return method;
522
+ throw errors_default.create(code, `${subject}: method "${errors_default.describe(method)}" does not exist. Methods: ${constants_default.METHODS.join(", ")}`);
523
+ },
524
+ readActions(actions, permissionPath) {
525
+ const declared = requireObject(actions, `${permissionPath}: registerActions expects an object`);
526
+ const registeredActions = Object.create(null);
527
+ for (const [method, definition] of Object.entries(declared)) {
528
+ definitions.checkMethod(method, "INVALID_DEFINITION", permissionPath);
529
+ registeredActions[method] = readActionDefinition(definition, `${permissionPath}.${method}`);
324
530
  }
325
- for (const [name, nameEntry] of registeredModule.names) {
326
- const permissionPath = `${action}::${name}`;
327
- if (nameEntry.actions.size === 0) {
328
- throw pkitError("INVALID_DEFINITION", `"${permissionPath}" has no registered actions for any role`);
531
+ return Object.freeze(registeredActions);
532
+ },
533
+ readGrant(actions, permissionPath) {
534
+ const registeredActions = definitions.readActions(actions, permissionPath);
535
+ for (const [method, definition] of Object.entries(registeredActions)) {
536
+ if (definition.enabled !== true) {
537
+ throw errors_default.create("INVALID_DEFINITION", `${permissionPath}.${method}: a grant does not allow enabled: false`);
538
+ }
539
+ if (definition.properties === constants_default.ALL_FIELDS) {
540
+ throw errors_default.create("INVALID_DEFINITION", `${permissionPath}.${method}: a grant requires an explicit properties list`);
329
541
  }
330
- validateGrantReferences(permissionPath, nameEntry, modules);
331
- validateRoleHooks(permissionPath, nameEntry);
332
542
  }
543
+ return registeredActions;
333
544
  }
545
+ };
546
+ function requireObject(value, message) {
547
+ if (value === null || typeof value !== "object" || Array.isArray(value))
548
+ throw errors_default.create("INVALID_DEFINITION", message);
549
+ return value;
334
550
  }
335
- function validateAssignments(permissions, role, assignable) {
336
- validateStrings(permissions, { code: "INVALID_INPUT", message: "permissions must be an array of strings", minimumLength: 1 });
337
- const assigned = new Set;
338
- for (const permissionId of permissions) {
339
- const reference = parsePermissionId(permissionId, {
340
- code: "INVALID_INPUT",
341
- message: `invalid permission identifier: "${permissionId}" (format role::module::name)`
342
- });
343
- if (reference.role !== role) {
344
- throw pkitError("PERMISSION_ROLE_MISMATCH", `"${permissionId}" belongs to role "${reference.role}", not the authenticated role "${role}"`);
345
- }
346
- if (!assignable.has(permissionId)) {
347
- throw pkitError("UNKNOWN_PERMISSION", `"${permissionId}" is not an assignable permission`);
348
- }
349
- assigned.add(permissionId);
551
+ function readActionDefinition(definition, permissionPath) {
552
+ const action = requireObject(definition, `${permissionPath}: must be an object`);
553
+ if (typeof action.enabled !== "boolean") {
554
+ throw errors_default.create("INVALID_DEFINITION", `${permissionPath}: enabled must be a boolean`);
350
555
  }
351
- return assigned;
352
- }
353
- function validateIdentity(assignments, state) {
354
- validateSnapshot(state.snapshot);
355
- const { role, permissions } = assignments;
356
- if (typeof role !== "string")
357
- throw pkitError("INVALID_INPUT", "role is required");
358
- validateRole(role, state.roles, "UNKNOWN_ROLE");
359
- return { role, assigned: validateAssignments(permissions, role, state.snapshot.assignable) };
360
- }
361
- function trimSelection(select, properties) {
362
- validateStrings(select, { code: "INVALID_INPUT", message: "select must be an array of strings", minimumLength: 0 });
363
- const selectedFields = [];
364
- for (const field of select) {
365
- if (properties.includes(field))
366
- selectedFields.push(field);
556
+ if (action.properties === constants_default.ALL_FIELDS) {
557
+ return Object.freeze({ enabled: action.enabled, properties: constants_default.ALL_FIELDS });
367
558
  }
368
- return selectedFields;
559
+ return Object.freeze({ enabled: action.enabled, properties: readDeclaredProperties(action.properties, permissionPath) });
369
560
  }
370
- function rejectForbiddenFields(data, properties, permissionPath) {
371
- const forbiddenFields = [];
372
- for (const field of Object.keys(data)) {
373
- if (!properties.includes(field))
374
- forbiddenFields.push(field);
561
+ function readDeclaredProperties(value, permissionPath) {
562
+ if (!Array.isArray(value)) {
563
+ throw errors_default.create("INVALID_DEFINITION", `${permissionPath}: properties must be string[] or '${constants_default.ALL_FIELDS}'`);
375
564
  }
376
- if (forbiddenFields.length === 0)
377
- return;
378
- throw Object.assign(pkitError("PROPERTIES_NOT_ALLOWED", `fields not allowed in "${permissionPath}": ${forbiddenFields.join(", ")}`), { fields: forbiddenFields });
379
- }
380
- function validateRequest(input, state) {
381
- validateSnapshot(state.snapshot);
382
- const { action, name, method } = input;
383
- validateMethod(method, { code: "INVALID_INPUT", message: "method is required" });
384
- if (method !== "find" && Object.hasOwn(input, "select"))
385
- throw pkitError("INVALID_INPUT", "select only applies to find");
386
- if (typeof action !== "string" || typeof name !== "string")
387
- throw pkitError("INVALID_INPUT", "action and name are required");
388
- const { role, assigned } = validateIdentity(input, state);
389
- const registeredModule = state.modules.get(action);
390
- if (!registeredModule)
391
- throw pkitError("UNKNOWN_ACTION", `module "${action}" is not registered`);
392
- const nameEntry = registeredModule.names.get(name);
393
- if (!nameEntry)
394
- throw pkitError("UNKNOWN_PERMISSION", `permission "${action}::${name}" is not registered`);
395
- const permissionId = permissionIdOf(role, action, name);
396
- const access = resolveAccess(nameEntry, permissionId, role, method, assigned);
397
- if (access.status === "unassigned") {
398
- throw pkitError("PERMISSION_NOT_ASSIGNED", `"${permissionId}" is not assigned or granted by the user permissions`);
565
+ for (const property of value) {
566
+ if (typeof property !== "string" || property.length === 0) {
567
+ throw errors_default.create("INVALID_DEFINITION", `${permissionPath}: properties must be string[] or '${constants_default.ALL_FIELDS}'`);
568
+ }
399
569
  }
400
- if (access.status === "disabled")
401
- throw pkitError("METHOD_DISABLED", `"${permissionId}.${method}" is not enabled`);
402
- const { data, context } = input;
403
- if (context !== undefined)
404
- validateObject(context, { code: "INVALID_INPUT", message: "context must be an object" });
405
- const { properties, authorization } = access;
406
- const permission = Object.freeze({ role, action, name, permissionId, method, enabled: true, properties, authorization });
407
- const request = { registeredModule, nameEntry, permission, data, context };
408
- if (method === "find") {
409
- if (data !== undefined)
410
- validateObject(data, { code: "INVALID_INPUT", message: "data must be an object" });
411
- const { select } = input;
412
- if (select === undefined)
413
- return { ...request, result: properties };
414
- if (properties === ALL_FIELDS) {
415
- validateStrings(select, { code: "INVALID_INPUT", message: "select must be an array of strings", minimumLength: 0 });
416
- return { ...request, result: select };
417
- }
418
- return { ...request, result: trimSelection(select, properties) };
419
- }
420
- validateObject(data, { code: "INVALID_INPUT", message: "data must be an object" });
421
- if (properties !== ALL_FIELDS)
422
- rejectForbiddenFields(data, properties, `${permissionId}.${method}`);
423
- return { ...request, result: data };
424
- }
425
-
426
- // src/context.ts
427
- function setRoles(key, roles) {
428
- validateContextKey(key);
429
- const state = getOrCreateState();
430
- validateRoleCatalog(roles, state);
431
- state.roles = new Set(roles);
432
- }
433
- function getRoles(key) {
434
- validateContextKey(key);
435
- return [...getOrCreateState().roles];
570
+ const declared = value;
571
+ if (declared.includes(constants_default.ALL_FIELDS)) {
572
+ throw errors_default.create("INVALID_DEFINITION", `${permissionPath}: '${constants_default.ALL_FIELDS}' is only allowed as the whole properties value`);
573
+ }
574
+ if (new Set(declared).size !== declared.length) {
575
+ throw errors_default.create("INVALID_DEFINITION", `${permissionPath}: properties contains duplicate fields`);
576
+ }
577
+ for (const property of declared)
578
+ properties_default.checkDeclaredPath(property, permissionPath);
579
+ return Object.freeze([...declared]);
436
580
  }
437
- var context = Object.freeze({ set: setRoles, get: getRoles });
581
+ var definitions_default = definitions;
438
582
 
439
583
  // src/registry.ts
440
- function appendHook(methodHooks, method, hook) {
441
- const hooks = methodHooks.get(method) ?? [];
442
- methodHooks.set(method, hooks);
443
- hooks.push(hook);
444
- }
445
- function registerActions(scope, actions) {
446
- const state = getOrCreateState();
447
- const registeredActions = validateActions(actions, scope, state);
448
- ensureName(state, scope.action, scope.name).actions.set(scope.role, registeredActions);
449
- return scope.builder;
450
- }
451
- function registerGrant(scope, actions) {
452
- const state = getOrCreateState();
453
- const grant = validateGrantActions(actions, scope, state);
454
- ensureName(state, scope.action, scope.name).grants.set(scope.permissionId, grant);
455
- return scope.builder;
584
+ var registry = {
585
+ defineModule(segment) {
586
+ identifiers_default.checkModuleSegment(segment);
587
+ return createModuleBuilder(segment);
588
+ }
589
+ };
590
+ function createModuleBuilder(action) {
591
+ const builder = {};
592
+ const scope = { action, builder };
593
+ return Object.assign(builder, {
594
+ module: appendModule.bind(null, action),
595
+ name: createNameBuilder.bind(null, action),
596
+ hook: registerModuleHook.bind(null, scope)
597
+ });
456
598
  }
457
- function registerModuleHook(scope, method, hook) {
458
- const state = getOrCreateState();
459
- validateHook(hook, { action: scope.action, method }, state);
460
- appendHook(ensureModule(state, scope.action).hooks, method, hook);
461
- return scope.builder;
599
+ function appendModule(parentAction, segment) {
600
+ identifiers_default.checkModuleSegment(segment);
601
+ return createModuleBuilder(`${parentAction}${constants_default.MODULE_SEPARATOR}${segment}`);
462
602
  }
463
- function registerNameHook(scope, method, hook) {
464
- const state = getOrCreateState();
465
- validateHook(hook, { ...scope, method }, state);
466
- const nameEntry = ensureName(state, scope.action, scope.name);
467
- const roleHooks = nameEntry.hooks.get(scope.role) ?? new Map;
468
- nameEntry.hooks.set(scope.role, roleHooks);
469
- appendHook(roleHooks, method, hook);
470
- return scope.builder;
603
+ function createNameBuilder(action, name) {
604
+ identifiers_default.checkName(name);
605
+ const builder = {};
606
+ const scope = { action, name, role: constants_default.GLOBAL_HOOK_OWNER, builder };
607
+ return Object.assign(builder, {
608
+ role: createRoleBuilder.bind(null, action, name),
609
+ grantTo: createGrantBuilder.bind(null, action, name),
610
+ hook: registerNameHook.bind(null, scope)
611
+ });
471
612
  }
472
613
  function createRoleBuilder(action, name, role) {
473
- validateRoleSegment(role);
614
+ identifiers_default.checkRole(role);
474
615
  const builder = {};
475
616
  const scope = { action, name, role, builder };
476
617
  return Object.assign(builder, {
@@ -483,43 +624,72 @@ function createGrantBuilder(action, name, permissionId) {
483
624
  const scope = { action, name, permissionId, builder };
484
625
  return Object.assign(builder, { registerActions: registerGrant.bind(null, scope) });
485
626
  }
486
- function createNameBuilder(action, name) {
487
- validatePermissionName(name);
488
- const builder = {};
489
- const scope = { action, name, role: GLOBAL_HOOK_OWNER, builder };
490
- return Object.assign(builder, {
491
- role: createRoleBuilder.bind(null, action, name),
492
- grantTo: createGrantBuilder.bind(null, action, name),
493
- hook: registerNameHook.bind(null, scope)
494
- });
627
+ function registerActions(scope, actions) {
628
+ const currentState = state_default.getOrCreate();
629
+ state_default.requireOpen(currentState);
630
+ requireDeclaredRole(scope.role, currentState.roles);
631
+ if (currentState.modules.get(scope.action)?.names.get(scope.name)?.actions.has(scope.role)) {
632
+ throw errors_default.create("DUPLICATE_REGISTRATION", `"${scope.action}::${scope.name}" already has actions registered for role "${scope.role}"`);
633
+ }
634
+ const registeredActions = definitions_default.readActions(actions, `${scope.action}::${scope.name} [${scope.role}]`);
635
+ ensureName(currentState, scope.action, scope.name).actions.set(scope.role, registeredActions);
636
+ return scope.builder;
495
637
  }
496
- function createModuleBuilder(action) {
497
- const builder = {};
498
- const scope = { action, builder };
499
- return Object.assign(builder, {
500
- module: appendModule.bind(null, action),
501
- name: createNameBuilder.bind(null, action),
502
- hook: registerModuleHook.bind(null, scope)
503
- });
638
+ function registerGrant(scope, actions) {
639
+ const currentState = state_default.getOrCreate();
640
+ state_default.requireOpen(currentState);
641
+ const source = identifiers_default.parse(scope.permissionId, "INVALID_DEFINITION", `"${scope.action}::${scope.name}": invalid grantTo identifier`);
642
+ requireDeclaredRole(source.role, currentState.roles);
643
+ if (source.action === scope.action && source.name === scope.name) {
644
+ throw errors_default.create("INVALID_DEFINITION", `"${scope.permissionId}" cannot grant to itself`);
645
+ }
646
+ if (currentState.modules.get(scope.action)?.names.get(scope.name)?.grants.has(scope.permissionId)) {
647
+ throw errors_default.create("DUPLICATE_REGISTRATION", `"${scope.action}::${scope.name}" already has a grant for "${scope.permissionId}"`);
648
+ }
649
+ const grantActions = definitions_default.readGrant(actions, `${scope.action}::${scope.name} [grantTo ${scope.permissionId}]`);
650
+ ensureName(currentState, scope.action, scope.name).grants.set(scope.permissionId, { source, actions: grantActions });
651
+ return scope.builder;
504
652
  }
505
- function appendModule(parentAction, segment) {
506
- validateModuleName(segment);
507
- return createModuleBuilder(`${parentAction}${MODULE_SEPARATOR}${segment}`);
653
+ function registerModuleHook(scope, method, hook) {
654
+ const currentState = state_default.getOrCreate();
655
+ state_default.requireOpen(currentState);
656
+ checkHook(hook, method, scope.action);
657
+ appendHook(ensureModule(currentState, scope.action).hooks, method, hook);
658
+ return scope.builder;
508
659
  }
509
- function defineModule(segment) {
510
- validateModuleName(segment);
511
- return createModuleBuilder(segment);
660
+ function registerNameHook(scope, method, hook) {
661
+ const currentState = state_default.getOrCreate();
662
+ state_default.requireOpen(currentState);
663
+ if (scope.role !== constants_default.GLOBAL_HOOK_OWNER)
664
+ requireDeclaredRole(scope.role, currentState.roles);
665
+ checkHook(hook, method, `${scope.action}::${scope.name}`);
666
+ const nameEntry = ensureName(currentState, scope.action, scope.name);
667
+ const roleHooks = nameEntry.hooks.get(scope.role) ?? new Map;
668
+ nameEntry.hooks.set(scope.role, roleHooks);
669
+ appendHook(roleHooks, method, hook);
670
+ return scope.builder;
671
+ }
672
+ function checkHook(hook, method, permissionPath) {
673
+ definitions_default.checkMethod(method, "INVALID_DEFINITION", permissionPath);
674
+ if (typeof hook !== "function")
675
+ throw errors_default.create("INVALID_DEFINITION", `${permissionPath}: hook("${method}") expects a function`);
676
+ }
677
+ function requireDeclaredRole(role, roles) {
678
+ if (roles.has(role))
679
+ return;
680
+ throw errors_default.create("ROLE_NOT_DECLARED", `role "${role}" is not declared. Available roles: ${[...roles].join(", ")}.
681
+ ` + "Is pkit.context.set('roles', [...]) missing from pkit.config.js, or was it imported after this file?");
512
682
  }
513
- function ensureModule(state, action) {
514
- const registeredModule = state.modules.get(action);
683
+ function ensureModule(currentState, action) {
684
+ const registeredModule = currentState.modules.get(action);
515
685
  if (registeredModule)
516
686
  return registeredModule;
517
687
  const newModule = { names: new Map, hooks: new Map };
518
- state.modules.set(action, newModule);
688
+ currentState.modules.set(action, newModule);
519
689
  return newModule;
520
690
  }
521
- function ensureName(state, action, name) {
522
- const registeredModule = ensureModule(state, action);
691
+ function ensureName(currentState, action, name) {
692
+ const registeredModule = ensureModule(currentState, action);
523
693
  const registeredName = registeredModule.names.get(name);
524
694
  if (registeredName)
525
695
  return registeredName;
@@ -527,60 +697,157 @@ function ensureName(state, action, name) {
527
697
  registeredModule.names.set(name, newName);
528
698
  return newName;
529
699
  }
700
+ function appendHook(methodHooks, method, hook) {
701
+ const hooks = methodHooks.get(method) ?? [];
702
+ methodHooks.set(method, hooks);
703
+ hooks.push(hook);
704
+ }
705
+ var registry_default = registry;
530
706
 
531
707
  // src/seal.ts
532
- function seal() {
533
- const state = getOrCreateState();
534
- if (state.snapshot)
535
- return;
536
- validateSealedRegistry(state.modules);
537
- const named = Object.create(null);
538
- for (const [action, registeredModule] of state.modules) {
708
+ var sealer = {
709
+ seal() {
710
+ const currentState = state_default.getOrCreate();
711
+ if (currentState.snapshot)
712
+ return;
713
+ checkRegistry(currentState.modules);
714
+ const named = Object.create(null);
715
+ for (const [action, registeredModule] of currentState.modules) {
716
+ for (const [name, nameEntry] of registeredModule.names) {
717
+ for (const [role, actions] of nameEntry.actions) {
718
+ named[identifiers_default.build(role, action, name)] = actions;
719
+ }
720
+ }
721
+ }
722
+ currentState.snapshot = { named: Object.freeze(named), assignable: new Set(Object.keys(named)) };
723
+ }
724
+ };
725
+ function checkRegistry(modules) {
726
+ for (const [action, registeredModule] of modules) {
727
+ if (registeredModule.names.size === 0) {
728
+ throw errors_default.create("INVALID_DEFINITION", `"${action}" has hooks but no name with registered actions`);
729
+ }
539
730
  for (const [name, nameEntry] of registeredModule.names) {
540
- for (const [role, actions] of nameEntry.actions) {
541
- named[permissionIdOf(role, action, name)] = actions;
731
+ const permissionPath = `${action}::${name}`;
732
+ if (nameEntry.actions.size === 0) {
733
+ throw errors_default.create("INVALID_DEFINITION", `"${permissionPath}" has no registered actions for any role`);
542
734
  }
735
+ checkGrantReferences(permissionPath, nameEntry, modules);
736
+ checkRoleHooks(permissionPath, nameEntry);
543
737
  }
544
738
  }
545
- state.snapshot = { named: Object.freeze(named), assignable: new Set(Object.keys(named)) };
546
739
  }
547
-
548
- // src/permissions.ts
549
- function getNamedCatalog() {
550
- const { snapshot } = getOrCreateState();
551
- validateSnapshot(snapshot);
552
- return snapshot.named;
553
- }
554
- function resolveMethodAccess(nameEntry, permissionId, role, assigned) {
555
- const methodAccess = Object.create(null);
556
- let reachable = false;
557
- for (const method of METHODS) {
558
- const access = resolveAccess(nameEntry, permissionId, role, method, assigned);
559
- methodAccess[method] = access.status === "granted";
560
- if (access.status !== "unassigned")
561
- reachable = true;
562
- }
563
- return reachable ? Object.freeze(methodAccess) : undefined;
564
- }
565
- function forUser(assignments) {
566
- const state = getOrCreateState();
567
- const { role, assigned } = validateIdentity(assignments, state);
568
- const access = Object.create(null);
569
- for (const [action, registeredModule] of state.modules) {
570
- for (const [name, nameEntry] of registeredModule.names) {
571
- const permissionId = permissionIdOf(role, action, name);
572
- const methodAccess = resolveMethodAccess(nameEntry, permissionId, role, assigned);
573
- if (methodAccess)
574
- access[permissionId] = methodAccess;
740
+ function checkGrantReferences(permissionPath, nameEntry, modules) {
741
+ for (const [permissionId, grant] of nameEntry.grants) {
742
+ const sourceEntry = modules.get(grant.source.action)?.names.get(grant.source.name);
743
+ if (!sourceEntry?.actions.has(grant.source.role)) {
744
+ throw errors_default.create("INVALID_DEFINITION", `"${permissionPath}": grantTo "${permissionId}" references a permission with no registered actions`);
745
+ }
746
+ for (const method of Object.keys(grant.actions)) {
747
+ if (declaresMethod(nameEntry, method))
748
+ continue;
749
+ throw errors_default.create("INVALID_DEFINITION", `"${permissionPath}": grantTo "${permissionId}" grants "${method}", which no role declares on that permission`);
750
+ }
751
+ }
752
+ }
753
+ function declaresMethod(nameEntry, method) {
754
+ for (const actions of nameEntry.actions.values()) {
755
+ if (Object.hasOwn(actions, method))
756
+ return true;
757
+ }
758
+ return false;
759
+ }
760
+ function checkRoleHooks(permissionPath, nameEntry) {
761
+ for (const [hookRole, methodHooks] of nameEntry.hooks) {
762
+ if (hookRole === constants_default.GLOBAL_HOOK_OWNER)
763
+ continue;
764
+ for (const method of methodHooks.keys()) {
765
+ if (hasAccessPath(nameEntry, hookRole, method))
766
+ continue;
767
+ throw errors_default.create("INVALID_DEFINITION", `"${permissionPath}": hook for "${hookRole}" on "${method}" has no registered actions or grant for that role`);
575
768
  }
576
769
  }
577
- return Object.freeze(access);
578
770
  }
579
- var permissions = Object.freeze(Object.defineProperty({ forUser }, "named", { get: getNamedCatalog, enumerable: true, configurable: false }));
771
+ function hasAccessPath(nameEntry, role, method) {
772
+ if (nameEntry.actions.get(role)?.[method])
773
+ return true;
774
+ for (const grant of nameEntry.grants.values()) {
775
+ if (grant.source.role === role && grant.actions[method])
776
+ return true;
777
+ }
778
+ return false;
779
+ }
780
+ var seal_default = sealer;
580
781
 
581
782
  // src/validate.ts
783
+ var validator = {
784
+ async validate(input) {
785
+ try {
786
+ const request = prepareRequest(input, state_default.getOrCreate());
787
+ const hookCalls = [];
788
+ for (const hook of request.hooks)
789
+ hookCalls.push(invokeHook(hook, request));
790
+ const hookResults = await Promise.allSettled(hookCalls);
791
+ const hookErrors = [];
792
+ for (const hookResult of hookResults) {
793
+ if (hookResult.status === "fulfilled")
794
+ continue;
795
+ const hookCause = hookResult.reason;
796
+ hookErrors.push({ code: "HOOK_ERROR", message: describeHookFailure(hookCause), cause: hookCause });
797
+ }
798
+ if (hookErrors.length)
799
+ return { result: null, errors: Object.freeze(hookErrors) };
800
+ return { result: { data: request.data }, errors: Object.freeze([]) };
801
+ } catch (cause) {
802
+ return { result: null, errors: Object.freeze([translateFailure(cause)]) };
803
+ }
804
+ }
805
+ };
806
+ function prepareRequest(input, currentState) {
807
+ const snapshot = state_default.requireSnapshot(currentState);
808
+ const method = definitions_default.checkMethod(input.method, "INVALID_INPUT", "method is required");
809
+ const { action, permissions } = input;
810
+ if (typeof action !== "string")
811
+ throw errors_default.create("INVALID_INPUT", "action is required");
812
+ const data = readOptionalObject(input.data, "data must be an object");
813
+ const context = readOptionalObject(input.context, "context must be an object");
814
+ const identity = resolve_default.identity(input, snapshot, currentState.roles);
815
+ const { role, assigned } = identity;
816
+ const registeredModule = currentState.modules.get(action);
817
+ if (!registeredModule)
818
+ throw errors_default.create("UNKNOWN_ACTION", `module "${action}" is not registered`);
819
+ const chosen = resolve_default.permission(registeredModule, action, identity);
820
+ if (!chosen) {
821
+ throw errors_default.create("PERMISSION_NOT_ASSIGNED", `no name of module "${action}" is assigned or granted to role "${role}" by the user permissions`);
822
+ }
823
+ const { permissionId, entry: nameEntry } = chosen;
824
+ const access = resolve_default.access(nameEntry, permissionId, role, method, assigned);
825
+ if (access.status === "unassigned") {
826
+ throw errors_default.create("PERMISSION_NOT_ASSIGNED", `"${permissionId}" is not assigned or granted by the user permissions`);
827
+ }
828
+ if (access.status === "disabled")
829
+ throw errors_default.create("METHOD_DISABLED", `"${permissionId}.${method}" is not enabled`);
830
+ const hookGroups = [
831
+ registeredModule.hooks.get(method),
832
+ nameEntry.hooks.get(constants_default.GLOBAL_HOOK_OWNER)?.get(method),
833
+ nameEntry.hooks.get(role)?.get(method)
834
+ ];
835
+ const hooks = [];
836
+ for (const group of hookGroups) {
837
+ if (group)
838
+ hooks.push(...group);
839
+ }
840
+ return { hooks, context, permissions, data: properties_default.resolve(data, access.properties, currentState.cropper) };
841
+ }
842
+ function readOptionalObject(value, message) {
843
+ if (value === undefined)
844
+ return {};
845
+ if (value === null || typeof value !== "object" || Array.isArray(value))
846
+ throw errors_default.create("INVALID_INPUT", message);
847
+ return value;
848
+ }
582
849
  async function invokeHook(hook, request) {
583
- return hook(request.data, request.context, request.permission);
850
+ return hook(request.data, request.context, request.permissions);
584
851
  }
585
852
  function describeHookFailure(reason) {
586
853
  try {
@@ -589,48 +856,24 @@ function describeHookFailure(reason) {
589
856
  return "the hook threw a value that cannot be described";
590
857
  }
591
858
  }
592
- async function validate(input) {
593
- try {
594
- const request = validateRequest(input, getOrCreateState());
595
- const { registeredModule, nameEntry, permission, result } = request;
596
- const { method, role } = permission;
597
- const hookGroups = [
598
- registeredModule.hooks.get(method),
599
- nameEntry.hooks.get(GLOBAL_HOOK_OWNER)?.get(method),
600
- nameEntry.hooks.get(role)?.get(method)
601
- ];
602
- const hookCalls = [];
603
- for (const hooks of hookGroups) {
604
- if (!hooks)
605
- continue;
606
- for (const hook of hooks)
607
- hookCalls.push(invokeHook(hook, request));
608
- }
609
- const hookResults = await Promise.allSettled(hookCalls);
610
- const errors = [];
611
- for (const hookResult of hookResults) {
612
- if (hookResult.status === "fulfilled")
613
- continue;
614
- const hookCause = hookResult.reason;
615
- errors.push({ code: "HOOK_ERROR", message: describeHookFailure(hookCause), cause: hookCause });
616
- }
617
- if (errors.length)
618
- return { result: null, errors: Object.freeze(errors) };
619
- return { result, errors: Object.freeze([]) };
620
- } catch (cause) {
621
- if (cause instanceof Error && cause.name === "PkitError") {
622
- const permissionError = cause;
623
- const error = permissionError.code === "PROPERTIES_NOT_ALLOWED" ? { code: permissionError.code, message: permissionError.message, fields: permissionError.fields } : { code: permissionError.code, message: permissionError.message };
624
- return { result: null, errors: Object.freeze([error]) };
625
- }
626
- return {
627
- result: null,
628
- errors: Object.freeze([{ code: "VALIDATION_ERROR", message: "permission could not be validated", cause }])
629
- };
859
+ function translateFailure(cause) {
860
+ if (!(cause instanceof Error) || cause.name !== "PkitError") {
861
+ return { code: "VALIDATION_ERROR", message: "permission could not be validated", cause };
630
862
  }
863
+ const permissionError = cause;
864
+ if (permissionError.code === "PROPERTIES_NOT_ALLOWED") {
865
+ return { code: permissionError.code, message: permissionError.message, fields: permissionError.fields };
866
+ }
867
+ return { code: permissionError.code, message: permissionError.message };
631
868
  }
869
+ var validate_default = validator;
870
+
632
871
  // src/index.ts
633
- var pkit = Object.freeze({ context, module: defineModule, seal, permissions, validate });
872
+ var METHODS2 = constants_default.METHODS;
873
+ var seal = seal_default.seal;
874
+ var validate = validate_default.validate;
875
+ var defineModule = registry_default.defineModule;
876
+ var pkit = Object.freeze({ context: context_default, module: defineModule, seal, permissions: permissions_default, validate });
634
877
  var src_default = pkit;
635
878
 
636
- //# debugId=B57D4832B42402DE64756E2164756E21
879
+ //# debugId=1BE6B3EEE711E91164756E2164756E21