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
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { ForbiddenError } from '../shared/errors.js';
|
|
2
|
+
import { decide, pickRoles, resolveRoles } from '../shared/roles.js';
|
|
3
|
+
import { compilePattern } from './pattern.js';
|
|
4
|
+
function normalizeMethod(method) {
|
|
5
|
+
const upper = method.toUpperCase();
|
|
6
|
+
// Express runs GET handlers for HEAD requests, so HEAD has to obey GET rules,
|
|
7
|
+
// otherwise a HEAD request would get around a GET deny.
|
|
8
|
+
return upper === 'HEAD' ? 'GET' : upper;
|
|
9
|
+
}
|
|
10
|
+
function compileRule(rule, role) {
|
|
11
|
+
try {
|
|
12
|
+
if (typeof rule === 'string')
|
|
13
|
+
return { pattern: compilePattern(rule), methods: null };
|
|
14
|
+
const pattern = compilePattern(rule.path);
|
|
15
|
+
if (!rule.methods || rule.methods.includes('*'))
|
|
16
|
+
return { pattern, methods: null };
|
|
17
|
+
if (rule.methods.length === 0)
|
|
18
|
+
throw new Error(`rolegate: "methods" for "${rule.path}" is empty`);
|
|
19
|
+
return { pattern, methods: new Set(rule.methods.map(normalizeMethod)) };
|
|
20
|
+
}
|
|
21
|
+
catch (err) {
|
|
22
|
+
// Say which role the bad rule belongs to. With rules from a database,
|
|
23
|
+
// that's the first thing you'll want to know.
|
|
24
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
25
|
+
throw new Error(`${message} (in role "${role}")`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function hits(rules, path, method) {
|
|
29
|
+
return rules.some((r) => (r.methods === null || r.methods.has(method)) && r.pattern.test(path));
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Builds the route checker:
|
|
33
|
+
*
|
|
34
|
+
* const pages = createRouteAccess({
|
|
35
|
+
* roles: {
|
|
36
|
+
* user: { allow: ['/', '/posts/*'] },
|
|
37
|
+
* admin: { extends: ['user'], allow: ['/admin/*'] },
|
|
38
|
+
* },
|
|
39
|
+
* });
|
|
40
|
+
* pages.can('user', '/posts/42'); // true
|
|
41
|
+
* pages.can('user', '/admin/users'); // false
|
|
42
|
+
*/
|
|
43
|
+
export function createRouteAccess(config) {
|
|
44
|
+
const definitions = {};
|
|
45
|
+
for (const [name, role] of Object.entries(config.roles)) {
|
|
46
|
+
definitions[name] = {
|
|
47
|
+
extends: role.extends,
|
|
48
|
+
allow: (role.allow ?? []).map((r) => compileRule(r, name)),
|
|
49
|
+
deny: (role.deny ?? []).map((r) => compileRule(r, name)),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const known = resolveRoles(definitions);
|
|
53
|
+
const can = (roles, path, method = 'GET') => {
|
|
54
|
+
const m = normalizeMethod(method);
|
|
55
|
+
return decide(pickRoles(known, roles), (role) => hits(role.deny, path, m), (role) => hits(role.allow, path, m));
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
can,
|
|
59
|
+
assert(roles, path, method = 'GET') {
|
|
60
|
+
if (!can(roles, path, method))
|
|
61
|
+
throw new ForbiddenError(path, method.toUpperCase());
|
|
62
|
+
},
|
|
63
|
+
roles: Object.keys(config.roles),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
//# sourceMappingURL=createRouteAccess.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createRouteAccess.js","sourceRoot":"","sources":["../../src/routes/createRouteAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;A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I,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,EAClC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CACpC,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO;QACL,GAAG;QACH,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,GAAG,KAAK;YAChC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,CAAC;gBAAE,MAAM,IAAI,cAAc,CAAC,IAAI,EAAE,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC;QACtF,CAAC;QACD,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;KACjC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { RouteAccessConfig } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* One row from a "who can open what" table. Column names are up to you:
|
|
4
|
+
* map your rows to this shape and you're done.
|
|
5
|
+
*/
|
|
6
|
+
export interface RouteRow {
|
|
7
|
+
role: string;
|
|
8
|
+
path: string;
|
|
9
|
+
/** Leave empty to mean "any method", which is the usual case for pages. */
|
|
10
|
+
method?: string | null;
|
|
11
|
+
/** Defaults to 'allow'. */
|
|
12
|
+
effect?: 'allow' | 'deny' | null;
|
|
13
|
+
}
|
|
14
|
+
export interface FromRowsOptions {
|
|
15
|
+
/** Role inheritance, if you keep it somewhere too: `{ admin: ['editor'] }`. */
|
|
16
|
+
extends?: Record<string, string[]>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Turns flat table rows into a config for `createRouteAccess`.
|
|
20
|
+
*
|
|
21
|
+
* const rows = await db.query('SELECT role, path, method, effect FROM route_permissions');
|
|
22
|
+
* const access = createRouteAccess(routeConfigFromRows(rows));
|
|
23
|
+
*
|
|
24
|
+
* It doesn't check the patterns itself. `createRouteAccess` does that and
|
|
25
|
+
* tells you which role has the broken one.
|
|
26
|
+
*/
|
|
27
|
+
export declare function routeConfigFromRows(rows: Iterable<RouteRow>, options?: FromRowsOptions): RouteAccessConfig;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns flat table rows into a config for `createRouteAccess`.
|
|
3
|
+
*
|
|
4
|
+
* const rows = await db.query('SELECT role, path, method, effect FROM route_permissions');
|
|
5
|
+
* const access = createRouteAccess(routeConfigFromRows(rows));
|
|
6
|
+
*
|
|
7
|
+
* It doesn't check the patterns itself. `createRouteAccess` does that and
|
|
8
|
+
* tells you which role has the broken one.
|
|
9
|
+
*/
|
|
10
|
+
export function routeConfigFromRows(rows, options = {}) {
|
|
11
|
+
const roles = {};
|
|
12
|
+
const roleFor = (name) => (roles[name] ?? (roles[name] = {}));
|
|
13
|
+
for (const row of rows) {
|
|
14
|
+
const effect = row.effect ?? 'allow';
|
|
15
|
+
if (effect !== 'allow' && effect !== 'deny') {
|
|
16
|
+
throw new Error(`rolegate: unknown effect "${effect}" for role "${row.role}" on "${row.path}"`);
|
|
17
|
+
}
|
|
18
|
+
const role = roleFor(row.role);
|
|
19
|
+
const list = (role[effect] ?? (role[effect] = []));
|
|
20
|
+
list.push(row.method ? { path: row.path, methods: [row.method] } : row.path);
|
|
21
|
+
}
|
|
22
|
+
for (const [name, parents] of Object.entries(options.extends ?? {})) {
|
|
23
|
+
roleFor(name).extends = [...parents];
|
|
24
|
+
}
|
|
25
|
+
return { roles };
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=fromRows.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fromRows.js","sourceRoot":"","sources":["../../src/routes/fromRows.ts"],"names":[],"mappings":"AAoBA;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAAwB,EAAE,UAA2B,EAAE;IACzF,MAAM,KAAK,GAAoC,EAAE,CAAC;IAClD,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,MAAV,KAAK,CAAC,IAAI,IAAM,EAAE,EAAC,CAAC;IAEvD,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;QACrC,IAAI,MAAM,KAAK,OAAO,IAAI,MAAM,KAAK,MAAM,EAAE,CAAC;YAC5C,MAAM,IAAI,KAAK,CAAC,6BAA6B,MAAM,eAAe,GAAG,CAAC,IAAI,SAAS,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC;QAClG,CAAC;QACD,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC/B,MAAM,IAAI,GAAG,CAAC,IAAI,CAAC,MAAM,MAAX,IAAI,CAAC,MAAM,IAAM,EAAE,EAAC,CAAC;QACnC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC/E,CAAC;IAED,KAAK,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,EAAE,CAAC;QACpE,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,EAAE,KAAK,EAAE,CAAC;AACnB,CAAC"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { createRouteAccess } from './createRouteAccess.js';
|
|
2
|
+
export { routeConfigFromRows } from './fromRows.js';
|
|
3
|
+
export { normalizePath } from './pattern.js';
|
|
4
|
+
export type { RouteAccess, RouteAccessConfig, RouteRoleConfig, RouteRule } from './types.js';
|
|
5
|
+
export type { RouteRow, FromRowsOptions } from './fromRows.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC"}
|
|
@@ -0,0 +1,28 @@
|
|
|
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 non-empty 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
|
+
export interface RoutePattern {
|
|
15
|
+
/** The pattern exactly as it was written, handy in error messages. */
|
|
16
|
+
readonly source: string;
|
|
17
|
+
test(path: string): boolean;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Brings a path to the form we compare against:
|
|
21
|
+
* no query or hash, no repeated or trailing slashes, lowercase.
|
|
22
|
+
*
|
|
23
|
+
* Lowercase because Express and React Router both match routes case-insensitively
|
|
24
|
+
* by default. If we were stricter than the router, someone could open
|
|
25
|
+
* "/ADMIN/users", slip past a deny written for "/admin/*" and still land on the admin page.
|
|
26
|
+
*/
|
|
27
|
+
export declare function normalizePath(path: string): string;
|
|
28
|
+
export declare function compilePattern(pattern: string): RoutePattern;
|
|
@@ -0,0 +1,63 @@
|
|
|
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 non-empty 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
|
+
* Brings a path to the form we compare against:
|
|
16
|
+
* no query or hash, no repeated or trailing slashes, lowercase.
|
|
17
|
+
*
|
|
18
|
+
* Lowercase because Express and React Router both match routes case-insensitively
|
|
19
|
+
* by default. If we were stricter than the router, someone could open
|
|
20
|
+
* "/ADMIN/users", slip past a deny written for "/admin/*" and still land on the admin page.
|
|
21
|
+
*/
|
|
22
|
+
export function normalizePath(path) {
|
|
23
|
+
let clean = path.split(/[?#]/, 1)[0];
|
|
24
|
+
clean = ('/' + clean).replace(/\/{2,}/g, '/');
|
|
25
|
+
if (clean.length > 1)
|
|
26
|
+
clean = clean.replace(/\/$/, '');
|
|
27
|
+
return clean.toLowerCase();
|
|
28
|
+
}
|
|
29
|
+
const PARAM = /^:[A-Za-z0-9_]+$/;
|
|
30
|
+
function segmentsOf(path) {
|
|
31
|
+
// "/" -> [], "/posts/42" -> ["posts", "42"]
|
|
32
|
+
return path === '/' ? [] : path.slice(1).split('/');
|
|
33
|
+
}
|
|
34
|
+
export function compilePattern(pattern) {
|
|
35
|
+
const fail = (why) => {
|
|
36
|
+
throw new Error(`rolegate: bad route pattern "${pattern}": ${why}`);
|
|
37
|
+
};
|
|
38
|
+
if (pattern === '*')
|
|
39
|
+
return { source: pattern, test: () => true };
|
|
40
|
+
if (typeof pattern !== 'string' || !pattern.startsWith('/'))
|
|
41
|
+
fail('it should start with "/" (or be just "*")');
|
|
42
|
+
if (/[?#]/.test(pattern))
|
|
43
|
+
fail('query strings and hashes are not part of a route');
|
|
44
|
+
const parts = segmentsOf(normalizePath(pattern));
|
|
45
|
+
const wildcard = parts[parts.length - 1] === '*';
|
|
46
|
+
const fixed = wildcard ? parts.slice(0, -1) : parts;
|
|
47
|
+
for (const part of fixed) {
|
|
48
|
+
if (part.includes('*'))
|
|
49
|
+
fail('"*" is only allowed as the last segment, like "/admin/*"');
|
|
50
|
+
if (part.startsWith(':') && !PARAM.test(part))
|
|
51
|
+
fail(`"${part}" is not a valid parameter (use something like ":id")`);
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
source: pattern,
|
|
55
|
+
test(path) {
|
|
56
|
+
const actual = segmentsOf(normalizePath(path));
|
|
57
|
+
if (wildcard ? actual.length < fixed.length : actual.length !== fixed.length)
|
|
58
|
+
return false;
|
|
59
|
+
return fixed.every((part, i) => (part.startsWith(':') ? actual[i] !== '' : part === actual[i]));
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=pattern.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../src/routes/pattern.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAQH;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY;IACxC,IAAI,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrC,KAAK,GAAG,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;IAC9C,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;QAAE,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACvD,OAAO,KAAK,C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I,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;YAAE,IAAI,CAAC,IAAI,IAAI,uDAAuD,CAAC,CAAC;IACvH,CAAC;IAED,OAAO;QACL,MAAM,EAAE,OAAO;QACf,IAAI,CAAC,IAAI;YACP,MAAM,MAAM,GAAG,UAAU,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;YAC/C,IAAI,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;gBAAE,OAAO,KAAK,CAAC;YAC3F,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAClG,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Roles } from '../shared/roles.js';
|
|
2
|
+
/**
|
|
3
|
+
* A route a role may (or may not) open.
|
|
4
|
+
*
|
|
5
|
+
* - A string, e.g. '/dashboard' or '/admin/*': any HTTP method. That's all
|
|
6
|
+
* you need for frontend pages.
|
|
7
|
+
* - An object with `methods`, e.g. `{ path: '/posts/:id', methods: ['PUT', 'DELETE'] }`,
|
|
8
|
+
* when you care about the method, which mostly happens with API routes.
|
|
9
|
+
*/
|
|
10
|
+
export type RouteRule = string | {
|
|
11
|
+
path: string;
|
|
12
|
+
methods?: readonly string[];
|
|
13
|
+
};
|
|
14
|
+
export interface RouteRoleConfig {
|
|
15
|
+
/** Take all routes of these roles, then add (or deny) on top. */
|
|
16
|
+
extends?: string[];
|
|
17
|
+
allow?: RouteRule[];
|
|
18
|
+
/** Wins over any allow, including inherited ones. */
|
|
19
|
+
deny?: RouteRule[];
|
|
20
|
+
}
|
|
21
|
+
export interface RouteAccessConfig {
|
|
22
|
+
roles: Record<string, RouteRoleConfig>;
|
|
23
|
+
}
|
|
24
|
+
export interface RouteAccess {
|
|
25
|
+
/**
|
|
26
|
+
* Can these roles open `path`? `method` defaults to GET, which is what
|
|
27
|
+
* "open a page" means. HEAD is checked as GET, same as Express handles it.
|
|
28
|
+
*/
|
|
29
|
+
can(roles: Roles, path: string, method?: string): boolean;
|
|
30
|
+
/** Same question, but throws ForbiddenError when the answer is no. */
|
|
31
|
+
assert(roles: Roles, path: string, method?: string): void;
|
|
32
|
+
/** Every role name from the config. */
|
|
33
|
+
readonly roles: readonly string[];
|
|
34
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/routes/types.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown by `assert()` in both engines.
|
|
3
|
+
*
|
|
4
|
+
* For resource checks it reads like "cannot delete posts",
|
|
5
|
+
* for route checks like "cannot DELETE /posts/42".
|
|
6
|
+
*/
|
|
7
|
+
export declare class ForbiddenError extends Error {
|
|
8
|
+
readonly resource: string;
|
|
9
|
+
readonly action: string;
|
|
10
|
+
constructor(resource: string, action: string);
|
|
11
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown by `assert()` in both engines.
|
|
3
|
+
*
|
|
4
|
+
* For resource checks it reads like "cannot delete posts",
|
|
5
|
+
* for route checks like "cannot DELETE /posts/42".
|
|
6
|
+
*/
|
|
7
|
+
export class ForbiddenError extends Error {
|
|
8
|
+
constructor(resource, action) {
|
|
9
|
+
super(`Forbidden: cannot ${action} ${resource}`);
|
|
10
|
+
this.name = 'ForbiddenError';
|
|
11
|
+
this.resource = resource;
|
|
12
|
+
this.action = action;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/shared/errors.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,OAAO,cAAe,SAAQ,KAAK;IAIvC,YAAY,QAAgB,EAAE,MAAc;QAC1C,KAAK,CAAC,qBAAqB,MAAM,IAAI,QAAQ,EAAE,CAAC,CAAC;QACjD,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;QAC7B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Role plumbing shared by both engines (resource checks and route checks).
|
|
3
|
+
*
|
|
4
|
+
* Both of them have the same idea of a role: it can extend other roles,
|
|
5
|
+
* it has things it allows and things it denies, and a deny always wins.
|
|
6
|
+
* The only difference is what a single "rule" looks like, so this file
|
|
7
|
+
* is generic over the rule type and doesn't care what's inside.
|
|
8
|
+
*/
|
|
9
|
+
/** One role, or several, or nobody (not signed in). */
|
|
10
|
+
export type Roles = string | readonly string[] | undefined;
|
|
11
|
+
export interface RoleDefinition<R> {
|
|
12
|
+
extends?: readonly string[];
|
|
13
|
+
allow?: readonly R[];
|
|
14
|
+
deny?: readonly R[];
|
|
15
|
+
}
|
|
16
|
+
/** A role after inheritance is applied: its own rules plus everything from its parents. */
|
|
17
|
+
export interface ResolvedRole<R> {
|
|
18
|
+
allow: R[];
|
|
19
|
+
deny: R[];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Flattens `extends` for every role and returns them in a Map.
|
|
23
|
+
*
|
|
24
|
+
* We do it for the whole config right away, so a typo in a role name or a
|
|
25
|
+
* circular `extends` blows up when the app starts and not in the middle of a request.
|
|
26
|
+
*/
|
|
27
|
+
export declare function resolveRoles<R>(definitions: Record<string, RoleDefinition<R>>): Map<string, ResolvedRole<R>>;
|
|
28
|
+
/** Turns whatever the app gave us into the resolved roles we actually know about. */
|
|
29
|
+
export declare function pickRoles<T>(known: Map<string, T>, roles: Roles): T[];
|
|
30
|
+
/**
|
|
31
|
+
* The one rule of the whole library: if any role denies, the answer is no.
|
|
32
|
+
* Otherwise it's yes if at least one role allows. No roles at all means no.
|
|
33
|
+
*/
|
|
34
|
+
export declare function decide<T>(roles: T[], denies: (role: T) => boolean, allows: (role: T) => boolean): boolean;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Role plumbing shared by both engines (resource checks and route checks).
|
|
3
|
+
*
|
|
4
|
+
* Both of them have the same idea of a role: it can extend other roles,
|
|
5
|
+
* it has things it allows and things it denies, and a deny always wins.
|
|
6
|
+
* The only difference is what a single "rule" looks like, so this file
|
|
7
|
+
* is generic over the rule type and doesn't care what's inside.
|
|
8
|
+
*/
|
|
9
|
+
const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
|
|
10
|
+
/**
|
|
11
|
+
* Flattens `extends` for every role and returns them in a Map.
|
|
12
|
+
*
|
|
13
|
+
* We do it for the whole config right away, so a typo in a role name or a
|
|
14
|
+
* circular `extends` blows up when the app starts and not in the middle of a request.
|
|
15
|
+
*/
|
|
16
|
+
export function resolveRoles(definitions) {
|
|
17
|
+
const resolved = new Map();
|
|
18
|
+
const resolve = (name, trail) => {
|
|
19
|
+
const cached = resolved.get(name);
|
|
20
|
+
if (cached)
|
|
21
|
+
return cached;
|
|
22
|
+
// hasOwn, not `in`: otherwise a role called "constructor" would quietly
|
|
23
|
+
// pick up Object.prototype.constructor and look like a real role.
|
|
24
|
+
if (!hasOwn(definitions, name)) {
|
|
25
|
+
const from = trail.length ? trail.join(' -> ') : 'config';
|
|
26
|
+
throw new Error(`rolegate: unknown role "${name}" (referenced by ${from})`);
|
|
27
|
+
}
|
|
28
|
+
if (trail.includes(name)) {
|
|
29
|
+
throw new Error(`rolegate: circular "extends": ${[...trail, name].join(' -> ')}`);
|
|
30
|
+
}
|
|
31
|
+
const def = definitions[name];
|
|
32
|
+
const role = { allow: [], deny: [] };
|
|
33
|
+
for (const parent of def.extends ?? []) {
|
|
34
|
+
const p = resolve(parent, [...trail, name]);
|
|
35
|
+
role.allow.push(...p.allow);
|
|
36
|
+
role.deny.push(...p.deny);
|
|
37
|
+
}
|
|
38
|
+
role.allow.push(...(def.allow ?? []));
|
|
39
|
+
role.deny.push(...(def.deny ?? []));
|
|
40
|
+
resolved.set(name, role);
|
|
41
|
+
return role;
|
|
42
|
+
};
|
|
43
|
+
for (const name of Object.keys(definitions))
|
|
44
|
+
resolve(name, []);
|
|
45
|
+
return resolved;
|
|
46
|
+
}
|
|
47
|
+
/** Turns whatever the app gave us into the resolved roles we actually know about. */
|
|
48
|
+
export function pickRoles(known, roles) {
|
|
49
|
+
const list = typeof roles === 'string' ? [roles] : roles ?? [];
|
|
50
|
+
const picked = [];
|
|
51
|
+
for (const name of list) {
|
|
52
|
+
const role = known.get(name);
|
|
53
|
+
if (role)
|
|
54
|
+
picked.push(role);
|
|
55
|
+
}
|
|
56
|
+
return picked;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The one rule of the whole library: if any role denies, the answer is no.
|
|
60
|
+
* Otherwise it's yes if at least one role allows. No roles at all means no.
|
|
61
|
+
*/
|
|
62
|
+
export function decide(roles, denies, allows) {
|
|
63
|
+
if (roles.length === 0)
|
|
64
|
+
return false;
|
|
65
|
+
if (roles.some(denies))
|
|
66
|
+
return false;
|
|
67
|
+
return roles.some(allows);
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=roles.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"roles.js","sourceRoot":"","sources":["../../src/shared/roles.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAiBH,MAAM,MAAM,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AAI,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,OAAO,KAAK,CAAC;IACrC,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,CAAC"}
|
package/docs/actions.md
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# Actions on resources
|
|
2
|
+
|
|
3
|
+
This is the classic part of rolegate: roles that may perform actions on resources. Use it when the question is "may this user **do** something", like edit a post or delete a comment, as opposed to "may they **open** a page" (that's [routes](pages.md)).
|
|
4
|
+
|
|
5
|
+
## The basics
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { createRbac } from 'rolegate';
|
|
9
|
+
|
|
10
|
+
export const rbac = createRbac({
|
|
11
|
+
roles: {
|
|
12
|
+
viewer: { allow: { posts: ['read'] } },
|
|
13
|
+
editor: { extends: ['viewer'], allow: { posts: ['write'], comments: ['read', 'write'] } },
|
|
14
|
+
admin: { allow: { '*': ['*'] } },
|
|
15
|
+
blocked: { deny: { '*': ['*'] } },
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
rbac.can('editor', 'posts', 'write'); // true
|
|
20
|
+
rbac.can('viewer', 'posts', 'write'); // false
|
|
21
|
+
rbac.can(['editor', 'blocked'], 'posts', 'read'); // false, a deny in any role wins
|
|
22
|
+
rbac.assert('viewer', 'posts', 'write'); // throws ForbiddenError
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Resource and action names are plain strings, so call them whatever fits your app. `'*'` means "any resource" or "any action".
|
|
26
|
+
|
|
27
|
+
## Conditions
|
|
28
|
+
|
|
29
|
+
Sometimes a role may do something only in certain cases, like deleting **their own** posts. That's what `when` is for:
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
type Ctx = { userId?: number; ownerId?: number };
|
|
33
|
+
|
|
34
|
+
// Make sure userId is actually there. Otherwise undefined === undefined is true,
|
|
35
|
+
// and anyone gets access the moment you forget to pass a context.
|
|
36
|
+
const isOwner = (c: Ctx) => c.userId !== undefined && c.userId === c.ownerId;
|
|
37
|
+
|
|
38
|
+
const rbac = createRbac<Ctx>({
|
|
39
|
+
roles: {
|
|
40
|
+
author: { allow: { posts: [{ action: 'delete', when: isOwner }] } },
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
rbac.can('author', 'posts', 'delete', { userId: 1, ownerId: 1 }); // true
|
|
45
|
+
rbac.can('author', 'posts', 'delete', { userId: 1, ownerId: 2 }); // false
|
|
46
|
+
rbac.can('author', 'posts', 'delete'); // false, no context means no access
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
> When you don't pass a context, `when` gets `{}`. Write your conditions so that missing data means "no".
|
|
50
|
+
|
|
51
|
+
Conditions are functions, so they live in code. If you keep permissions in a database, keep the simple ones there and leave the conditional rules here.
|
|
52
|
+
|
|
53
|
+
## Express
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import { requirePermission } from 'rolegate/express';
|
|
57
|
+
|
|
58
|
+
app.delete('/posts/:id', requirePermission(rbac, 'posts', 'delete'), handler);
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
By default it reads roles from `req.user.roles` (or `req.user.role`). It sends `401` if there are none and `403` if the action isn't allowed. Express isn't actually required: anything with `(req, res, next)` and `res.status().json()` works.
|
|
62
|
+
|
|
63
|
+
To pass a context, annotate the request type so you get proper typings:
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
import type { Request } from 'express';
|
|
67
|
+
|
|
68
|
+
app.put('/posts/:id', loadPost, requirePermission(rbac, 'posts', 'update', {
|
|
69
|
+
getContext: (req: Request) => ({ userId: req.user?.id, ownerId: req.post?.authorId }),
|
|
70
|
+
}), handler);
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`getContext` is synchronous. Load what it needs in an earlier middleware (`loadPost` above), or skip the middleware and call `rbac.assert()` inside your async handler.
|
|
74
|
+
|
|
75
|
+
If you rebuild `rbac` at runtime, pass a function instead of the object, `requirePermission(() => rbac, ...)`, and the middleware will always use the latest one.
|
|
76
|
+
|
|
77
|
+
## React
|
|
78
|
+
|
|
79
|
+
```tsx
|
|
80
|
+
import { RbacProvider, Can, useCan } from 'rolegate/react';
|
|
81
|
+
|
|
82
|
+
<RbacProvider rbac={rbac} roles={user.roles}>
|
|
83
|
+
<Can resource="posts" action="write" fallback={<span>Read only</span>}>
|
|
84
|
+
<EditButton />
|
|
85
|
+
</Can>
|
|
86
|
+
</RbacProvider>;
|
|
87
|
+
|
|
88
|
+
const can = useCan();
|
|
89
|
+
if (can('posts', 'delete', { userId, ownerId })) { /* ... */ }
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
> Checks in the UI only make the interface nicer. Always check on the server too.
|
|
93
|
+
|
|
94
|
+
## Example: a blog where people manage their own posts
|
|
95
|
+
|
|
96
|
+
Every signed-in user can read all posts and write new ones, but can only edit and delete **their own**. Guests get a `401`.
|
|
97
|
+
|
|
98
|
+
Two things are up to your app, rolegate doesn't do them:
|
|
99
|
+
|
|
100
|
+
- **Authentication**: something that sets `req.user = { id, roles: ['user'] }`.
|
|
101
|
+
- **Ownership**: store `authorId` on every post and pass it in the context.
|
|
102
|
+
|
|
103
|
+
**1. Shared permissions**, imported by both the server and the client:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
// shared/permissions.ts
|
|
107
|
+
import { createRbac } from 'rolegate';
|
|
108
|
+
|
|
109
|
+
export type Ctx = { userId?: number; ownerId?: number };
|
|
110
|
+
const isOwner = (c: Ctx) => c.userId !== undefined && c.userId === c.ownerId;
|
|
111
|
+
|
|
112
|
+
export const rbac = createRbac<Ctx>({
|
|
113
|
+
roles: {
|
|
114
|
+
user: {
|
|
115
|
+
allow: {
|
|
116
|
+
posts: ['read', 'create', { action: 'update', when: isOwner }, { action: 'delete', when: isOwner }],
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
admin: { allow: { '*': ['*'] } },
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
**2. The server**, where the check that actually matters happens:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
import express from 'express';
|
|
128
|
+
import { ForbiddenError } from 'rolegate';
|
|
129
|
+
import { requirePermission } from 'rolegate/express';
|
|
130
|
+
import { rbac } from '../shared/permissions.js';
|
|
131
|
+
|
|
132
|
+
const app = express();
|
|
133
|
+
app.use(authenticate); // your auth, sets req.user
|
|
134
|
+
|
|
135
|
+
app.get('/posts', requirePermission(rbac, 'posts', 'read'), listPosts);
|
|
136
|
+
app.post('/posts', requirePermission(rbac, 'posts', 'create'), async (req, res) => {
|
|
137
|
+
const post = await db.posts.create({ ...req.body, authorId: req.user!.id });
|
|
138
|
+
res.status(201).json(post);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
app.delete('/posts/:id', async (req, res, next) => {
|
|
142
|
+
try {
|
|
143
|
+
const post = await db.posts.find(req.params.id);
|
|
144
|
+
rbac.assert(req.user?.roles, 'posts', 'delete', { userId: req.user?.id, ownerId: post.authorId });
|
|
145
|
+
await db.posts.delete(post.id);
|
|
146
|
+
res.sendStatus(204);
|
|
147
|
+
} catch (err) {
|
|
148
|
+
next(err);
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
app.use((err, _req, res, next) => {
|
|
153
|
+
if (err instanceof ForbiddenError) return res.status(403).json({ error: err.message });
|
|
154
|
+
next(err);
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
**3. The client** hides what the user can't do anyway:
|
|
159
|
+
|
|
160
|
+
```tsx
|
|
161
|
+
import { RbacProvider, Can, useCan } from 'rolegate/react';
|
|
162
|
+
import { rbac } from '../shared/permissions';
|
|
163
|
+
|
|
164
|
+
<RbacProvider rbac={rbac} roles={me?.roles}>
|
|
165
|
+
<Can resource="posts" action="create"><NewPostButton /></Can>
|
|
166
|
+
<PostList />
|
|
167
|
+
</RbacProvider>;
|
|
168
|
+
|
|
169
|
+
function PostCard({ post }) {
|
|
170
|
+
const can = useCan();
|
|
171
|
+
const ctx = { userId: me.id, ownerId: post.authorId };
|
|
172
|
+
return (
|
|
173
|
+
<article>
|
|
174
|
+
<h2>{post.title}</h2>
|
|
175
|
+
{can('posts', 'update', ctx) && <EditButton />}
|
|
176
|
+
{can('posts', 'delete', ctx) && <DeleteButton />}
|
|
177
|
+
</article>
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
rolegate checks one action on one object at a time. For a "My posts" page, filter in the query (`WHERE author_id = :me`) instead of checking every row.
|