@ahmed109/gatekeeper-core 0.0.0-stage → 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ahmed Tamer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # @ahmed109/gatekeeper-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Pure, framework-independent authorization and feature-flag evaluator for TypeScript.
4
+
5
+ Part of the **Gatekeeper** toolkit. Zero runtime dependencies, deterministic evaluation, and full TypeScript type safety for role-based (RBAC) and attribute-based (ABAC) access control.
6
+
7
+ ## Installation
8
+
9
+ `ash
10
+ npm install @ahmed109/gatekeeper-core
11
+
12
+ # or
13
+
14
+ pnpm add @ahmed109/gatekeeper-core
15
+
16
+ # or
17
+
18
+ yarn add @ahmed109/gatekeeper-core
19
+ `
20
+
21
+ ## Features
22
+
23
+ - **Zero runtime dependencies**: Pure functional logic running identically in Node.js, browsers, Edge runtimes, and Cloudflare Workers.
24
+ - **Layered Privilege Model**: Evaluates base role permissions (dmin, manager, member, or custom) combined with explicit user-level direct grants.
25
+ - **Feature Flag Engine**: Side-by-side authorization and feature-flag evaluation.
26
+ - **Compound Checks**: Built-in support for can(), canAll(), and canAny().
27
+
28
+ ## Quickstart
29
+
30
+ ` ypescript
31
+ import { can, canAll, isFeatureEnabled, type GatekeeperUser } from '@ahmed109/gatekeeper-core';
32
+
33
+ const user: GatekeeperUser = {
34
+ id: 'usr_123',
35
+ name: 'Alice Admin',
36
+ email: 'alice@example.com',
37
+ role: 'admin',
38
+ permissions: ['custom.override'],
39
+ };
40
+
41
+ // Check single permission
42
+ if (can(user, 'users.delete')) {
43
+ console.log('User can delete users');
44
+ }
45
+
46
+ // Check multiple permissions
47
+ if (canAll(user, ['users.read', 'settings.manage'])) {
48
+ console.log('User possesses all required permissions');
49
+ }
50
+
51
+ // Evaluate feature flags
52
+ const flags = { 'new-dashboard': true, 'beta-analytics': false };
53
+ if (isFeatureEnabled('new-dashboard', flags)) {
54
+ console.log('Feature is enabled');
55
+ }
56
+ `
57
+
58
+ ## License
59
+
60
+ MIT © [Ahmed Tamer](https://github.com/Ahmed1092002)
package/dist/index.cjs ADDED
@@ -0,0 +1,417 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DEFAULT_ROLE_PERMISSIONS: () => DEFAULT_ROLE_PERMISSIONS,
24
+ can: () => can,
25
+ canAll: () => canAll,
26
+ canAny: () => canAny,
27
+ createSubject: () => createSubject,
28
+ defineRoleHierarchy: () => defineRoleHierarchy,
29
+ defineRolePermissions: () => defineRolePermissions,
30
+ evaluatePermission: () => evaluatePermission,
31
+ explain: () => explain,
32
+ fromJwtClaims: () => fromJwtClaims,
33
+ fromPermissions: () => fromPermissions,
34
+ fromRoles: () => fromRoles,
35
+ getUserEffectivePermissions: () => getUserEffectivePermissions,
36
+ isFeatureEnabled: () => isFeatureEnabled,
37
+ normalizeFeatureFlags: () => normalizeFeatureFlags,
38
+ parseEvaluateOptions: () => parseEvaluateOptions,
39
+ permissionMatches: () => permissionMatches,
40
+ resolveInheritedRoles: () => resolveInheritedRoles
41
+ });
42
+ module.exports = __toCommonJS(index_exports);
43
+
44
+ // src/roles.ts
45
+ var DEFAULT_ROLE_PERMISSIONS = {
46
+ admin: ["users.read", "users.create", "users.delete", "reports.view", "settings.manage"],
47
+ manager: ["users.read", "reports.view"],
48
+ member: ["reports.view"]
49
+ };
50
+ function defineRolePermissions(customMap, baseMap = DEFAULT_ROLE_PERMISSIONS) {
51
+ if (!customMap) {
52
+ return { ...baseMap };
53
+ }
54
+ const merged = { ...baseMap };
55
+ for (const [role, perms] of Object.entries(customMap)) {
56
+ if (perms) {
57
+ merged[role] = [...perms];
58
+ }
59
+ }
60
+ return merged;
61
+ }
62
+ function defineRoleHierarchy(hierarchy) {
63
+ return Object.fromEntries(
64
+ Object.entries(hierarchy).map(([role, parents]) => [role, [...parents]])
65
+ );
66
+ }
67
+ function resolveInheritedRoles(roles, hierarchy) {
68
+ const resolved = /* @__PURE__ */ new Set();
69
+ const visit = (role) => {
70
+ if (resolved.has(role)) return;
71
+ resolved.add(role);
72
+ for (const parent of hierarchy?.[role] ?? []) visit(parent);
73
+ };
74
+ for (const role of roles) visit(role);
75
+ return [...resolved];
76
+ }
77
+
78
+ // src/evaluator.ts
79
+ function parseEvaluateOptions(options) {
80
+ if (!options || typeof options !== "object") {
81
+ return {};
82
+ }
83
+ if ("roleMap" in options || "roleHierarchy" in options || "context" in options || "policy" in options) {
84
+ return options;
85
+ }
86
+ const values = Object.values(options);
87
+ if (values.length === 0 || values.every((v) => Array.isArray(v))) {
88
+ return { roleMap: options };
89
+ }
90
+ return options;
91
+ }
92
+ function getUserEffectivePermissions(subject, roleMapOrOptions) {
93
+ const permissions = /* @__PURE__ */ new Set();
94
+ if (!subject) {
95
+ return permissions;
96
+ }
97
+ const opts = parseEvaluateOptions(roleMapOrOptions);
98
+ const roleMap = opts.roleMap ?? DEFAULT_ROLE_PERMISSIONS;
99
+ const rolesToEvaluate = /* @__PURE__ */ new Set();
100
+ if (Array.isArray(subject.roles)) {
101
+ for (const r of subject.roles) {
102
+ if (r) rolesToEvaluate.add(r);
103
+ }
104
+ }
105
+ if (subject.role) {
106
+ rolesToEvaluate.add(subject.role);
107
+ }
108
+ for (const role of resolveInheritedRoles(rolesToEvaluate, opts.roleHierarchy)) {
109
+ const rolePerms = roleMap[role];
110
+ if (rolePerms && Array.isArray(rolePerms)) {
111
+ for (const perm of rolePerms) {
112
+ permissions.add(perm);
113
+ }
114
+ }
115
+ }
116
+ if (Array.isArray(subject.permissions)) {
117
+ for (const perm of subject.permissions) {
118
+ if (perm) permissions.add(perm);
119
+ }
120
+ }
121
+ return permissions;
122
+ }
123
+ function permissionMatches(granted, requested) {
124
+ return granted === requested || granted.endsWith(".*") && requested.startsWith(granted.slice(0, -1));
125
+ }
126
+ function can(subject, permission, options) {
127
+ if (!subject || !permission) {
128
+ return false;
129
+ }
130
+ const opts = parseEvaluateOptions(options);
131
+ if (opts.policy) {
132
+ const decision = opts.policy(subject, permission, opts.context);
133
+ if (typeof decision === "boolean") {
134
+ return decision;
135
+ }
136
+ }
137
+ const effective = getUserEffectivePermissions(subject, options !== void 0 ? opts : void 0);
138
+ return [...effective].some((granted) => permissionMatches(granted, permission));
139
+ }
140
+ function canAll(subject, permissions, options) {
141
+ if (!subject || !permissions.length) {
142
+ return false;
143
+ }
144
+ return permissions.every((p) => can(subject, p, options));
145
+ }
146
+ function canAny(subject, permissions, options) {
147
+ if (!subject || !permissions.length) {
148
+ return false;
149
+ }
150
+ return permissions.some((p) => can(subject, p, options));
151
+ }
152
+ function evaluatePermission(subject, permission, options) {
153
+ if (!subject) {
154
+ return {
155
+ allowed: false,
156
+ reason: "No authenticated user provided.",
157
+ missingPermissions: [permission]
158
+ };
159
+ }
160
+ const opts = parseEvaluateOptions(options);
161
+ if (opts.policy) {
162
+ const decision = opts.policy(subject, permission, opts.context);
163
+ if (typeof decision === "boolean") {
164
+ return {
165
+ allowed: decision,
166
+ reason: decision ? "Permission granted by policy." : "Permission denied by policy.",
167
+ missingPermissions: decision ? void 0 : [permission]
168
+ };
169
+ }
170
+ }
171
+ const effective = getUserEffectivePermissions(subject, options !== void 0 ? opts : void 0);
172
+ const matchedPermission = [...effective].find((granted) => permissionMatches(granted, permission));
173
+ const allowed = matchedPermission !== void 0;
174
+ if (allowed) {
175
+ return {
176
+ allowed: true,
177
+ reason: "Permission granted.",
178
+ matchedPermission,
179
+ source: subject.permissions?.includes(matchedPermission) ? "direct-permission" : "role-permission",
180
+ evaluatedRoles: resolveInheritedRoles(
181
+ [...subject.roles ?? [], ...subject.role ? [subject.role] : []],
182
+ opts.roleHierarchy
183
+ )
184
+ };
185
+ }
186
+ const roleDesc = subject.role ?? (subject.roles?.length ? subject.roles.join(", ") : "none");
187
+ return {
188
+ allowed: false,
189
+ reason: `User with role '${roleDesc}' lacks required permission '${permission}'.`,
190
+ missingPermissions: [permission],
191
+ source: "none",
192
+ evaluatedRoles: resolveInheritedRoles(
193
+ [...subject.roles ?? [], ...subject.role ? [subject.role] : []],
194
+ opts.roleHierarchy
195
+ )
196
+ };
197
+ }
198
+ var explain = evaluatePermission;
199
+ function normalizeFeatureFlags(flags) {
200
+ if (!flags) {
201
+ return {};
202
+ }
203
+ if (Array.isArray(flags)) {
204
+ const result = {};
205
+ for (const flag of flags) {
206
+ result[flag.key] = flag.enabled;
207
+ }
208
+ return result;
209
+ }
210
+ return { ...flags };
211
+ }
212
+ function isFeatureEnabled(flags, flagKey) {
213
+ if (!flags || !flagKey) {
214
+ return false;
215
+ }
216
+ if (Array.isArray(flags)) {
217
+ const found = flags.find((f) => f.key === flagKey);
218
+ return Boolean(found?.enabled);
219
+ }
220
+ return Boolean(flags[flagKey]);
221
+ }
222
+
223
+ // src/adapters.ts
224
+ function fromRoles(idOrInput, roles, attributes) {
225
+ if (typeof idOrInput === "object" && idOrInput !== null) {
226
+ const rolesList2 = [];
227
+ if (Array.isArray(idOrInput.roles)) {
228
+ rolesList2.push(...idOrInput.roles);
229
+ } else if (idOrInput.roles) {
230
+ rolesList2.push(idOrInput.roles);
231
+ }
232
+ if (idOrInput.role && !rolesList2.includes(idOrInput.role)) {
233
+ rolesList2.push(idOrInput.role);
234
+ }
235
+ return {
236
+ id: String(idOrInput.id),
237
+ roles: rolesList2,
238
+ role: idOrInput.role ?? rolesList2[0],
239
+ ...idOrInput.permissions ? { permissions: idOrInput.permissions } : {},
240
+ ...idOrInput.attributes ? { attributes: idOrInput.attributes } : {},
241
+ ...idOrInput.name ? { name: idOrInput.name } : {},
242
+ ...idOrInput.email ? { email: idOrInput.email } : {}
243
+ };
244
+ }
245
+ const rolesList = [];
246
+ if (Array.isArray(roles)) {
247
+ rolesList.push(...roles);
248
+ } else if (roles) {
249
+ rolesList.push(roles);
250
+ }
251
+ return {
252
+ id: String(idOrInput),
253
+ roles: rolesList,
254
+ role: rolesList[0],
255
+ ...attributes ? { attributes } : {}
256
+ };
257
+ }
258
+ function fromPermissions(idOrInput, permissions, attributes) {
259
+ if (typeof idOrInput === "object" && idOrInput !== null) {
260
+ return {
261
+ id: String(idOrInput.id),
262
+ roles: [],
263
+ permissions: Array.isArray(idOrInput.permissions) ? [...idOrInput.permissions] : [],
264
+ ...idOrInput.attributes ? { attributes: idOrInput.attributes } : {},
265
+ ...idOrInput.name ? { name: idOrInput.name } : {},
266
+ ...idOrInput.email ? { email: idOrInput.email } : {}
267
+ };
268
+ }
269
+ return {
270
+ id: String(idOrInput),
271
+ roles: [],
272
+ permissions: Array.isArray(permissions) ? [...permissions] : [],
273
+ ...attributes ? { attributes } : {}
274
+ };
275
+ }
276
+ function getByPath(obj, path) {
277
+ const parts = path.split(".");
278
+ let current = obj;
279
+ for (const part of parts) {
280
+ if (current && typeof current === "object" && part in current) {
281
+ current = current[part];
282
+ } else {
283
+ return void 0;
284
+ }
285
+ }
286
+ return current;
287
+ }
288
+ function fromJwtClaims(claims, options = {}) {
289
+ if (!claims || typeof claims !== "object") {
290
+ return { id: "", roles: [], permissions: [] };
291
+ }
292
+ const idFields = options.idField ? Array.isArray(options.idField) ? options.idField : [options.idField] : ["sub", "id"];
293
+ let resolvedId = "";
294
+ for (const field of idFields) {
295
+ const val = getByPath(claims, field);
296
+ if (val !== void 0 && val !== null && String(val).trim()) {
297
+ resolvedId = String(val);
298
+ break;
299
+ }
300
+ }
301
+ const rolesFields = options.rolesField ? Array.isArray(options.rolesField) ? options.rolesField : [options.rolesField] : ["roles", "role", "realm_access.roles"];
302
+ const resolvedRoles = [];
303
+ for (const field of rolesFields) {
304
+ const val = getByPath(claims, field);
305
+ if (Array.isArray(val)) {
306
+ for (const item of val) {
307
+ if (typeof item === "string") {
308
+ resolvedRoles.push(item);
309
+ }
310
+ }
311
+ if (resolvedRoles.length > 0) break;
312
+ } else if (typeof val === "string" && val.trim()) {
313
+ resolvedRoles.push(val);
314
+ break;
315
+ }
316
+ }
317
+ const permFields = options.permissionsField ? Array.isArray(options.permissionsField) ? options.permissionsField : [options.permissionsField] : ["permissions", "perms"];
318
+ const resolvedPerms = [];
319
+ for (const field of permFields) {
320
+ const val = getByPath(claims, field);
321
+ if (Array.isArray(val)) {
322
+ for (const item of val) {
323
+ if (typeof item === "string") {
324
+ resolvedPerms.push(item);
325
+ }
326
+ }
327
+ if (resolvedPerms.length > 0) break;
328
+ } else if (typeof val === "string" && val.trim()) {
329
+ resolvedPerms.push(val);
330
+ break;
331
+ }
332
+ }
333
+ const attributes = {};
334
+ if (options.attributesFields && Array.isArray(options.attributesFields)) {
335
+ for (const attrField of options.attributesFields) {
336
+ const val = getByPath(claims, attrField);
337
+ if (val !== void 0) {
338
+ attributes[attrField] = val;
339
+ }
340
+ }
341
+ } else {
342
+ const excludedKeys = /* @__PURE__ */ new Set([
343
+ "sub",
344
+ "id",
345
+ "roles",
346
+ "role",
347
+ "realm_access",
348
+ "permissions",
349
+ "perms"
350
+ ]);
351
+ for (const [k, v] of Object.entries(claims)) {
352
+ if (!excludedKeys.has(k) && v !== void 0) {
353
+ attributes[k] = v;
354
+ }
355
+ }
356
+ }
357
+ const email = typeof claims.email === "string" ? claims.email : void 0;
358
+ const name = typeof claims.name === "string" ? claims.name : typeof claims.preferred_username === "string" ? claims.preferred_username : void 0;
359
+ return {
360
+ id: resolvedId,
361
+ roles: resolvedRoles,
362
+ role: resolvedRoles[0],
363
+ permissions: resolvedPerms,
364
+ attributes,
365
+ ...name ? { name } : {},
366
+ ...email ? { email } : {}
367
+ };
368
+ }
369
+ function createSubject(source, mapping) {
370
+ if (typeof mapping === "function") {
371
+ return mapping(source);
372
+ }
373
+ const rawRoles = mapping.getRoles ? mapping.getRoles(source) : void 0;
374
+ const rolesList = [];
375
+ if (Array.isArray(rawRoles)) {
376
+ for (const r of rawRoles) {
377
+ if (r) rolesList.push(r);
378
+ }
379
+ } else if (rawRoles) {
380
+ rolesList.push(rawRoles);
381
+ }
382
+ const rawPerms = mapping.getPermissions ? mapping.getPermissions(source) : void 0;
383
+ const permsList = Array.isArray(rawPerms) ? [...rawPerms] : [];
384
+ const attributes = mapping.getAttributes ? mapping.getAttributes(source) : void 0;
385
+ const name = mapping.getName ? mapping.getName(source) : void 0;
386
+ const email = mapping.getEmail ? mapping.getEmail(source) : void 0;
387
+ return {
388
+ id: mapping.getId(source),
389
+ roles: rolesList,
390
+ role: rolesList[0],
391
+ permissions: permsList,
392
+ ...attributes ? { attributes } : {},
393
+ ...name ? { name } : {},
394
+ ...email ? { email } : {}
395
+ };
396
+ }
397
+ // Annotate the CommonJS export names for ESM import in node:
398
+ 0 && (module.exports = {
399
+ DEFAULT_ROLE_PERMISSIONS,
400
+ can,
401
+ canAll,
402
+ canAny,
403
+ createSubject,
404
+ defineRoleHierarchy,
405
+ defineRolePermissions,
406
+ evaluatePermission,
407
+ explain,
408
+ fromJwtClaims,
409
+ fromPermissions,
410
+ fromRoles,
411
+ getUserEffectivePermissions,
412
+ isFeatureEnabled,
413
+ normalizeFeatureFlags,
414
+ parseEvaluateOptions,
415
+ permissionMatches,
416
+ resolveInheritedRoles
417
+ });