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.
- package/LICENSE +21 -0
- package/README.md +115 -2
- package/dist/core/createRbac.d.ts +8 -0
- package/dist/core/createRbac.js +63 -0
- package/dist/core/createRbac.js.map +1 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +2 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/types.d.ts +30 -0
- package/dist/core/types.js +2 -0
- package/dist/core/types.js.map +1 -0
- package/dist/express/guardRoutes.d.ts +26 -0
- package/dist/express/guardRoutes.js +36 -0
- package/dist/express/guardRoutes.js.map +1 -0
- package/dist/express/index.d.ts +5 -0
- package/dist/express/index.js +7 -0
- package/dist/express/index.js.map +1 -0
- package/dist/express/requirePermission.d.ts +20 -0
- package/dist/express/requirePermission.js +27 -0
- package/dist/express/requirePermission.js.map +1 -0
- package/dist/express/types.d.ts +32 -0
- package/dist/express/types.js +12 -0
- package/dist/express/types.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/react/index.d.ts +4 -0
- package/dist/react/index.js +7 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/rbac.d.ts +23 -0
- package/dist/react/rbac.js +21 -0
- package/dist/react/rbac.js.map +1 -0
- package/dist/react/routes.d.ts +26 -0
- package/dist/react/routes.js +26 -0
- package/dist/react/routes.js.map +1 -0
- package/dist/routes/createRouteAccess.d.ts +14 -0
- package/dist/routes/createRouteAccess.js +66 -0
- package/dist/routes/createRouteAccess.js.map +1 -0
- package/dist/routes/fromRows.d.ts +27 -0
- package/dist/routes/fromRows.js +27 -0
- package/dist/routes/fromRows.js.map +1 -0
- package/dist/routes/index.d.ts +5 -0
- package/dist/routes/index.js +4 -0
- package/dist/routes/index.js.map +1 -0
- package/dist/routes/pattern.d.ts +28 -0
- package/dist/routes/pattern.js +63 -0
- package/dist/routes/pattern.js.map +1 -0
- package/dist/routes/types.d.ts +34 -0
- package/dist/routes/types.js +2 -0
- package/dist/routes/types.js.map +1 -0
- package/dist/shared/errors.d.ts +11 -0
- package/dist/shared/errors.js +15 -0
- package/dist/shared/errors.js.map +1 -0
- package/dist/shared/roles.d.ts +34 -0
- package/dist/shared/roles.js +69 -0
- package/dist/shared/roles.js.map +1 -0
- package/docs/actions.md +182 -0
- package/docs/api-routes.md +122 -0
- package/docs/database.md +121 -0
- package/docs/pages.md +133 -0
- package/package.json +72 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vladyslav Katrych
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,116 @@
|
|
|
1
|
-
#
|
|
1
|
+
# rolegate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Tiny, dependency-free access control for TypeScript. You describe who can do what once, and the same rules work on the server, in Express and in React.
|
|
4
|
+
|
|
5
|
+
It answers two kinds of questions, and you can use either one on its own or both together:
|
|
6
|
+
|
|
7
|
+
- **Actions on things.** "Can an editor delete posts?" Roles, actions, inheritance, and conditions like "only their own posts".
|
|
8
|
+
- **Routes and pages.** "Can an editor open `/admin/users`?" "Can they `PUT /api/posts/42`?" Route patterns like `/posts/:id` and `/admin/*`, with rules you can keep in a database.
|
|
9
|
+
|
|
10
|
+
What you get either way:
|
|
11
|
+
|
|
12
|
+
- **Deny always wins**, including over rules a role inherits from another one.
|
|
13
|
+
- **Mistakes fail early.** Unknown roles, circular `extends` and broken route patterns throw when the config is created, not halfway through a request.
|
|
14
|
+
- **No runtime dependencies.** React is an optional peer dependency, and Express isn't needed at all.
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install rolegate
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
The package is ESM only. In TypeScript, use `"moduleResolution": "nodenext"` or `"bundler"` so that `rolegate/express` and `rolegate/react` resolve.
|
|
21
|
+
|
|
22
|
+
## A quick taste
|
|
23
|
+
|
|
24
|
+
Actions on things:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { createRbac } from 'rolegate';
|
|
28
|
+
|
|
29
|
+
const rbac = createRbac({
|
|
30
|
+
roles: {
|
|
31
|
+
viewer: { allow: { posts: ['read'] } },
|
|
32
|
+
editor: { extends: ['viewer'], allow: { posts: ['write'] } },
|
|
33
|
+
admin: { allow: { '*': ['*'] } },
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
rbac.can('editor', 'posts', 'write'); // true
|
|
38
|
+
rbac.can('viewer', 'posts', 'write'); // false
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Pages:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { createRouteAccess } from 'rolegate';
|
|
45
|
+
|
|
46
|
+
const pages = createRouteAccess({
|
|
47
|
+
roles: {
|
|
48
|
+
guest: { allow: ['/', '/login', '/posts/*'] },
|
|
49
|
+
user: { extends: ['guest'], allow: ['/profile'] },
|
|
50
|
+
admin: { extends: ['user'], allow: ['/admin/*'] },
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
pages.can('user', '/posts/42'); // true
|
|
55
|
+
pages.can('user', '/admin/users'); // false
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Docs
|
|
59
|
+
|
|
60
|
+
Pick the page that matches what you're building:
|
|
61
|
+
|
|
62
|
+
| I want to... | Read |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| Check actions like "edit a post", with roles and conditions | [Actions on resources](docs/actions.md) |
|
|
65
|
+
| Show or hide frontend pages, menus and links by role | [Frontend pages](docs/pages.md) |
|
|
66
|
+
| Protect API endpoints by path and HTTP method | [API routes](docs/api-routes.md) |
|
|
67
|
+
| Keep route permissions in a database and update them live | [Permissions from a database](docs/database.md) |
|
|
68
|
+
|
|
69
|
+
## Which entry point has what
|
|
70
|
+
|
|
71
|
+
| Import from | What's there |
|
|
72
|
+
| --- | --- |
|
|
73
|
+
| `rolegate` | `createRbac`, `createRouteAccess`, `routeConfigFromRows`, `ForbiddenError` |
|
|
74
|
+
| `rolegate/express` | `requirePermission` (one action), `guardRoutes` (many routes at once) |
|
|
75
|
+
| `rolegate/react` | `RbacProvider`, `useCan`, `<Can>`, `RouteAccessProvider`, `useCanVisit`, `<CanVisit>` |
|
|
76
|
+
|
|
77
|
+
## How a decision is made
|
|
78
|
+
|
|
79
|
+
The same rules apply to both kinds of checks:
|
|
80
|
+
|
|
81
|
+
| Situation | Result |
|
|
82
|
+
| --- | --- |
|
|
83
|
+
| Some role allows it and none deny it | allowed |
|
|
84
|
+
| Any role denies it | denied, even if another role allows it |
|
|
85
|
+
| A role `extends` another one | it gets all of that role's allows **and** denies |
|
|
86
|
+
| A role that isn't in the config, or no role at all | denied |
|
|
87
|
+
|
|
88
|
+
## Development
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
npm install
|
|
92
|
+
npm test # node:test via tsx, React tests run in jsdom
|
|
93
|
+
npm run typecheck # type-checks the sources and the tests
|
|
94
|
+
npm run build # compiles src/ to dist/ (tsconfig.build.json)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Project layout:
|
|
98
|
+
|
|
99
|
+
```
|
|
100
|
+
src/
|
|
101
|
+
shared/ role inheritance and the "deny wins" rule, used by both engines
|
|
102
|
+
core/ createRbac: actions on resources
|
|
103
|
+
routes/ createRouteAccess: route patterns, page and API access, rows from a DB
|
|
104
|
+
express/ requirePermission and guardRoutes
|
|
105
|
+
react/ providers, hooks and components
|
|
106
|
+
docs/ usage guides
|
|
107
|
+
test/
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Status
|
|
111
|
+
|
|
112
|
+
Everything is covered by tests: the resource engine, route patterns and the route engine, loading rules from rows, both Express middlewares, and the React providers, hooks and components (Testing Library on top of jsdom).
|
|
113
|
+
|
|
114
|
+
## License
|
|
115
|
+
|
|
116
|
+
MIT
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Context, Rbac, RbacConfig } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Builds the resource/action checker:
|
|
4
|
+
*
|
|
5
|
+
* const rbac = createRbac({ roles: { editor: { allow: { posts: ['read', 'write'] } } } });
|
|
6
|
+
* rbac.can('editor', 'posts', 'write'); // true
|
|
7
|
+
*/
|
|
8
|
+
export declare function createRbac<C extends Context = Context>(config: RbacConfig<C>): Rbac<C>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { ForbiddenError } from '../shared/errors.js';
|
|
2
|
+
import { decide, pickRoles, resolveRoles } from '../shared/roles.js';
|
|
3
|
+
const ANY = '*';
|
|
4
|
+
function toEntries(rules = {}) {
|
|
5
|
+
return Object.entries(rules).flatMap(([resource, list]) => list.map((rule) => ({ resource, rule })));
|
|
6
|
+
}
|
|
7
|
+
function toIndex(entries) {
|
|
8
|
+
const index = new Map();
|
|
9
|
+
for (const { resource, rule } of entries) {
|
|
10
|
+
const list = index.get(resource);
|
|
11
|
+
if (list)
|
|
12
|
+
list.push(rule);
|
|
13
|
+
else
|
|
14
|
+
index.set(resource, [rule]);
|
|
15
|
+
}
|
|
16
|
+
return index;
|
|
17
|
+
}
|
|
18
|
+
function matches(index, resource, action, ctx) {
|
|
19
|
+
// Look at rules for this exact resource and at the "any resource" ones.
|
|
20
|
+
const keys = resource === ANY ? [ANY] : [resource, ANY];
|
|
21
|
+
for (const key of keys) {
|
|
22
|
+
for (const rule of index.get(key) ?? []) {
|
|
23
|
+
const name = typeof rule === 'string' ? rule : rule.action;
|
|
24
|
+
if (name !== ANY && name !== action)
|
|
25
|
+
continue;
|
|
26
|
+
const when = typeof rule === 'string' ? undefined : rule.when;
|
|
27
|
+
if (!when || when(ctx))
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Builds the resource/action checker:
|
|
35
|
+
*
|
|
36
|
+
* const rbac = createRbac({ roles: { editor: { allow: { posts: ['read', 'write'] } } } });
|
|
37
|
+
* rbac.can('editor', 'posts', 'write'); // true
|
|
38
|
+
*/
|
|
39
|
+
export function createRbac(config) {
|
|
40
|
+
// Turn the "resource -> rules" maps into flat lists so the shared role code
|
|
41
|
+
// can handle extends/deny the same way it does for routes.
|
|
42
|
+
const definitions = {};
|
|
43
|
+
for (const [name, role] of Object.entries(config.roles)) {
|
|
44
|
+
definitions[name] = { extends: role.extends, allow: toEntries(role.allow), deny: toEntries(role.deny) };
|
|
45
|
+
}
|
|
46
|
+
const known = new Map();
|
|
47
|
+
for (const [name, role] of resolveRoles(definitions)) {
|
|
48
|
+
known.set(name, { allow: toIndex(role.allow), deny: toIndex(role.deny) });
|
|
49
|
+
}
|
|
50
|
+
const can = (roles, resource, action, ctx) => {
|
|
51
|
+
const context = (ctx ?? {});
|
|
52
|
+
return decide(pickRoles(known, roles), (role) => matches(role.deny, resource, action, context), (role) => matches(role.allow, resource, action, context));
|
|
53
|
+
};
|
|
54
|
+
return {
|
|
55
|
+
can,
|
|
56
|
+
assert(roles, resource, action, ctx) {
|
|
57
|
+
if (!can(roles, resource, action, ctx))
|
|
58
|
+
throw new ForbiddenError(resource, action);
|
|
59
|
+
},
|
|
60
|
+
roles: Object.keys(config.roles),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=createRbac.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createRbac.js","sourceRoot":"","sources":["../../src/core/createRbac.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Roles } from '../shared/roles.js';
|
|
2
|
+
/** Whatever extra data your conditions need, e.g. `{ userId, ownerId }`. */
|
|
3
|
+
export type Context = Record<string, unknown>;
|
|
4
|
+
/** Return true to let the rule apply. Gets `{}` when no context was passed. */
|
|
5
|
+
export type Condition<C extends Context = Context> = (ctx: C) => boolean;
|
|
6
|
+
/** Either just an action name, or an action that only counts when a condition holds. */
|
|
7
|
+
export type Rule<C extends Context = Context> = string | {
|
|
8
|
+
action: string;
|
|
9
|
+
when?: Condition<C>;
|
|
10
|
+
};
|
|
11
|
+
/** Resource name -> rules for it. `'*'` works both as "any resource" and "any action". */
|
|
12
|
+
export type ResourceRules<C extends Context = Context> = Record<string, Rule<C>[]>;
|
|
13
|
+
export interface RoleConfig<C extends Context = Context> {
|
|
14
|
+
/** Take everything these roles have, then add (or deny) on top. */
|
|
15
|
+
extends?: string[];
|
|
16
|
+
allow?: ResourceRules<C>;
|
|
17
|
+
/** Wins over any allow, including the ones inherited through `extends`. */
|
|
18
|
+
deny?: ResourceRules<C>;
|
|
19
|
+
}
|
|
20
|
+
export interface RbacConfig<C extends Context = Context> {
|
|
21
|
+
roles: Record<string, RoleConfig<C>>;
|
|
22
|
+
}
|
|
23
|
+
export interface Rbac<C extends Context = Context> {
|
|
24
|
+
/** Can these roles do `action` on `resource`? */
|
|
25
|
+
can(roles: Roles, resource: string, action: string, ctx?: C): boolean;
|
|
26
|
+
/** Same question, but throws ForbiddenError when the answer is no. */
|
|
27
|
+
assert(roles: Roles, resource: string, action: string, ctx?: C): void;
|
|
28
|
+
/** Every role name from the config. */
|
|
29
|
+
readonly roles: readonly string[];
|
|
30
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/core/types.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { RouteAccess } from '../routes/types.js';
|
|
2
|
+
import type { Roles } from '../shared/roles.js';
|
|
3
|
+
import type { NextLike, RequestLike, ResponseLike, Source } from './types.js';
|
|
4
|
+
export interface GuardRoutesOptions<Req = RequestLike> {
|
|
5
|
+
/** Where to get the user's roles. Default: req.user.roles, then req.user.role. */
|
|
6
|
+
getRoles?: (req: Req) => Roles;
|
|
7
|
+
/**
|
|
8
|
+
* Which path to check. By default it's `req.baseUrl + req.path`, the full
|
|
9
|
+
* path even when the guard sits inside a router mounted at '/api'.
|
|
10
|
+
* The query string isn't part of it.
|
|
11
|
+
*/
|
|
12
|
+
getPath?: (req: Req) => string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* One middleware for many routes. It looks at the method and path of each
|
|
16
|
+
* request and checks them against your route rules:
|
|
17
|
+
*
|
|
18
|
+
* app.use('/api', guardRoutes(apiAccess));
|
|
19
|
+
*
|
|
20
|
+
* Sends 401 when the user has no roles and 403 when the route isn't allowed.
|
|
21
|
+
*
|
|
22
|
+
* It runs before Express has picked a route, so it checks the real path
|
|
23
|
+
* ("/api/posts/42") against your patterns ("/api/posts/:id"). Public routes
|
|
24
|
+
* like login go above it, or get allowed for a "guest" role (see the docs).
|
|
25
|
+
*/
|
|
26
|
+
export declare function guardRoutes<Req = RequestLike>(access: Source<RouteAccess>, options?: GuardRoutesOptions<Req>): (req: Req, res: ResponseLike, next: NextLike) => void;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { defaultGetRoles, hasNoRoles, read } from './types.js';
|
|
2
|
+
function defaultGetPath(req) {
|
|
3
|
+
const { baseUrl = '', path = '/' } = req;
|
|
4
|
+
return baseUrl + path;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* One middleware for many routes. It looks at the method and path of each
|
|
8
|
+
* request and checks them against your route rules:
|
|
9
|
+
*
|
|
10
|
+
* app.use('/api', guardRoutes(apiAccess));
|
|
11
|
+
*
|
|
12
|
+
* Sends 401 when the user has no roles and 403 when the route isn't allowed.
|
|
13
|
+
*
|
|
14
|
+
* It runs before Express has picked a route, so it checks the real path
|
|
15
|
+
* ("/api/posts/42") against your patterns ("/api/posts/:id"). Public routes
|
|
16
|
+
* like login go above it, or get allowed for a "guest" role (see the docs).
|
|
17
|
+
*/
|
|
18
|
+
export function guardRoutes(access, options = {}) {
|
|
19
|
+
const getRoles = options.getRoles ?? defaultGetRoles;
|
|
20
|
+
const getPath = options.getPath ?? defaultGetPath;
|
|
21
|
+
return (req, res, next) => {
|
|
22
|
+
const roles = getRoles(req);
|
|
23
|
+
if (hasNoRoles(roles)) {
|
|
24
|
+
res.status(401).json({ error: 'Unauthorized' });
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const path = getPath(req);
|
|
28
|
+
const method = req.method ?? 'GET';
|
|
29
|
+
if (!read(access).can(roles, path, method)) {
|
|
30
|
+
res.status(403).json({ error: 'Forbidden', path, method });
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
next();
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=guardRoutes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardRoutes.js","sourceRoot":"","sources":["../../src/express/guardRoutes.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAc/D,SAAS,cAAc,CAAC,GAAY;IAClC,MAAM,EAAE,OAAO,GAAG,EAAE,EAAE,IAAI,GAAG,GAAG,EAAE,GAAG,GAAkB,CAAC;IACxD,OAAO,OAAO,GAAG,IAAI,CAAC;AACxB,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,WAAW,CAAoB,MAA2B,EAAE,UAAmC,EAAE;IAC/G,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,eAAe,CAAC;IACrD,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,cAAc,CAAC;IAElD,OAAO,CAAC,GAAQ,EAAE,GAAiB,EAAE,IAAc,EAAQ,EAAE;QAC3D,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC5B,IAAI,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;YACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAC;YAChD,OAAO;QACT,CAAC;QAED,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;QAC1B,MAAM,MAAM,GAAI,GAAmB,CAAC,MAAM,IAAI,KAAK,CAAC;QACpD,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,CAAC,EAAE,CAAC;YAC3C,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;YAC3D,OAAO;QACT,CAAC;QACD,IAAI,EAAE,CAAC;IACT,CAAC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { requirePermission } from './requirePermission.js';
|
|
2
|
+
export type { RequirePermissionOptions } from './requirePermission.js';
|
|
3
|
+
export { guardRoutes } from './guardRoutes.js';
|
|
4
|
+
export type { GuardRoutesOptions } from './guardRoutes.js';
|
|
5
|
+
export type { RequestLike, ResponseLike, NextLike, Source } from './types.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Express bindings. Express itself isn't a dependency: any framework with
|
|
2
|
+
// (req, res, next) and res.status().json() will work.
|
|
3
|
+
// One resource, one action, mounted on a specific route.
|
|
4
|
+
export { requirePermission } from './requirePermission.js';
|
|
5
|
+
// A single guard for a whole bunch of routes, driven by route rules.
|
|
6
|
+
export { guardRoutes } from './guardRoutes.js';
|
|
7
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/express/index.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,sDAAsD;AAEtD,yDAAyD;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAG3D,qEAAqE;AACrE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Context, Rbac } from '../core/types.js';
|
|
2
|
+
import type { Roles } from '../shared/roles.js';
|
|
3
|
+
import type { NextLike, RequestLike, ResponseLike, Source } from './types.js';
|
|
4
|
+
export interface RequirePermissionOptions<C extends Context = Context, Req = RequestLike> {
|
|
5
|
+
/** Where to get the user's roles. Default: req.user.roles, then req.user.role. */
|
|
6
|
+
getRoles?: (req: Req) => Roles;
|
|
7
|
+
/** Data for conditional rules, e.g. who owns the post. */
|
|
8
|
+
getContext?: (req: Req) => C | undefined;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Checks one fixed action on one resource:
|
|
12
|
+
*
|
|
13
|
+
* app.delete('/posts/:id', requirePermission(rbac, 'posts', 'delete'), handler);
|
|
14
|
+
*
|
|
15
|
+
* Sends 401 when the user has no roles and 403 when the action isn't allowed.
|
|
16
|
+
*
|
|
17
|
+
* `Req` gets inferred from `getRoles` / `getContext` once you annotate them,
|
|
18
|
+
* e.g. `getContext: (req: express.Request) => ({ ... })`.
|
|
19
|
+
*/
|
|
20
|
+
export declare function requirePermission<C extends Context = Context, Req = RequestLike>(rbac: Source<Rbac<C>>, resource: string, action: string, options?: RequirePermissionOptions<C, Req>): (req: Req, res: ResponseLike, next: NextLike) => void;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { defaultGetRoles, hasNoRoles, read } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Checks one fixed action on one resource:
|
|
4
|
+
*
|
|
5
|
+
* app.delete('/posts/:id', requirePermission(rbac, 'posts', 'delete'), handler);
|
|
6
|
+
*
|
|
7
|
+
* Sends 401 when the user has no roles and 403 when the action isn't allowed.
|
|
8
|
+
*
|
|
9
|
+
* `Req` gets inferred from `getRoles` / `getContext` once you annotate them,
|
|
10
|
+
* e.g. `getContext: (req: express.Request) => ({ ... })`.
|
|
11
|
+
*/
|
|
12
|
+
export function requirePermission(rbac, resource, action, options = {}) {
|
|
13
|
+
const getRoles = options.getRoles ?? defaultGetRoles;
|
|
14
|
+
return (req, res, next) => {
|
|
15
|
+
const roles = getRoles(req);
|
|
16
|
+
if (hasNoRoles(roles)) {
|
|
17
|
+
res.status(401).json({ error: 'Unauthorized' });
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
if (!read(rbac).can(roles, resource, action, options.getContext?.(req))) {
|
|
21
|
+
res.status(403).json({ error: 'Forbidden', resource, action });
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
next();
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=requirePermission.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"requirePermission.js","sourceRoot":"","sources":["../../src/express/requirePermission.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAU/D;;;;;;;;;GASG;AACH,MAAM,UAAU,iBAAiB,CAC/B,IAAqB,EACrB,QAAgB,EAChB,MAAc,EACd,UAA4C,EAAE;IAE9C,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,eAAe,CAAC;IAErD,OAAO,CAAC,GAAQ,EAAE,GAAiB,EAAE,IAAc,EAAQ,EAAE;QAC3D,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC5B,IAAI,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;YACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAC;YAChD,OAAO;QACT,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,UAAU,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;YACxE,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;YAC/D,OAAO;QACT,CAAC;QACD,IAAI,EAAE,CAAC;IACT,CAAC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Roles } from '../shared/roles.js';
|
|
2
|
+
/**
|
|
3
|
+
* Bare-minimum shapes of req/res, so rolegate doesn't have to depend on Express.
|
|
4
|
+
*
|
|
5
|
+
* No index signature here on purpose: Express's `Request` is an interface
|
|
6
|
+
* without one, and adding it would make a real Request not fit these types.
|
|
7
|
+
*/
|
|
8
|
+
export interface RequestLike {
|
|
9
|
+
user?: {
|
|
10
|
+
role?: string;
|
|
11
|
+
roles?: string[];
|
|
12
|
+
} | null;
|
|
13
|
+
method?: string;
|
|
14
|
+
path?: string;
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface ResponseLike {
|
|
18
|
+
status(code: number): ResponseLike;
|
|
19
|
+
json(body: unknown): unknown;
|
|
20
|
+
}
|
|
21
|
+
export type NextLike = (err?: unknown) => void;
|
|
22
|
+
/**
|
|
23
|
+
* Either the checker itself, or a function that returns the current one.
|
|
24
|
+
* Pass a function when permissions can change while the app runs (say, they
|
|
25
|
+
* live in a database): rebuild the checker, and the middleware picks it up
|
|
26
|
+
* on the next request without re-mounting anything.
|
|
27
|
+
*/
|
|
28
|
+
export type Source<T> = T | (() => T);
|
|
29
|
+
export declare function read<T extends object>(source: Source<T>): T;
|
|
30
|
+
/** By default we expect your auth middleware to put roles on req.user. */
|
|
31
|
+
export declare function defaultGetRoles(req: unknown): Roles;
|
|
32
|
+
export declare function hasNoRoles(roles: Roles): boolean;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export function read(source) {
|
|
2
|
+
return typeof source === 'function' ? source() : source;
|
|
3
|
+
}
|
|
4
|
+
/** By default we expect your auth middleware to put roles on req.user. */
|
|
5
|
+
export function defaultGetRoles(req) {
|
|
6
|
+
const user = req.user;
|
|
7
|
+
return user?.roles ?? user?.role;
|
|
8
|
+
}
|
|
9
|
+
export function hasNoRoles(roles) {
|
|
10
|
+
return roles === undefined || roles === '' || (Array.isArray(roles) && roles.length === 0);
|
|
11
|
+
}
|
|
12
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/express/types.ts"],"names":[],"mappings":"AA8BA,MAAM,UAAU,IAAI,CAAmB,MAAiB;IACtD,OAAO,OAAO,MAAM,KAAK,UAAU,CAAC,CAAC,CAAE,MAAkB,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;AACvE,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,eAAe,CAAC,GAAY;IAC1C,MAAM,IAAI,GAAI,GAAmB,CAAC,IAAI,CAAC;IACvC,OAAO,IAAI,EAAE,KAAK,IAAI,IAAI,EAAE,IAAI,CAAC;AACnC,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,KAAY;IACrC,OAAO,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC;AAC7F,CAAC"}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
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
|
+
// Checking actions on resources: "can an editor delete posts?"
|
|
4
|
+
export * from './core/index.js';
|
|
5
|
+
// Checking routes and pages: "can an editor open /admin/users?"
|
|
6
|
+
export * from './routes/index.js';
|
|
7
|
+
export { ForbiddenError } from './shared/errors.js';
|
|
8
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,+FAA+F;AAE/F,+DAA+D;AAC/D,cAAc,iBAAiB,CAAC;AAEhC,gEAAgE;AAChE,cAAc,mBAAmB,CAAC;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
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
|
+
// Actions on resources: <Can resource="posts" action="delete">
|
|
4
|
+
export { RbacProvider, useCan, Can } from './rbac.js';
|
|
5
|
+
// Pages: <CanVisit path="/admin">
|
|
6
|
+
export { RouteAccessProvider, useCanVisit, CanVisit } from './routes.js';
|
|
7
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,2EAA2E;AAE3E,+DAA+D;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAGtD,kCAAkC;AAClC,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { Context, Rbac } from '../core/types.js';
|
|
3
|
+
import type { Roles } from '../shared/roles.js';
|
|
4
|
+
export interface RbacProviderProps<C extends Context = Context> {
|
|
5
|
+
rbac: Rbac<C>;
|
|
6
|
+
/** The current user's role(s), usually straight from your auth state. */
|
|
7
|
+
roles: Roles;
|
|
8
|
+
children?: ReactNode;
|
|
9
|
+
}
|
|
10
|
+
/** Makes `useCan` and `<Can>` work for everything inside. */
|
|
11
|
+
export declare function RbacProvider<C extends Context = Context>({ rbac, roles, children }: RbacProviderProps<C>): import("react").JSX.Element;
|
|
12
|
+
/** Gives you `can(resource, action, ctx?)` for the current user. */
|
|
13
|
+
export declare function useCan(): (resource: string, action: string, ctx?: Context) => boolean;
|
|
14
|
+
export interface CanProps {
|
|
15
|
+
resource: string;
|
|
16
|
+
action: string;
|
|
17
|
+
ctx?: Context;
|
|
18
|
+
/** What to show when the answer is no. Nothing by default. */
|
|
19
|
+
fallback?: ReactNode;
|
|
20
|
+
children?: ReactNode;
|
|
21
|
+
}
|
|
22
|
+
/** Shows its children only if the current user can do the action. */
|
|
23
|
+
export declare function Can({ resource, action, ctx, fallback, children }: CanProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { createContext, useCallback, useContext, useMemo } from 'react';
|
|
3
|
+
const RbacContext = createContext(null);
|
|
4
|
+
/** Makes `useCan` and `<Can>` work for everything inside. */
|
|
5
|
+
export function RbacProvider({ rbac, roles, children }) {
|
|
6
|
+
const value = useMemo(() => ({ rbac, roles }), [rbac, roles]);
|
|
7
|
+
return _jsx(RbacContext.Provider, { value: value, children: children });
|
|
8
|
+
}
|
|
9
|
+
/** Gives you `can(resource, action, ctx?)` for the current user. */
|
|
10
|
+
export function useCan() {
|
|
11
|
+
const state = useContext(RbacContext);
|
|
12
|
+
if (!state)
|
|
13
|
+
throw new Error('rolegate: useCan must be used inside <RbacProvider>');
|
|
14
|
+
return useCallback((resource, action, ctx) => state.rbac.can(state.roles, resource, action, ctx), [state]);
|
|
15
|
+
}
|
|
16
|
+
/** Shows its children only if the current user can do the action. */
|
|
17
|
+
export function Can({ resource, action, ctx, fallback = null, children }) {
|
|
18
|
+
const can = useCan();
|
|
19
|
+
return _jsx(_Fragment, { children: can(resource, action, ctx) ? children : fallback });
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=rbac.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rbac.js","sourceRoot":"","sources":["../../src/react/rbac.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAUxE,MAAM,WAAW,GAAG,aAAa,CAAmB,IAAI,CAAC,CAAC;AAS1D,6DAA6D;AAC7D,MAAM,UAAU,YAAY,CAA8B,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAwB;IACvG,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;IAC9D,OAAO,KAAC,WAAW,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAAwB,CAAC;AAC/E,CAAC;AAED,oEAAoE;AACpE,MAAM,UAAU,MAAM;IACpB,MAAM,KAAK,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;IACtC,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACnF,OAAO,WAAW,CAChB,CAAC,QAAgB,EAAE,MAAc,EAAE,GAAa,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,EACvG,CAAC,KAAK,CAAC,CACR,CAAC;AACJ,CAAC;AAWD,qEAAqE;AACrE,MAAM,UAAU,GAAG,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,GAAG,IAAI,EAAE,QAAQ,EAAY;IAChF,MAAM,GAAG,GAAG,MAAM,EAAE,CAAC;IACrB,OAAO,4BAAG,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,GAAI,CAAC;AACjE,CAAC"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { RouteAccess } from '../routes/types.js';
|
|
3
|
+
import type { Roles } from '../shared/roles.js';
|
|
4
|
+
export interface RouteAccessProviderProps {
|
|
5
|
+
access: RouteAccess;
|
|
6
|
+
/** The current user's role(s). For guests, pass something like 'guest'. */
|
|
7
|
+
roles: Roles;
|
|
8
|
+
children?: ReactNode;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Makes `useCanVisit` and `<CanVisit>` work for everything inside.
|
|
12
|
+
*
|
|
13
|
+
* If you load page permissions from the server, just pass a new `access`
|
|
14
|
+
* object when they change. Everything below re-renders with the new rules.
|
|
15
|
+
*/
|
|
16
|
+
export declare function RouteAccessProvider({ access, roles, children }: RouteAccessProviderProps): import("react").JSX.Element;
|
|
17
|
+
/** Gives you `canVisit(path)` for the current user. Handy for filtering menus. */
|
|
18
|
+
export declare function useCanVisit(): (path: string) => boolean;
|
|
19
|
+
export interface CanVisitProps {
|
|
20
|
+
path: string;
|
|
21
|
+
/** What to show when the user can't open this page. Nothing by default. */
|
|
22
|
+
fallback?: ReactNode;
|
|
23
|
+
children?: ReactNode;
|
|
24
|
+
}
|
|
25
|
+
/** Shows its children only if the current user can open `path`. Good for links and menu items. */
|
|
26
|
+
export declare function CanVisit({ path, fallback, children }: CanVisitProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { createContext, useCallback, useContext, useMemo } from 'react';
|
|
3
|
+
const RouteAccessContext = createContext(null);
|
|
4
|
+
/**
|
|
5
|
+
* Makes `useCanVisit` and `<CanVisit>` work for everything inside.
|
|
6
|
+
*
|
|
7
|
+
* If you load page permissions from the server, just pass a new `access`
|
|
8
|
+
* object when they change. Everything below re-renders with the new rules.
|
|
9
|
+
*/
|
|
10
|
+
export function RouteAccessProvider({ access, roles, children }) {
|
|
11
|
+
const value = useMemo(() => ({ access, roles }), [access, roles]);
|
|
12
|
+
return _jsx(RouteAccessContext.Provider, { value: value, children: children });
|
|
13
|
+
}
|
|
14
|
+
/** Gives you `canVisit(path)` for the current user. Handy for filtering menus. */
|
|
15
|
+
export function useCanVisit() {
|
|
16
|
+
const state = useContext(RouteAccessContext);
|
|
17
|
+
if (!state)
|
|
18
|
+
throw new Error('rolegate: useCanVisit must be used inside <RouteAccessProvider>');
|
|
19
|
+
return useCallback((path) => state.access.can(state.roles, path), [state]);
|
|
20
|
+
}
|
|
21
|
+
/** Shows its children only if the current user can open `path`. Good for links and menu items. */
|
|
22
|
+
export function CanVisit({ path, fallback = null, children }) {
|
|
23
|
+
const canVisit = useCanVisit();
|
|
24
|
+
return _jsx(_Fragment, { children: canVisit(path) ? children : fallback });
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=routes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.js","sourceRoot":"","sources":["../../src/react/routes.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAUxE,MAAM,kBAAkB,GAAG,aAAa,CAAoB,IAAI,CAAC,CAAC;AASlE;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAA4B;IACvF,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;IAClE,OAAO,KAAC,kBAAkB,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAA+B,CAAC;AAC7F,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,WAAW;IACzB,MAAM,KAAK,GAAG,UAAU,CAAC,kBAAkB,CAAC,CAAC;IAC7C,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;IAC/F,OAAO,WAAW,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACrF,CAAC;AASD,kGAAkG;AAClG,MAAM,UAAU,QAAQ,CAAC,EAAE,IAAI,EAAE,QAAQ,GAAG,IAAI,EAAE,QAAQ,EAAiB;IACzE,MAAM,QAAQ,GAAG,WAAW,EAAE,CAAC;IAC/B,OAAO,4BAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,GAAI,CAAC;AACrD,CAAC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { RouteAccess, RouteAccessConfig } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Builds the route checker:
|
|
4
|
+
*
|
|
5
|
+
* const pages = createRouteAccess({
|
|
6
|
+
* roles: {
|
|
7
|
+
* user: { allow: ['/', '/posts/*'] },
|
|
8
|
+
* admin: { extends: ['user'], allow: ['/admin/*'] },
|
|
9
|
+
* },
|
|
10
|
+
* });
|
|
11
|
+
* pages.can('user', '/posts/42'); // true
|
|
12
|
+
* pages.can('user', '/admin/users'); // false
|
|
13
|
+
*/
|
|
14
|
+
export declare function createRouteAccess(config: RouteAccessConfig): RouteAccess;
|