rolegate 0.1.0 → 0.1.1

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.
Files changed (97) hide show
  1. package/README.md +23 -10
  2. package/dist/core/createRbac.d.ts +3 -0
  3. package/dist/core/createRbac.d.ts.map +1 -0
  4. package/dist/core/createRbac.js +14 -34
  5. package/dist/core/createRbac.js.map +1 -1
  6. package/dist/core/index.d.ts +1 -0
  7. package/dist/core/index.d.ts.map +1 -0
  8. package/dist/core/rules.d.ts +17 -0
  9. package/dist/core/rules.d.ts.map +1 -0
  10. package/dist/core/rules.js +62 -0
  11. package/dist/core/rules.js.map +1 -0
  12. package/dist/core/types.d.ts +1 -0
  13. package/dist/core/types.d.ts.map +1 -0
  14. package/dist/express/guardRoutes.d.ts +6 -0
  15. package/dist/express/guardRoutes.d.ts.map +1 -0
  16. package/dist/express/guardRoutes.js +6 -1
  17. package/dist/express/guardRoutes.js.map +1 -1
  18. package/dist/express/index.d.ts +1 -0
  19. package/dist/express/index.d.ts.map +1 -0
  20. package/dist/express/requirePermission.d.ts +1 -0
  21. package/dist/express/requirePermission.d.ts.map +1 -0
  22. package/dist/express/types.d.ts +2 -0
  23. package/dist/express/types.d.ts.map +1 -0
  24. package/dist/express/types.js +3 -1
  25. package/dist/express/types.js.map +1 -1
  26. package/dist/index.d.ts +1 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/react/index.d.ts +1 -0
  29. package/dist/react/index.d.ts.map +1 -0
  30. package/dist/react/rbac.d.ts +1 -0
  31. package/dist/react/rbac.d.ts.map +1 -0
  32. package/dist/react/routes.d.ts +1 -0
  33. package/dist/react/routes.d.ts.map +1 -0
  34. package/dist/routes/createRouteAccess.d.ts +3 -0
  35. package/dist/routes/createRouteAccess.d.ts.map +1 -0
  36. package/dist/routes/createRouteAccess.js +15 -33
  37. package/dist/routes/createRouteAccess.js.map +1 -1
  38. package/dist/routes/fromRows.d.ts +1 -0
  39. package/dist/routes/fromRows.d.ts.map +1 -0
  40. package/dist/routes/fromRows.js +21 -7
  41. package/dist/routes/fromRows.js.map +1 -1
  42. package/dist/routes/index.d.ts +2 -1
  43. package/dist/routes/index.d.ts.map +1 -0
  44. package/dist/routes/index.js +1 -1
  45. package/dist/routes/index.js.map +1 -1
  46. package/dist/routes/matching/path.d.ts +14 -0
  47. package/dist/routes/matching/path.d.ts.map +1 -0
  48. package/dist/routes/matching/path.js +49 -0
  49. package/dist/routes/matching/path.js.map +1 -0
  50. package/dist/routes/{pattern.d.ts → matching/pattern.d.ts} +5 -10
  51. package/dist/routes/matching/pattern.d.ts.map +1 -0
  52. package/dist/routes/{pattern.js → matching/pattern.js} +21 -27
  53. package/dist/routes/matching/pattern.js.map +1 -0
  54. package/dist/routes/rules.d.ts +14 -0
  55. package/dist/routes/rules.d.ts.map +1 -0
  56. package/dist/routes/rules.js +53 -0
  57. package/dist/routes/rules.js.map +1 -0
  58. package/dist/routes/types.d.ts +1 -0
  59. package/dist/routes/types.d.ts.map +1 -0
  60. package/dist/shared/errors.d.ts +1 -0
  61. package/dist/shared/errors.d.ts.map +1 -0
  62. package/dist/shared/roles.d.ts +4 -1
  63. package/dist/shared/roles.d.ts.map +1 -0
  64. package/dist/shared/roles.js +7 -3
  65. package/dist/shared/roles.js.map +1 -1
  66. package/dist/shared/validate.d.ts +14 -0
  67. package/dist/shared/validate.d.ts.map +1 -0
  68. package/dist/shared/validate.js +35 -0
  69. package/dist/shared/validate.js.map +1 -0
  70. package/docs/actions.md +3 -1
  71. package/docs/api-routes.md +21 -1
  72. package/docs/database.md +4 -0
  73. package/docs/pages.md +6 -0
  74. package/package.json +4 -3
  75. package/src/core/createRbac.ts +58 -0
  76. package/src/core/index.ts +2 -0
  77. package/src/core/rules.ts +69 -0
  78. package/src/core/types.ts +36 -0
  79. package/src/express/guardRoutes.ts +64 -0
  80. package/src/express/index.ts +12 -0
  81. package/src/express/requirePermission.ts +43 -0
  82. package/src/express/types.ts +45 -0
  83. package/src/index.ts +11 -0
  84. package/src/react/index.ts +10 -0
  85. package/src/react/rbac.tsx +49 -0
  86. package/src/react/routes.tsx +49 -0
  87. package/src/routes/createRouteAccess.ts +57 -0
  88. package/src/routes/fromRows.ts +61 -0
  89. package/src/routes/index.ts +5 -0
  90. package/src/routes/matching/path.ts +48 -0
  91. package/src/routes/matching/pattern.ts +67 -0
  92. package/src/routes/rules.ts +62 -0
  93. package/src/routes/types.ts +35 -0
  94. package/src/shared/errors.ts +17 -0
  95. package/src/shared/roles.ts +92 -0
  96. package/src/shared/validate.ts +37 -0
  97. package/dist/routes/pattern.js.map +0 -1
