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 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,YAAY,EAAE,WAAW,EAAE,iBAAiB,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC7F,YAAY,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC"}
@@ -1,4 +1,4 @@
1
1
  export { createRouteAccess } from './createRouteAccess.js';
2
2
  export { routeConfigFromRows } from './fromRows.js';
3
- export { normalizePath } from './pattern.js';
3
+ export { normalizePath } from './matching/path.js';
4
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * "/Public/%2e%2e/Admin/?x=1" -> ["admin"].
3
+ *
4
+ * Drops the query and hash, decodes %xx, resolves "." and "..", skips empty
5
+ * segments and lowercases (routers ignore case by default).
6
+ * Returns null for broken encoding like "%zz", and callers deny such paths.
7
+ */
8
+ export declare function splitPath(path: string): string[] | null;
9
+ /**
10
+ * The path as the checks see it: "/Posts/./42/?tab=1" -> "/posts/42".
11
+ * Never throws, broken %xx is just left as is. Handy for debugging rules.
12
+ */
13
+ export declare function normalizePath(path: string): string;
14
+ //# sourceMappingURL=path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../../../src/routes/matching/path.ts"],"names":[],"mappings":"AAIA;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,IAAI,CAgBvD;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMlD"}
@@ -0,0 +1,49 @@
1
+ // We read a path the way express.static or nginx would: decoded, with ".."
2
+ // resolved. Otherwise "/public/../admin" would pass an allow for "/public/*"
3
+ // and the static server would happily serve /admin.
4
+ /**
5
+ * "/Public/%2e%2e/Admin/?x=1" -> ["admin"].
6
+ *
7
+ * Drops the query and hash, decodes %xx, resolves "." and "..", skips empty
8
+ * segments and lowercases (routers ignore case by default).
9
+ * Returns null for broken encoding like "%zz", and callers deny such paths.
10
+ */
11
+ export function splitPath(path) {
12
+ const withoutQuery = String(path).split(/[?#]/, 1)[0];
13
+ const segments = [];
14
+ for (const piece of withoutQuery.split('/')) {
15
+ const decoded = decode(piece);
16
+ if (decoded === null)
17
+ return null;
18
+ // a decoded "%2F" or a "\" splits the segment, same as on a static server
19
+ for (const segment of decoded.split(/[/\\]/)) {
20
+ if (segment === '' || segment === '.')
21
+ continue;
22
+ if (segment === '..')
23
+ segments.pop();
24
+ else
25
+ segments.push(segment.toLowerCase());
26
+ }
27
+ }
28
+ return segments;
29
+ }
30
+ /**
31
+ * The path as the checks see it: "/Posts/./42/?tab=1" -> "/posts/42".
32
+ * Never throws, broken %xx is just left as is. Handy for debugging rules.
33
+ */
34
+ export function normalizePath(path) {
35
+ const segments = splitPath(path);
36
+ if (segments)
37
+ return '/' + segments.join('/');
38
+ const withoutQuery = String(path).split(/[?#]/, 1)[0];
39
+ return '/' + withoutQuery.split('/').filter(Boolean).join('/').toLowerCase();
40
+ }
41
+ function decode(piece) {
42
+ try {
43
+ return decodeURIComponent(piece);
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ //# sourceMappingURL=path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path.js","sourceRoot":"","sources":["../../../src/routes/matching/path.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,oDAAoD;AAEpD;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACtD,MAAM,QAAQ,GAAa,EAAE,CAAC;IAE9B,KAAK,MAAM,KAAK,IAAI,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QAC5C,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QAC9B,IAAI,OAAO,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;QAElC,0EAA0E;QAC1E,KAAK,MAAM,OAAO,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;YAC7C,IAAI,OAAO,KAAK,EAAE,IAAI,OAAO,KAAK,GAAG;gBAAE,SAAS;YAChD,IAAI,OAAO,KAAK,IAAI;gBAAE,QAAQ,CAAC,GAAG,EAAE,CAAC;;gBAChC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY;IACxC,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IACjC,IAAI,QAAQ;QAAE,OAAO,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAE9C,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACtD,OAAO,GAAG,GAAG,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;AAC/E,CAAC;AAED,SAAS,MAAM,CAAC,KAAa;IAC3B,IAAI,CAAC;QACH,OAAO,kBAAkB,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"}
@@ -2,7 +2,7 @@
2
2
  * Tiny route patterns. On purpose there are only three kinds of segments:
3
3
  *
4
4
  * /settings a plain segment, has to match exactly
5
- * /posts/:id a parameter, matches any single non-empty segment
5
+ * /posts/:id a parameter, matches any single segment
6
6
  * /admin/* a wildcard, only at the end: "/admin" and everything below it
7
7
  *
8
8
  * Plus a lone '*' meaning "any path at all".
@@ -14,15 +14,10 @@
14
14
  export interface RoutePattern {
15
15
  /** The pattern exactly as it was written, handy in error messages. */
16
16
  readonly source: string;
17
+ /** Checks a path that has already gone through `splitPath`. */
18
+ matches(segments: readonly string[]): boolean;
19
+ /** The same for a raw path. A path we can't make sense of never matches. */
17
20
  test(path: string): boolean;
18
21
  }
19
- /**
20
- * Brings a path to the form we compare against:
21
- * no query or hash, no repeated or trailing slashes, lowercase.
22
- *
23
- * Lowercase because Express and React Router both match routes case-insensitively
24
- * by default. If we were stricter than the router, someone could open
25
- * "/ADMIN/users", slip past a deny written for "/admin/*" and still land on the admin page.
26
- */
27
- export declare function normalizePath(path: string): string;
28
22
  export declare function compilePattern(pattern: string): RoutePattern;
23
+ //# sourceMappingURL=pattern.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pattern.d.ts","sourceRoot":"","sources":["../../../src/routes/matching/pattern.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,MAAM,WAAW,YAAY;IAC3B,sEAAsE;IACtE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,+DAA+D;IAC/D,OAAO,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC;IAC9C,4EAA4E;IAC5E,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;CAC7B;AAID,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,YAAY,CA4B5D"}
@@ -2,7 +2,7 @@
2
2
  * Tiny route patterns. On purpose there are only three kinds of segments:
3
3
  *
4
4
  * /settings a plain segment, has to match exactly
5
- * /posts/:id a parameter, matches any single non-empty segment
5
+ * /posts/:id a parameter, matches any single segment
6
6
  * /admin/* a wildcard, only at the end: "/admin" and everything below it
7
7
  *
8
8
  * Plus a lone '*' meaning "any path at all".
@@ -11,37 +11,23 @@
11
11
  * right away. Patterns often come from a database, and a pattern that
12
12
  * silently matches nothing is much worse than an error on startup.
13
13
  */
14
- /**
15
- * Brings a path to the form we compare against:
16
- * no query or hash, no repeated or trailing slashes, lowercase.
17
- *
18
- * Lowercase because Express and React Router both match routes case-insensitively
19
- * by default. If we were stricter than the router, someone could open
20
- * "/ADMIN/users", slip past a deny written for "/admin/*" and still land on the admin page.
21
- */
22
- export function normalizePath(path) {
23
- let clean = path.split(/[?#]/, 1)[0];
24
- clean = ('/' + clean).replace(/\/{2,}/g, '/');
25
- if (clean.length > 1)
26
- clean = clean.replace(/\/$/, '');
27
- return clean.toLowerCase();
28
- }
14
+ import { splitPath } from './path.js';
29
15
  const PARAM = /^:[A-Za-z0-9_]+$/;
30
- function segmentsOf(path) {
31
- // "/" -> [], "/posts/42" -> ["posts", "42"]
32
- return path === '/' ? [] : path.slice(1).split('/');
33
- }
34
16
  export function compilePattern(pattern) {
35
17
  const fail = (why) => {
36
18
  throw new Error(`rolegate: bad route pattern "${pattern}": ${why}`);
37
19
  };
38
20
  if (pattern === '*')
39
- return { source: pattern, test: () => true };
21
+ return fromMatcher(pattern, () => true);
40
22
  if (typeof pattern !== 'string' || !pattern.startsWith('/'))
41
23
  fail('it should start with "/" (or be just "*")');
42
24
  if (/[?#]/.test(pattern))
43
25
  fail('query strings and hashes are not part of a route');
44
- const parts = segmentsOf(normalizePath(pattern));
26
+ // ".." in a rule is almost always a typo, better to say so
27
+ if (pattern.split(/[/\\]/).some((s) => s === '.' || s === '..'))
28
+ fail('"." and ".." segments are not allowed');
29
+ // same splitting as for paths, so both sides are compared in the same form
30
+ const parts = splitPath(pattern) ?? fail('it has broken percent-encoding');
45
31
  const wildcard = parts[parts.length - 1] === '*';
46
32
  const fixed = wildcard ? parts.slice(0, -1) : parts;
47
33
  for (const part of fixed) {
@@ -50,13 +36,21 @@ export function compilePattern(pattern) {
50
36
  if (part.startsWith(':') && !PARAM.test(part))
51
37
  fail(`"${part}" is not a valid parameter (use something like ":id")`);
52
38
  }
39
+ return fromMatcher(pattern, (actual) => {
40
+ const lengthFits = wildcard ? actual.length >= fixed.length : actual.length === fixed.length;
41
+ if (!lengthFits)
42
+ return false;
43
+ // no empty segments after splitPath, so :param always gets a value
44
+ return fixed.every((part, i) => part.startsWith(':') || part === actual[i]);
45
+ });
46
+ }
47
+ function fromMatcher(source, matches) {
53
48
  return {
54
- source: pattern,
49
+ source,
50
+ matches,
55
51
  test(path) {
56
- const actual = segmentsOf(normalizePath(path));
57
- if (wildcard ? actual.length < fixed.length : actual.length !== fixed.length)
58
- return false;
59
- return fixed.every((part, i) => (part.startsWith(':') ? actual[i] !== '' : part === actual[i]));
52
+ const segments = splitPath(path);
53
+ return segments !== null && matches(segments);
60
54
  },
61
55
  };
62
56
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../../src/routes/matching/pattern.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAWtC,MAAM,KAAK,GAAG,kBAAkB,CAAC;AAEjC,MAAM,UAAU,cAAc,CAAC,OAAe;IAC5C,MAAM,IAAI,GAAG,CAAC,GAAW,EAAS,EAAE;QAClC,MAAM,IAAI,KAAK,CAAC,gCAAgC,OAAO,MAAM,GAAG,EAAE,CAAC,CAAC;IACtE,CAAC,CAAC;IAEF,IAAI,OAAO,KAAK,GAAG;QAAE,OAAO,WAAW,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;IAE7D,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,IAAI,CAAC,2CAA2C,CAAC,CAAC;IAC/G,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC;QAAE,IAAI,CAAC,kDAAkD,CAAC,CAAC;IACnF,2DAA2D;IAC3D,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,CAAC;QAAE,IAAI,CAAC,uCAAuC,CAAC,CAAC;IAE/G,2EAA2E;IAC3E,MAAM,KAAK,GAAG,SAAS,CAAC,O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AK,IAAI,IAAI,OAAO,CAAC,QAAQ,CAAC,CAAC;QAChD,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,14 @@
1
+ import type { RoutePattern } from './matching/pattern.js';
2
+ import type { RouteRule } from './types.js';
3
+ export interface CompiledRule {
4
+ pattern: RoutePattern;
5
+ /** null means "any method". */
6
+ methods: ReadonlySet<string> | null;
7
+ }
8
+ /** Express runs GET handlers for HEAD, so HEAD follows GET rules. Otherwise it would dodge a GET deny. */
9
+ export declare function normalizeMethod(method: string): string;
10
+ /** Compiles the allow (or deny) list of one role. */
11
+ export declare function compileRules(list: RouteRule[] | undefined, role: string, kind: 'allow' | 'deny'): CompiledRule[];
12
+ /** Does any of the rules cover this path and method? */
13
+ export declare function hits(rules: CompiledRule[], segments: readonly string[], method: string): boolean;
14
+ //# sourceMappingURL=rules.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../src/routes/rules.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,YAAY,CAAC;IACtB,+BAA+B;IAC/B,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;CACrC;AAED,0GAA0G;AAC1G,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAGtD;AAED,qDAAqD;AACrD,wBAAgB,YAAY,CAAC,IAAI,EAAE,SAAS,EAAE,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,YAAY,EAAE,CAahH;AAED,wDAAwD;AACxD,wBAAgB,IAAI,CAAC,KAAK,EAAE,YAAY,EAAE,EAAE,QAAQ,EAAE,SAAS,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAKhG"}
@@ -0,0 +1,53 @@
1
+ // Route rules from the config, compiled once: pattern parsed, methods in a Set.
2
+ import { configError, isObject } from '../shared/validate.js';
3
+ import { compilePattern } from './matching/pattern.js';
4
+ /** Express runs GET handlers for HEAD, so HEAD follows GET rules. Otherwise it would dodge a GET deny. */
5
+ export function normalizeMethod(method) {
6
+ const upper = method.toUpperCase();
7
+ return upper === 'HEAD' ? 'GET' : upper;
8
+ }
9
+ /** Compiles the allow (or deny) list of one role. */
10
+ export function compileRules(list, role, kind) {
11
+ if (list === undefined)
12
+ return [];
13
+ if (!Array.isArray(list))
14
+ configError(`${kind} of role "${role}" should be a list of routes`);
15
+ return list.map((rule) => {
16
+ try {
17
+ return compileRule(rule);
18
+ }
19
+ catch (err) {
20
+ // with rules from a DB you'll want to know which role it is
21
+ const message = err instanceof Error ? err.message : String(err);
22
+ throw new Error(`${message} (in role "${role}")`);
23
+ }
24
+ });
25
+ }
26
+ /** Does any of the rules cover this path and method? */
27
+ export function hits(rules, segments, method) {
28
+ return rules.some((rule) => {
29
+ const methodFits = rule.methods === null || rule.methods.has(method);
30
+ return methodFits && rule.pattern.matches(segments);
31
+ });
32
+ }
33
+ function compileRule(rule) {
34
+ // just a path means any method
35
+ if (typeof rule === 'string')
36
+ return { pattern: compilePattern(rule), methods: null };
37
+ if (!isObject(rule) || typeof rule.path !== 'string') {
38
+ configError('a route rule should be a path or { path, methods? }');
39
+ }
40
+ const pattern = compilePattern(rule.path);
41
+ const { methods } = rule;
42
+ if (methods === undefined)
43
+ return { pattern, methods: null };
44
+ if (!Array.isArray(methods) || methods.some((m) => typeof m !== 'string' || m === '')) {
45
+ configError(`"methods" for "${rule.path}" should be a list like ['GET', 'POST']`);
46
+ }
47
+ if (methods.length === 0)
48
+ configError(`"methods" for "${rule.path}" is empty`);
49
+ if (methods.includes('*'))
50
+ return { pattern, methods: null };
51
+ return { pattern, methods: new Set(methods.map(normalizeMethod)) };
52
+ }
53
+ //# sour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EAAE,CAAC;IAE7D,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,EAAE,CAAC;AACrE,CAAC"}
@@ -32,3 +32,4 @@ export interface RouteAccess {
32
32
  /** Every role name from the config. */
33
33
  readonly roles: readonly string[];
34
34
  }
35
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/routes/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAEhD;;;;;;;GAOG;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAC;AAE/E,MAAM,WAAW,eAAe;IAC9B,iEAAiE;IACjE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,KAAK,CAAC,EAAE,SAAS,EAAE,CAAC;IACpB,qDAAqD;IACrD,IAAI,CAAC,EAAE,SAAS,EAAE,CAAC;CACpB;AAED,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;CACxC;AAED,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;IAC1D,sEAAsE;IACtE,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1D,uCAAuC;IACvC,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;CACnC"}
@@ -9,3 +9,4 @@ export declare class ForbiddenError extends Error {
9
9
  readonly action: string;
10
10
  constructor(resource: string, action: string);
11
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"}
@@ -25,10 +25,13 @@ export interface ResolvedRole<R> {
25
25
  * circular `extends` blows up when the app starts and not in the middle of a request.
26
26
  */
27
27
  export declare function resolveRoles<R>(definitions: Record<string, RoleDefinition<R>>): Map<string, ResolvedRole<R>>;
28
- /** Turns whatever the app gave us into the resolved roles we actually know about. */
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. */
29
31
  export declare function pickRoles<T>(known: Map<string, T>, roles: Roles): T[];
30
32
  /**
31
33
  * The one rule of the whole library: if any role denies, the answer is no.
32
34
  * Otherwise it's yes if at least one role allows. No roles at all means no.
33
35
  */
34
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"}
@@ -44,11 +44,15 @@ export function resolveRoles(definitions) {
44
44
  resolve(name, []);
45
45
  return resolved;
46
46
  }
47
- /** Turns whatever the app gave us into the resolved roles we actually know about. */
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. */
48
53
  export function pickRoles(known, roles) {
49
- const list = typeof roles === 'string' ? [roles] : roles ?? [];
50
54
  const picked = [];
51
- for (const name of list) {
55
+ for (const name of roleNames(roles)) {
52
56
  const role = known.get(name);
53
57
  if (role)
54
58
  picked.push(role);
@@ -1 +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,EAAmB,EAAE;QACjE,MAAM,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAClC,IAAI,MAAM;YAAE,OAAO,MAAM,CAAC;QAE1B,wEAAwE;QACxE,kEAAkE;QAClE,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,IAAI,CAAC,EAAE,CAAC;YAC/B,MAAM,IAAI,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;YAC1D,MAAM,IAAI,KAAK,CAAC,2BAA2B,IAAI,oBAAoB,IAAI,GAAG,CAAC,CAAC;QAC9E,CAAC;QACD,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,GAAG,KAAK,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACpF,CAAC;QAED,MAAM,GAAG,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;QAC9B,MAAM,IAAI,GAAoB,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;QACtD,KAAK,MAAM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C,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;IACzG,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,EAAkB,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,EAAE,CAAC,CAAC;AACxF,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,SAAS,CAAI,KAAqB,EAAE,KAAY;IAC9D,MAAM,MAAM,GAAQ,EAAE,CAAC;IACvB,KAAK,MAAM,IAAI,IAAI,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;QACpC,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC7B,IAAI,IAAI;YAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,MAAM,CAAI,KAAU,EAAE,MAA4B,EAAE,MAA4B;IAC9F,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACrC,IAAI,KAAK,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"}
package/docs/actions.md CHANGED
@@ -24,6 +24,8 @@ rbac.assert('viewer', 'posts', 'write'); // throws ForbiddenError
24
24
 
25
25
  Resource and action names are plain strings, so call them whatever fits your app. `'*'` means "any resource" or "any action".
26
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
+
27
29
  ## Conditions
28
30
 
29
31
  Sometimes a role may do something only in certain cases, like deleting **their own** posts. That's what `when` is for:
@@ -58,7 +60,7 @@ import { requirePermission } from 'rolegate/express';
58
60
  app.delete('/posts/:id', requirePermission(rbac, 'posts', 'delete'), handler);
59
61
  ```
60
62
 
61
- By default it reads roles from `req.user.roles` (or `req.user.role`). It sends `401` if there are none and `403` if the action isn't allowed. Express isn't actually required: anything with `(req, res, next)` and `res.status().json()` works.
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.
62
64
 
63
65
  To pass a context, annotate the request type so you get proper typings:
64
66
 
@@ -41,6 +41,7 @@ Some details worth knowing:
41
41
  - If you leave out the method, it's `GET`.
42
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
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.
44
45
 
45
46
  ## One guard for everything
46
47
 
@@ -63,7 +64,7 @@ app.put('/api/posts/:id', updatePost);
63
64
 
64
65
  What the guard does on each request:
65
66
 
66
- 1. It takes the roles from `req.user.roles` (or `req.user.role`). No roles means `401`.
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.
67
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`.
68
69
  3. If the route isn't allowed, it sends `403` with `{ error: 'Forbidden', path, method }`. Otherwise it calls `next()`.
69
70
 
@@ -96,6 +97,25 @@ There are two ways to do it, pick whichever reads better in your code:
96
97
 
97
98
  With this setup the guard never sends `401`, since everyone has at least the `guest` role. Instead of 401 they get `403`.
98
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
+
99
119
  ## Routes and actions together
100
120
 
101
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:
package/docs/database.md CHANGED
@@ -50,6 +50,10 @@ You don't have to use the helper. The config is a plain object, so you can build
50
50
  rolegate: bad route pattern "admin/*": it should start with "/" (or be just "*") (in role "editor")
51
51
  ```
52
52
 
53
+ The shape is checked too, since TypeScript can't see what's in your table. A `path` that isn't a string or a `method` that's a number throws right away.
54
+
55
+ The role name `__proto__` is refused. In a plain JS object that key swaps the prototype, and a row like that could hand its routes to every other role.
56
+
53
57
  At startup that's exactly what you want. When you're reloading at runtime, though, you don't want one bad row to take the whole app down. So keep the old rules if the new ones don't build (see below). It's also a good idea to run the same check in the admin screen before saving: call `createRouteAccess` with the new data and show the error to the person who's editing.
54
58
 
55
59
  ## Updating the rules without a restart
package/docs/pages.md CHANGED
@@ -41,6 +41,12 @@ A few things are handled for you, so they don't catch you off guard:
41
41
  - The query string and hash are ignored: `/posts/42?tab=comments` is `/posts/42`.
42
42
  - A trailing slash and repeated slashes don't matter: `/admin/users/` is `/admin/users`.
43
43
  - Case doesn't matter, the same as in React Router and Express. That way `/ADMIN` can't sneak past a deny written for `/admin/*`.
44
+ - `%xx` is decoded and `..` is resolved, the way static servers and proxies do it. So `/public/../admin` and `/public/%2e%2e/admin` are both checked as `/admin`.
45
+ - A path with broken encoding, like `/posts/%zz`, is always denied.
46
+
47
+ If a rule doesn't match the way you expect, `normalizePath(path)` shows the path as the checks see it.
48
+
49
+ `.` and `..` aren't allowed in patterns themselves. In a rule they're almost always a typo.
44
50
 
45
51
  Anything fancier, like regex parameters (`:id(\d+)`), optional segments or a `*` in the middle, throws an error when you create the config. We'd rather tell you right away than have a pattern quietly match nothing.
46
52
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rolegate",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Tiny, dependency-free access control for TypeScript: roles, actions and routes. One config for Node, Express and React.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -30,11 +30,12 @@
30
30
  },
31
31
  "files": [
32
32
  "dist",
33
- "docs"
33
+ "docs",
34
+ "src"
34
35
  ],
35
36
  "scripts": {
36
37
  "build": "tsc -p tsconfig.build.json",
37
- "test": "tsx --test test/*.test.ts test/*.test.tsx",
38
+ "test": "tsx --test \"test/**/*.test.ts\" \"test/**/*.test.tsx\"",
38
39
  "typecheck": "tsc -p .",
39
40
  "prepublishOnly": "npm run typecheck && npm test && npm run build"
40
41
  },
@@ -0,0 +1,58 @@
1
+ import { ForbiddenError } from '../shared/errors.js';
2
+ import { decide, pickRoles, resolveRoles } from '../shared/roles.js';
3
+ import type { RoleDefinition } from '../shared/roles.js';
4
+ import { checkRolesObject, dictionary } from '../shared/validate.js';
5
+ import { matches, toEntries, toIndex } from './rules.js';
6
+ import type { Entry, RuleIndex } from './rules.js';
7
+ import type { Context, Rbac, RbacConfig } from './types.js';
8
+
9
+ interface IndexedRole<C extends Context> {
10
+ allow: RuleIndex<C>;
11
+ deny: RuleIndex<C>;
12
+ }
13
+
14
+ /**
15
+ * Builds the resource/action checker:
16
+ *
17
+ * const rbac = createRbac({ roles: { editor: { allow: { posts: ['read', 'write'] } } } });
18
+ * rbac.can('editor', 'posts', 'write'); // true
19
+ *
20
+ * The config is checked here, so a typo throws on startup.
21
+ */
22
+ export function createRbac<C extends Context = Context>(config: RbacConfig<C>): Rbac<C> {
23
+ checkRolesObject(config?.roles);
24
+
25
+ // flat lists for the shared role code (extends, deny wins)
26
+ const definitions = dictionary<RoleDefinition<Entry<C>>>();
27
+ for (const [name, role] of Object.entries(config.roles)) {
28
+ definitions[name] = {
29
+ extends: role.extends,
30
+ allow: toEntries(role.allow, `allow of role "${name}"`),
31
+ deny: toEntries(role.deny, `deny of role "${name}"`),
32
+ };
33
+ }
34
+
35
+ // and back to "by resource" for fast checks
36
+ const known = new Map<string, IndexedRole<C>>();
37
+ for (const [name, role] of resolveRoles(definitions)) {
38
+ known.set(name, { allow: toIndex(role.allow), deny: toIndex(role.deny) });
39
+ }
40
+
41
+ const can: Rbac<C>['can'] = (roles, resource, action, ctx) => {
42
+ // so `when` never gets undefined
43
+ const context = (ctx ?? {}) as C;
44
+ return decide(
45
+ pickRoles(known, roles),
46
+ (role) => matches(role.deny, resource, action, context),
47
+ (role) => matches(role.allow, resource, action, context),
48
+ );
49
+ };
50
+
51
+ return {
52
+ can,
53
+ assert(roles, resource, action, ctx) {
54
+ if (!can(roles, resource, action, ctx)) throw new ForbiddenError(resource, action);
55
+ },
56
+ roles: Object.keys(config.roles),
57
+ };
58
+ }
@@ -0,0 +1,2 @@
1
+ export { createRbac } from './createRbac.js';
2
+ export type { Rbac, RbacConfig, RoleConfig, Rule, ResourceRules, Condition, Context } from './types.js';