rolegate 0.0.0-stage → 0.1.0

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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +115 -2
  3. package/dist/core/createRbac.d.ts +8 -0
  4. package/dist/core/createRbac.js +63 -0
  5. package/dist/core/createRbac.js.map +1 -0
  6. package/dist/core/index.d.ts +2 -0
  7. package/dist/core/index.js +2 -0
  8. package/dist/core/index.js.map +1 -0
  9. package/dist/core/types.d.ts +30 -0
  10. package/dist/core/types.js +2 -0
  11. package/dist/core/types.js.map +1 -0
  12. package/dist/express/guardRoutes.d.ts +26 -0
  13. package/dist/express/guardRoutes.js +36 -0
  14. package/dist/express/guardRoutes.js.map +1 -0
  15. package/dist/express/index.d.ts +5 -0
  16. package/dist/express/index.js +7 -0
  17. package/dist/express/index.js.map +1 -0
  18. package/dist/express/requirePermission.d.ts +20 -0
  19. package/dist/express/requirePermission.js +27 -0
  20. package/dist/express/requirePermission.js.map +1 -0
  21. package/dist/express/types.d.ts +32 -0
  22. package/dist/express/types.js +12 -0
  23. package/dist/express/types.js.map +1 -0
  24. package/dist/index.d.ts +4 -0
  25. package/dist/index.js +8 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/react/index.d.ts +4 -0
  28. package/dist/react/index.js +7 -0
  29. package/dist/react/index.js.map +1 -0
  30. package/dist/react/rbac.d.ts +23 -0
  31. package/dist/react/rbac.js +21 -0
  32. package/dist/react/rbac.js.map +1 -0
  33. package/dist/react/routes.d.ts +26 -0
  34. package/dist/react/routes.js +26 -0
  35. package/dist/react/routes.js.map +1 -0
  36. package/dist/routes/createRouteAccess.d.ts +14 -0
  37. package/dist/routes/createRouteAccess.js +66 -0
  38. package/dist/routes/createRouteAccess.js.map +1 -0
  39. package/dist/routes/fromRows.d.ts +27 -0
  40. package/dist/routes/fromRows.js +27 -0
  41. package/dist/routes/fromRows.js.map +1 -0
  42. package/dist/routes/index.d.ts +5 -0
  43. package/dist/routes/index.js +4 -0
  44. package/dist/routes/index.js.map +1 -0
  45. package/dist/routes/pattern.d.ts +28 -0
  46. package/dist/routes/pattern.js +63 -0
  47. package/dist/routes/pattern.js.map +1 -0
  48. package/dist/routes/types.d.ts +34 -0
  49. package/dist/routes/types.js +2 -0
  50. package/dist/routes/types.js.map +1 -0
  51. package/dist/shared/errors.d.ts +11 -0
  52. package/dist/shared/errors.js +15 -0
  53. package/dist/shared/errors.js.map +1 -0
  54. package/dist/shared/roles.d.ts +34 -0
  55. package/dist/shared/roles.js +69 -0
  56. package/dist/shared/roles.js.map +1 -0
  57. package/docs/actions.md +182 -0
  58. package/docs/api-routes.md +122 -0
  59. package/docs/database.md +121 -0
  60. package/docs/pages.md +133 -0
  61. package/package.json +72 -4