@@ -0,0 +1,62 @@
1
+ // Route rules from the config, compiled once: pattern parsed, methods in a Set.
2
+
3
+ import { configError, isObject } from '../shared/validate.js';
4
+ import { compilePattern } from './matching/pattern.js';
5
+ import type { RoutePattern } from './matching/pattern.js';
6
+ import type { RouteRule } from './types.js';
7
+
8
+ export interface CompiledRule {
9
+ pattern: RoutePattern;
10
+ /** null means "any method". */
11
+ methods: ReadonlySet<string> | null;
12
+ }
13
+
14
+ /** Express runs GET handlers for HEAD, so HEAD follows GET rules. Otherwise it would dodge a GET deny. */
15
+ export function normalizeMethod(method: string): string {
16
+ const upper = method.toUpperCase();
17
+ return upper === 'HEAD' ? 'GET' : upper;
18
+ }
19
+
20
+ /** Compiles the allow (or deny) list of one role. */
21
+ export function compileRules(list: RouteRule[] | undefined, role: string, kind: 'allow' | 'deny'): CompiledRule[] {
22
+ if (list === undefined) return [];
23
+ if (!Array.isArray(list)) configError(`${kind} of role "${role}" should be a list of routes`);
24
+
25
+ return list.map((rule) => {
26
+ try {
27
+ return compileRule(rule);
28
+ } catch (err) {
29
+ // with rules from a DB you'll want to know which role it is
30
+ const message = err instanceof Error ? err.message : String(err);
31
+ throw new Error(`${message} (in role "${role}")`);
32
+ }
33
+ });
34
+ }
35
+
36
+ /** Does any of the rules cover this path and method? */
37
+ export function hits(rules: CompiledRule[], segments: readonly string[], method: string): boolean {
38
+ return rules.some((rule) => {
39
+ const methodFits = rule.methods === null || rule.methods.has(method);
40
+ return methodFits && rule.pattern.matches(segments);
41
+ });
42
+ }
43
+
44
+ function compileRule(rule: RouteRule): CompiledRule {
45
+ // just a path means any method
46
+ if (typeof rule === 'string') return { pattern: compilePattern(rule), methods: null };
47
+
48
+ if (!isObject(rule) || typeof rule.path !== 'string') {
49
+ configError('a route rule should be a path or { path, methods? }');
50
+ }
51
+ const pattern = compilePattern(rule.path);
52
+ const { methods } = rule;
53
+
54
+ if (methods === undefined) return { pattern, methods: null };
55
+ if (!Array.isArray(methods) || methods.some((m) => typeof m !== 'string' || m === '')) {
56
+ configError(`"methods" for "${rule.path}" should be a list like ['GET', 'POST']`);
57
+ }
58
+ if (methods.length === 0) configError(`"methods" for "${rule.path}" is empty`);
59
+ if (methods.includes('*')) return { pattern, methods: null };
60
+
61
+ return { pattern, methods: new Set(methods.map(normalizeMethod)) };
62
+ }
@@ -0,0 +1,35 @@
1
+ import type { Roles } from '../shared/roles.js';
2
+
3
+ /**
4
+ * A route a role may (or may not) open.
5
+ *
6
+ * - A string, e.g. '/dashboard' or '/admin/*': any HTTP method. That's all
7
+ * you need for frontend pages.
8
+ * - An object with `methods`, e.g. `{ path: '/posts/:id', methods: ['PUT', 'DELETE'] }`,
9
+ * when you care about the method, which mostly happens with API routes.
10
+ */
11
+ export type RouteRule = string | { path: string; methods?: readonly string[] };
12
+
13
+ export interface RouteRoleConfig {
14
+ /** Take all routes of these roles, then add (or deny) on top. */
15
+ extends?: string[];
16
+ allow?: RouteRule[];
17
+ /** Wins over any allow, including inherited ones. */
18
+ deny?: RouteRule[];
19
+ }
20
+
21
+ export interface RouteAccessConfig {
22
+ roles: Record<string, RouteRoleConfig>;
23
+ }
24
+
25
+ export interface RouteAccess {
26
+ /**
27
+ * Can these roles open `path`? `method` defaults to GET, which is what
28
+ * "open a page" means. HEAD is checked as GET, same as Express handles it.
29
+ */
30
+ can(roles: Roles, path: string, method?: string): boolean;
31
+ /** Same question, but throws ForbiddenError when the answer is no. */
32
+ assert(roles: Roles, path: string, method?: string): void;
33
+ /** Every role name from the config. */
34
+ readonly roles: readonly string[];
35
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Thrown by `assert()` in both engines.
3
+ *
4
+ * For resource checks it reads like "cannot delete posts",
5
+ * for route checks like "cannot DELETE /posts/42".
6
+ */
7
+ export class ForbiddenError extends Error {
8
+ readonly resource: string;
9
+ readonly action: string;
10
+
11
+ constructor(resource: string, action: string) {
12
+ super(`Forbidden: cannot ${action} ${resource}`);
13
+ this.name = 'ForbiddenError';
14
+ this.resource = resource;
15
+ this.action = action;
16
+ }
17
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Role plumbing shared by both engines (resource checks and route checks).
3
+ *
4
+ * Both of them have the same idea of a role: it can extend other roles,
5
+ * it has things it allows and things it denies, and a deny always wins.
6
+ * The only difference is what a single "rule" looks like, so this file
7
+ * is generic over the rule type and doesn't care what's inside.
8
+ */
9
+
10
+ /** One role, or several, or nobody (not signed in). */
11
+ export type Roles = string | readonly string[] | undefined;
12
+
13
+ export interface RoleDefinition<R> {
14
+ extends?: readonly string[];
15
+ allow?: readonly R[];
16
+ deny?: readonly R[];
17
+ }
18
+
19
+ /** A role after inheritance is applied: its own rules plus everything from its parents. */
20
+ export interface ResolvedRole<R> {
21
+ allow: R[];
22
+ deny: R[];
23
+ }
24
+
25
+ const hasOwn = (obj: object, key: string) => Object.prototype.hasOwnProperty.call(obj, key);
26
+
27
+ /**
28
+ * Flattens `extends` for every role and returns them in a Map.
29
+ *
30
+ * We do it for the whole config right away, so a typo in a role name or a
31
+ * circular `extends` blows up when the app starts and not in the middle of a request.
32
+ */
33
+ export function resolveRoles<R>(definitions: Record<string, RoleDefinition<R>>): Map<string, ResolvedRole<R>> {
34
+ const resolved = new Map<string, ResolvedRole<R>>();
35
+
36
+ const resolve = (name: string, trail: string[]): ResolvedRole<R> => {
37
+ const cached = resolved.get(name);
38
+ if (cached) return cached;
39
+
40
+ // hasOwn, not `in`: otherwise a role called "constructor" would quietly
41
+ // pick up Object.prototype.constructor and look like a real role.
42
+ if (!hasOwn(definitions, name)) {
43
+ const from = trail.length ? trail.join(' -> ') : 'config';
44
+ throw new Error(`rolegate: unknown role "${name}" (referenced by ${from})`);
45
+ }
46
+ if (trail.includes(name)) {
47
+ throw new Error(`rolegate: circular "extends": ${[...trail, name].join(' -> ')}`);
48
+ }
49
+
50
+ const def = definitions[name];
51
+ const role: ResolvedRole<R> = { allow: [], deny: [] };
52
+ for (const parent of def.extends ?? []) {
53
+ const p = resolve(parent, [...trail, name]);
54
+ role.allow.push(...p.allow);
55
+ role.deny.push(...p.deny);
56
+ }
57
+ role.allow.push(...(def.allow ?? []));
58
+ role.deny.push(...(def.deny ?? []));
59
+
60
+ resolved.set(name, role);
61
+ return role;
62
+ };
63
+
64
+ for (const name of Object.keys(definitions)) resolve(name, []);
65
+ return resolved;
66
+ }
67
+
68
+ /** Role names from whatever the app passed. Roles come from tokens, so junk like null or '' is skipped. */
69
+ export function roleNames(roles: Roles): string[] {
70
+ const list: readonly unknown[] = typeof roles === 'string' ? [roles] : Array.isArray(roles) ? roles : [];
71
+ return list.filter((name): name is string => typeof name === 'string' && name !== '');
72
+ }
73
+
74
+ /** The resolved roles we actually know about, out of the ones the app gave us. */
75
+ export function pickRoles<T>(known: Map<string, T>, roles: Roles): T[] {
76
+ const picked: T[] = [];
77
+ for (const name of roleNames(roles)) {
78
+ const role = known.get(name);
79
+ if (role) picked.push(role);
80
+ }
81
+ return picked;
82
+ }
83
+
84
+ /**
85
+ * The one rule of the whole library: if any role denies, the answer is no.
86
+ * Otherwise it's yes if at least one role allows. No roles at all means no.
87
+ */
88
+ export function decide<T>(roles: T[], denies: (role: T) => boolean, allows: (role: T) => boolean): boolean {
89
+ if (roles.length === 0) return false;
90
+ if (roles.some(denies)) return false;
91
+ return roles.some(allows);
92
+ }
@@ -0,0 +1,37 @@
1
+ // Configs often come from JSON or a database, where TypeScript can't help.
2
+ // So we check the shape ourselves and fail on startup, not mid-request.
3
+
4
+ export function configError(message: string): never {
5
+ throw new Error(`rolegate: ${message}`);
6
+ }
7
+
8
+ export const isObject = (value: unknown): value is Record<string, unknown> =>
9
+ typeof value === 'object' && value !== null && !Array.isArray(value);
10
+
11
+ /** An object without a prototype, so keys like "constructor" are just keys. */
12
+ export const dictionary = <T>(): Record<string, T> => Object.create(null);
13
+
14
+ /**
15
+ * In a plain object "__proto__" swaps the prototype instead of adding a key,
16
+ * so a role with that name could leak its rules into every object. We refuse it.
17
+ */
18
+ export function checkRoleName(name: unknown, where: string): asserts name is string {
19
+ if (typeof name !== 'string' || name === '') configError(`role names must be non-empty strings (${where})`);
20
+ if (name === '__proto__') configError(`"__proto__" can't be used as a role name (${where})`);
21
+ }
22
+
23
+ /** Checks `config.roles` and the `extends` of each role. */
24
+ export function checkRolesObject(roles: unknown): asserts roles is Record<string, { extends?: unknown }> {
25
+ if (!isObject(roles)) configError('config.roles should be an object like { admin: { ... } }');
26
+
27
+ for (const [name, role] of Object.entries(roles)) {
28
+ checkRoleName(name, 'in config.roles');
29
+ if (!isObject(role)) configError(`role "${name}" should be an object`);
30
+
31
+ const parents = role.extends;
32
+ if (parents === undefined) continue;
33
+ if (!Array.isArray(parents) || parents.some((p) => typeof p !== 'string')) {
34
+ configError(`"extends" of role "${name}" should be a list of role names`);
35
+ }
36
+ }
37
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../src/routes/pattern.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAQH;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY;IACxC,IAAI,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrC,KAAK,GAAG,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;IAC9C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