@anievo-id/rbac-evolution-hono 0.5.0 → 0.6.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/dist/index.cjs +15 -67
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +15 -67
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var rbacEvolution = require('@anievo-id/rbac-evolution');
|
|
4
|
+
|
|
3
5
|
// src/middleware.ts
|
|
4
6
|
function rbacMiddleware(options) {
|
|
5
7
|
const { rbac, getSubject, guard, team } = options;
|
|
@@ -18,8 +20,6 @@ function rbacMiddleware(options) {
|
|
|
18
20
|
await next();
|
|
19
21
|
};
|
|
20
22
|
}
|
|
21
|
-
|
|
22
|
-
// src/guards.ts
|
|
23
23
|
var RbacMiddlewareMissingError = class extends Error {
|
|
24
24
|
code = "RBAC_MIDDLEWARE_MISSING";
|
|
25
25
|
constructor() {
|
|
@@ -27,102 +27,50 @@ var RbacMiddlewareMissingError = class extends Error {
|
|
|
27
27
|
this.name = "RbacMiddlewareMissingError";
|
|
28
28
|
}
|
|
29
29
|
};
|
|
30
|
-
var
|
|
31
|
-
permission: "User does not have the right permissions.",
|
|
32
|
-
role: "User does not have the right roles.",
|
|
33
|
-
role_or_permission: "User does not have any of the necessary access rights."
|
|
34
|
-
};
|
|
35
|
-
var defaultUnauthenticated = (c) => c.json({ error: "UNAUTHENTICATED", message: "User is not logged in." }, 401);
|
|
30
|
+
var defaultUnauthenticated = (c) => c.json({ error: "UNAUTHENTICATED", message: rbacEvolution.UNAUTHENTICATED_MESSAGE }, 401);
|
|
36
31
|
var defaultForbidden = (expose) => (c, context) => c.json(
|
|
37
32
|
{
|
|
38
33
|
error: "FORBIDDEN",
|
|
39
34
|
reason: context.kind,
|
|
40
|
-
message:
|
|
35
|
+
message: rbacEvolution.REQUIREMENT_MESSAGES[context.kind],
|
|
41
36
|
...expose && { required: context.requirements }
|
|
42
37
|
},
|
|
43
38
|
403
|
|
44
39
|
);
|
|
45
|
-
|
|
46
|
-
function toGroups(names) {
|
|
47
|
-
const groups = [];
|
|
48
|
-
for (const name of names) {
|
|
49
|
-
for (const item of typeof name === "string" ? [name] : name) {
|
|
50
|
-
const group = split(item);
|
|
51
|
-
if (group.length > 0) groups.push(group);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
return groups;
|
|
55
|
-
}
|
|
56
|
-
function parseArgs(args) {
|
|
57
|
-
const last = args[args.length - 1];
|
|
58
|
-
if (last !== void 0 && typeof last === "object" && !Array.isArray(last)) {
|
|
59
|
-
return { names: args.slice(0, -1), options: last };
|
|
60
|
-
}
|
|
61
|
-
return { names: args, options: void 0 };
|
|
62
|
-
}
|
|
63
|
-
function createGuard(kind, requirements, handlers, check) {
|
|
64
|
-
if (requirements.length === 0) {
|
|
65
|
-
throw new TypeError(`[rbac-evolution] A ${kind} guard needs at least one name.`);
|
|
66
|
-
}
|
|
40
|
+
function createGuard(requirement, handlers) {
|
|
67
41
|
const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated;
|
|
68
42
|
const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false);
|
|
69
|
-
const context = { kind, requirements };
|
|
43
|
+
const context = { kind: requirement.kind, requirements: requirement.requirements };
|
|
70
44
|
return async (c, next) => {
|
|
71
45
|
const rbac = c.get("rbac");
|
|
72
46
|
if (rbac === void 0) throw new RbacMiddlewareMissingError();
|
|
73
47
|
if (rbac === null) return onUnauthenticated(c, context);
|
|
74
|
-
if (await
|
|
48
|
+
if (await rbacEvolution.satisfiesRequirement(rbac, requirement)) {
|
|
75
49
|
await next();
|
|
76
50
|
return;
|
|
77
51
|
}
|
|
78
52
|
return onForbidden(c, context);
|
|
79
53
|
};
|
|
80
54
|
}
|
|
81
|
-
async function every(groups, test) {
|
|
82
|
-
for (const group of groups) {
|
|
83
|
-
if (!await test(group)) return false;
|
|
84
|
-
}
|
|
85
|
-
return true;
|
|
86
|
-
}
|
|
87
55
|
function createGuards(defaults = {}) {
|
|
88
56
|
function requirePermission2(...args) {
|
|
89
|
-
const { names, options = {} } =
|
|
90
|
-
|
|
91
|
-
const requirements = options.any ? [groups.flat()] : groups;
|
|
92
|
-
return createGuard(
|
|
93
|
-
"permission",
|
|
94
|
-
requirements,
|
|
95
|
-
{ ...defaults, ...options },
|
|
96
|
-
(rbac) => every(requirements, (group) => rbac.canAny(group))
|
|
97
|
-
);
|
|
57
|
+
const { names, options = {} } = rbacEvolution.splitRequirementArgs(args);
|
|
58
|
+
return createGuard(rbacEvolution.permissionRequirement(names, options), { ...defaults, ...options });
|
|
98
59
|
}
|
|
99
60
|
function requireRole2(...args) {
|
|
100
|
-
const { names, options = {} } =
|
|
101
|
-
|
|
102
|
-
const requirements = options.all ? all.map((r) => [r]) : [all];
|
|
103
|
-
return createGuard(
|
|
104
|
-
"role",
|
|
105
|
-
requirements,
|
|
106
|
-
{ ...defaults, ...options },
|
|
107
|
-
async (rbac) => options.all ? rbac.hasAllRoles(all) : rbac.hasAnyRole(all)
|
|
108
|
-
);
|
|
61
|
+
const { names, options = {} } = rbacEvolution.splitRequirementArgs(args);
|
|
62
|
+
return createGuard(rbacEvolution.roleRequirement(names, options), { ...defaults, ...options });
|
|
109
63
|
}
|
|
110
64
|
function requireRoleOrPermission2(...args) {
|
|
111
|
-
const { names, options = {} } =
|
|
112
|
-
|
|
113
|
-
return createGuard(
|
|
114
|
-
"role_or_permission",
|
|
115
|
-
[all],
|
|
116
|
-
{ ...defaults, ...options },
|
|
117
|
-
async (rbac) => await rbac.hasAnyRole(all) || rbac.canAny(all)
|
|
118
|
-
);
|
|
65
|
+
const { names, options = {} } = rbacEvolution.splitRequirementArgs(args);
|
|
66
|
+
return createGuard(rbacEvolution.roleOrPermissionRequirement(names), { ...defaults, ...options });
|
|
119
67
|
}
|
|
120
68
|
function canAny2(...args) {
|
|
121
|
-
const { names, options } =
|
|
69
|
+
const { names, options } = rbacEvolution.splitRequirementArgs(args);
|
|
122
70
|
return requirePermission2(...names, { ...options, any: true });
|
|
123
71
|
}
|
|
124
72
|
function canAll2(...args) {
|
|
125
|
-
const { names, options } =
|
|
73
|
+
const { names, options } = rbacEvolution.splitRequirementArgs(args);
|
|
126
74
|
return requirePermission2(...names, { ...options, any: false });
|
|
127
75
|
}
|
|
128
76
|
return { requirePermission: requirePermission2, requireRole: requireRole2, requireRoleOrPermission: requireRoleOrPermission2, canAny: canAny2, canAll: canAll2 };
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/middleware.ts","../src/guards.ts"],"names":["requirePermission","requireRole","requireRoleOrPermission","canAny","canAll"],"mappings":";;;AAwCO,SAAS,eAAoC,OAAA,EAAmE;AACrH,EAAA,MAAM,EAAE,IAAA,EAAM,UAAA,EAAY,KAAA,EAAO,MAAK,GAAI,OAAA;AAE1C,EAAA,OAAO,OAAO,GAAG,IAAA,KAAS;AACxB,IAAA,MAAM,GAAA,GAAM,CAAA;AACZ,IAAA,MAAM,OAAA,GAAU,MAAM,UAAA,CAAW,GAAG,CAAA;AACpC,IAAA,IAAI,KAAA,GAA4B,IAAA;AAChC,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,MAAM,MAAA,GAAS,IAAA,GAAO,MAAM,IAAA,CAAK,GAAG,CAAA,GAAI,MAAA;AACxC,MAAA,KAAA,GAAQ,IAAA,CAAK,IAAI,OAAA,EAAS;AAAA,QACxB,GAAI,KAAA,KAAU,MAAA,IAAa,EAAE,KAAA,EAAM;AAAA,QACnC,GAAI,MAAA,KAAW,MAAA,IAAa,EAAE,MAAM,MAAA;AAAO,OAC5C,CAAA;AAAA,IACH;AACC,IAAC,CAAA,CAAkC,GAAA,CAAI,MAAA,EAAQ,KAAK,CAAA;AACr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AC/D;AAEA,EAAA,OAAO,EAAE,iBAAA,EAAAA,kBAAAA,EAAmB,WAAA,EAAAC,YAAAA,EAAa,yBAAAC,wBAAAA,EAAyB,MAAA,EAAAC,OAAAA,EAAQ,MAAA,EAAAC,OAAAA,EAAO;AACnF;AAEO,IAAM,EAAE,iBAAA,EAAmB,WAAA,EAAa,yBAAyB,MAAA,EAAQ,MAAA,KAAW,YAAA","file":"index.cjs","sourcesContent":["import type { Rbac, Subject, SubjectRbac, TeamId } from '@anievo-id/rbac-evolution'\nimport type { Context, Env, MiddlewareHandler } from 'hono'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** Context variables set by `rbacMiddleware()`. */\nexport type RbacVariables = {\n /** Roles & permissions of the current subject. `null` for guests. */\n rbac: SubjectRbac | null\n}\n\n/**\n * Hono env for apps using `rbacMiddleware()`: `new Hono<RbacEnv>()` types `c.var.rbac`.\n * Combine it with your own variables: `new Hono<{ Variables: RbacVariables & { user: User } }>()`.\n */\nexport type RbacEnv = {\n Variables: RbacVariables\n}\n\nexport interface RbacMiddlewareOptions<E extends Env = Env> {\n /** The RBAC engine created with `createRbac(...)`. */\n rbac: Rbac\n /**\n * Resolves the authenticated subject for this request (e.g. from `c.var.user` or a JWT payload).\n * Return `null` / `undefined` for guests.\n */\n getSubject: (c: Context<E>) => MaybePromise<Subject | null | undefined>\n /** Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. */\n guard?: string\n /** Resolves the current team (only when the engine was created with `teams: true`). */\n team?: (c: Context<E>) => MaybePromise<TeamId | undefined>\n}\n\n/**\n * Resolves the current subject and sets `c.var.rbac` (a `SubjectRbac`, or `null` for guests).\n *\n * ```ts\n * app.use(rbacMiddleware({ rbac, getSubject: (c) => (c.var.user ? { type: 'user', id: c.var.user.id } : null) }))\n * ```\n */\nexport function rbacMiddleware<E extends Env = Env>(options: RbacMiddlewareOptions<E>): MiddlewareHandler<E & RbacEnv> {\n const { rbac, getSubject, guard, team } = options\n\n return async (c, next) => {\n const ctx = c as unknown as Context<E>\n const subject = await getSubject(ctx)\n let value: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(ctx) : undefined\n value = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n ;(c as unknown as Context<RbacEnv>).set('rbac', value)\n await next()\n }\n}\n","import type { SubjectRbac } from '@anievo-id/rbac-evolution'\nimport type { Context, MiddlewareHandler } from 'hono'\nimport type { RbacEnv } from './middleware'\n\nexport type GuardKind = 'permission' | 'role' | 'role_or_permission'\n\n/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */\nexport interface GuardContext {\n kind: GuardKind\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\n requirements: string[][]\n}\n\n/** Returns the response to send (or throws, e.g. an `HTTPException`). */\nexport type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>\n\nexport interface GuardHandlers {\n /** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */\n onUnauthenticated?: GuardHandler\n /** Called when the subject lacks access. Default: 403 JSON. */\n onForbidden?: GuardHandler\n /**\n * Include the required roles/permissions in the default 403 body.\n * Default: `false` (like spatie's `display_permission_in_exception`).\n */\n exposeRequirements?: boolean\n}\n\nexport interface PermissionGuardOptions extends GuardHandlers {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean\n}\n\nexport interface RoleGuardOptions extends GuardHandlers {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean\n}\n\nexport type RoleOrPermissionGuardOptions = GuardHandlers\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = string | readonly string[]\n\nexport class RbacMiddlewareMissingError extends Error {\n readonly code = 'RBAC_MIDDLEWARE_MISSING'\n\n constructor() {\n super('`c.var.rbac` is not set. Register `rbacMiddleware()` before using RBAC guards.')\n this.name = 'RbacMiddlewareMissingError'\n }\n}\n\nconst MESSAGES: Record<GuardKind, string> = {\n permission: 'User does not have the right permissions.',\n role: 'User does not have the right roles.',\n role_or_permission: 'User does not have any of the necessary access rights.',\n}\n\nconst defaultUnauthenticated: GuardHandler = (c) =>\n c.json({ error: 'UNAUTHENTICATED', message: 'User is not logged in.' }, 401)\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (c, context) =>\n c.json(\n {\n error: 'FORBIDDEN',\n reason: context.kind,\n message: MESSAGES[context.kind],\n ...(expose && { required: context.requirements }),\n },\n 403,\n )\n\nconst split = (name: string): string[] =>\n name\n .split('|')\n .map((n) => n.trim())\n .filter((n) => n !== '')\n\n/** Each argument is a group (pipes = any within the group); arrays contribute one group per item. */\nfunction toGroups(names: readonly GuardNames[]): string[][] {\n const groups: string[][] = []\n for (const name of names) {\n for (const item of typeof name === 'string' ? [name] : name) {\n const group = split(item)\n if (group.length > 0) groups.push(group)\n }\n }\n return groups\n}\n\nfunction parseArgs<O extends object>(args: readonly (GuardNames | O)[]): { names: GuardNames[]; options: O | undefined } {\n const last = args[args.length - 1]\n if (last !== undefined && typeof last === 'object' && !Array.isArray(last)) {\n return { names: args.slice(0, -1) as GuardNames[], options: last as O }\n }\n return { names: args as GuardNames[], options: undefined }\n}\n\nfunction createGuard(\n kind: GuardKind,\n requirements: string[][],\n handlers: GuardHandlers,\n check: (rbac: SubjectRbac) => Promise<boolean>,\n): MiddlewareHandler<RbacEnv> {\n if (requirements.length === 0) {\n throw new TypeError(`[rbac-evolution] A ${kind} guard needs at least one name.`)\n }\n const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated\n const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false)\n const context: GuardContext = { kind, requirements }\n\n return async (c, next) => {\n const rbac = c.get('rbac') as SubjectRbac | null | undefined\n if (rbac === undefined) throw new RbacMiddlewareMissingError()\n if (rbac === null) return onUnauthenticated(c, context)\n if (await check(rbac)) {\n await next()\n return\n }\n return onForbidden(c, context)\n }\n}\n\nasync function every(groups: readonly string[][], test: (group: string[]) => Promise<boolean>): Promise<boolean> {\n for (const group of groups) {\n if (!(await test(group))) return false\n }\n return true\n}\n\n/** Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page). */\nexport function createGuards(defaults: GuardHandlers = {}) {\n /**\n * Requires permissions, like spatie's `permission:` middleware.\n *\n * - `requirePermission('edit articles')`\n * - `requirePermission('edit articles|delete articles')` — any of them\n * - `requirePermission('edit articles', 'publish articles')` — all of them\n * - `requirePermission('a', 'b', { any: true })` — any of them\n */\n function requirePermission(...args: (GuardNames | PermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = parseArgs<PermissionGuardOptions>(args)\n const groups = toGroups(names)\n const requirements = options.any ? [groups.flat()] : groups\n return createGuard('permission', requirements, { ...defaults, ...options }, (rbac) =>\n every(requirements, (group) => rbac.canAny(group)),\n )\n }\n\n /**\n * Requires roles, like spatie's `role:` middleware.\n *\n * - `requireRole('admin')`, `requireRole('admin|editor')`, `requireRole('admin', 'editor')` — any of them\n * - `requireRole('admin', 'editor', { all: true })` — all of them\n */\n function requireRole(...args: (GuardNames | RoleGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = parseArgs<RoleGuardOptions>(args)\n const all = toGroups(names).flat()\n const requirements = options.all ? all.map((r) => [r]) : [all]\n return createGuard('role', requirements, { ...defaults, ...options }, async (rbac) =>\n options.all ? rbac.hasAllRoles(all) : rbac.hasAnyRole(all),\n )\n }\n\n /**\n * Passes when the subject has ANY of the names as a role OR as a permission,\n * like spatie's `role_or_permission:` middleware.\n *\n * - `requireRoleOrPermission('admin|edit articles')`\n */\n function requireRoleOrPermission(...args: (GuardNames | RoleOrPermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = parseArgs<RoleOrPermissionGuardOptions>(args)\n const all = toGroups(names).flat()\n return createGuard('role_or_permission', [all], { ...defaults, ...options }, async (rbac) =>\n (await rbac.hasAnyRole(all)) || rbac.canAny(all),\n )\n }\n\n /**\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `canAny('edit articles', 'publish articles')`, `canAny(['edit articles', 'publish articles'])`\n */\n function canAny(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = parseArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: true })\n }\n\n /**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `canAll('edit articles', 'publish articles')`, `canAll(['edit articles', 'publish|review'])`\n */\n function canAll(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = parseArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: false })\n }\n\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll }\n}\n\nexport const { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } = createGuards()\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/middleware.ts","../src/guards.ts"],"names":["UNAUTHENTICATED_MESSAGE","REQUIREMENT_MESSAGES","satisfiesRequirement","requirePermission","splitRequirementArgs","permissionRequirement","requireRole","roleRequirement","requireRoleOrPermission","roleOrPermissionRequirement","canAny","canAll"],"mappings":";;;;;AAwCO,SAAS,eAAoC,OAAA,EAAmE;AACrH,EAAA,MAAM,EAAE,IAAA,EAAM,UAAA,EAAY,KAAA,EAAO,MAAK,GAAI,OAAA;AAE1C,EAAA,OAAO,OAAO,GAAG,IAAA,KAAS;AACxB,IAAA,MAAM,GAAA,GAAM,CAAA;AACZ,IAAA,MAAM,OAAA,GAAU,MAAM,UAAA,CAAW,GAAG,CAAA;AACpC,IAAA,IAAI,KAAA,GAA4B,IAAA;AAChC,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,MAAM,MAAA,GAAS,IAAA,GAAO,MAAM,IAAA,CAAK,GAAG,CAAA,GAAI,MAAA;AACxC,MAAA,KAAA,GAAQ,IAAA,CAAK,IAAI,OAAA,EA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AG,OAAA,EAAS,CAAA;AAAA,EACpF;AAOA,EAAA,SAASC,WAAU,IAAA,EAAkE;AACnF,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAIN,mCAAoC,IAAI,CAAA;AACnE,IAAA,OAAOD,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,MAAM,CAAA;AAAA,EAC9D;AAOA,EAAA,SAASQ,WAAU,IAAA,EAAkE;AACnF,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAIP,mCAAoC,IAAI,CAAA;AACnE,IAAA,OAAOD,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,OAAO,CAAA;AAAA,EAC/D;AAEA,EAAA,OAAO,EAAE,iBAAA,EAAAA,kBAAAA,EAAmB,WAAA,EAAAG,YAAAA,EAAa,yBAAAE,wBAAAA,EAAyB,MAAA,EAAAE,OAAAA,EAAQ,MAAA,EAAAC,OAAAA,EAAO;AACnF;AAEO,IAAM,EAAE,iBAAA,EAAmB,WAAA,EAAa,yBAAyB,MAAA,EAAQ,MAAA,KAAW,YAAA","file":"index.cjs","sourcesContent":["import type { Rbac, Subject, SubjectRbac, TeamId } from '@anievo-id/rbac-evolution'\nimport type { Context, Env, MiddlewareHandler } from 'hono'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** Context variables set by `rbacMiddleware()`. */\nexport type RbacVariables = {\n /** Roles & permissions of the current subject. `null` for guests. */\n rbac: SubjectRbac | null\n}\n\n/**\n * Hono env for apps using `rbacMiddleware()`: `new Hono<RbacEnv>()` types `c.var.rbac`.\n * Combine it with your own variables: `new Hono<{ Variables: RbacVariables & { user: User } }>()`.\n */\nexport type RbacEnv = {\n Variables: RbacVariables\n}\n\nexport interface RbacMiddlewareOptions<E extends Env = Env> {\n /** The RBAC engine created with `createRbac(...)`. */\n rbac: Rbac\n /**\n * Resolves the authenticated subject for this request (e.g. from `c.var.user` or a JWT payload).\n * Return `null` / `undefined` for guests.\n */\n getSubject: (c: Context<E>) => MaybePromise<Subject | null | undefined>\n /** Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. */\n guard?: string\n /** Resolves the current team (only when the engine was created with `teams: true`). */\n team?: (c: Context<E>) => MaybePromise<TeamId | undefined>\n}\n\n/**\n * Resolves the current subject and sets `c.var.rbac` (a `SubjectRbac`, or `null` for guests).\n *\n * ```ts\n * app.use(rbacMiddleware({ rbac, getSubject: (c) => (c.var.user ? { type: 'user', id: c.var.user.id } : null) }))\n * ```\n */\nexport function rbacMiddleware<E extends Env = Env>(options: RbacMiddlewareOptions<E>): MiddlewareHandler<E & RbacEnv> {\n const { rbac, getSubject, guard, team } = options\n\n return async (c, next) => {\n const ctx = c as unknown as Context<E>\n const subject = await getSubject(ctx)\n let value: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(ctx) : undefined\n value = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n ;(c as unknown as Context<RbacEnv>).set('rbac', value)\n await next()\n }\n}\n","import {\n permissionRequirement,\n type RbacRequirement,\n type RequirementKind,\n type RequirementNames,\n REQUIREMENT_MESSAGES,\n roleOrPermissionRequirement,\n roleRequirement,\n satisfiesRequirement,\n splitRequirementArgs,\n type SubjectRbac,\n UNAUTHENTICATED_MESSAGE,\n} from '@anievo-id/rbac-evolution'\nimport type { Context, MiddlewareHandler } from 'hono'\nimport type { RbacEnv } from './middleware'\n\nexport type GuardKind = RequirementKind\n\n/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */\nexport interface GuardContext {\n kind: GuardKind\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\n requirements: string[][]\n}\n\n/** Returns the response to send (or throws, e.g. an `HTTPException`). */\nexport type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>\n\nexport interface GuardHandlers {\n /** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */\n onUnauthenticated?: GuardHandler\n /** Called when the subject lacks access. Default: 403 JSON. */\n onForbidden?: GuardHandler\n /**\n * Include the required roles/permissions in the default 403 body.\n * Default: `false` (like spatie's `display_permission_in_exception`).\n */\n exposeRequirements?: boolean\n}\n\nexport interface PermissionGuardOptions extends GuardHandlers {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean\n}\n\nexport interface RoleGuardOptions extends GuardHandlers {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean\n}\n\nexport type RoleOrPermissionGuardOptions = GuardHandlers\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = RequirementNames\n\nexport class RbacMiddlewareMissingError extends Error {\n readonly code = 'RBAC_MIDDLEWARE_MISSING'\n\n constructor() {\n super('`c.var.rbac` is not set. Register `rbacMiddleware()` before using RBAC guards.')\n this.name = 'RbacMiddlewareMissingError'\n }\n}\n\nconst defaultUnauthenticated: GuardHandler = (c) =>\n c.json({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }, 401)\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (c, context) =>\n c.json(\n {\n error: 'FORBIDDEN',\n reason: context.kind,\n message: REQUIREMENT_MESSAGES[context.kind],\n ...(expose && { required: context.requirements }),\n },\n 403,\n )\n\nfunction createGuard(requirement: RbacRequirement, handlers: GuardHandlers): MiddlewareHandler<RbacEnv> {\n const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated\n const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false)\n const context: GuardContext = { kind: requirement.kind, requirements: requirement.requirements }\n\n return async (c, next) => {\n const rbac = c.get('rbac') as SubjectRbac | null | undefined\n if (rbac === undefined) throw new RbacMiddlewareMissingError()\n if (rbac === null) return onUnauthenticated(c, context)\n if (await satisfiesRequirement(rbac, requirement)) {\n await next()\n return\n }\n return onForbidden(c, context)\n }\n}\n\n/** Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page). */\nexport function createGuards(defaults: GuardHandlers = {}) {\n /**\n * Requires permissions, like spatie's `permission:` middleware.\n *\n * - `requirePermission('edit articles')`\n * - `requirePermission('edit articles|delete articles')` — any of them\n * - `requirePermission('edit articles', 'publish articles')` — all of them\n * - `requirePermission('a', 'b', { any: true })` — any of them\n */\n function requirePermission(...args: (GuardNames | PermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\n return createGuard(permissionRequirement(names, options), { ...defaults, ...options })\n }\n\n /**\n * Requires roles, like spatie's `role:` middleware.\n *\n * - `requireRole('admin')`, `requireRole('admin|editor')`, `requireRole('admin', 'editor')` — any of them\n * - `requireRole('admin', 'editor', { all: true })` — all of them\n */\n function requireRole(...args: (GuardNames | RoleGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\n return createGuard(roleRequirement(names, options), { ...defaults, ...options })\n }\n\n /**\n * Passes when the subject has ANY of the names as a role OR as a permission,\n * like spatie's `role_or_permission:` middleware.\n *\n * - `requireRoleOrPermission('admin|edit articles')`\n */\n function requireRoleOrPermission(...args: (GuardNames | RoleOrPermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\n return createGuard(roleOrPermissionRequirement(names), { ...defaults, ...options })\n }\n\n /**\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `canAny('edit articles', 'publish articles')`, `canAny(['edit articles', 'publish articles'])`\n */\n function canAny(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: true })\n }\n\n /**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `canAll('edit articles', 'publish articles')`, `canAll(['edit articles', 'publish|review'])`\n */\n function canAll(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: false })\n }\n\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll }\n}\n\nexport const { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } = createGuards()\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SubjectRbac, Rbac, Subject, TeamId } from '@anievo-id/rbac-evolution';
|
|
1
|
+
import { SubjectRbac, Rbac, Subject, TeamId, RequirementKind, RequirementNames } from '@anievo-id/rbac-evolution';
|
|
2
2
|
import { Env, Context, MiddlewareHandler } from 'hono';
|
|
3
3
|
|
|
4
4
|
type MaybePromise<T> = T | Promise<T>;
|
|
@@ -36,7 +36,7 @@ interface RbacMiddlewareOptions<E extends Env = Env> {
|
|
|
36
36
|
*/
|
|
37
37
|
declare function rbacMiddleware<E extends Env = Env>(options: RbacMiddlewareOptions<E>): MiddlewareHandler<E & RbacEnv>;
|
|
38
38
|
|
|
39
|
-
type GuardKind =
|
|
39
|
+
type GuardKind = RequirementKind;
|
|
40
40
|
/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */
|
|
41
41
|
interface GuardContext {
|
|
42
42
|
kind: GuardKind;
|
|
@@ -66,7 +66,7 @@ interface RoleGuardOptions extends GuardHandlers {
|
|
|
66
66
|
}
|
|
67
67
|
type RoleOrPermissionGuardOptions = GuardHandlers;
|
|
68
68
|
/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
|
|
69
|
-
type GuardNames =
|
|
69
|
+
type GuardNames = RequirementNames;
|
|
70
70
|
declare class RbacMiddlewareMissingError extends Error {
|
|
71
71
|
readonly code = "RBAC_MIDDLEWARE_MISSING";
|
|
72
72
|
constructor();
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SubjectRbac, Rbac, Subject, TeamId } from '@anievo-id/rbac-evolution';
|
|
1
|
+
import { SubjectRbac, Rbac, Subject, TeamId, RequirementKind, RequirementNames } from '@anievo-id/rbac-evolution';
|
|
2
2
|
import { Env, Context, MiddlewareHandler } from 'hono';
|
|
3
3
|
|
|
4
4
|
type MaybePromise<T> = T | Promise<T>;
|
|
@@ -36,7 +36,7 @@ interface RbacMiddlewareOptions<E extends Env = Env> {
|
|
|
36
36
|
*/
|
|
37
37
|
declare function rbacMiddleware<E extends Env = Env>(options: RbacMiddlewareOptions<E>): MiddlewareHandler<E & RbacEnv>;
|
|
38
38
|
|
|
39
|
-
type GuardKind =
|
|
39
|
+
type GuardKind = RequirementKind;
|
|
40
40
|
/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */
|
|
41
41
|
interface GuardContext {
|
|
42
42
|
kind: GuardKind;
|
|
@@ -66,7 +66,7 @@ interface RoleGuardOptions extends GuardHandlers {
|
|
|
66
66
|
}
|
|
67
67
|
type RoleOrPermissionGuardOptions = GuardHandlers;
|
|
68
68
|
/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
|
|
69
|
-
type GuardNames =
|
|
69
|
+
type GuardNames = RequirementNames;
|
|
70
70
|
declare class RbacMiddlewareMissingError extends Error {
|
|
71
71
|
readonly code = "RBAC_MIDDLEWARE_MISSING";
|
|
72
72
|
constructor();
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { splitRequirementArgs, permissionRequirement, roleRequirement, roleOrPermissionRequirement, satisfiesRequirement, UNAUTHENTICATED_MESSAGE, REQUIREMENT_MESSAGES } from '@anievo-id/rbac-evolution';
|
|
2
|
+
|
|
1
3
|
// src/middleware.ts
|
|
2
4
|
function rbacMiddleware(options) {
|
|
3
5
|
const { rbac, getSubject, guard, team } = options;
|
|
@@ -16,8 +18,6 @@ function rbacMiddleware(options) {
|
|
|
16
18
|
await next();
|
|
17
19
|
};
|
|
18
20
|
}
|
|
19
|
-
|
|
20
|
-
// src/guards.ts
|
|
21
21
|
var RbacMiddlewareMissingError = class extends Error {
|
|
22
22
|
code = "RBAC_MIDDLEWARE_MISSING";
|
|
23
23
|
constructor() {
|
|
@@ -25,102 +25,50 @@ var RbacMiddlewareMissingError = class extends Error {
|
|
|
25
25
|
this.name = "RbacMiddlewareMissingError";
|
|
26
26
|
}
|
|
27
27
|
};
|
|
28
|
-
var
|
|
29
|
-
permission: "User does not have the right permissions.",
|
|
30
|
-
role: "User does not have the right roles.",
|
|
31
|
-
role_or_permission: "User does not have any of the necessary access rights."
|
|
32
|
-
};
|
|
33
|
-
var defaultUnauthenticated = (c) => c.json({ error: "UNAUTHENTICATED", message: "User is not logged in." }, 401);
|
|
28
|
+
var defaultUnauthenticated = (c) => c.json({ error: "UNAUTHENTICATED", message: UNAUTHENTICATED_MESSAGE }, 401);
|
|
34
29
|
var defaultForbidden = (expose) => (c, context) => c.json(
|
|
35
30
|
{
|
|
36
31
|
error: "FORBIDDEN",
|
|
37
32
|
reason: context.kind,
|
|
38
|
-
message:
|
|
33
|
+
message: REQUIREMENT_MESSAGES[context.kind],
|
|
39
34
|
...expose && { required: context.requirements }
|
|
40
35
|
},
|
|
41
36
|
403
|
|
42
37
|
);
|
|
43
|
-
|
|
44
|
-
function toGroups(names) {
|
|
45
|
-
const groups = [];
|
|
46
|
-
for (const name of names) {
|
|
47
|
-
for (const item of typeof name === "string" ? [name] : name) {
|
|
48
|
-
const group = split(item);
|
|
49
|
-
if (group.length > 0) groups.push(group);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
return groups;
|
|
53
|
-
}
|
|
54
|
-
function parseArgs(args) {
|
|
55
|
-
const last = args[args.length - 1];
|
|
56
|
-
if (last !== void 0 && typeof last === "object" && !Array.isArray(last)) {
|
|
57
|
-
return { names: args.slice(0, -1), options: last };
|
|
58
|
-
}
|
|
59
|
-
return { names: args, options: void 0 };
|
|
60
|
-
}
|
|
61
|
-
function createGuard(kind, requirements, handlers, check) {
|
|
62
|
-
if (requirements.length === 0) {
|
|
63
|
-
throw new TypeError(`[rbac-evolution] A ${kind} guard needs at least one name.`);
|
|
64
|
-
}
|
|
38
|
+
function createGuard(requirement, handlers) {
|
|
65
39
|
const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated;
|
|
66
40
|
const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false);
|
|
67
|
-
const context = { kind, requirements };
|
|
41
|
+
const context = { kind: requirement.kind, requirements: requirement.requirements };
|
|
68
42
|
return async (c, next) => {
|
|
69
43
|
const rbac = c.get("rbac");
|
|
70
44
|
if (rbac === void 0) throw new RbacMiddlewareMissingError();
|
|
71
45
|
if (rbac === null) return onUnauthenticated(c, context);
|
|
72
|
-
if (await
|
|
46
|
+
if (await satisfiesRequirement(rbac, requirement)) {
|
|
73
47
|
await next();
|
|
74
48
|
return;
|
|
75
49
|
}
|
|
76
50
|
return onForbidden(c, context);
|
|
77
51
|
};
|
|
78
52
|
}
|
|
79
|
-
async function every(groups, test) {
|
|
80
|
-
for (const group of groups) {
|
|
81
|
-
if (!await test(group)) return false;
|
|
82
|
-
}
|
|
83
|
-
return true;
|
|
84
|
-
}
|
|
85
53
|
function createGuards(defaults = {}) {
|
|
86
54
|
function requirePermission2(...args) {
|
|
87
|
-
const { names, options = {} } =
|
|
88
|
-
|
|
89
|
-
const requirements = options.any ? [groups.flat()] : groups;
|
|
90
|
-
return createGuard(
|
|
91
|
-
"permission",
|
|
92
|
-
requirements,
|
|
93
|
-
{ ...defaults, ...options },
|
|
94
|
-
(rbac) => every(requirements, (group) => rbac.canAny(group))
|
|
95
|
-
);
|
|
55
|
+
const { names, options = {} } = splitRequirementArgs(args);
|
|
56
|
+
return createGuard(permissionRequirement(names, options), { ...defaults, ...options });
|
|
96
57
|
}
|
|
97
58
|
function requireRole2(...args) {
|
|
98
|
-
const { names, options = {} } =
|
|
99
|
-
|
|
100
|
-
const requirements = options.all ? all.map((r) => [r]) : [all];
|
|
101
|
-
return createGuard(
|
|
102
|
-
"role",
|
|
103
|
-
requirements,
|
|
104
|
-
{ ...defaults, ...options },
|
|
105
|
-
async (rbac) => options.all ? rbac.hasAllRoles(all) : rbac.hasAnyRole(all)
|
|
106
|
-
);
|
|
59
|
+
const { names, options = {} } = splitRequirementArgs(args);
|
|
60
|
+
return createGuard(roleRequirement(names, options), { ...defaults, ...options });
|
|
107
61
|
}
|
|
108
62
|
function requireRoleOrPermission2(...args) {
|
|
109
|
-
const { names, options = {} } =
|
|
110
|
-
|
|
111
|
-
return createGuard(
|
|
112
|
-
"role_or_permission",
|
|
113
|
-
[all],
|
|
114
|
-
{ ...defaults, ...options },
|
|
115
|
-
async (rbac) => await rbac.hasAnyRole(all) || rbac.canAny(all)
|
|
116
|
-
);
|
|
63
|
+
const { names, options = {} } = splitRequirementArgs(args);
|
|
64
|
+
return createGuard(roleOrPermissionRequirement(names), { ...defaults, ...options });
|
|
117
65
|
}
|
|
118
66
|
function canAny2(...args) {
|
|
119
|
-
const { names, options } =
|
|
67
|
+
const { names, options } = splitRequirementArgs(args);
|
|
120
68
|
return requirePermission2(...names, { ...options, any: true });
|
|
121
69
|
}
|
|
122
70
|
function canAll2(...args) {
|
|
123
|
-
const { names, options } =
|
|
71
|
+
const { names, options } = splitRequirementArgs(args);
|
|
124
72
|
return requirePermission2(...names, { ...options, any: false });
|
|
125
73
|
}
|
|
126
74
|
return { requirePermission: requirePermission2, requireRole: requireRole2, requireRoleOrPermission: requireRoleOrPermission2, canAny: canAny2, canAll: canAll2 };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/middleware.ts","../src/guards.ts"],"names":["requirePermission","requireRole","requireRoleOrPermission","canAny","canAll"],"mappings":";AAwCO,SAAS,eAAoC,OAAA,EAAmE;AACrH,EAAA,MAAM,EAAE,IAAA,EAAM,UAAA,EAAY,KAAA,EAAO,MAA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,EAAQ;AAAA,MAAG,OAAO,SACjF,MAAM,IAAA,CAAK,WAAW,GAAG,CAAA,IAAM,IAAA,CAAK,MAAA,CAAO,GAAG;AAAA,KACjD;AAAA,EACF;AAOA,EAAA,SAASC,WAAU,IAAA,EAAkE;AACnF,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAI,UAAyB,IAAI,CAAA;AACxD,IAAA,OAAOH,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,MAAM,CAAA;AAAA,EAC9D;AAOA,EAAA,SAASI,WAAU,IAAA,EAAkE;AACnF,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAI,UAAyB,IAAI,CAAA;AACxD,IAAA,OAAOJ,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,OAAO,CAAA;AAAA,EAC/D;AAEA,EAAA,OAAO,EAAE,iBAAA,EAAAA,kBAAAA,EAAmB,WAAA,EAAAC,YAAAA,EAAa,yBAAAC,wBAAAA,EAAyB,MAAA,EAAAC,OAAAA,EAAQ,MAAA,EAAAC,OAAAA,EAAO;AACnF;AAEO,IAAM,EAAE,iBAAA,EAAmB,WAAA,EAAa,yBAAyB,MAAA,EAAQ,MAAA,KAAW,YAAA","file":"index.js","sourcesContent":["import type { Rbac, Subject, SubjectRbac, TeamId } from '@anievo-id/rbac-evolution'\nimport type { Context, Env, MiddlewareHandler } from 'hono'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** Context variables set by `rbacMiddleware()`. */\nexport type RbacVariables = {\n /** Roles & permissions of the current subject. `null` for guests. */\n rbac: SubjectRbac | null\n}\n\n/**\n * Hono env for apps using `rbacMiddleware()`: `new Hono<RbacEnv>()` types `c.var.rbac`.\n * Combine it with your own variables: `new Hono<{ Variables: RbacVariables & { user: User } }>()`.\n */\nexport type RbacEnv = {\n Variables: RbacVariables\n}\n\nexport interface RbacMiddlewareOptions<E extends Env = Env> {\n /** The RBAC engine created with `createRbac(...)`. */\n rbac: Rbac\n /**\n * Resolves the authenticated subject for this request (e.g. from `c.var.user` or a JWT payload).\n * Return `null` / `undefined` for guests.\n */\n getSubject: (c: Context<E>) => MaybePromise<Subject | null | undefined>\n /** Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. */\n guard?: string\n /** Resolves the current team (only when the engine was created with `teams: true`). */\n team?: (c: Context<E>) => MaybePromise<TeamId | undefined>\n}\n\n/**\n * Resolves the current subject and sets `c.var.rbac` (a `SubjectRbac`, or `null` for guests).\n *\n * ```ts\n * app.use(rbacMiddleware({ rbac, getSubject: (c) => (c.var.user ? { type: 'user', id: c.var.user.id } : null) }))\n * ```\n */\nexport function rbacMiddleware<E extends Env = Env>(options: RbacMiddlewareOptions<E>): MiddlewareHandler<E & RbacEnv> {\n const { rbac, getSubject, guard, team } = options\n\n return async (c, next) => {\n const ctx = c as unknown as Context<E>\n const subject = await getSubject(ctx)\n let value: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(ctx) : undefined\n value = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n ;(c as unknown as Context<RbacEnv>).set('rbac', value)\n await next()\n }\n}\n","import type { SubjectRbac } from '@anievo-id/rbac-evolution'\nimport type { Context, MiddlewareHandler } from 'hono'\nimport type { RbacEnv } from './middleware'\n\nexport type GuardKind = 'permission' | 'role' | 'role_or_permission'\n\n/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */\nexport interface GuardContext {\n kind: GuardKind\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\n requirements: string[][]\n}\n\n/** Returns the response to send (or throws, e.g. an `HTTPException`). */\nexport type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>\n\nexport interface GuardHandlers {\n /** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */\n onUnauthenticated?: GuardHandler\n /** Called when the subject lacks access. Default: 403 JSON. */\n onForbidden?: GuardHandler\n /**\n * Include the required roles/permissions in the default 403 body.\n * Default: `false` (like spatie's `display_permission_in_exception`).\n */\n exposeRequirements?: boolean\n}\n\nexport interface PermissionGuardOptions extends GuardHandlers {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean\n}\n\nexport interface RoleGuardOptions extends GuardHandlers {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean\n}\n\nexport type RoleOrPermissionGuardOptions = GuardHandlers\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = string | readonly string[]\n\nexport class RbacMiddlewareMissingError extends Error {\n readonly code = 'RBAC_MIDDLEWARE_MISSING'\n\n constructor() {\n super('`c.var.rbac` is not set. Register `rbacMiddleware()` before using RBAC guards.')\n this.name = 'RbacMiddlewareMissingError'\n }\n}\n\nconst MESSAGES: Record<GuardKind, string> = {\n permission: 'User does not have the right permissions.',\n role: 'User does not have the right roles.',\n role_or_permission: 'User does not have any of the necessary access rights.',\n}\n\nconst defaultUnauthenticated: GuardHandler = (c) =>\n c.json({ error: 'UNAUTHENTICATED', message: 'User is not logged in.' }, 401)\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (c, context) =>\n c.json(\n {\n error: 'FORBIDDEN',\n reason: context.kind,\n message: MESSAGES[context.kind],\n ...(expose && { required: context.requirements }),\n },\n 403,\n )\n\nconst split = (name: string): string[] =>\n name\n .split('|')\n .map((n) => n.trim())\n .filter((n) => n !== '')\n\n/** Each argument is a group (pipes = any within the group); arrays contribute one group per item. */\nfunction toGroups(names: readonly GuardNames[]): string[][] {\n const groups: string[][] = []\n for (const name of names) {\n for (const item of typeof name === 'string' ? [name] : name) {\n const group = split(item)\n if (group.length > 0) groups.push(group)\n }\n }\n return groups\n}\n\nfunction parseArgs<O extends object>(args: readonly (GuardNames | O)[]): { names: GuardNames[]; options: O | undefined } {\n const last = args[args.length - 1]\n if (last !== undefined && typeof last === 'object' && !Array.isArray(last)) {\n return { names: args.slice(0, -1) as GuardNames[], options: last as O }\n }\n return { names: args as GuardNames[], options: undefined }\n}\n\nfunction createGuard(\n kind: GuardKind,\n requirements: string[][],\n handlers: GuardHandlers,\n check: (rbac: SubjectRbac) => Promise<boolean>,\n): MiddlewareHandler<RbacEnv> {\n if (requirements.length === 0) {\n throw new TypeError(`[rbac-evolution] A ${kind} guard needs at least one name.`)\n }\n const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated\n const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false)\n const context: GuardContext = { kind, requirements }\n\n return async (c, next) => {\n const rbac = c.get('rbac') as SubjectRbac | null | undefined\n if (rbac === undefined) throw new RbacMiddlewareMissingError()\n if (rbac === null) return onUnauthenticated(c, context)\n if (await check(rbac)) {\n await next()\n return\n }\n return onForbidden(c, context)\n }\n}\n\nasync function every(groups: readonly string[][], test: (group: string[]) => Promise<boolean>): Promise<boolean> {\n for (const group of groups) {\n if (!(await test(group))) return false\n }\n return true\n}\n\n/** Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page). */\nexport function createGuards(defaults: GuardHandlers = {}) {\n /**\n * Requires permissions, like spatie's `permission:` middleware.\n *\n * - `requirePermission('edit articles')`\n * - `requirePermission('edit articles|delete articles')` — any of them\n * - `requirePermission('edit articles', 'publish articles')` — all of them\n * - `requirePermission('a', 'b', { any: true })` — any of them\n */\n function requirePermission(...args: (GuardNames | PermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = parseArgs<PermissionGuardOptions>(args)\n const groups = toGroups(names)\n const requirements = options.any ? [groups.flat()] : groups\n return createGuard('permission', requirements, { ...defaults, ...options }, (rbac) =>\n every(requirements, (group) => rbac.canAny(group)),\n )\n }\n\n /**\n * Requires roles, like spatie's `role:` middleware.\n *\n * - `requireRole('admin')`, `requireRole('admin|editor')`, `requireRole('admin', 'editor')` — any of them\n * - `requireRole('admin', 'editor', { all: true })` — all of them\n */\n function requireRole(...args: (GuardNames | RoleGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = parseArgs<RoleGuardOptions>(args)\n const all = toGroups(names).flat()\n const requirements = options.all ? all.map((r) => [r]) : [all]\n return createGuard('role', requirements, { ...defaults, ...options }, async (rbac) =>\n options.all ? rbac.hasAllRoles(all) : rbac.hasAnyRole(all),\n )\n }\n\n /**\n * Passes when the subject has ANY of the names as a role OR as a permission,\n * like spatie's `role_or_permission:` middleware.\n *\n * - `requireRoleOrPermission('admin|edit articles')`\n */\n function requireRoleOrPermission(...args: (GuardNames | RoleOrPermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = parseArgs<RoleOrPermissionGuardOptions>(args)\n const all = toGroups(names).flat()\n return createGuard('role_or_permission', [all], { ...defaults, ...options }, async (rbac) =>\n (await rbac.hasAnyRole(all)) || rbac.canAny(all),\n )\n }\n\n /**\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `canAny('edit articles', 'publish articles')`, `canAny(['edit articles', 'publish articles'])`\n */\n function canAny(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = parseArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: true })\n }\n\n /**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `canAll('edit articles', 'publish articles')`, `canAll(['edit articles', 'publish|review'])`\n */\n function canAll(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = parseArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: false })\n }\n\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll }\n}\n\nexport const { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } = createGuards()\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/middleware.ts","../src/guards.ts"],"names":["requirePermission","requireRole","requireRoleOrPermission","canAny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ubjectRbac, TeamId } from '@anievo-id/rbac-evolution'\nimport type { Context, Env, MiddlewareHandler } from 'hono'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** Context variables set by `rbacMiddleware()`. */\nexport type RbacVariables = {\n /** Roles & permissions of the current subject. `null` for guests. */\n rbac: SubjectRbac | null\n}\n\n/**\n * Hono env for apps using `rbacMiddleware()`: `new Hono<RbacEnv>()` types `c.var.rbac`.\n * Combine it with your own variables: `new Hono<{ Variables: RbacVariables & { user: User } }>()`.\n */\nexport type RbacEnv = {\n Variables: RbacVariables\n}\n\nexport interface RbacMiddlewareOptions<E extends Env = Env> {\n /** The RBAC engine created with `createRbac(...)`. */\n rbac: Rbac\n /**\n * Resolves the authenticated subject for this request (e.g. from `c.var.user` or a JWT payload).\n * Return `null` / `undefined` for guests.\n */\n getSubject: (c: Context<E>) => MaybePromise<Subject | null | undefined>\n /** Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. */\n guard?: string\n /** Resolves the current team (only when the engine was created with `teams: true`). */\n team?: (c: Context<E>) => MaybePromise<TeamId | undefined>\n}\n\n/**\n * Resolves the current subject and sets `c.var.rbac` (a `SubjectRbac`, or `null` for guests).\n *\n * ```ts\n * app.use(rbacMiddleware({ rbac, getSubject: (c) => (c.var.user ? { type: 'user', id: c.var.user.id } : null) }))\n * ```\n */\nexport function rbacMiddleware<E extends Env = Env>(options: RbacMiddlewareOptions<E>): MiddlewareHandler<E & RbacEnv> {\n const { rbac, getSubject, guard, team } = options\n\n return async (c, next) => {\n const ctx = c as unknown as Context<E>\n const subject = await getSubject(ctx)\n let value: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(ctx) : undefined\n value = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n ;(c as unknown as Context<RbacEnv>).set('rbac', value)\n await next()\n }\n}\n","import {\n permissionRequirement,\n type RbacRequirement,\n type RequirementKind,\n type RequirementNames,\n REQUIREMENT_MESSAGES,\n roleOrPermissionRequirement,\n roleRequirement,\n satisfiesRequirement,\n splitRequirementArgs,\n type SubjectRbac,\n UNAUTHENTICATED_MESSAGE,\n} from '@anievo-id/rbac-evolution'\nimport type { Context, MiddlewareHandler } from 'hono'\nimport type { RbacEnv } from './middleware'\n\nexport type GuardKind = RequirementKind\n\n/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */\nexport interface GuardContext {\n kind: GuardKind\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\n requirements: string[][]\n}\n\n/** Returns the response to send (or throws, e.g. an `HTTPException`). */\nexport type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>\n\nexport interface GuardHandlers {\n /** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */\n onUnauthenticated?: GuardHandler\n /** Called when the subject lacks access. Default: 403 JSON. */\n onForbidden?: GuardHandler\n /**\n * Include the required roles/permissions in the default 403 body.\n * Default: `false` (like spatie's `display_permission_in_exception`).\n */\n exposeRequirements?: boolean\n}\n\nexport interface PermissionGuardOptions extends GuardHandlers {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean\n}\n\nexport interface RoleGuardOptions extends GuardHandlers {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean\n}\n\nexport type RoleOrPermissionGuardOptions = GuardHandlers\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = RequirementNames\n\nexport class RbacMiddlewareMissingError extends Error {\n readonly code = 'RBAC_MIDDLEWARE_MISSING'\n\n constructor() {\n super('`c.var.rbac` is not set. Register `rbacMiddleware()` before using RBAC guards.')\n this.name = 'RbacMiddlewareMissingError'\n }\n}\n\nconst defaultUnauthenticated: GuardHandler = (c) =>\n c.json({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }, 401)\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (c, context) =>\n c.json(\n {\n error: 'FORBIDDEN',\n reason: context.kind,\n message: REQUIREMENT_MESSAGES[context.kind],\n ...(expose && { required: context.requirements }),\n },\n 403,\n )\n\nfunction createGuard(requirement: RbacRequirement, handlers: GuardHandlers): MiddlewareHandler<RbacEnv> {\n const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated\n const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false)\n const context: GuardContext = { kind: requirement.kind, requirements: requirement.requirements }\n\n return async (c, next) => {\n const rbac = c.get('rbac') as SubjectRbac | null | undefined\n if (rbac === undefined) throw new RbacMiddlewareMissingError()\n if (rbac === null) return onUnauthenticated(c, context)\n if (await satisfiesRequirement(rbac, requirement)) {\n await next()\n return\n }\n return onForbidden(c, context)\n }\n}\n\n/** Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page). */\nexport function createGuards(defaults: GuardHandlers = {}) {\n /**\n * Requires permissions, like spatie's `permission:` middleware.\n *\n * - `requirePermission('edit articles')`\n * - `requirePermission('edit articles|delete articles')` — any of them\n * - `requirePermission('edit articles', 'publish articles')` — all of them\n * - `requirePermission('a', 'b', { any: true })` — any of them\n */\n function requirePermission(...args: (GuardNames | PermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\n return createGuard(permissionRequirement(names, options), { ...defaults, ...options })\n }\n\n /**\n * Requires roles, like spatie's `role:` middleware.\n *\n * - `requireRole('admin')`, `requireRole('admin|editor')`, `requireRole('admin', 'editor')` — any of them\n * - `requireRole('admin', 'editor', { all: true })` — all of them\n */\n function requireRole(...args: (GuardNames | RoleGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\n return createGuard(roleRequirement(names, options), { ...defaults, ...options })\n }\n\n /**\n * Passes when the subject has ANY of the names as a role OR as a permission,\n * like spatie's `role_or_permission:` middleware.\n *\n * - `requireRoleOrPermission('admin|edit articles')`\n */\n function requireRoleOrPermission(...args: (GuardNames | RoleOrPermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\n return createGuard(roleOrPermissionRequirement(names), { ...defaults, ...options })\n }\n\n /**\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `canAny('edit articles', 'publish articles')`, `canAny(['edit articles', 'publish articles'])`\n */\n function canAny(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: true })\n }\n\n /**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `canAll('edit articles', 'publish articles')`, `canAll(['edit articles', 'publish|review'])`\n */\n function canAll(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: false })\n }\n\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll }\n}\n\nexport const { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } = createGuards()\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anievo-id/rbac-evolution-hono",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Hono middleware for rbac-evolution — runs on Node, Bun, Deno, Cloudflare Workers and other edge runtimes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "AniEvo-ID (https://github.com/AniEvo-ID)",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"access": "public"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@anievo-id/rbac-evolution": "^0.
|
|
52
|
+
"@anievo-id/rbac-evolution": "^0.6.1"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"hono": ">=4"
|