@anievo-id/rbac-evolution-hono 0.0.0-stage → 0.3.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AniEvo-ID
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,114 @@
1
- # Temporary Holding Version
1
+ # @anievo-id/rbac-evolution-hono
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Hono](https://hono.dev) middleware for [rbac-evolution](../core) — the counterpart of spatie/laravel-permission's
4
+ `role`, `permission` and `role_or_permission` middleware. Runs anywhere Hono runs: **Node, Bun, Deno,
5
+ Cloudflare Workers and other edge runtimes** (no Node-only APIs).
6
+
7
+ ```bash
8
+ npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-hono hono
9
+ ```
10
+
11
+ ## Setup
12
+
13
+ ```ts
14
+ import { Hono } from 'hono'
15
+ import { createRbac, MemoryAdapter } from '@anievo-id/rbac-evolution'
16
+ import { type RbacEnv, rbacMiddleware, requirePermission, requireRole } from '@anievo-id/rbac-evolution-hono'
17
+
18
+ const rbac = createRbac({ adapter: new MemoryAdapter() })
19
+ const app = new Hono<RbacEnv>()
20
+
21
+ app.use(yourAuthMiddleware) // your authentication runs first
22
+
23
+ app.use(
24
+ rbacMiddleware({
25
+ rbac,
26
+ // return null/undefined for guests
27
+ getSubject: (c) => {
28
+ const userId = c.req.header('x-user-id')
29
+ return userId ? { type: 'user', id: userId } : null
30
+ },
31
+ guard: 'web', // optional, defaults to the engine's defaultGuard
32
+ team: (c) => c.req.header('x-team-id'), // optional, only with createRbac({ teams: true })
33
+ }),
34
+ )
35
+ ```
36
+
37
+ `rbacMiddleware` sets `c.var.rbac`: a `SubjectRbac` for the current subject, or `null` for guests.
38
+ Type it with `new Hono<RbacEnv>()`, or merge `RbacVariables` into your own variables:
39
+
40
+ ```ts
41
+ import type { RbacVariables } from '@anievo-id/rbac-evolution-hono'
42
+
43
+ type AppEnv = { Variables: RbacVariables & { user: User | undefined } }
44
+ const app = new Hono<AppEnv>()
45
+
46
+ app.use(rbacMiddleware<AppEnv>({ rbac, getSubject: (c) => (c.var.user ? { type: 'user', id: c.var.user.id } : null) }))
47
+
48
+ app.get('/me/permissions', async (c) => c.json(c.var.rbac ? await c.var.rbac.snapshot() : null))
49
+
50
+ app.post('/articles/:id/publish', async (c) => {
51
+ if (!(await c.var.rbac?.can('publish articles'))) return c.json({ error: 'FORBIDDEN' }, 403)
52
+ // ...
53
+ })
54
+ ```
55
+
56
+ ## Guards
57
+
58
+ ```ts
59
+ app.put('/articles/:id', requirePermission('edit articles'), handler)
60
+ app.put('/articles/:id', requirePermission('edit articles|delete articles'), handler) // any of (pipe, like spatie)
61
+ app.put('/articles/:id', requirePermission('edit articles', 'publish articles'), handler) // all of
62
+ app.put('/articles/:id', requirePermission('edit articles', 'publish articles', { any: true }), handler) // any of
63
+
64
+ app.get('/admin', requireRole('admin'), handler)
65
+ app.get('/staff', requireRole('admin|editor'), handler) // any of
66
+ app.get('/staff', requireRole('admin', 'editor'), handler) // any of
67
+ app.get('/both', requireRole('writer', 'editor', { all: true }), handler) // all of
68
+
69
+ app.get('/dashboard', requireRoleOrPermission('admin|view dashboard'), handler) // any role OR any permission
70
+
71
+ app.use('/admin/*', requireRole('admin')) // guard a whole sub-tree
72
+ ```
73
+
74
+ Arrays are accepted anywhere a name is (`requirePermission(['a', 'b'])` = all of).
75
+ Unknown permissions simply fail the check (no exception). Permission checks go through `can()`,
76
+ so `superAdminRoles` and the engine's `before` hook apply.
77
+
78
+ ### Responses
79
+
80
+ - No subject (`c.var.rbac === null`) → **401** `{ "error": "UNAUTHENTICATED", "message": "User is not logged in." }`
81
+ - Not allowed → **403** `{ "error": "FORBIDDEN", "reason": "permission" | "role" | "role_or_permission", "message": "..." }`
82
+ - `rbacMiddleware` not registered → throws `RbacMiddlewareMissingError` (`code: 'RBAC_MIDDLEWARE_MISSING'`), handled by `app.onError`
83
+
84
+ The required names are not included in the 403 body unless you pass `exposeRequirements: true`
85
+ (like spatie's `display_permission_in_exception`).
86
+
87
+ ### Custom handlers
88
+
89
+ Handlers return the `Response` to send (or throw, e.g. an `HTTPException`). Per guard:
90
+
91
+ ```ts
92
+ requirePermission('edit articles', {
93
+ onUnauthenticated: (c) => c.redirect('/login'),
94
+ onForbidden: (c, { kind, requirements }) => c.html('<h1>Forbidden</h1>', 403),
95
+ })
96
+ ```
97
+
98
+ Or once for all guards:
99
+
100
+ ```ts
101
+ import { HTTPException } from 'hono/http-exception'
102
+ import { createGuards } from '@anievo-id/rbac-evolution-hono'
103
+
104
+ export const { requirePermission, requireRole, requireRoleOrPermission } = createGuards({
105
+ onUnauthenticated: (c) => c.redirect('/login'),
106
+ onForbidden: () => {
107
+ throw new HTTPException(403)
108
+ },
109
+ })
110
+ ```
111
+
112
+ ## License
113
+
114
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,131 @@
1
+ 'use strict';
2
+
3
+ // src/middleware.ts
4
+ function rbacMiddleware(options) {
5
+ const { rbac, getSubject, guard, team } = options;
6
+ return async (c, next) => {
7
+ const ctx = c;
8
+ const subject = await getSubject(ctx);
9
+ let value = null;
10
+ if (subject) {
11
+ const teamId = team ? await team(ctx) : void 0;
12
+ value = rbac.for(subject, {
13
+ ...guard !== void 0 && { guard },
14
+ ...teamId !== void 0 && { team: teamId }
15
+ });
16
+ }
17
+ c.set("rbac", value);
18
+ await next();
19
+ };
20
+ }
21
+
22
+ // src/guards.ts
23
+ var RbacMiddlewareMissingError = class extends Error {
24
+ code = "RBAC_MIDDLEWARE_MISSING";
25
+ constructor() {
26
+ super("`c.var.rbac` is not set. Register `rbacMiddleware()` before using RBAC guards.");
27
+ this.name = "RbacMiddlewareMissingError";
28
+ }
29
+ };
30
+ var MESSAGES = {
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);
36
+ var defaultForbidden = (expose) => (c, context) => c.json(
37
+ {
38
+ error: "FORBIDDEN",
39
+ reason: context.kind,
40
+ message: MESSAGES[context.kind],
41
+ ...expose && { required: context.requirements }
42
+ },
43
+ 403
44
+ );
45
+ var split = (name) => name.split("|").map((n) => n.trim()).filter((n) => n !== "");
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
+ }
67
+ const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated;
68
+ const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false);
69
+ const context = { kind, requirements };
70
+ return async (c, next) => {
71
+ const rbac = c.get("rbac");
72
+ if (rbac === void 0) throw new RbacMiddlewareMissingError();
73
+ if (rbac === null) return onUnauthenticated(c, context);
74
+ if (await check(rbac)) {
75
+ await next();
76
+ return;
77
+ }
78
+ return onForbidden(c, context);
79
+ };
80
+ }
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
+ function createGuards(defaults = {}) {
88
+ function requirePermission2(...args) {
89
+ const { names, options = {} } = parseArgs(args);
90
+ const groups = toGroups(names);
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
+ );
98
+ }
99
+ function requireRole2(...args) {
100
+ const { names, options = {} } = parseArgs(args);
101
+ const all = toGroups(names).flat();
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
+ );
109
+ }
110
+ function requireRoleOrPermission2(...args) {
111
+ const { names, options = {} } = parseArgs(args);
112
+ const all = toGroups(names).flat();
113
+ return createGuard(
114
+ "role_or_permission",
115
+ [all],
116
+ { ...defaults, ...options },
117
+ async (rbac) => await rbac.hasAnyRole(all) || rbac.canAny(all)
118
+ );
119
+ }
120
+ return { requirePermission: requirePermission2, requireRole: requireRole2, requireRoleOrPermission: requireRoleOrPermission2 };
121
+ }
122
+ var { requirePermission, requireRole, requireRoleOrPermission } = createGuards();
123
+
124
+ exports.RbacMiddlewareMissingError = RbacMiddlewareMissingError;
125
+ exports.createGuards = createGuards;
126
+ exports.rbacMiddleware = rbacMiddleware;
127
+ exports.requirePermission = requirePermission;
128
+ exports.requireRole = requireRole;
129
+ exports.requireRoleOrPermission = requireRoleOrPermission;
130
+ //# sourceMappingURL=index.cjs.map
131
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/middleware.ts","../src/guards.ts"],"names":["requirePermission","requireRole","requireRoleOrPermission"],"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;AACrD,IAAA,MAAM,IAAA,EAAK;AAAA,EACb,CAAA;AACF;;;ACdO,IAAM,0BAAA,GAAN,cAAyC,KAAA,CAAM;AAAA,EAC3C,IAAA,GAAO,yBAAA;AAAA,EAEhB,WAAA,GAAc;AACZ,IAAA,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EAAU,GAAG,OAAA,EAAQ;AAAA,MAAG,OAAO,IAAA,KAC3E,OAAA,CAAQ,GAAA,GAAM,IAAA,CAAK,YAAY,GAAG,CAAA,GAAI,IAAA,CAAK,UAAA,CAAW,GAAG;AAAA,KAC3D;AAAA,EACF;AAQA,EAAA,SAASC,4BAA2B,IAAA,EAAiF;AACnH,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,GAAU,EAAC,EAAE,GAAI,UAAwC,IAAI,CAAA;AAC5E,IAAA,MAAM,GAAA,GAAM,QAAA,CAAS,KAAK,CAAA,CAAE,IAAA,EAAK;AACjC,IAAA,OAAO,WAAA;AAAA,MAAY,oBAAA;AAAA,MAAsB,CAAC,GAAG,CAAA;AAAA,MAAG,EAAE,GAAG,QAAA,EAAU,GAAG,OAAA,EAAQ;AAAA,MAAG,OAAO,SACjF,MAAM,IAAA,CAAK,WAAW,GAAG,CAAA,IAAM,IAAA,CAAK,MAAA,CAAO,GAAG;AAAA,KACjD;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,iBAAA,EAAAF,kBAAAA,EAAmB,WAAA,EAAAC,YAAAA,EAAa,yBAAAC,wBAAAA,EAAwB;AACnE;AAEO,IAAM,EAAE,iBAAA,EAAmB,WAAA,EAAa,uBAAA,KAA4B,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 return { requirePermission, requireRole, requireRoleOrPermission }\n}\n\nexport const { requirePermission, requireRole, requireRoleOrPermission } = createGuards()\n"]}
@@ -0,0 +1,84 @@
1
+ import { SubjectRbac, Rbac, Subject, TeamId } from '@anievo-id/rbac-evolution';
2
+ import { Env, Context, MiddlewareHandler } from 'hono';
3
+
4
+ type MaybePromise<T> = T | Promise<T>;
5
+ /** Context variables set by `rbacMiddleware()`. */
6
+ type RbacVariables = {
7
+ /** Roles & permissions of the current subject. `null` for guests. */
8
+ rbac: SubjectRbac | null;
9
+ };
10
+ /**
11
+ * Hono env for apps using `rbacMiddleware()`: `new Hono<RbacEnv>()` types `c.var.rbac`.
12
+ * Combine it with your own variables: `new Hono<{ Variables: RbacVariables & { user: User } }>()`.
13
+ */
14
+ type RbacEnv = {
15
+ Variables: RbacVariables;
16
+ };
17
+ interface RbacMiddlewareOptions<E extends Env = Env> {
18
+ /** The RBAC engine created with `createRbac(...)`. */
19
+ rbac: Rbac;
20
+ /**
21
+ * Resolves the authenticated subject for this request (e.g. from `c.var.user` or a JWT payload).
22
+ * Return `null` / `undefined` for guests.
23
+ */
24
+ getSubject: (c: Context<E>) => MaybePromise<Subject | null | undefined>;
25
+ /** Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. */
26
+ guard?: string;
27
+ /** Resolves the current team (only when the engine was created with `teams: true`). */
28
+ team?: (c: Context<E>) => MaybePromise<TeamId | undefined>;
29
+ }
30
+ /**
31
+ * Resolves the current subject and sets `c.var.rbac` (a `SubjectRbac`, or `null` for guests).
32
+ *
33
+ * ```ts
34
+ * app.use(rbacMiddleware({ rbac, getSubject: (c) => (c.var.user ? { type: 'user', id: c.var.user.id } : null) }))
35
+ * ```
36
+ */
37
+ declare function rbacMiddleware<E extends Env = Env>(options: RbacMiddlewareOptions<E>): MiddlewareHandler<E & RbacEnv>;
38
+
39
+ type GuardKind = 'permission' | 'role' | 'role_or_permission';
40
+ /** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */
41
+ interface GuardContext {
42
+ kind: GuardKind;
43
+ /** Groups of names: every group must pass, a group passes when ANY of its names matches. */
44
+ requirements: string[][];
45
+ }
46
+ /** Returns the response to send (or throws, e.g. an `HTTPException`). */
47
+ type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>;
48
+ interface GuardHandlers {
49
+ /** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */
50
+ onUnauthenticated?: GuardHandler;
51
+ /** Called when the subject lacks access. Default: 403 JSON. */
52
+ onForbidden?: GuardHandler;
53
+ /**
54
+ * Include the required roles/permissions in the default 403 body.
55
+ * Default: `false` (like spatie's `display_permission_in_exception`).
56
+ */
57
+ exposeRequirements?: boolean;
58
+ }
59
+ interface PermissionGuardOptions extends GuardHandlers {
60
+ /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */
61
+ any?: boolean;
62
+ }
63
+ interface RoleGuardOptions extends GuardHandlers {
64
+ /** Require ALL of the roles (instead of any). Default: `false`. */
65
+ all?: boolean;
66
+ }
67
+ type RoleOrPermissionGuardOptions = GuardHandlers;
68
+ /** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
69
+ type GuardNames = string | readonly string[];
70
+ declare class RbacMiddlewareMissingError extends Error {
71
+ readonly code = "RBAC_MIDDLEWARE_MISSING";
72
+ constructor();
73
+ }
74
+ /** Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page). */
75
+ declare function createGuards(defaults?: GuardHandlers): {
76
+ requirePermission: (...args: (GuardNames | PermissionGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
77
+ requireRole: (...args: (GuardNames | RoleGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
78
+ requireRoleOrPermission: (...args: (GuardNames | RoleOrPermissionGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
79
+ };
80
+ declare const requirePermission: (...args: (GuardNames | PermissionGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
81
+ declare const requireRole: (...args: (GuardNames | RoleGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
82
+ declare const requireRoleOrPermission: (...args: (GuardNames | RoleOrPermissionGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
83
+
84
+ export { type GuardContext, type GuardHandler, type GuardHandlers, type GuardKind, type GuardNames, type PermissionGuardOptions, type RbacEnv, RbacMiddlewareMissingError, type RbacMiddlewareOptions, type RbacVariables, type RoleGuardOptions, type RoleOrPermissionGuardOptions, createGuards, rbacMiddleware, requirePermission, requireRole, requireRoleOrPermission };
@@ -0,0 +1,84 @@
1
+ import { SubjectRbac, Rbac, Subject, TeamId } from '@anievo-id/rbac-evolution';
2
+ import { Env, Context, MiddlewareHandler } from 'hono';
3
+
4
+ type MaybePromise<T> = T | Promise<T>;
5
+ /** Context variables set by `rbacMiddleware()`. */
6
+ type RbacVariables = {
7
+ /** Roles & permissions of the current subject. `null` for guests. */
8
+ rbac: SubjectRbac | null;
9
+ };
10
+ /**
11
+ * Hono env for apps using `rbacMiddleware()`: `new Hono<RbacEnv>()` types `c.var.rbac`.
12
+ * Combine it with your own variables: `new Hono<{ Variables: RbacVariables & { user: User } }>()`.
13
+ */
14
+ type RbacEnv = {
15
+ Variables: RbacVariables;
16
+ };
17
+ interface RbacMiddlewareOptions<E extends Env = Env> {
18
+ /** The RBAC engine created with `createRbac(...)`. */
19
+ rbac: Rbac;
20
+ /**
21
+ * Resolves the authenticated subject for this request (e.g. from `c.var.user` or a JWT payload).
22
+ * Return `null` / `undefined` for guests.
23
+ */
24
+ getSubject: (c: Context<E>) => MaybePromise<Subject | null | undefined>;
25
+ /** Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. */
26
+ guard?: string;
27
+ /** Resolves the current team (only when the engine was created with `teams: true`). */
28
+ team?: (c: Context<E>) => MaybePromise<TeamId | undefined>;
29
+ }
30
+ /**
31
+ * Resolves the current subject and sets `c.var.rbac` (a `SubjectRbac`, or `null` for guests).
32
+ *
33
+ * ```ts
34
+ * app.use(rbacMiddleware({ rbac, getSubject: (c) => (c.var.user ? { type: 'user', id: c.var.user.id } : null) }))
35
+ * ```
36
+ */
37
+ declare function rbacMiddleware<E extends Env = Env>(options: RbacMiddlewareOptions<E>): MiddlewareHandler<E & RbacEnv>;
38
+
39
+ type GuardKind = 'permission' | 'role' | 'role_or_permission';
40
+ /** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */
41
+ interface GuardContext {
42
+ kind: GuardKind;
43
+ /** Groups of names: every group must pass, a group passes when ANY of its names matches. */
44
+ requirements: string[][];
45
+ }
46
+ /** Returns the response to send (or throws, e.g. an `HTTPException`). */
47
+ type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>;
48
+ interface GuardHandlers {
49
+ /** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */
50
+ onUnauthenticated?: GuardHandler;
51
+ /** Called when the subject lacks access. Default: 403 JSON. */
52
+ onForbidden?: GuardHandler;
53
+ /**
54
+ * Include the required roles/permissions in the default 403 body.
55
+ * Default: `false` (like spatie's `display_permission_in_exception`).
56
+ */
57
+ exposeRequirements?: boolean;
58
+ }
59
+ interface PermissionGuardOptions extends GuardHandlers {
60
+ /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */
61
+ any?: boolean;
62
+ }
63
+ interface RoleGuardOptions extends GuardHandlers {
64
+ /** Require ALL of the roles (instead of any). Default: `false`. */
65
+ all?: boolean;
66
+ }
67
+ type RoleOrPermissionGuardOptions = GuardHandlers;
68
+ /** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
69
+ type GuardNames = string | readonly string[];
70
+ declare class RbacMiddlewareMissingError extends Error {
71
+ readonly code = "RBAC_MIDDLEWARE_MISSING";
72
+ constructor();
73
+ }
74
+ /** Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page). */
75
+ declare function createGuards(defaults?: GuardHandlers): {
76
+ requirePermission: (...args: (GuardNames | PermissionGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
77
+ requireRole: (...args: (GuardNames | RoleGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
78
+ requireRoleOrPermission: (...args: (GuardNames | RoleOrPermissionGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
79
+ };
80
+ declare const requirePermission: (...args: (GuardNames | PermissionGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
81
+ declare const requireRole: (...args: (GuardNames | RoleGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
82
+ declare const requireRoleOrPermission: (...args: (GuardNames | RoleOrPermissionGuardOptions)[]) => MiddlewareHandler<RbacEnv>;
83
+
84
+ export { type GuardContext, type GuardHandler, type GuardHandlers, type GuardKind, type GuardNames, type PermissionGuardOptions, type RbacEnv, RbacMiddlewareMissingError, type RbacMiddlewareOptions, type RbacVariables, type RoleGuardOptions, type RoleOrPermissionGuardOptions, createGuards, rbacMiddleware, requirePermission, requireRole, requireRoleOrPermission };
package/dist/index.js ADDED
@@ -0,0 +1,124 @@
1
+ // src/middleware.ts
2
+ function rbacMiddleware(options) {
3
+ const { rbac, getSubject, guard, team } = options;
4
+ return async (c, next) => {
5
+ const ctx = c;
6
+ const subject = await getSubject(ctx);
7
+ let value = null;
8
+ if (subject) {
9
+ const teamId = team ? await team(ctx) : void 0;
10
+ value = rbac.for(subject, {
11
+ ...guard !== void 0 && { guard },
12
+ ...teamId !== void 0 && { team: teamId }
13
+ });
14
+ }
15
+ c.set("rbac", value);
16
+ await next();
17
+ };
18
+ }
19
+
20
+ // src/guards.ts
21
+ var RbacMiddlewareMissingError = class extends Error {
22
+ code = "RBAC_MIDDLEWARE_MISSING";
23
+ constructor() {
24
+ super("`c.var.rbac` is not set. Register `rbacMiddleware()` before using RBAC guards.");
25
+ this.name = "RbacMiddlewareMissingError";
26
+ }
27
+ };
28
+ var MESSAGES = {
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);
34
+ var defaultForbidden = (expose) => (c, context) => c.json(
35
+ {
36
+ error: "FORBIDDEN",
37
+ reason: context.kind,
38
+ message: MESSAGES[context.kind],
39
+ ...expose && { required: context.requirements }
40
+ },
41
+ 403
42
+ );
43
+ var split = (name) => name.split("|").map((n) => n.trim()).filter((n) => n !== "");
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
+ }
65
+ const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated;
66
+ const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false);
67
+ const context = { kind, requirements };
68
+ return async (c, next) => {
69
+ const rbac = c.get("rbac");
70
+ if (rbac === void 0) throw new RbacMiddlewareMissingError();
71
+ if (rbac === null) return onUnauthenticated(c, context);
72
+ if (await check(rbac)) {
73
+ await next();
74
+ return;
75
+ }
76
+ return onForbidden(c, context);
77
+ };
78
+ }
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
+ function createGuards(defaults = {}) {
86
+ function requirePermission2(...args) {
87
+ const { names, options = {} } = parseArgs(args);
88
+ const groups = toGroups(names);
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
+ );
96
+ }
97
+ function requireRole2(...args) {
98
+ const { names, options = {} } = parseArgs(args);
99
+ const all = toGroups(names).flat();
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
+ );
107
+ }
108
+ function requireRoleOrPermission2(...args) {
109
+ const { names, options = {} } = parseArgs(args);
110
+ const all = toGroups(names).flat();
111
+ return createGuard(
112
+ "role_or_permission",
113
+ [all],
114
+ { ...defaults, ...options },
115
+ async (rbac) => await rbac.hasAnyRole(all) || rbac.canAny(all)
116
+ );
117
+ }
118
+ return { requirePermission: requirePermission2, requireRole: requireRole2, requireRoleOrPermission: requireRoleOrPermission2 };
119
+ }
120
+ var { requirePermission, requireRole, requireRoleOrPermission } = createGuards();
121
+
122
+ export { RbacMiddlewareMissingError, createGuards, rbacMiddleware, requirePermission, requireRole, requireRoleOrPermission };
123
+ //# sourceMappingURL=index.js.map
124
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1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A,MAAM,GAAA,GAAM,QAAA,CAAS,KAAK,CAAA,CAAE,IAAA,EAAK;AACjC,IAAA,OAAO,WAAA;AAAA,MAAY,oBAAA;AAAA,MAAsB,CAAC,GAAG,CAAA;AAAA,MAAG,EAAE,GAAG,QAAA,EAAU,GAAG,OAAA,EAAQ;AAAA,MAAG,OAAO,SACjF,MAAM,IAAA,CAAK,WAAW,GAAG,CAAA,IAAM,IAAA,CAAK,MAAA,CAAO,GAAG;AAAA,KACjD;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,iBAAA,EAAAF,kBAAAA,EAAmB,WAAA,EAAAC,YAAAA,EAAa,yBAAAC,wBAAAA,EAAwB;AACnE;AAEO,IAAM,EAAE,iBAAA,EAAmB,WAAA,EAAa,uBAAA,KAA4B,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 return { requirePermission, requireRole, requireRoleOrPermission }\n}\n\nexport const { requirePermission, requireRole, requireRoleOrPermission } = createGuards()\n"]}
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@anievo-id/rbac-evolution-hono",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Hono middleware for rbac-evolution — runs on Node, Bun, Deno, Cloudflare Workers and other edge runtimes.",
5
+ "license": "MIT",
6
+ "author": "AniEvo-ID (https://github.com/AniEvo-ID)",
7
+ "homepage": "https://github.com/AniEvo-ID/rbac-evolution/tree/main/packages/hono#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/AniEvo-ID/rbac-evolution/issues"
10
+ },
11
+ "type": "module",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/AniEvo-ID/rbac-evolution.git",
15
+ "directory": "packages/hono"
16
+ },
17
+ "keywords": [
18
+ "rbac",
19
+ "permissions",
20
+ "roles",
21
+ "authorization",
22
+ "hono",
23
+ "middleware",
24
+ "edge",
25
+ "cloudflare-workers",
26
+ "bun"
27
+ ],
28
+ "sideEffects": false,
29
+ "main": "./dist/index.cjs",
30
+ "module": "./dist/index.js",
31
+ "types": "./dist/index.d.ts",
32
+ "exports": {
33
+ ".": {
34
+ "import": {
35
+ "types": "./dist/index.d.ts",
36
+ "default": "./dist/index.js"
37
+ },
38
+ "require": {
39
+ "types": "./dist/index.d.cts",
40
+ "default": "./dist/index.cjs"
41
+ }
42
+ },
43
+ "./package.json": "./package.json"
44
+ },
45
+ "files": [
46
+ "dist"
47
+ ],
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "dependencies": {
52
+ "@anievo-id/rbac-evolution": "^0.3.0"
53
+ },
54
+ "peerDependencies": {
55
+ "hono": ">=4"
56
+ },
57
+ "devDependencies": {
58
+ "hono": "^4.6.0",
59
+ "tsup": "^8.3.0",
60
+ "typescript": "^5.7.0",
61
+ "vitest": "^2.1.0"
62
+ },
63
+ "engines": {
64
+ "node": ">=20"
65
+ },
66
+ "scripts": {
67
+ "build": "tsup",
68
+ "dev": "tsup --watch",
69
+ "typecheck": "tsc --noEmit",
70
+ "test": "vitest run --passWithNoTests",
71
+ "clean": "rm -rf dist .turbo"
72
+ }
6
73
  }