rolegate 0.0.0-stage → 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 (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +128 -2
  3. package/dist/core/createRbac.d.ts +11 -0
  4. package/dist/core/createRbac.d.ts.map +1 -0
  5. package/dist/core/createRbac.js +43 -0
  6. package/dist/core/createRbac.js.map +1 -0
  7. package/dist/core/index.d.ts +3 -0
  8. package/dist/core/index.d.ts.map +1 -0
  9. package/dist/core/index.js +2 -0
  10. package/dist/core/index.js.map +1 -0
  11. package/dist/core/rules.d.ts +17 -0
  12. package/dist/core/rules.d.ts.map +1 -0
  13. package/dist/core/rules.js +62 -0
  14. package/dist/core/rules.js.map +1 -0
  15. package/dist/core/types.d.ts +31 -0
  16. package/dist/core/types.d.ts.map +1 -0
  17. package/dist/core/types.js +2 -0
  18. package/dist/core/types.js.map +1 -0
  19. package/dist/express/guardRoutes.d.ts +32 -0
  20. package/dist/express/guardRoutes.d.ts.map +1 -0
  21. package/dist/express/guardRoutes.js +41 -0
  22. package/dist/express/guardRoutes.js.map +1 -0
  23. package/dist/express/index.d.ts +6 -0
  24. package/dist/express/index.d.ts.map +1 -0
  25. package/dist/express/index.js +7 -0
  26. package/dist/express/index.js.map +1 -0
  27. package/dist/express/requirePermission.d.ts +21 -0
  28. package/dist/express/requirePermission.d.ts.map +1 -0
  29. package/dist/express/requirePermission.js +27 -0
  30. package/dist/express/requirePermission.js.map +1 -0
  31. package/dist/express/types.d.ts +34 -0
  32. package/dist/express/types.d.ts.map +1 -0
  33. package/dist/express/types.js +14 -0
  34. package/dist/express/types.js.map +1 -0
  35. package/dist/index.d.ts +5 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +8 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/react/index.d.ts +5 -0
  40. package/dist/react/index.d.ts.map +1 -0
  41. package/dist/react/index.js +7 -0
  42. package/dist/react/index.js.map +1 -0
  43. package/dist/react/rbac.d.ts +24 -0
  44. package/dist/react/rbac.d.ts.map +1 -0
  45. package/dist/react/rbac.js +21 -0
  46. package/dist/react/rbac.js.map +1 -0
  47. package/dist/react/routes.d.ts +27 -0
  48. package/dist/react/routes.d.ts.map +1 -0
  49. package/dist/react/routes.js +26 -0
  50. package/dist/react/routes.js.map +1 -0
  51. package/dist/routes/createRouteAccess.d.ts +17 -0
  52. package/dist/routes/createRouteAccess.d.ts.map +1 -0
  53. package/dist/routes/createRouteAccess.js +48 -0
  54. package/dist/routes/createRouteAccess.js.map +1 -0
  55. package/dist/routes/fromRows.d.ts +28 -0
  56. package/dist/routes/fromRows.d.ts.map +1 -0
  57. package/dist/routes/fromRows.js +41 -0
  58. package/dist/routes/fromRows.js.map +1 -0
  59. package/dist/routes/index.d.ts +6 -0
  60. package/dist/routes/index.d.ts.map +1 -0
  61. package/dist/routes/index.js +4 -0
  62. package/dist/routes/index.js.map +1 -0
  63. package/dist/routes/matching/path.d.ts +14 -0
  64. package/dist/routes/matching/path.d.ts.map +1 -0
  65. package/dist/routes/matching/path.js +49 -0
  66. package/dist/routes/matching/path.js.map +1 -0
  67. package/dist/routes/matching/pattern.d.ts +23 -0
  68. package/dist/routes/matching/pattern.d.ts.map +1 -0
  69. package/dist/routes/matching/pattern.js +57 -0
  70. package/dist/routes/matching/pattern.js.map +1 -0
  71. package/dist/routes/rules.d.ts +14 -0
  72. package/dist/routes/rules.d.ts.map +1 -0
  73. package/dist/routes/rules.js +53 -0
  74. package/dist/routes/rules.js.map +1 -0
  75. package/dist/routes/types.d.ts +35 -0
  76. package/dist/routes/types.d.ts.map +1 -0
  77. package/dist/routes/types.js +2 -0
  78. package/dist/routes/types.js.map +1 -0
  79. package/dist/shared/errors.d.ts +12 -0
  80. package/dist/shared/errors.d.ts.map +1 -0
  81. package/dist/shared/errors.js +15 -0
  82. package/dist/shared/errors.js.map +1 -0
  83. package/dist/shared/roles.d.ts +37 -0
  84. package/dist/shared/roles.d.ts.map +1 -0
  85. package/dist/shared/roles.js +73 -0
  86. package/dist/shared/roles.js.map +1 -0
  87. package/dist/shared/validate.d.ts +14 -0
  88. package/dist/shared/validate.d.ts.map +1 -0
  89. package/dist/shared/validate.js +35 -0
  90. package/dist/shared/validate.js.map +1 -0
  91. package/docs/actions.md +184 -0
  92. package/docs/api-routes.md +142 -0
  93. package/docs/database.md +125 -0
  94. package/docs/pages.md +139 -0
  95. package/package.json +73 -4
  96. package/src/core/createRbac.ts +58 -0
  97. package/src/core/index.ts +2 -0
  98. package/src/core/rules.ts +69 -0
  99. package/src/core/types.ts +36 -0
  100. package/src/express/guardRoutes.ts +64 -0
  101. package/src/express/index.ts +12 -0
  102. package/src/express/requirePermission.ts +43 -0
  103. package/src/express/types.ts +45 -0
  104. package/src/index.ts +11 -0
  105. package/src/react/index.ts +10 -0
  106. package/src/react/rbac.tsx +49 -0
  107. package/src/react/routes.tsx +49 -0
  108. package/src/routes/createRouteAccess.ts +57 -0
  109. package/src/routes/fromRows.ts +61 -0
  110. package/src/routes/index.ts +5 -0
  111. package/src/routes/matching/path.ts +48 -0
  112. package/src/routes/matching/pattern.ts +67 -0
  113. package/src/routes/rules.ts +62 -0
  114. package/src/routes/types.ts +35 -0
  115. package/src/shared/errors.ts +17 -0
  116. package/src/shared/roles.ts +92 -0
  117. package/src/shared/validate.ts +37 -0
@@ -0,0 +1,12 @@
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 declare class ForbiddenError extends Error {
8
+ readonly resource: string;
9
+ readonly action: string;
10
+ constructor(resource: string, action: string);
11
+ }
12
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/shared/errors.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,qBAAa,cAAe,SAAQ,KAAK;IACvC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;gBAEZ,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAM7C"}
@@ -0,0 +1,15 @@
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
+ constructor(resource, action) {
9
+ super(`Forbidden: cannot ${action} ${resource}`);
10
+ this.name = 'ForbiddenError';
11
+ this.resource = resource;
12
+ this.action = action;
13
+ }
14
+ }
15
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/shared/errors.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,OAAO,cAAe,SAAQ,KAAK;IAIvC,YAAY,QAAgB,EAAE,MAAc;QAC1C,KAAK,CAAC,qBAAqB,MAAM,IAAI,QAAQ,EAAE,CAAC,CAAC;QACjD,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;QAC7B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF"}
@@ -0,0 +1,37 @@
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
+ /** One role, or several, or nobody (not signed in). */
10
+ export type Roles = string | readonly string[] | undefined;
11
+ export interface RoleDefinition<R> {
12
+ extends?: readonly string[];
13
+ allow?: readonly R[];
14
+ deny?: readonly R[];
15
+ }
16
+ /** A role after inheritance is applied: its own rules plus everything from its parents. */
17
+ export interface ResolvedRole<R> {
18
+ allow: R[];
19
+ deny: R[];
20
+ }
21
+ /**
22
+ * Flattens `extends` for every role and returns them in a Map.
23
+ *
24
+ * We do it for the whole config right away, so a typo in a role name or a
25
+ * circular `extends` blows up when the app starts and not in the middle of a request.
26
+ */
27
+ export declare function resolveRoles<R>(definitions: Record<string, RoleDefinition<R>>): Map<string, ResolvedRole<R>>;
28
+ /** Role names from whatever the app passed. Roles come from tokens, so junk like null or '' is skipped. */
29
+ export declare function roleNames(roles: Roles): string[];
30
+ /** The resolved roles we actually know about, out of the ones the app gave us. */
31
+ export declare function pickRoles<T>(known: Map<string, T>, roles: Roles): T[];
32
+ /**
33
+ * The one rule of the whole library: if any role denies, the answer is no.
34
+ * Otherwise it's yes if at least one role allows. No roles at all means no.
35
+ */
36
+ export declare function decide<T>(roles: T[], denies: (role: T) => boolean, allows: (role: T) => boolean): boolean;
37
+ //# sourceMappingURL=roles.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"roles.d.ts","sourceRoot":"","sources":["../../src/shared/roles.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,uDAAuD;AACvD,MAAM,MAAM,KAAK,GAAG,MAAM,GAAG,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC;AAE3D,MAAM,WAAW,cAAc,CAAC,CAAC;IAC/B,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,KAAK,CAAC,EAAE,SAAS,CAAC,EAAE,CAAC;IACrB,IAAI,CAAC,EAAE,SAAS,CAAC,EAAE,CAAC;CACrB;AAED,2FAA2F;AAC3F,MAAM,WAAW,YAAY,CAAC,CAAC;IAC7B,KAAK,EAAE,CAAC,EAAE,CAAC;IACX,IAAI,EAAE,CAAC,EAAE,CAAC;CACX;AAID;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,CAiC5G;AAED,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,EAAE,CAGhD;AAED,kFAAkF;AAClF,wBAAgB,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,GAAG,CAAC,EAAE,CAOrE;AAED;;;GAGG;AACH,wBAAgB,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,OAAO,EAAE,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,OAAO,GAAG,OAAO,CAIzG"}
@@ -0,0 +1,73 @@
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
+ const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
10
+ /**
11
+ * Flattens `extends` for every role and returns them in a Map.
12
+ *
13
+ * We do it for the whole config right away, so a typo in a role name or a
14
+ * circular `extends` blows up when the app starts and not in the middle of a request.
15
+ */
16
+ export function resolveRoles(definitions) {
17
+ const resolved = new Map();
18
+ const resolve = (name, trail) => {
19
+ const cached = resolved.get(name);
20
+ if (cached)
21
+ return cached;
22
+ // hasOwn, not `in`: otherwise a role called "constructor" would quietly
23
+ // pick up Object.prototype.constructor and look like a real role.
24
+ if (!hasOwn(definitions, name)) {
25
+ const from = trail.length ? trail.join(' -> ') : 'config';
26
+ throw new Error(`rolegate: unknown role "${name}" (referenced by ${from})`);
27
+ }
28
+ if (trail.includes(name)) {
29
+ throw new Error(`rolegate: circular "extends": ${[...trail, name].join(' -> ')}`);
30
+ }
31
+ const def = definitions[name];
32
+ const role = { allow: [], deny: [] };
33
+ for (const parent of def.extends ?? []) {
34
+ const p = resolve(parent, [...trail, name]);
35
+ role.allow.push(...p.allow);
36
+ role.deny.push(...p.deny);
37
+ }
38
+ role.allow.push(...(def.allow ?? []));
39
+ role.deny.push(...(def.deny ?? []));
40
+ resolved.set(name, role);
41
+ return role;
42
+ };
43
+ for (const name of Object.keys(definitions))
44
+ resolve(name, []);
45
+ return resolved;
46
+ }
47
+ /** Role names from whatever the app passed. Roles come from tokens, so junk like null or '' is skipped. */
48
+ export function roleNames(roles) {
49
+ const list = typeof roles === 'string' ? [roles] : Array.isArray(roles) ? roles : [];
50
+ return list.filter((name) => typeof name === 'string' && name !== '');
51
+ }
52
+ /** The resolved roles we actually know about, out of the ones the app gave us. */
53
+ export function pickRoles(known, roles) {
54
+ const picked = [];
55
+ for (const name of roleNames(roles)) {
56
+ const role = known.get(name);
57
+ if (role)
58
+ picked.push(role);
59
+ }
60
+ return picked;
61
+ }
62
+ /**
63
+ * The one rule of the whole library: if any role denies, the answer is no.
64
+ * Otherwise it's yes if at least one role allows. No roles at all means no.
65
+ */
66
+ export function decide(roles, denies, allows) {
67
+ if (roles.length === 0)
68
+ return false;
69
+ if (roles.some(denies))
70
+ return false;
71
+ return roles.some(allows);
72
+ }
73
+ //# sourceMappingURL=roles.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"roles.js","sourceRoot":"","sources":["../../src/shared/roles.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAiBH,MAAM,MAAM,GAAG,CAAC,GAAW,EAAE,GAAW,EAAE,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAE5F;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAI,WAA8C;IAC5E,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA2B,CAAC;IAEpD,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,KAAe,EAAm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CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,OAAO,KAAK,CAAC;IACrC,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,CAAC"}
@@ -0,0 +1,14 @@
1
+ export declare function configError(message: string): never;
2
+ export declare const isObject: (value: unknown) => value is Record<string, unknown>;
3
+ /** An object without a prototype, so keys like "constructor" are just keys. */
4
+ export declare const dictionary: <T>() => Record<string, T>;
5
+ /**
6
+ * In a plain object "__proto__" swaps the prototype instead of adding a key,
7
+ * so a role with that name could leak its rules into every object. We refuse it.
8
+ */
9
+ export declare function checkRoleName(name: unknown, where: string): asserts name is string;
10
+ /** Checks `config.roles` and the `extends` of each role. */
11
+ export declare function checkRolesObject(roles: unknown): asserts roles is Record<string, {
12
+ extends?: unknown;
13
+ }>;
14
+ //# sourceMappingURL=validate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.d.ts","sourceRoot":"","sources":["../../src/shared/validate.ts"],"names":[],"mappings":"AAGA,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,KAAK,CAElD;AAED,eAAO,MAAM,QAAQ,GAAI,OAAO,OAAO,KAAG,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CACH,CAAC;AAEvE,+EAA+E;AAC/E,eAAO,MAAM,UAAU,GAAI,CAAC,OAAK,MAAM,CAAC,MAAM,EAAE,CAAC,CAAwB,CAAC;AAE1E;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,IAAI,MAAM,CAGlF;AAED,4DAA4D;AAC5D,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC,CAavG"}
@@ -0,0 +1,35 @@
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
+ export function configError(message) {
4
+ throw new Error(`rolegate: ${message}`);
5
+ }
6
+ export const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
7
+ /** An object without a prototype, so keys like "constructor" are just keys. */
8
+ export const dictionary = () => Object.create(null);
9
+ /**
10
+ * In a plain object "__proto__" swaps the prototype instead of adding a key,
11
+ * so a role with that name could leak its rules into every object. We refuse it.
12
+ */
13
+ export function checkRoleName(name, where) {
14
+ if (typeof name !== 'string' || name === '')
15
+ configError(`role names must be non-empty strings (${where})`);
16
+ if (name === '__proto__')
17
+ configError(`"__proto__" can't be used as a role name (${where})`);
18
+ }
19
+ /** Checks `config.roles` and the `extends` of each role. */
20
+ export function checkRolesObject(roles) {
21
+ if (!isObject(roles))
22
+ configError('config.roles should be an object like { admin: { ... } }');
23
+ for (const [name, role] of Object.entries(roles)) {
24
+ checkRoleName(name, 'in config.roles');
25
+ if (!isObject(role))
26
+ configError(`role "${name}" should be an object`);
27
+ const parents = role.extends;
28
+ if (parents === undefined)
29
+ continue;
30
+ if (!Array.isArray(parents) || parents.some((p) => typeof p !== 'string')) {
31
+ configError(`"extends" of role "${name}" should be a list of role names`);
32
+ }
33
+ }
34
+ }
35
+ //# sourceMappingURL=validate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.js","sourceRoot":"","sources":["../../src/shared/validate.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,wEAAwE;AAExE,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,MAAM,IAAI,KAAK,CAAC,aAAa,OAAO,EAAE,CAAC,CAAC;AAC1C,CAAC;AAED,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAoC,EAAE,CAC3E,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAEvE,+EAA+E;AAC/E,MAAM,CAAC,MAAM,UAAU,GAAG,GAAyB,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAE1E;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,IAAa,EAAE,KAAa;IACxD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,EAAE;QAAE,WAAW,CAAC,yCAAyC,KAAK,GAAG,CAAC,CAAC;IAC5G,IAAI,IAAI,KAAK,WAAW;QAAE,WAAW,CAAC,6CAA6C,KAAK,GAAG,CAAC,CAAC;AAC/F,CAAC;AAED,4DAA4D;AAC5D,MAAM,UAAU,gBAAgB,CAAC,KAAc;IAC7C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,WAAW,CAAC,0DAA0D,CAAC,CAAC;IAE9F,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACjD,aAAa,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;QACvC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,WAAW,CAAC,SAAS,IAAI,uBAAuB,CAAC,CAAC;QAEvE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC7B,IAAI,OAAO,KAAK,SAAS;YAAE,SAAS;QACpC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,EAAE,CAAC;YAC1E,WAAW,CAAC,sBAAsB,IAAI,kCAAkC,CAAC,CAAC;QAC5E,CAAC;IACH,CAAC;AACH,CAAC"}
@@ -0,0 +1,184 @@
1
+ # Actions on resources
2
+
3
+ This is the classic part of rolegate: roles that may perform actions on resources. Use it when the question is "may this user **do** something", like edit a post or delete a comment, as opposed to "may they **open** a page" (that's [routes](pages.md)).
4
+
5
+ ## The basics
6
+
7
+ ```ts
8
+ import { createRbac } from 'rolegate';
9
+
10
+ export const rbac = createRbac({
11
+ roles: {
12
+ viewer: { allow: { posts: ['read'] } },
13
+ editor: { extends: ['viewer'], allow: { posts: ['write'], comments: ['read', 'write'] } },
14
+ admin: { allow: { '*': ['*'] } },
15
+ blocked: { deny: { '*': ['*'] } },
16
+ },
17
+ });
18
+
19
+ rbac.can('editor', 'posts', 'write'); // true
20
+ rbac.can('viewer', 'posts', 'write'); // false
21
+ rbac.can(['editor', 'blocked'], 'posts', 'read'); // false, a deny in any role wins
22
+ rbac.assert('viewer', 'posts', 'write'); // throws ForbiddenError
23
+ ```
24
+
25
+ Resource and action names are plain strings, so call them whatever fits your app. `'*'` means "any resource" or "any action".
26
+
27
+ The config is checked when you call `createRbac`. An unknown role in `extends`, a rule that isn't a string or `{ action, when? }`, or a `when` that isn't a function throws right there. That matters when the config comes from JSON, where TypeScript can't catch it. The role name `__proto__` isn't allowed.
28
+
29
+ ## Conditions
30
+
31
+ Sometimes a role may do something only in certain cases, like deleting **their own** posts. That's what `when` is for:
32
+
33
+ ```ts
34
+ type Ctx = { userId?: number; ownerId?: number };
35
+
36
+ // Make sure userId is actually there. Otherwise undefined === undefined is true,
37
+ // and anyone gets access the moment you forget to pass a context.
38
+ const isOwner = (c: Ctx) => c.userId !== undefined && c.userId === c.ownerId;
39
+
40
+ const rbac = createRbac<Ctx>({
41
+ roles: {
42
+ author: { allow: { posts: [{ action: 'delete', when: isOwner }] } },
43
+ },
44
+ });
45
+
46
+ rbac.can('author', 'posts', 'delete', { userId: 1, ownerId: 1 }); // true
47
+ rbac.can('author', 'posts', 'delete', { userId: 1, ownerId: 2 }); // false
48
+ rbac.can('author', 'posts', 'delete'); // false, no context means no access
49
+ ```
50
+
51
+ > When you don't pass a context, `when` gets `{}`. Write your conditions so that missing data means "no".
52
+
53
+ Conditions are functions, so they live in code. If you keep permissions in a database, keep the simple ones there and leave the conditional rules here.
54
+
55
+ ## Express
56
+
57
+ ```ts
58
+ import { requirePermission } from 'rolegate/express';
59
+
60
+ app.delete('/posts/:id', requirePermission(rbac, 'posts', 'delete'), handler);
61
+ ```
62
+
63
+ By default it reads roles from `req.user.roles` (or `req.user.role`). It sends `401` if there are none (empty strings and `null`s don't count) and `403` if the action isn't allowed. Express isn't actually required: anything with `(req, res, next)` and `res.status().json()` works.
64
+
65
+ To pass a context, annotate the request type so you get proper typings:
66
+
67
+ ```ts
68
+ import type { Request } from 'express';
69
+
70
+ app.put('/posts/:id', loadPost, requirePermission(rbac, 'posts', 'update', {
71
+ getContext: (req: Request) => ({ userId: req.user?.id, ownerId: req.post?.authorId }),
72
+ }), handler);
73
+ ```
74
+
75
+ `getContext` is synchronous. Load what it needs in an earlier middleware (`loadPost` above), or skip the middleware and call `rbac.assert()` inside your async handler.
76
+
77
+ If you rebuild `rbac` at runtime, pass a function instead of the object, `requirePermission(() => rbac, ...)`, and the middleware will always use the latest one.
78
+
79
+ ## React
80
+
81
+ ```tsx
82
+ import { RbacProvider, Can, useCan } from 'rolegate/react';
83
+
84
+ <RbacProvider rbac={rbac} roles={user.roles}>
85
+ <Can resource="posts" action="write" fallback={<span>Read only</span>}>
86
+ <EditButton />
87
+ </Can>
88
+ </RbacProvider>;
89
+
90
+ const can = useCan();
91
+ if (can('posts', 'delete', { userId, ownerId })) { /* ... */ }
92
+ ```
93
+
94
+ > Checks in the UI only make the interface nicer. Always check on the server too.
95
+
96
+ ## Example: a blog where people manage their own posts
97
+
98
+ Every signed-in user can read all posts and write new ones, but can only edit and delete **their own**. Guests get a `401`.
99
+
100
+ Two things are up to your app, rolegate doesn't do them:
101
+
102
+ - **Authentication**: something that sets `req.user = { id, roles: ['user'] }`.
103
+ - **Ownership**: store `authorId` on every post and pass it in the context.
104
+
105
+ **1. Shared permissions**, imported by both the server and the client:
106
+
107
+ ```ts
108
+ // shared/permissions.ts
109
+ import { createRbac } from 'rolegate';
110
+
111
+ export type Ctx = { userId?: number; ownerId?: number };
112
+ const isOwner = (c: Ctx) => c.userId !== undefined && c.userId === c.ownerId;
113
+
114
+ export const rbac = createRbac<Ctx>({
115
+ roles: {
116
+ user: {
117
+ allow: {
118
+ posts: ['read', 'create', { action: 'update', when: isOwner }, { action: 'delete', when: isOwner }],
119
+ },
120
+ },
121
+ admin: { allow: { '*': ['*'] } },
122
+ },
123
+ });
124
+ ```
125
+
126
+ **2. The server**, where the check that actually matters happens:
127
+
128
+ ```ts
129
+ import express from 'express';
130
+ import { ForbiddenError } from 'rolegate';
131
+ import { requirePermission } from 'rolegate/express';
132
+ import { rbac } from '../shared/permissions.js';
133
+
134
+ const app = express();
135
+ app.use(authenticate); // your auth, sets req.user
136
+
137
+ app.get('/posts', requirePermission(rbac, 'posts', 'read'), listPosts);
138
+ app.post('/posts', requirePermission(rbac, 'posts', 'create'), async (req, res) => {
139
+ const post = await db.posts.create({ ...req.body, authorId: req.user!.id });
140
+ res.status(201).json(post);
141
+ });
142
+
143
+ app.delete('/posts/:id', async (req, res, next) => {
144
+ try {
145
+ const post = await db.posts.find(req.params.id);
146
+ rbac.assert(req.user?.roles, 'posts', 'delete', { userId: req.user?.id, ownerId: post.authorId });
147
+ await db.posts.delete(post.id);
148
+ res.sendStatus(204);
149
+ } catch (err) {
150
+ next(err);
151
+ }
152
+ });
153
+
154
+ app.use((err, _req, res, next) => {
155
+ if (err instanceof ForbiddenError) return res.status(403).json({ error: err.message });
156
+ next(err);
157
+ });
158
+ ```
159
+
160
+ **3. The client** hides what the user can't do anyway:
161
+
162
+ ```tsx
163
+ import { RbacProvider, Can, useCan } from 'rolegate/react';
164
+ import { rbac } from '../shared/permissions';
165
+
166
+ <RbacProvider rbac={rbac} roles={me?.roles}>
167
+ <Can resource="posts" action="create"><NewPostButton /></Can>
168
+ <PostList />
169
+ </RbacProvider>;
170
+
171
+ function PostCard({ post }) {
172
+ const can = useCan();
173
+ const ctx = { userId: me.id, ownerId: post.authorId };
174
+ return (
175
+ <article>
176
+ <h2>{post.title}</h2>
177
+ {can('posts', 'update', ctx) && <EditButton />}
178
+ {can('posts', 'delete', ctx) && <DeleteButton />}
179
+ </article>
180
+ );
181
+ }
182
+ ```
183
+
184
+ rolegate checks one action on one object at a time. For a "My posts" page, filter in the query (`WHERE author_id = :me`) instead of checking every row.
@@ -0,0 +1,142 @@
1
+ # API routes
2
+
3
+ Use this when you'd like to protect a bunch of endpoints with **one** middleware instead of adding `requirePermission` to each route. The rules talk about paths and HTTP methods: "a reader can `GET /api/posts/*`, a writer can also `PUT /api/posts/:id`".
4
+
5
+ The patterns are the same as for [pages](pages.md#route-patterns): `/posts/:id`, `/admin/*`, `*`.
6
+
7
+ ## Rules with methods
8
+
9
+ A plain string means "any method". Add `methods` to narrow it down:
10
+
11
+ ```ts
12
+ // server/apiAccess.ts
13
+ import { createRouteAccess } from 'rolegate';
14
+
15
+ export const apiAccess = createRouteAccess({
16
+ roles: {
17
+ reader: {
18
+ allow: [{ path: '/api/posts/*', methods: ['GET'] }],
19
+ },
20
+ writer: {
21
+ extends: ['reader'],
22
+ allow: [
23
+ { path: '/api/posts', methods: ['POST'] },
24
+ { path: '/api/posts/:id', methods: ['PUT', 'PATCH'] },
25
+ ],
26
+ },
27
+ admin: {
28
+ allow: ['/api/*'],
29
+ deny: [{ path: '/api/posts/:id', methods: ['DELETE'] }], // even admins don't delete posts
30
+ },
31
+ },
32
+ });
33
+
34
+ apiAccess.can('reader', '/api/posts/1', 'GET'); // true
35
+ apiAccess.can('reader', '/api/posts/1', 'PUT'); // false
36
+ apiAccess.can('writer', '/api/posts/1', 'put'); // true, case doesn't matter
37
+ ```
38
+
39
+ Some details worth knowing:
40
+
41
+ - If you leave out the method, it's `GET`.
42
+ - `HEAD` is checked as `GET`. Express runs GET handlers for HEAD requests, so otherwise HEAD would be a way around a GET deny.
43
+ - `methods: ['*']` is the same as not listing any methods.
44
+ - Paths are read the way a server reads them: `/api/posts/../admin` is checked as `/api/admin`. Details are on the [pages](pages.md#route-patterns) page.
45
+
46
+ ## One guard for everything
47
+
48
+ ```ts
49
+ import express from 'express';
50
+ import { guardRoutes } from 'rolegate/express';
51
+ import { apiAccess } from './apiAccess.js';
52
+
53
+ const app = express();
54
+ app.use(authenticate); // your auth, sets req.user
55
+
56
+ // Public endpoints go above the guard
57
+ app.post('/api/login', login);
58
+
59
+ // Everything below goes through the guard
60
+ app.use('/api', guardRoutes(apiAccess));
61
+ app.get('/api/posts/:id', getPost);
62
+ app.put('/api/posts/:id', updatePost);
63
+ ```
64
+
65
+ What the guard does on each request:
66
+
67
+ 1. It takes the roles from `req.user.roles` (or `req.user.role`). No roles means `401`. Empty strings and `null`s in the list don't count, so `roles: ['']` is a `401` too.
68
+ 2. It takes the method and the full path, `req.baseUrl + req.path`. So even inside `app.use('/api', ...)` it sees `/api/posts/1` and not just `/posts/1`.
69
+ 3. If the route isn't allowed, it sends `403` with `{ error: 'Forbidden', path, method }`. Otherwise it calls `next()`.
70
+
71
+ Both can be changed:
72
+
73
+ ```ts
74
+ guardRoutes(apiAccess, {
75
+ getRoles: (req: Request) => req.session?.roles,
76
+ getPath: (req: Request) => req.originalUrl, // the query string is ignored anyway
77
+ });
78
+ ```
79
+
80
+ ## Public endpoints
81
+
82
+ There are two ways to do it, pick whichever reads better in your code:
83
+
84
+ - **Mount them above the guard**, as in the example above. This is the simplest way.
85
+ - **Give unauthenticated users a `guest` role** and allow them what they need:
86
+
87
+ ```ts
88
+ const apiAccess = createRouteAccess({
89
+ roles: {
90
+ guest: { allow: [{ path: '/api/posts/*', methods: ['GET'] }, { path: '/api/login', methods: ['POST'] }] },
91
+ user: { extends: ['guest'], allow: [/* ... */] },
92
+ },
93
+ });
94
+
95
+ app.use(guardRoutes(apiAccess, { getRoles: (req: Request) => req.user?.roles ?? 'guest' }));
96
+ ```
97
+
98
+ With this setup the guard never sends `401`, since everyone has at least the `guest` role. Instead of 401 they get `403`.
99
+
100
+ ## CORS
101
+
102
+ If the frontend is on another domain, the browser first sends a preflight `OPTIONS` request. It has no cookies or token, so the guard answers `401` and the real request never happens.
103
+
104
+ The simplest fix is to put `cors()` above the guard. It answers preflights itself:
105
+
106
+ ```ts
107
+ app.use(cors({ origin: 'https://app.example.com', credentials: true }));
108
+ app.use('/api', guardRoutes(apiAccess));
109
+ ```
110
+
111
+ Or let the guard skip them:
112
+
113
+ ```ts
114
+ app.use('/api', guardRoutes(apiAccess, { skipMethods: ['OPTIONS'] }));
115
+ ```
116
+
117
+ Nothing is skipped by default.
118
+
119
+ ## Routes and actions together
120
+
121
+ The guard knows the path and method, but not your data. "Only the author can edit a post" can't be decided from the URL. A common split:
122
+
123
+ - `guardRoutes` keeps the rough boundaries: who can reach which part of the API at all.
124
+ - `rbac.assert()` inside the handler does the fine-grained check with a context. See [actions on resources](actions.md#conditions).
125
+
126
+ ```ts
127
+ app.use('/api', guardRoutes(apiAccess)); // writers can reach PUT /api/posts/:id
128
+
129
+ app.put('/api/posts/:id', async (req, res, next) => {
130
+ try {
131
+ const post = await db.posts.find(req.params.id);
132
+ rbac.assert(req.user?.roles, 'posts', 'update', { userId: req.user?.id, ownerId: post.authorId });
133
+ // ...
134
+ } catch (err) {
135
+ next(err);
136
+ }
137
+ });
138
+ ```
139
+
140
+ ## Without Express
141
+
142
+ Express isn't a dependency. The guard works with anything that has `(req, res, next)`, `req.method`, `req.path` and `res.status().json()`. And `apiAccess.can(roles, path, method)` is a plain function, so you can call it from any framework yourself.