@@ -0,0 +1,122 @@
1
+ # API routes
2
+
3
+ Use this when you'd like to protect a bunch of endpoints with **one** middleware instead of adding `requirePermission` to each route. The rules talk about paths and HTTP methods: "a reader can `GET /api/posts/*`, a writer can also `PUT /api/posts/:id`".
4
+
5
+ The patterns are the same as for [pages](pages.md#route-patterns): `/posts/:id`, `/admin/*`, `*`.
6
+
7
+ ## Rules with methods
8
+
9
+ A plain string means "any method". Add `methods` to narrow it down:
10
+
11
+ ```ts
12
+ // server/apiAccess.ts
13
+ import { createRouteAccess } from 'rolegate';
14
+
15
+ export const apiAccess = createRouteAccess({
16
+ roles: {
17
+ reader: {
18
+ allow: [{ path: '/api/posts/*', methods: ['GET'] }],
19
+ },
20
+ writer: {
21
+ extends: ['reader'],
22
+ allow: [
23
+ { path: '/api/posts', methods: ['POST'] },
24
+ { path: '/api/posts/:id', methods: ['PUT', 'PATCH'] },
25
+ ],
26
+ },
27
+ admin: {
28
+ allow: ['/api/*'],
29
+ deny: [{ path: '/api/posts/:id', methods: ['DELETE'] }], // even admins don't delete posts
30
+ },
31
+ },
32
+ });
33
+
34
+ apiAccess.can('reader', '/api/posts/1', 'GET'); // true
35
+ apiAccess.can('reader', '/api/posts/1', 'PUT'); // false
36
+ apiAccess.can('writer', '/api/posts/1', 'put'); // true, case doesn't matter
37
+ ```
38
+
39
+ Some details worth knowing:
40
+
41
+ - If you leave out the method, it's `GET`.
42
+ - `HEAD` is checked as `GET`. Express runs GET handlers for HEAD requests, so otherwise HEAD would be a way around a GET deny.
43
+ - `methods: ['*']` is the same as not listing any methods.
44
+
45
+ ## One guard for everything
46
+
47
+ ```ts
48
+ import express from 'express';
49
+ import { guardRoutes } from 'rolegate/express';
50
+ import { apiAccess } from './apiAccess.js';
51
+
52
+ const app = express();
53
+ app.use(authenticate); // your auth, sets req.user
54
+
55
+ // Public endpoints go above the guard
56
+ app.post('/api/login', login);
57
+
58
+ // Everything below goes through the guard
59
+ app.use('/api', guardRoutes(apiAccess));
60
+ app.get('/api/posts/:id', getPost);
61
+ app.put('/api/posts/:id', updatePost);
62
+ ```
63
+
64
+ What the guard does on each request:
65
+
66
+ 1. It takes the roles from `req.user.roles` (or `req.user.role`). No roles means `401`.
67
+ 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
+ 3. If the route isn't allowed, it sends `403` with `{ error: 'Forbidden', path, method }`. Otherwise it calls `next()`.
69
+
70
+ Both can be changed:
71
+
72
+ ```ts
73
+ guardRoutes(apiAccess, {
74
+ getRoles: (req: Request) => req.session?.roles,
75
+ getPath: (req: Request) => req.originalUrl, // the query string is ignored anyway
76
+ });
77
+ ```
78
+
79
+ ## Public endpoints
80
+
81
+ There are two ways to do it, pick whichever reads better in your code:
82
+
83
+ - **Mount them above the guard**, as in the example above. This is the simplest way.
84
+ - **Give unauthenticated users a `guest` role** and allow them what they need:
85
+
86
+ ```ts
87
+ const apiAccess = createRouteAccess({
88
+ roles: {
89
+ guest: { allow: [{ path: '/api/posts/*', methods: ['GET'] }, { path: '/api/login', methods: ['POST'] }] },
90
+ user: { extends: ['guest'], allow: [/* ... */] },
91
+ },
92
+ });
93
+
94
+ app.use(guardRoutes(apiAccess, { getRoles: (req: Request) => req.user?.roles ?? 'guest' }));
95
+ ```
96
+
97
+ With this setup the guard never sends `401`, since everyone has at least the `guest` role. Instead of 401 they get `403`.
98
+
99
+ ## Routes and actions together
100
+
101
+ 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:
102
+
103
+ - `guardRoutes` keeps the rough boundaries: who can reach which part of the API at all.
104
+ - `rbac.assert()` inside the handler does the fine-grained check with a context. See [actions on resources](actions.md#conditions).
105
+
106
+ ```ts
107
+ app.use('/api', guardRoutes(apiAccess)); // writers can reach PUT /api/posts/:id
108
+
109
+ app.put('/api/posts/:id', async (req, res, next) => {
110
+ try {
111
+ const post = await db.posts.find(req.params.id);
112
+ rbac.assert(req.user?.roles, 'posts', 'update', { userId: req.user?.id, ownerId: post.authorId });
113
+ // ...
114
+ } catch (err) {
115
+ next(err);
116
+ }
117
+ });
118
+ ```
119
+
120
+ ## Without Express
121
+
122
+ Express isn't a dependency. The guard works with anything that has `(req, res, next)`, `req.method`, `req.path` and `res.status().json()`. And `apiAccess.can(roles, path, method)` is a plain function, so you can call it from any framework yourself.
@@ -0,0 +1,121 @@
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
+ 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
+
55
+ ## Updating the rules without a restart
56
+
57
+ ### On the server
58
+
59
+ `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:
60
+
61
+ ```ts
62
+ import { guardRoutes } from 'rolegate/express';
63
+
64
+ let access = await loadAccess();
65
+
66
+ async function loadAccess() {
67
+ const rows = await db.query('SELECT role, path, method, effect FROM route_permissions');
68
+ return createRouteAccess(routeConfigFromRows(rows));
69
+ }
70
+
71
+ async function refresh() {
72
+ try {
73
+ access = await loadAccess();
74
+ } catch (err) {
75
+ // Broken data in the DB: log it and keep working with the old rules
76
+ console.error('Could not reload permissions, keeping the old ones', err);
77
+ }
78
+ }
79
+
80
+ setInterval(refresh, 60_000); // or call refresh() right after the admin screen saves changes
81
+
82
+ app.use('/api', guardRoutes(() => access));
83
+ ```
84
+
85
+ `requirePermission` accepts a function the same way: `requirePermission(() => rbac, 'posts', 'delete')`.
86
+
87
+ ### On the frontend
88
+
89
+ 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:
90
+
91
+ ```tsx
92
+ import { useMemo } from 'react';
93
+ import { createRouteAccess, routeConfigFromRows } from 'rolegate';
94
+ import { RouteAccessProvider } from 'rolegate/react';
95
+
96
+ function AccessRoot({ children }) {
97
+ const { user, routeRows } = useSession(); // however you load them
98
+
99
+ const access = useMemo(
100
+ () => createRouteAccess(routeConfigFromRows(routeRows ?? [])),
101
+ [routeRows],
102
+ );
103
+
104
+ return (
105
+ <RouteAccessProvider access={access} roles={user?.roles ?? 'guest'}>
106
+ {children}
107
+ </RouteAccessProvider>
108
+ );
109
+ }
110
+ ```
111
+
112
+ When `routeRows` changes, `access` is rebuilt and every `useCanVisit` and `<CanVisit>` re-renders with the new rules.
113
+
114
+ 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.
115
+
116
+ ## What can't go in the database
117
+
118
+ Conditions like "only the post's author" are functions (`when` in [actions](actions.md#conditions)), and they live in code. A sensible split:
119
+
120
+ - **Database**: which pages and endpoints each role can reach at all. These are the things admins change.
121
+ - **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,133 @@
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
+
45
+ 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
+
47
+ ## Guests
48
+
49
+ 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:
50
+
51
+ ```tsx
52
+ <RouteAccessProvider access={pages} roles={user?.roles ?? 'guest'}>
53
+ ```
54
+
55
+ ## React
56
+
57
+ Wrap your app in the provider:
58
+
59
+ ```tsx
60
+ import { RouteAccessProvider } from 'rolegate/react';
61
+ import { pages } from './shared/pages';
62
+
63
+ <RouteAccessProvider access={pages} roles={user?.roles ?? 'guest'}>
64
+ <App />
65
+ </RouteAccessProvider>;
66
+ ```
67
+
68
+ ### Show a link only if the page can be opened
69
+
70
+ ```tsx
71
+ import { CanVisit } from 'rolegate/react';
72
+
73
+ <CanVisit path="/admin">
74
+ <Link to="/admin">Admin</Link>
75
+ </CanVisit>
76
+ ```
77
+
78
+ ### Filter a menu
79
+
80
+ ```tsx
81
+ import { useCanVisit } from 'rolegate/react';
82
+
83
+ const menu = [
84
+ { title: 'Home', path: '/' },
85
+ { title: 'Profile', path: '/profile' },
86
+ { title: 'Users', path: '/admin/users' },
87
+ ];
88
+
89
+ function Menu() {
90
+ const canVisit = useCanVisit();
91
+ return (
92
+ <nav>
93
+ {menu.filter((item) => canVisit(item.path)).map((item) => (
94
+ <Link key={item.path} to={item.path}>{item.title}</Link>
95
+ ))}
96
+ </nav>
97
+ );
98
+ }
99
+ ```
100
+
101
+ ### Protect routes in React Router
102
+
103
+ rolegate doesn't depend on any router. With React Router, a small layout route is all you need:
104
+
105
+ ```tsx
106
+ import { Navigate, Outlet, useLocation } from 'react-router-dom';
107
+ import { useCanVisit } from 'rolegate/react';
108
+
109
+ function PageGuard() {
110
+ const { pathname } = useLocation();
111
+ const canVisit = useCanVisit();
112
+ return canVisit(pathname) ? <Outlet /> : <Navigate to="/forbidden" replace />;
113
+ }
114
+
115
+ <Routes>
116
+ <Route element={<PageGuard />}>
117
+ <Route path="/" element={<Home />} />
118
+ <Route path="/profile" element={<Profile />} />
119
+ <Route path="/admin/*" element={<Admin />} />
120
+ </Route>
121
+ <Route path="/forbidden" element={<Forbidden />} />
122
+ </Routes>
123
+ ```
124
+
125
+ The guard checks the real address (`/admin/users`), not the route pattern, so it works even when you nest routes.
126
+
127
+ ## Remember: this is UX, not security
128
+
129
+ 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).
130
+
131
+ ## Loading page permissions from the server
132
+
133
+ 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,74 @@
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.0",
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
+ ],
35
+ "scripts": {
36
+ "build": "tsc -p tsconfig.build.json",
37
+ "test": "tsx --test test/*.test.ts test/*.test.tsx",
38
+ "typecheck": "tsc -p .",
39
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
40
+ },
41
+ "keywords": [
42
+ "rbac",
43
+ "permissions",
44
+ "access-control",
45
+ "authorization",
46
+ "typescript",
47
+ "react",
48
+ "express",
49
+ "routes",
50
+ "route-guard"
51
+ ],
52
+ "author": "Vladyslav Katrych",
53
+ "license": "MIT",
54
+ "peerDependencies": {
55
+ "react": ">=17"
56
+ },
57
+ "peerDependenciesMeta": {
58
+ "react": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "devDependencies": {
63
+ "@testing-library/react": "^16.3.3",
64
+ "@types/node": "^22.20.5",
65
+ "@types/react": "^18.3.0",
66
+ "@types/react-dom": "^18.3.7",
67
+ "global-jsdom": "^29.0.0",
68
+ "jsdom": "^29.1.1",
69
+ "react": "^18.3.0",
70
+ "react-dom": "^18.3.1",
71
+ "tsx": "^4.19.0",
72
+ "typescript": "^5.6.0"
73
+ }
74
+ }