rolegate 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -10
- package/dist/core/createRbac.d.ts +3 -0
- package/dist/core/createRbac.d.ts.map +1 -0
- package/dist/core/createRbac.js +14 -34
- package/dist/core/createRbac.js.map +1 -1
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/rules.d.ts +17 -0
- package/dist/core/rules.d.ts.map +1 -0
- package/dist/core/rules.js +62 -0
- package/dist/core/rules.js.map +1 -0
- package/dist/core/types.d.ts +1 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/express/guardRoutes.d.ts +6 -0
- package/dist/express/guardRoutes.d.ts.map +1 -0
- package/dist/express/guardRoutes.js +6 -1
- package/dist/express/guardRoutes.js.map +1 -1
- package/dist/express/index.d.ts +1 -0
- package/dist/express/index.d.ts.map +1 -0
- package/dist/express/requirePermission.d.ts +1 -0
- package/dist/express/requirePermission.d.ts.map +1 -0
- package/dist/express/types.d.ts +2 -0
- package/dist/express/types.d.ts.map +1 -0
- package/dist/express/types.js +3 -1
- package/dist/express/types.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/react/index.d.ts +1 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/rbac.d.ts +1 -0
- package/dist/react/rbac.d.ts.map +1 -0
- package/dist/react/routes.d.ts +1 -0
- package/dist/react/routes.d.ts.map +1 -0
- package/dist/routes/createRouteAccess.d.ts +3 -0
- package/dist/routes/createRouteAccess.d.ts.map +1 -0
- package/dist/routes/createRouteAccess.js +15 -33
- package/dist/routes/createRouteAccess.js.map +1 -1
- package/dist/routes/fromRows.d.ts +1 -0
- package/dist/routes/fromRows.d.ts.map +1 -0
- package/dist/routes/fromRows.js +21 -7
- package/dist/routes/fromRows.js.map +1 -1
- package/dist/routes/index.d.ts +2 -1
- package/dist/routes/index.d.ts.map +1 -0
- package/dist/routes/index.js +1 -1
- package/dist/routes/index.js.map +1 -1
- package/dist/routes/matching/path.d.ts +14 -0
- package/dist/routes/matching/path.d.ts.map +1 -0
- package/dist/routes/matching/path.js +49 -0
- package/dist/routes/matching/path.js.map +1 -0
- package/dist/routes/{pattern.d.ts → matching/pattern.d.ts} +5 -10
- package/dist/routes/matching/pattern.d.ts.map +1 -0
- package/dist/routes/{pattern.js → matching/pattern.js} +21 -27
- package/dist/routes/matching/pattern.js.map +1 -0
- package/dist/routes/rules.d.ts +14 -0
- package/dist/routes/rules.d.ts.map +1 -0
- package/dist/routes/rules.js +53 -0
- package/dist/routes/rules.js.map +1 -0
- package/dist/routes/types.d.ts +1 -0
- package/dist/routes/types.d.ts.map +1 -0
- package/dist/shared/errors.d.ts +1 -0
- package/dist/shared/errors.d.ts.map +1 -0
- package/dist/shared/roles.d.ts +4 -1
- package/dist/shared/roles.d.ts.map +1 -0
- package/dist/shared/roles.js +7 -3
- package/dist/shared/roles.js.map +1 -1
- package/dist/shared/validate.d.ts +14 -0
- package/dist/shared/validate.d.ts.map +1 -0
- package/dist/shared/validate.js +35 -0
- package/dist/shared/validate.js.map +1 -0
- package/docs/actions.md +3 -1
- package/docs/api-routes.md +21 -1
- package/docs/database.md +4 -0
- package/docs/pages.md +6 -0
- package/package.json +4 -3
- package/src/core/createRbac.ts +58 -0
- package/src/core/index.ts +2 -0
- package/src/core/rules.ts +69 -0
- package/src/core/types.ts +36 -0
- package/src/express/guardRoutes.ts +64 -0
- package/src/express/index.ts +12 -0
- package/src/express/requirePermission.ts +43 -0
- package/src/express/types.ts +45 -0
- package/src/index.ts +11 -0
- package/src/react/index.ts +10 -0
- package/src/react/rbac.tsx +49 -0
- package/src/react/routes.tsx +49 -0
- package/src/routes/createRouteAccess.ts +57 -0
- package/src/routes/fromRows.ts +61 -0
- package/src/routes/index.ts +5 -0
- package/src/routes/matching/path.ts +48 -0
- package/src/routes/matching/pattern.ts +67 -0
- package/src/routes/rules.ts +62 -0
- package/src/routes/types.ts +35 -0
- package/src/shared/errors.ts +17 -0
- package/src/shared/roles.ts +92 -0
- package/src/shared/validate.ts +37 -0
- package/dist/routes/pattern.js.map +0 -1
|
@@ -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
|
+
}
|
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
|
+
}
|