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,125 @@
1
+ # Permissions from a database
2
+
3
+ Say you have a table of pages (or endpoints) and an admin screen where someone ticks which role can open what. rolegate doesn't talk to databases, but it's built so that wiring this up takes a few lines.
4
+
5
+ ## A table that works well
6
+
7
+ Nothing forces you to use exactly this table, but it maps one to one:
8
+
9
+ ```sql
10
+ CREATE TABLE route_permissions (
11
+ role text NOT NULL, -- 'user', 'admin', ...
12
+ path text NOT NULL, -- '/admin/*', '/posts/:id', ...
13
+ method text, -- NULL = any method (all you need for pages)
14
+ effect text NOT NULL DEFAULT 'allow' CHECK (effect IN ('allow', 'deny'))
15
+ );
16
+ ```
17
+
18
+ If you keep role inheritance in the database too, a second table like `role_parents(role, parent)` is enough.
19
+
20
+ ## From rows to a config
21
+
22
+ `routeConfigFromRows` turns rows into a config for `createRouteAccess`:
23
+
24
+ ```ts
25
+ import { createRouteAccess, routeConfigFromRows } from 'rolegate';
26
+
27
+ const rows = await db.query('SELECT role, path, method, effect FROM route_permissions');
28
+ const parents = await db.query('SELECT role, parent FROM role_parents');
29
+
30
+ const access = createRouteAccess(
31
+ routeConfigFromRows(rows, {
32
+ extends: groupBy(parents, (p) => p.role, (p) => p.parent), // { admin: ['user'], ... }
33
+ }),
34
+ );
35
+ ```
36
+
37
+ It expects rows shaped like `{ role, path, method?, effect? }`. If your columns are named differently, map them first:
38
+
39
+ ```ts
40
+ routeConfigFromRows(rows.map((r) => ({ role: r.role_name, path: r.url, method: r.http_method })));
41
+ ```
42
+
43
+ You don't have to use the helper. The config is a plain object, so you can build it however you like. The helper just saves you a loop.
44
+
45
+ ## When the data is broken
46
+
47
+ `createRouteAccess` checks everything up front. If someone saves the pattern `admin/*` (without the leading slash), or a role extends one that doesn't exist, you get an error that names the role:
48
+
49
+ ```
50
+ rolegate: bad route pattern "admin/*": it should start with "/" (or be just "*") (in role "editor")
51
+ ```
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
+
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.
58
+
59
+ ## Updating the rules without a restart
60
+
61
+ ### On the server
62
+
63
+ `createRouteAccess` returns an immutable object. To apply new rules, build a new one and swap the variable. Pass the middleware **a function** that returns the current object, not the object itself. That way it always uses the latest rules:
64
+
65
+ ```ts
66
+ import { guardRoutes } from 'rolegate/express';
67
+
68
+ let access = await loadAccess();
69
+
70
+ async function loadAccess() {
71
+ const rows = await db.query('SELECT role, path, method, effect FROM route_permissions');
72
+ return createRouteAccess(routeConfigFromRows(rows));
73
+ }
74
+
75
+ async function refresh() {
76
+ try {
77
+ access = await loadAccess();
78
+ } catch (err) {
79
+ // Broken data in the DB: log it and keep working with the old rules
80
+ console.error('Could not reload permissions, keeping the old ones', err);
81
+ }
82
+ }
83
+
84
+ setInterval(refresh, 60_000); // or call refresh() right after the admin screen saves changes
85
+
86
+ app.use('/api', guardRoutes(() => access));
87
+ ```
88
+
89
+ `requirePermission` accepts a function the same way: `requirePermission(() => rbac, 'posts', 'delete')`.
90
+
91
+ ### On the frontend
92
+
93
+ Usually you fetch the rules once, after login, together with the user. Give the server an endpoint that returns rows (or a ready-made config) and build the object in the browser:
94
+
95
+ ```tsx
96
+ import { useMemo } from 'react';
97
+ import { createRouteAccess, routeConfigFromRows } from 'rolegate';
98
+ import { RouteAccessProvider } from 'rolegate/react';
99
+
100
+ function AccessRoot({ children }) {
101
+ const { user, routeRows } = useSession(); // however you load them
102
+
103
+ const access = useMemo(
104
+ () => createRouteAccess(routeConfigFromRows(routeRows ?? [])),
105
+ [routeRows],
106
+ );
107
+
108
+ return (
109
+ <RouteAccessProvider access={access} roles={user?.roles ?? 'guest'}>
110
+ {children}
111
+ </RouteAccessProvider>
112
+ );
113
+ }
114
+ ```
115
+
116
+ When `routeRows` changes, `access` is rebuilt and every `useCanVisit` and `<CanVisit>` re-renders with the new rules.
117
+
118
+ The client doesn't need everyone's rules. You can send only the rows for the user's roles, and it'll work just the same.
119
+
120
+ ## What can't go in the database
121
+
122
+ Conditions like "only the post's author" are functions (`when` in [actions](actions.md#conditions)), and they live in code. A sensible split:
123
+
124
+ - **Database**: which pages and endpoints each role can reach at all. These are the things admins change.
125
+ - **Code**: rules that depend on data, like ownership, status or limits. These are the things developers change.
package/docs/pages.md ADDED
@@ -0,0 +1,139 @@
1
+ # Frontend pages
2
+
3
+ Use this when the question is "can this user open this page?" Think of an admin section only admins can see, a menu that shows only the links the user can actually follow, or a "you don't have access" screen instead of a broken page.
4
+
5
+ ## Describe who can open what
6
+
7
+ ```ts
8
+ // shared/pages.ts
9
+ import { createRouteAccess } from 'rolegate';
10
+
11
+ export const pages = createRouteAccess({
12
+ roles: {
13
+ guest: { allow: ['/', '/login', '/posts/*'] },
14
+ user: { extends: ['guest'], allow: ['/profile', '/settings/*'], deny: ['/login'] },
15
+ admin: { extends: ['user'], allow: ['/admin/*'], deny: ['/admin/billing'] },
16
+ },
17
+ });
18
+
19
+ pages.can('guest', '/posts/42'); // true
20
+ pages.can('user', '/admin'); // false
21
+ pages.can('admin', '/admin/users'); // true
22
+ pages.can('admin', '/admin/billing'); // false, the deny wins over '/admin/*'
23
+ ```
24
+
25
+ Everything you know from roles works the same here: `extends` inherits all the routes of another role, a deny in any role wins, and an unknown role sees nothing.
26
+
27
+ ## Route patterns
28
+
29
+ The patterns are deliberately simple, so you can read them at a glance and store them as plain strings:
30
+
31
+ | Pattern | Matches | Doesn't match |
32
+ | --- | --- | --- |
33
+ | `/settings` | `/settings` | `/settings/profile` |
34
+ | `/posts/:id` | `/posts/42`, `/posts/hello` | `/posts`, `/posts/42/edit` |
35
+ | `/posts/:id/edit` | `/posts/42/edit` | `/posts/42` |
36
+ | `/admin/*` | `/admin`, `/admin/users`, `/admin/users/7` | `/administrator` |
37
+ | `*` | anything | |
38
+
39
+ A few things are handled for you, so they don't catch you off guard:
40
+
41
+ - The query string and hash are ignored: `/posts/42?tab=comments` is `/posts/42`.
42
+ - A trailing slash and repeated slashes don't matter: `/admin/users/` is `/admin/users`.
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.
50
+
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.
52
+
53
+ ## Guests
54
+
55
+ People who aren't signed in still have to see something, like the home page and the login screen. The easiest way is a `guest` role, which you pass when there's no user:
56
+
57
+ ```tsx
58
+ <RouteAccessProvider access={pages} roles={user?.roles ?? 'guest'}>
59
+ ```
60
+
61
+ ## React
62
+
63
+ Wrap your app in the provider:
64
+
65
+ ```tsx
66
+ import { RouteAccessProvider } from 'rolegate/react';
67
+ import { pages } from './shared/pages';
68
+
69
+ <RouteAccessProvider access={pages} roles={user?.roles ?? 'guest'}>
70
+ <App />
71
+ </RouteAccessProvider>;
72
+ ```
73
+
74
+ ### Show a link only if the page can be opened
75
+
76
+ ```tsx
77
+ import { CanVisit } from 'rolegate/react';
78
+
79
+ <CanVisit path="/admin">
80
+ <Link to="/admin">Admin</Link>
81
+ </CanVisit>
82
+ ```
83
+
84
+ ### Filter a menu
85
+
86
+ ```tsx
87
+ import { useCanVisit } from 'rolegate/react';
88
+
89
+ const menu = [
90
+ { title: 'Home', path: '/' },
91
+ { title: 'Profile', path: '/profile' },
92
+ { title: 'Users', path: '/admin/users' },
93
+ ];
94
+
95
+ function Menu() {
96
+ const canVisit = useCanVisit();
97
+ return (
98
+ <nav>
99
+ {menu.filter((item) => canVisit(item.path)).map((item) => (
100
+ <Link key={item.path} to={item.path}>{item.title}</Link>
101
+ ))}
102
+ </nav>
103
+ );
104
+ }
105
+ ```
106
+
107
+ ### Protect routes in React Router
108
+
109
+ rolegate doesn't depend on any router. With React Router, a small layout route is all you need:
110
+
111
+ ```tsx
112
+ import { Navigate, Outlet, useLocation } from 'react-router-dom';
113
+ import { useCanVisit } from 'rolegate/react';
114
+
115
+ function PageGuard() {
116
+ const { pathname } = useLocation();
117
+ const canVisit = useCanVisit();
118
+ return canVisit(pathname) ? <Outlet /> : <Navigate to="/forbidden" replace />;
119
+ }
120
+
121
+ <Routes>
122
+ <Route element={<PageGuard />}>
123
+ <Route path="/" element={<Home />} />
124
+ <Route path="/profile" element={<Profile />} />
125
+ <Route path="/admin/*" element={<Admin />} />
126
+ </Route>
127
+ <Route path="/forbidden" element={<Forbidden />} />
128
+ </Routes>
129
+ ```
130
+
131
+ The guard checks the real address (`/admin/users`), not the route pattern, so it works even when you nest routes.
132
+
133
+ ## Remember: this is UX, not security
134
+
135
+ Hiding a page in the browser doesn't stop anyone from calling your API directly. Whatever data those pages load has to be protected on the server too. See [API routes](api-routes.md) or [actions on resources](actions.md).
136
+
137
+ ## Loading page permissions from the server
138
+
139
+ If the list of pages and who can see them lives in a database, see [Permissions from a database](database.md). The short version: fetch the rows, build `pages` from them, and pass it to the provider. When the rules change, pass a new object and the UI updates.
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "rolegate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Tiny, dependency-free access control for TypeScript: roles, actions and routes. One config for Node, Express and React.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/SunKat1/rolegate.git"
10
+ },
11
+ "homepage": "https://github.com/SunKat1/rolegate#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/SunKat1/rolegate/issues"
14
+ },
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ },
22
+ "./express": {
23
+ "types": "./dist/express/index.d.ts",
24
+ "import": "./dist/express/index.js"
25
+ },
26
+ "./react": {
27
+ "types": "./dist/react/index.d.ts",
28
+ "import": "./dist/react/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "docs",
34
+ "src"
35
+ ],
36
+ "scripts": {
37
+ "build": "tsc -p tsconfig.build.json",
38
+ "test": "tsx --test \"test/**/*.test.ts\" \"test/**/*.test.tsx\"",
39
+ "typecheck": "tsc -p .",
40
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
41
+ },
42
+ "keywords": [
43
+ "rbac",
44
+ "permissions",
45
+ "access-control",
46
+ "authorization",
47
+ "typescript",
48
+ "react",
49
+ "express",
50
+ "routes",
51
+ "route-guard"
52
+ ],
53
+ "author": "Vladyslav Katrych",
54
+ "license": "MIT",
55
+ "peerDependencies": {
56
+ "react": ">=17"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "react": {
60
+ "optional": true
61
+ }
62
+ },
63
+ "devDependencies": {
64
+ "@testing-library/react": "^16.3.3",
65
+ "@types/node": "^22.20.5",
66
+ "@types/react": "^18.3.0",
67
+ "@types/react-dom": "^18.3.7",
68
+ "global-jsdom": "^29.0.0",
69
+ "jsdom": "^29.1.1",
70
+ "react": "^18.3.0",
71
+ "react-dom": "^18.3.1",
72
+ "tsx": "^4.19.0",
73
+ "typescript": "^5.6.0"
74
+ }
75
+ }
@@ -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';
@@ -0,0 +1,69 @@
1
+ // Rules are grouped by resource in the config: { posts: ['read'] }.
2
+ // The shared role code wants a flat list, so we flatten them, apply
3
+ // inheritance, then group them back by resource for fast lookups.
4
+
5
+ import { configError, isObject } from '../shared/validate.js';
6
+ import type { Context, ResourceRules, Rule } from './types.js';
7
+
8
+ /** '*' means "any resource" in the resource slot and "any action" in the action slot. */
9
+ export const ANY = '*';
10
+
11
+ /** One rule together with the resource it was written for. */
12
+ export interface Entry<C extends Context> {
13
+ resource: string;
14
+ rule: Rule<C>;
15
+ }
16
+
17
+ /** Rules grouped by resource name. */
18
+ export type RuleIndex<C extends Context> = Map<string, Rule<C>[]>;
19
+
20
+ /** `{ posts: ['read'] }` -> `[{ resource: 'posts', rule: 'read' }]`, checking the shape on the way. */
21
+ export function toEntries<C extends Context>(rules: ResourceRules<C> | undefined, where: string): Entry<C>[] {
22
+ if (rules === undefined) return [];
23
+ if (!isObject(rules)) configError(`${where} should be an object like { posts: ['read'] }`);
24
+
25
+ return Object.entries(rules).flatMap(([resource, list]) => {
26
+ if (!Array.isArray(list)) configError(`rules for "${resource}" should be a list (${where})`);
27
+ for (const rule of list) checkRule(rule, `${where}, resource "${resource}"`);
28
+ return list.map((rule) => ({ resource, rule }));
29
+ });
30
+ }
31
+
32
+ /** Groups the flat entries back by resource. */
33
+ export function toIndex<C extends Context>(entries: Entry<C>[]): RuleIndex<C> {
34
+ const index: RuleIndex<C> = new Map();
35
+ for (const { resource, rule } of entries) {
36
+ const list = index.get(resource);
37
+ if (list) list.push(rule);
38
+ else index.set(resource, [rule]);
39
+ }
40
+ return index;
41
+ }
42
+
43
+ /** Is there a rule for this resource and action whose condition (if any) holds? */
44
+ export function matches<C extends Context>(index: RuleIndex<C>, resource: string, action: string, ctx: C): boolean {
45
+ // this resource plus the '*' ones
46
+ const keys = resource === ANY ? [ANY] : [resource, ANY];
47
+
48
+ for (const key of keys) {
49
+ for (const rule of index.get(key) ?? []) {
50
+ if (typeof rule === 'string') {
51
+ if (rule === ANY || rule === action) return true;
52
+ continue;
53
+ }
54
+ if (rule.action !== ANY && rule.action !== action) continue;
55
+ if (!rule.when || rule.when(ctx)) return true;
56
+ }
57
+ }
58
+ return false;
59
+ }
60
+
61
+ function checkRule(rule: unknown, where: string): void {
62
+ if (typeof rule === 'string') return;
63
+ if (!isObject(rule) || typeof rule.action !== 'string') {
64
+ configError(`a rule should be an action name or { action, when? } (${where})`);
65
+ }
66
+ if (rule.when !== undefined && typeof rule.when !== 'function') {
67
+ configError(`"when" for action "${rule.action}" should be a function (${where})`);
68
+ }
69
+ }
@@ -0,0 +1,36 @@
1
+ import type { Roles } from '../shared/roles.js';
2
+
3
+ /** Whatever extra data your conditions need, e.g. `{ userId, ownerId }`. */
4
+ export type Context = Record<string, unknown>;
5
+
6
+ /** Return true to let the rule apply. Gets `{}` when no context was passed. */
7
+ export type Condition<C extends Context = Context> = (ctx: C) => boolean;
8
+
9
+ /** Either just an action name, or an action that only counts when a condition holds. */
10
+ export type Rule<C extends Context = Context> =
11
+ | string
12
+ | { action: string; when?: Condition<C> };
13
+
14
+ /** Resource name -> rules for it. `'*'` works both as "any resource" and "any action". */
15
+ export type ResourceRules<C extends Context = Context> = Record<string, Rule<C>[]>;
16
+
17
+ export interface RoleConfig<C extends Context = Context> {
18
+ /** Take everything these roles have, then add (or deny) on top. */
19
+ extends?: string[];
20
+ allow?: ResourceRules<C>;
21
+ /** Wins over any allow, including the ones inherited through `extends`. */
22
+ deny?: ResourceRules<C>;
23
+ }
24
+
25
+ export interface RbacConfig<C extends Context = Context> {
26
+ roles: Record<string, RoleConfig<C>>;
27
+ }
28
+
29
+ export interface Rbac<C extends Context = Context> {
30
+ /** Can these roles do `action` on `resource`? */
31
+ can(roles: Roles, resource: string, action: string, ctx?: C): boolean;
32
+ /** Same question, but throws ForbiddenError when the answer is no. */
33
+ assert(roles: Roles, resource: string, action: string, ctx?: C): void;
34
+ /** Every role name from the config. */
35
+ readonly roles: readonly string[];
36
+ }
@@ -0,0 +1,64 @@
1
+ import type { RouteAccess } from '../routes/types.js';
2
+ import type { Roles } from '../shared/roles.js';
3
+ import { defaultGetRoles, hasNoRoles, read } from './types.js';
4
+ import type { NextLike, RequestLike, ResponseLike, Source } from './types.js';
5
+
6
+ export interface GuardRoutesOptions<Req = RequestLike> {
7
+ /** Where to get the user's roles. Default: req.user.roles, then req.user.role. */
8
+ getRoles?: (req: Req) => Roles;
9
+ /**
10
+ * Which path to check. By default it's `req.baseUrl + req.path`, the full
11
+ * path even when the guard sits inside a router mounted at '/api'.
12
+ * The query string isn't part of it.
13
+ */
14
+ getPath?: (req: Req) => string;
15
+ /**
16
+ * Methods to let through without a check, e.g. `['OPTIONS']` for CORS preflights
17
+ * (they come without a token). Empty by default. Putting `cors()` above the guard works too.
18
+ */
19
+ skipMethods?: readonly string[];
20
+ }
21
+
22
+ function defaultGetPath(req: unknown): string {
23
+ const { baseUrl = '', path = '/' } = req as RequestLike;
24
+ return baseUrl + path;
25
+ }
26
+
27
+ /**
28
+ * One middleware for many routes. It looks at the method and path of each
29
+ * request and checks them against your route rules:
30
+ *
31
+ * app.use('/api', guardRoutes(apiAccess));
32
+ *
33
+ * Sends 401 when the user has no roles and 403 when the route isn't allowed.
34
+ *
35
+ * It runs before Express has picked a route, so it checks the real path
36
+ * ("/api/posts/42") against your patterns ("/api/posts/:id"). Public routes
37
+ * like login go above it, or get allowed for a "guest" role (see the docs).
38
+ */
39
+ export function guardRoutes<Req = RequestLike>(access: Source<RouteAccess>, options: GuardRoutesOptions<Req> = {}) {
40
+ const getRoles = options.getRoles ?? defaultGetRoles;
41
+ const getPath = options.getPath ?? defaultGetPath;
42
+ const skip = new Set((options.skipMethods ?? []).map((m) => m.toUpperCase()));
43
+
44
+ return (req: Req, res: ResponseLike, next: NextLike): void => {
45
+ const method = (req as RequestLike).method ?? 'GET';
46
+ if (skip.has(method.toUpperCase())) {
47
+ next();
48
+ return;
49
+ }
50
+
51
+ const roles = getRoles(req);
52
+ if (hasNoRoles(roles)) {
53
+ res.status(401).json({ error: 'Unauthorized' });
54
+ return;
55
+ }
56
+
57
+ const path = getPath(req);
58
+ if (!read(access).can(roles, path, method)) {
59
+ res.status(403).json({ error: 'Forbidden', path, method });
60
+ return;
61
+ }
62
+ next();
63
+ };
64
+ }
@@ -0,0 +1,12 @@
1
+ // Express bindings. Express itself isn't a dependency: any framework with
2
+ // (req, res, next) and res.status().json() will work.
3
+
4
+ // One resource, one action, mounted on a specific route.
5
+ export { requirePermission } from './requirePermission.js';
6
+ export type { RequirePermissionOptions } from './requirePermission.js';
7
+
8
+ // A single guard for a whole bunch of routes, driven by route rules.
9
+ export { guardRoutes } from './guardRoutes.js';
10
+ export type { GuardRoutesOptions } from './guardRoutes.js';
11
+
12
+ export type { RequestLike, ResponseLike, NextLike, Source } from './types.js';
@@ -0,0 +1,43 @@
1
+ import type { Context, Rbac } from '../core/types.js';
2
+ import type { Roles } from '../shared/roles.js';
3
+ import { defaultGetRoles, hasNoRoles, read } from './types.js';
4
+ import type { NextLike, RequestLike, ResponseLike, Source } from './types.js';
5
+
6
+ export interface RequirePermissionOptions<C extends Context = Context, Req = RequestLike> {
7
+ /** Where to get the user's roles. Default: req.user.roles, then req.user.role. */
8
+ getRoles?: (req: Req) => Roles;
9
+ /** Data for conditional rules, e.g. who owns the post. */
10
+ getContext?: (req: Req) => C | undefined;
11
+ }
12
+
13
+ /**
14
+ * Checks one fixed action on one resource:
15
+ *
16
+ * app.delete('/posts/:id', requirePermission(rbac, 'posts', 'delete'), handler);
17
+ *
18
+ * Sends 401 when the user has no roles and 403 when the action isn't allowed.
19
+ *
20
+ * `Req` gets inferred from `getRoles` / `getContext` once you annotate them,
21
+ * e.g. `getContext: (req: express.Request) => ({ ... })`.
22
+ */
23
+ export function requirePermission<C extends Context = Context, Req = RequestLike>(
24
+ rbac: Source<Rbac<C>>,
25
+ resource: string,
26
+ action: string,
27
+ options: RequirePermissionOptions<C, Req> = {},
28
+ ) {
29
+ const getRoles = options.getRoles ?? defaultGetRoles;
30
+
31
+ return (req: Req, res: ResponseLike, next: NextLike): void => {
32
+ const roles = getRoles(req);
33
+ if (hasNoRoles(roles)) {
34
+ res.status(401).json({ error: 'Unauthorized' });
35
+ return;
36
+ }
37
+ if (!read(rbac).can(roles, resource, action, options.getContext?.(req))) {
38
+ res.status(403).json({ error: 'Forbidden', resource, action });
39
+ return;
40
+ }
41
+ next();
42
+ };
43
+ }
@@ -0,0 +1,45 @@
1
+ import { roleNames } from '../shared/roles.js';
2
+ import type { Roles } from '../shared/roles.js';
3
+
4
+ /**
5
+ * Bare-minimum shapes of req/res, so rolegate doesn't have to depend on Express.
6
+ *
7
+ * No index signature here on purpose: Express's `Request` is an interface
8
+ * without one, and adding it would make a real Request not fit these types.
9
+ */
10
+ export interface RequestLike {
11
+ user?: { role?: string; roles?: string[] } | null;
12
+ method?: string;
13
+ path?: string;
14
+ baseUrl?: string;
15
+ }
16
+
17
+ export interface ResponseLike {
18
+ status(code: number): ResponseLike;
19
+ json(body: unknown): unknown;
20
+ }
21
+
22
+ export type NextLike = (err?: unknown) => void;
23
+
24
+ /**
25
+ * Either the checker itself, or a function that returns the current one.
26
+ * Pass a function when permissions can change while the app runs (say, they
27
+ * live in a database): rebuild the checker, and the middleware picks it up
28
+ * on the next request without re-mounting anything.
29
+ */
30
+ export type Source<T> = T | (() => T);
31
+
32
+ export function read<T extends object>(source: Source<T>): T {
33
+ return typeof source === 'function' ? (source as () => T)() : source;
34
+ }
35
+
36
+ /** By default we expect your auth middleware to put roles on req.user. */
37
+ export function defaultGetRoles(req: unknown): Roles {
38
+ const user = (req as RequestLike).user;
39
+ return user?.roles ?? user?.role;
40
+ }
41
+
42
+ /** No usable role name means not signed in, so `['']` or `[null]` is a 401 too. */
43
+ export function hasNoRoles(roles: Roles): boolean {
44
+ return roleNames(roles).length === 0;
45
+ }