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