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
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ // Everything that doesn't depend on a framework lives here.
2
+ // Express and React bindings have their own entry points: rolegate/express and rolegate/react.
3
+
4
+ // Checking actions on resources: "can an editor delete posts?"
5
+ export * from './core/index.js';
6
+
7
+ // Checking routes and pages: "can an editor open /admin/users?"
8
+ export * from './routes/index.js';
9
+
10
+ export { ForbiddenError } from './shared/errors.js';
11
+ export type { Roles } from './shared/roles.js';
@@ -0,0 +1,10 @@
1
+ // React bindings. These are for the UI only: hiding buttons and links the user
2
+ // can't use anyway. The real check always has to happen on the server too.
3
+
4
+ // Actions on resources: <Can resource="posts" action="delete">
5
+ export { RbacProvider, useCan, Can } from './rbac.js';
6
+ export type { RbacProviderProps, CanProps } from './rbac.js';
7
+
8
+ // Pages: <CanVisit path="/admin">
9
+ export { RouteAccessProvider, useCanVisit, CanVisit } from './routes.js';
10
+ export type { RouteAccessProviderProps, CanVisitProps } from './routes.js';
@@ -0,0 +1,49 @@
1
+ import { createContext, useCallback, useContext, useMemo } from 'react';
2
+ import type { ReactNode } from 'react';
3
+ import type { Context, Rbac } from '../core/types.js';
4
+ import type { Roles } from '../shared/roles.js';
5
+
6
+ interface RbacState {
7
+ rbac: Rbac<any>;
8
+ roles: Roles;
9
+ }
10
+
11
+ const RbacContext = createContext<RbacState | null>(null);
12
+
13
+ export interface RbacProviderProps<C extends Context = Context> {
14
+ rbac: Rbac<C>;
15
+ /** The current user's role(s), usually straight from your auth state. */
16
+ roles: Roles;
17
+ children?: ReactNode;
18
+ }
19
+
20
+ /** Makes `useCan` and `<Can>` work for everything inside. */
21
+ export function RbacProvider<C extends Context = Context>({ rbac, roles, children }: RbacProviderProps<C>) {
22
+ const value = useMemo(() => ({ rbac, roles }), [rbac, roles]);
23
+ return <RbacContext.Provider value={value}>{children}</RbacContext.Provider>;
24
+ }
25
+
26
+ /** Gives you `can(resource, action, ctx?)` for the current user. */
27
+ export function useCan() {
28
+ const state = useContext(RbacContext);
29
+ if (!state) throw new Error('rolegate: useCan must be used inside <RbacProvider>');
30
+ return useCallback(
31
+ (resource: string, action: string, ctx?: Context) => state.rbac.can(state.roles, resource, action, ctx),
32
+ [state],
33
+ );
34
+ }
35
+
36
+ export interface CanProps {
37
+ resource: string;
38
+ action: string;
39
+ ctx?: Context;
40
+ /** What to show when the answer is no. Nothing by default. */
41
+ fallback?: ReactNode;
42
+ children?: ReactNode;
43
+ }
44
+
45
+ /** Shows its children only if the current user can do the action. */
46
+ export function Can({ resource, action, ctx, fallback = null, children }: CanProps) {
47
+ const can = useCan();
48
+ return <>{can(resource, action, ctx) ? children : fallback}</>;
49
+ }
@@ -0,0 +1,49 @@
1
+ import { createContext, useCallback, useContext, useMemo } from 'react';
2
+ import type { ReactNode } from 'react';
3
+ import type { RouteAccess } from '../routes/types.js';
4
+ import type { Roles } from '../shared/roles.js';
5
+
6
+ interface RouteState {
7
+ access: RouteAccess;
8
+ roles: Roles;
9
+ }
10
+
11
+ const RouteAccessContext = createContext<RouteState | null>(null);
12
+
13
+ export interface RouteAccessProviderProps {
14
+ access: RouteAccess;
15
+ /** The current user's role(s). For guests, pass something like 'guest'. */
16
+ roles: Roles;
17
+ children?: ReactNode;
18
+ }
19
+
20
+ /**
21
+ * Makes `useCanVisit` and `<CanVisit>` work for everything inside.
22
+ *
23
+ * If you load page permissions from the server, just pass a new `access`
24
+ * object when they change. Everything below re-renders with the new rules.
25
+ */
26
+ export function RouteAccessProvider({ access, roles, children }: RouteAccessProviderProps) {
27
+ const value = useMemo(() => ({ access, roles }), [access, roles]);
28
+ return <RouteAccessContext.Provider value={value}>{children}</RouteAccessContext.Provider>;
29
+ }
30
+
31
+ /** Gives you `canVisit(path)` for the current user. Handy for filtering menus. */
32
+ export function useCanVisit() {
33
+ const state = useContext(RouteAccessContext);
34
+ if (!state) throw new Error('rolegate: useCanVisit must be used inside <RouteAccessProvider>');
35
+ return useCallback((path: string) => state.access.can(state.roles, path), [state]);
36
+ }
37
+
38
+ export interface CanVisitProps {
39
+ path: string;
40
+ /** What to show when the user can't open this page. Nothing by default. */
41
+ fallback?: ReactNode;
42
+ children?: ReactNode;
43
+ }
44
+
45
+ /** Shows its children only if the current user can open `path`. Good for links and menu items. */
46
+ export function CanVisit({ path, fallback = null, children }: CanVisitProps) {
47
+ const canVisit = useCanVisit();
48
+ return <>{canVisit(path) ? children : fallback}</>;
49
+ }
@@ -0,0 +1,57 @@
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 { splitPath } from './matching/path.js';
6
+ import { compileRules, hits, normalizeMethod } from './rules.js';
7
+ import type { CompiledRule } from './rules.js';
8
+ import type { RouteAccess, RouteAccessConfig } from './types.js';
9
+
10
+ /**
11
+ * Builds the route checker:
12
+ *
13
+ * const pages = createRouteAccess({
14
+ * roles: {
15
+ * user: { allow: ['/', '/posts/*'] },
16
+ * admin: { extends: ['user'], allow: ['/admin/*'] },
17
+ * },
18
+ * });
19
+ * pages.can('user', '/posts/42'); // true
20
+ * pages.can('user', '/admin/users'); // false
21
+ *
22
+ * Rules are compiled here, so a broken one throws on startup.
23
+ */
24
+ export function createRouteAccess(config: RouteAccessConfig): RouteAccess {
25
+ checkRolesObject(config?.roles);
26
+
27
+ const definitions = dictionary<RoleDefinition<CompiledRule>>();
28
+ for (const [name, role] of Object.entries(config.roles)) {
29
+ definitions[name] = {
30
+ extends: role.extends,
31
+ allow: compileRules(role.allow, name, 'allow'),
32
+ deny: compileRules(role.deny, name, 'deny'),
33
+ };
34
+ }
35
+ const known = resolveRoles(definitions);
36
+
37
+ const can: RouteAccess['can'] = (roles, path, method = 'GET') => {
38
+ // can't decode the path - can't know where it goes, so no
39
+ const segments = splitPath(path);
40
+ if (segments === null || typeof method !== 'string') return false;
41
+
42
+ const m = normalizeMethod(method);
43
+ return decide(
44
+ pickRoles(known, roles),
45
+ (role) => hits(role.deny, segments, m),
46
+ (role) => hits(role.allow, segments, m),
47
+ );
48
+ };
49
+
50
+ return {
51
+ can,
52
+ assert(roles, path, method = 'GET') {
53
+ if (!can(roles, path, method)) throw new ForbiddenError(path, String(method).toUpperCase());
54
+ },
55
+ roles: Object.keys(config.roles),
56
+ };
57
+ }
@@ -0,0 +1,61 @@
1
+ import { checkRoleName, configError, dictionary, isObject } from '../shared/validate.js';
2
+ import type { RouteAccessConfig, RouteRoleConfig } from './types.js';
3
+
4
+ /**
5
+ * One row from a "who can open what" table. Column names are up to you:
6
+ * map your rows to this shape and you're done.
7
+ */
8
+ export interface RouteRow {
9
+ role: string;
10
+ path: string;
11
+ /** Leave empty to mean "any method", which is the usual case for pages. */
12
+ method?: string | null;
13
+ /** Defaults to 'allow'. */
14
+ effect?: 'allow' | 'deny' | null;
15
+ }
16
+
17
+ export interface FromRowsOptions {
18
+ /** Role inheritance, if you keep it somewhere too: `{ admin: ['editor'] }`. */
19
+ extends?: Record<string, string[]>;
20
+ }
21
+
22
+ /**
23
+ * Turns flat table rows into a config for `createRouteAccess`.
24
+ *
25
+ * const rows = await db.query('SELECT role, path, method, effect FROM route_permissions');
26
+ * const access = createRouteAccess(routeConfigFromRows(rows));
27
+ *
28
+ * It doesn't check the patterns itself. `createRouteAccess` does that and
29
+ * tells you which role has the broken one.
30
+ */
31
+ export function routeConfigFromRows(rows: Iterable<RouteRow>, options: FromRowsOptions = {}): RouteAccessConfig {
32
+ // no prototype: with a plain {} a "__proto__" row would write into Object.prototype
33
+ const roles = dictionary<RouteRoleConfig>();
34
+ const roleFor = (name: string, where: string) => {
35
+ checkRoleName(name, where);
36
+ return (roles[name] ??= {});
37
+ };
38
+
39
+ for (const row of rows) {
40
+ if (!isObject(row)) configError('every row should be an object like { role, path }');
41
+
42
+ // rows come from a DB, so TypeScript can't check them for us
43
+ const where = `row for role "${row.role}" on "${row.path}"`;
44
+ if (typeof row.path !== 'string') configError(`"path" should be a string (${where})`);
45
+ if (row.method != null && typeof row.method !== 'string') configError(`"method" should be a string (${where})`);
46
+
47
+ const effect = row.effect ?? 'allow';
48
+ if (effect !== 'allow' && effect !== 'deny') configError(`unknown effect "${effect}" (${where})`);
49
+
50
+ const role = roleFor(row.role, where);
51
+ const list = (role[effect] ??= []);
52
+ list.push(row.method ? { path: row.path, methods: [row.method] } : row.path);
53
+ }
54
+
55
+ for (const [name, parents] of Object.entries(options.extends ?? {})) {
56
+ if (!Array.isArray(parents)) configError(`parents of role "${name}" should be a list`);
57
+ roleFor(name, 'in options.extends').extends = [...parents];
58
+ }
59
+
60
+ return { roles };
61
+ }
@@ -0,0 +1,5 @@
1
+ export { createRouteAccess } from './createRouteAccess.js';
2
+ export { routeConfigFromRows } from './fromRows.js';
3
+ export { normalizePath } from './matching/path.js';
4
+ export type { RouteAccess, RouteAccessConfig, RouteRoleConfig, RouteRule } from './types.js';
5
+ export type { RouteRow, FromRowsOptions } from './fromRows.js';
@@ -0,0 +1,48 @@
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
+ /**
6
+ * "/Public/%2e%2e/Admin/?x=1" -> ["admin"].
7
+ *
8
+ * Drops the query and hash, decodes %xx, resolves "." and "..", skips empty
9
+ * segments and lowercases (routers ignore case by default).
10
+ * Returns null for broken encoding like "%zz", and callers deny such paths.
11
+ */
12
+ export function splitPath(path: string): string[] | null {
13
+ const withoutQuery = String(path).split(/[?#]/, 1)[0];
14
+ const segments: string[] = [];
15
+
16
+ for (const piece of withoutQuery.split('/')) {
17
+ const decoded = decode(piece);
18
+ if (decoded === null) return null;
19
+
20
+ // a decoded "%2F" or a "\" splits the segment, same as on a static server
21
+ for (const segment of decoded.split(/[/\\]/)) {
22
+ if (segment === '' || segment === '.') continue;
23
+ if (segment === '..') segments.pop();
24
+ else segments.push(segment.toLowerCase());
25
+ }
26
+ }
27
+ return segments;
28
+ }
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: string): string {
35
+ const segments = splitPath(path);
36
+ if (segments) return '/' + segments.join('/');
37
+
38
+ const withoutQuery = String(path).split(/[?#]/, 1)[0];
39
+ return '/' + withoutQuery.split('/').filter(Boolean).join('/').toLowerCase();
40
+ }
41
+
42
+ function decode(piece: string): string | null {
43
+ try {
44
+ return decodeURIComponent(piece);
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Tiny route patterns. On purpose there are only three kinds of segments:
3
+ *
4
+ * /settings a plain segment, has to match exactly
5
+ * /posts/:id a parameter, matches any single segment
6
+ * /admin/* a wildcard, only at the end: "/admin" and everything below it
7
+ *
8
+ * Plus a lone '*' meaning "any path at all".
9
+ *
10
+ * Anything fancier (regex params, optional segments, a '*' in the middle) throws
11
+ * right away. Patterns often come from a database, and a pattern that
12
+ * silently matches nothing is much worse than an error on startup.
13
+ */
14
+
15
+ import { splitPath } from './path.js';
16
+
17
+ export interface RoutePattern {
18
+ /** The pattern exactly as it was written, handy in error messages. */
19
+ readonly source: string;
20
+ /** Checks a path that has already gone through `splitPath`. */
21
+ matches(segments: readonly string[]): boolean;
22
+ /** The same for a raw path. A path we can't make sense of never matches. */
23
+ test(path: string): boolean;
24
+ }
25
+
26
+ const PARAM = /^:[A-Za-z0-9_]+$/;
27
+
28
+ export function compilePattern(pattern: string): RoutePattern {
29
+ const fail = (why: string): never => {
30
+ throw new Error(`rolegate: bad route pattern "${pattern}": ${why}`);
31
+ };
32
+
33
+ if (pattern === '*') return fromMatcher(pattern, () => true);
34
+
35
+ if (typeof pattern !== 'string' || !pattern.startsWith('/')) fail('it should start with "/" (or be just "*")');
36
+ if (/[?#]/.test(pattern)) fail('query strings and hashes are not part of a route');
37
+ // ".." in a rule is almost always a typo, better to say so
38
+ if (pattern.split(/[/\\]/).some((s) => s === '.' || s === '..')) fail('"." and ".." segments are not allowed');
39
+
40
+ // same splitting as for paths, so both sides are compared in the same form
41
+ const parts = splitPath(pattern) ?? fail('it has broken percent-encoding');
42
+ const wildcard = parts[parts.length - 1] === '*';
43
+ const fixed = wildcard ? parts.slice(0, -1) : parts;
44
+
45
+ for (const part of fixed) {
46
+ if (part.includes('*')) fail('"*" is only allowed as the last segment, like "/admin/*"');
47
+ if (part.startsWith(':') && !PARAM.test(part)) fail(`"${part}" is not a valid parameter (use something like ":id")`);
48
+ }
49
+
50
+ return fromMatcher(pattern, (actual) => {
51
+ const lengthFits = wildcard ? actual.length >= fixed.length : actual.length === fixed.length;
52
+ if (!lengthFits) return false;
53
+ // no empty segments after splitPath, so :param always gets a value
54
+ return fixed.every((part, i) => part.startsWith(':') || part === actual[i]);
55
+ });
56
+ }
57
+
58
+ function fromMatcher(source: string, matches: (segments: readonly string[]) => boolean): RoutePattern {
59
+ return {
60
+ source,
61
+ matches,
62
+ test(path) {
63
+ const segments = splitPath(path);
64
+ return segments !== null && matches(segments);
65
+ },
66
+ };
67
+ }
@@ -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
+ }