@anievo-id/rbac-evolution-elysia 0.0.0 → 1.5.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,50 @@
1
1
  # @anievo-id/rbac-evolution-elysia
2
2
 
3
- Placeholder. The first real release is 1.x: https://github.com/AniEvo-ID/rbac-evolution
3
+ [Elysia](https://elysiajs.com) plugin for [RBAC Evolution](https://github.com/AniEvo-ID/rbac-evolution): a typed
4
+ `rbac` in the request context, and permission and role guards as `beforeHandle` hooks. Bun first, also on Node,
5
+ Deno and Cloudflare Workers.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ bun add @anievo-id/rbac-evolution @anievo-id/rbac-evolution-elysia
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { Elysia } from 'elysia'
17
+ import { createRbac, MemoryAdapter } from '@anievo-id/rbac-evolution'
18
+ import { rbacPlugin, requirePermission, requireRole } from '@anievo-id/rbac-evolution-elysia'
19
+
20
+ const rbac = createRbac({ adapter: new MemoryAdapter() })
21
+
22
+ new Elysia()
23
+ .use(
24
+ rbacPlugin({
25
+ rbac,
26
+ getSubject: async ({ headers }) => {
27
+ const user = await getUser(headers.authorization) // yours
28
+ return user ? { type: 'user', id: user.id } : null
29
+ },
30
+ }),
31
+ )
32
+ .get('/me', ({ rbac }) => rbac?.getRoleNames() ?? [])
33
+ .patch('/articles/:id', updateArticle, { beforeHandle: requirePermission('edit articles') })
34
+ .guard({ beforeHandle: requireRole('admin|editor') }, (admin) => admin.get('/admin/stats', getStats))
35
+ .listen(3000)
36
+ ```
37
+
38
+ - Guests get `401`, users without access `403`, with the same JSON bodies as the other integrations. The required
39
+ names are only added with `exposeRequirements: true`. Leave it off in production.
40
+ - `createGuards<typeof rbac>()` checks names at compile time; `onUnauthenticated` / `onForbidden` customize the
41
+ responses.
42
+ - `guard: 'api'` and `team` on the plugin, `{ guard: 'api' }` on a guard (spatie's `role:admin,api`).
43
+
44
+ ## Documentation
45
+
46
+ https://creation.anievo.id/rbac-evolution/frameworks/elysia
47
+
48
+ ## License
49
+
50
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,101 @@
1
+ 'use strict';
2
+
3
+ var elysia = require('elysia');
4
+ var rbacEvolution = require('@anievo-id/rbac-evolution');
5
+
6
+ // src/plugin.ts
7
+ function rbacPlugin(options) {
8
+ const { getSubject, team } = options;
9
+ const guard = options.guard;
10
+ const rbac = options.rbac;
11
+ return new elysia.Elysia({ name: options.name ?? "rbac-evolution", seed: guard }).resolve(
12
+ { as: "global" },
13
+ async (ctx) => {
14
+ const subject = await getSubject(ctx);
15
+ if (!subject) return { rbac: null };
16
+ const teamId = team ? await team(ctx) : void 0;
17
+ const value = rbac.for(subject, {
18
+ ...guard !== void 0 && { guard },
19
+ ...teamId !== void 0 && { team: teamId }
20
+ });
21
+ return { rbac: value };
22
+ }
23
+ );
24
+ }
25
+ var RbacPluginMissingError = class extends Error {
26
+ code = "RBAC_PLUGIN_MISSING";
27
+ constructor() {
28
+ super("`rbac` is not set on the context. Register `rbacPlugin()` before the routes that use RBAC guards.");
29
+ this.name = "RbacPluginMissingError";
30
+ }
31
+ };
32
+ var json = (body, status) => Response.json(body, { status });
33
+ var defaultUnauthenticated = () => json({ error: "UNAUTHENTICATED", message: rbacEvolution.UNAUTHENTICATED_MESSAGE }, 401);
34
+ var defaultForbidden = (expose) => (_ctx, context) => json(
35
+ {
36
+ error: "FORBIDDEN",
37
+ reason: context.kind,
38
+ message: rbacEvolution.REQUIREMENT_MESSAGES[context.kind],
39
+ ...expose && { required: context.requirements }
40
+ },
41
+ 403
42
+ );
43
+ function createGuard(requirement, handlers, guard) {
44
+ const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated;
45
+ const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false);
46
+ const context = { kind: requirement.kind, requirements: requirement.requirements };
47
+ return async (ctx) => {
48
+ const rbac = ctx.rbac;
49
+ if (rbac === void 0) throw new RbacPluginMissingError();
50
+ const handlerCtx = ctx;
51
+ if (rbac === null) return onUnauthenticated(handlerCtx, context);
52
+ if (await rbacEvolution.satisfiesRequirement(guard === void 0 ? rbac : rbac.withScope({ guard }), requirement)) return void 0;
53
+ return onForbidden(handlerCtx, context);
54
+ };
55
+ }
56
+ function withDefaults(defaults, options) {
57
+ const merged = { ...defaults };
58
+ for (const [key, value] of Object.entries(options)) if (value !== void 0) merged[key] = value;
59
+ return merged;
60
+ }
61
+ function createGuards(defaults = {}) {
62
+ const shared = defaults;
63
+ function requirePermission2(...args) {
64
+ const { names, options = {} } = rbacEvolution.splitRequirementArgs(args);
65
+ return createGuard(rbacEvolution.permissionRequirement(names, options), withDefaults(shared, options), options.guard);
66
+ }
67
+ function requireRole2(...args) {
68
+ const { names, options = {} } = rbacEvolution.splitRequirementArgs(args);
69
+ return createGuard(rbacEvolution.roleRequirement(names, options), withDefaults(shared, options), options.guard);
70
+ }
71
+ function requireRoleOrPermission2(...args) {
72
+ const { names, options = {} } = rbacEvolution.splitRequirementArgs(args);
73
+ return createGuard(rbacEvolution.roleOrPermissionRequirement(names), withDefaults(shared, options), options.guard);
74
+ }
75
+ function canAny2(...args) {
76
+ const { names, options } = rbacEvolution.splitRequirementArgs(args);
77
+ return requirePermission2(...names, { ...options, any: true });
78
+ }
79
+ function canAll2(...args) {
80
+ const { names, options } = rbacEvolution.splitRequirementArgs(args);
81
+ return requirePermission2(...names, { ...options, any: false });
82
+ }
83
+ return { requirePermission: requirePermission2, requireRole: requireRole2, requireRoleOrPermission: requireRoleOrPermission2, canAny: canAny2, canAll: canAll2 };
84
+ }
85
+ var defaultGuards = createGuards();
86
+ var requirePermission = defaultGuards.requirePermission;
87
+ var requireRole = defaultGuards.requireRole;
88
+ var requireRoleOrPermission = defaultGuards.requireRoleOrPermission;
89
+ var canAny = defaultGuards.canAny;
90
+ var canAll = defaultGuards.canAll;
91
+
92
+ exports.RbacPluginMissingError = RbacPluginMissingError;
93
+ exports.canAll = canAll;
94
+ exports.canAny = canAny;
95
+ exports.createGuards = createGuards;
96
+ exports.rbacPlugin = rbacPlugin;
97
+ exports.requirePermission = requirePermission;
98
+ exports.requireRole = requireRole;
99
+ exports.requireRoleOrPermission = requireRoleOrPermission;
100
+ //# sourceMappingURL=index.cjs.map
101
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugin.ts","../src/guards.ts"],"names":["Elysia","UNAUTHENTICATED_MESSAGE","REQUIREMENT_MESSAGES","satisfiesRequirement","requirePermission","splitRequirementArgs","permissionRequirement","requireRole","roleRequirement","requireRoleOrPermission","roleOrPermissionRequirement","canAny","canAll"],"mappings":";;;;;;AA0EO,SAAS,WACd,OA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,IAAI,CAAA;AACvE,IAAA,OAAOD,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,MAAM,CAAA;AAAA,EAC9D;AAGA,EAAA,SAASQ,WAAU,IAAA,EAAiE;AAClF,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAIP,mCAAwC,IAAI,CAAA;AACvE,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;AAEA,IAAM,gBAAwB,YAAA,EAAa;AAEpC,IAAM,oBAA2D,aAAA,CAAc;AAC/E,IAAM,cAA+C,aAAA,CAAc;AACnE,IAAM,0BAA4D,aAAA,CAAc;AAChF,IAAM,SAA2C,aAAA,CAAc;AAC/D,IAAM,SAA2C,aAAA,CAAc","file":"index.cjs","sourcesContent":["import type {\n CheckGuard,\n DefaultGuardName,\n DefaultRbacTypes,\n GuardOptions,\n Rbac,\n RbacTypeConfig,\n ScopedGuardName,\n Subject,\n SubjectRbac,\n TeamId,\n} from '@anievo-id/rbac-evolution'\nimport { Elysia } from 'elysia'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */\nexport type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never\n\n/**\n * The request context `rbacPlugin()` reads the subject from. Elysia's full context type depends on the app, so the\n * plugin types only what every request has; read your own derived values (e.g. `user`) with a cast or from\n * `request`, or resolve them before the plugin.\n */\nexport interface RbacRequestContext {\n request: Request\n headers: Record<string, string | undefined>\n [key: string]: unknown\n}\n\n/**\n * What `rbacPlugin()` adds to the context of every route after it. `T` (a names type like `AppRbac`, or\n * `typeof rbac`) types the names `rbac` accepts; with per-guard names, `G` is the guard of the subject.\n */\nexport type RbacContext<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends string = DefaultGuardName<TypesOf<T>>,\n> = {\n /** Roles & permissions of the current subject. `null` for guests. */\n rbac: SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>> | null\n}\n\nexport interface RbacPluginOptions<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> {\n /** The RBAC engine created with `createRbac(...)`. Its typed names flow into the `rbac` context value. */\n rbac: Rbac<T>\n /**\n * Resolves the authenticated subject for this request (e.g. from a session cookie or a JWT payload).\n * Return `null` / `undefined` for guests.\n */\n getSubject: (ctx: RbacRequestContext) => MaybePromise<Subject | null | undefined>\n /**\n * Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. With per-guard names, it must be one\n * of the typed guards, and the `rbac` context value gets its names.\n */\n guard?: G | undefined\n /** Resolves the current team (only when the engine was created with `teams: true`). */\n team?: (ctx: RbacRequestContext) => MaybePromise<TeamId | undefined>\n /**\n * Plugin name, used by Elysia to register it once. Default: `'rbac-evolution'`. Give each instance its own name\n * when you register two (e.g. a `web` and an `api` guard).\n */\n name?: string | undefined\n}\n\n/**\n * Resolves the current subject and adds `rbac` (a `SubjectRbac`, or `null` for guests) to the context of every\n * route registered after it.\n *\n * ```ts\n * const app = new Elysia()\n * .use(rbacPlugin({ rbac, getSubject: ({ headers }) => (headers['x-user'] ? { type: 'user', id: headers['x-user'] } : null) }))\n * .get('/me', ({ rbac }) => rbac?.getRoleNames() ?? [])\n * ```\n */\nexport function rbacPlugin<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>>(\n options: RbacPluginOptions<T, G> & (T extends { guards: object } ? GuardOptions<CheckGuard<T, G>> : unknown),\n) {\n const { getSubject, team } = options\n const guard: string | undefined = options.guard\n // `T` only narrows the names on `rbac`; the subject is the same object either way.\n const rbac = options.rbac as unknown as Rbac\n\n return new Elysia({ name: options.name ?? 'rbac-evolution', seed: guard }).resolve(\n { as: 'global' },\n async (ctx): Promise<RbacContext<T, ScopedGuardName<T, G>>> => {\n // Pass `ctx` itself: Elysia reads this function's source to decide which context fields to parse, and a\n // context handed to another function makes it parse them all (an alias would hide `headers` & co).\n const subject = await getSubject(ctx as unknown as RbacRequestContext)\n if (!subject) return { rbac: null }\n const teamId = team ? await team(ctx as unknown as RbacRequestContext) : undefined\n const value = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n return { rbac: value } as unknown as RbacContext<T, ScopedGuardName<T, G>>\n },\n )\n}\n","import {\n type DefaultGuardName,\n type DefaultRbacTypes,\n type GuardName,\n type GuardRequirementArgs,\n type PermissionName,\n permissionRequirement,\n type Rbac,\n type RbacRequirement,\n type RbacTypeConfig,\n type RequirementArgs,\n type RequirementKind,\n type RequirementNames,\n REQUIREMENT_MESSAGES,\n type RoleName,\n roleOrPermissionRequirement,\n roleRequirement,\n satisfiesRequirement,\n splitRequirementArgs,\n type SubjectRbac,\n UNAUTHENTICATED_MESSAGE,\n} from '@anievo-id/rbac-evolution'\nimport type { RbacContext, RbacRequestContext, TypesOf } from './plugin'\n\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/**\n * The context the handlers of `createGuards<T>()` get: the request context plus an `rbac` with the names of `T`\n * (of guard `G` with per-guard names).\n */\nexport type GuardHandlerContext<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends string = DefaultGuardName<TypesOf<T>>,\n> = RbacRequestContext & RbacContext<T, G>\n\n/**\n * Returns the response to send (any value Elysia can send: a `Response`, an object, a string), or throws (e.g.\n * Elysia's `status(403)` / an `error()`).\n */\nexport type GuardHandler<C = GuardHandlerContext> = (ctx: C, context: GuardContext) => unknown\n\nexport interface GuardHandlers<C = GuardHandlerContext> {\n /** Called when there is no subject (`rbac` is `null`). Default: 401 JSON. */\n onUnauthenticated?: GuardHandler<C> | undefined\n /** Called when the subject lacks access. Default: 403 JSON. */\n onForbidden?: GuardHandler<C> | undefined\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 | undefined\n}\n\n/** The options every guard takes: the handlers plus `guard` (check in another guard, like spatie's `role:admin,api`). */\nexport interface RouteGuardOptions<C = GuardHandlerContext> extends GuardHandlers<C> {\n /** Check in this guard instead of the request's (`subject.withScope({ guard })`). Default: the request's guard. */\n guard?: string | undefined\n}\n\nexport interface PermissionGuardOptions<C = GuardHandlerContext> extends RouteGuardOptions<C> {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean | undefined\n}\n\nexport interface RoleGuardOptions<C = GuardHandlerContext> extends RouteGuardOptions<C> {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean | undefined\n}\n\nexport type RoleOrPermissionGuardOptions<C = GuardHandlerContext> = RouteGuardOptions<C>\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = RequirementNames\n\n/**\n * A guard, used as an Elysia `beforeHandle` hook: `app.get('/x', handler, { beforeHandle: requireRole('admin') })`\n * or `app.guard({ beforeHandle: [...] }, (app) => ...)`. It returns nothing when the check passes, and the\n * response of `onUnauthenticated` / `onForbidden` otherwise, which ends the request.\n */\nexport type BeforeHandle = (ctx: object) => Promise<unknown>\n\nexport class RbacPluginMissingError extends Error {\n readonly code = 'RBAC_PLUGIN_MISSING'\n\n constructor() {\n super('`rbac` is not set on the context. Register `rbacPlugin()` before the routes that use RBAC guards.')\n this.name = 'RbacPluginMissingError'\n }\n}\n\nconst json = (body: unknown, status: number): Response => Response.json(body, { status })\n\nconst defaultUnauthenticated: GuardHandler = () => json({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }, 401)\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (_ctx, context) =>\n 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, guard: string | undefined): BeforeHandle {\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 (ctx) => {\n const rbac = (ctx as { rbac?: SubjectRbac | null }).rbac\n if (rbac === undefined) throw new RbacPluginMissingError()\n const handlerCtx = ctx as unknown as GuardHandlerContext\n if (rbac === null) return onUnauthenticated(handlerCtx, context)\n if (await satisfiesRequirement(guard === undefined ? rbac : rbac.withScope({ guard }), requirement)) return undefined\n return onForbidden(handlerCtx, context)\n }\n}\n\n/** `options` over `defaults`, where an option set to `undefined` keeps the default (as if left out). */\nfunction withDefaults(defaults: GuardHandlers, options: GuardHandlers): GuardHandlers {\n const merged: Record<string, unknown> = { ...defaults }\n for (const [key, value] of Object.entries(options)) if (value !== undefined) merged[key] = value\n return merged as GuardHandlers\n}\n\n/**\n * A guard typed with the names `N` it accepts and its options `O`: `(...names, options?)`.\n * Every name (each part of a `'a|b'` list, each array item) must be one of `N`; with `N = string`, any name is.\n */\nexport type Guard<N extends string, O> = <const A extends readonly (GuardNames | O)[]>(\n ...args: A & RequirementArgs<A, N, O>\n) => BeforeHandle\n\n/** The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). */\nexport interface Guards<T extends RbacTypeConfig = DefaultRbacTypes> {\n requirePermission: Guard<PermissionName<T>, PermissionGuardOptions<GuardHandlerContext<T>>>\n requireRole: Guard<RoleName<T>, RoleGuardOptions<GuardHandlerContext<T>>>\n requireRoleOrPermission: Guard<PermissionName<T> | RoleName<T>, RoleOrPermissionGuardOptions<GuardHandlerContext<T>>>\n canAny: Guard<PermissionName<T>, RouteGuardOptions<GuardHandlerContext<T>>>\n canAll: Guard<PermissionName<T>, RouteGuardOptions<GuardHandlerContext<T>>>\n}\n\n/**\n * A guard of `createGuards<T, G>()` when `T` has per-guard names: the names are those of the guard the call checks\n * in, its `{ guard }` option or else `G` (the guard of the request).\n */\nexport type ScopedGuard<T extends RbacTypeConfig, G extends string, K extends GuardKind, O> = <\n const A extends readonly (GuardNames | O)[],\n>(\n ...args: A & GuardRequirementArgs<A, T, K, G, O>\n) => BeforeHandle\n\n/** The guards returned by `createGuards<T, G>()` when `T` has per-guard names. */\nexport interface ScopedGuards<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> {\n requirePermission: ScopedGuard<T, G, 'permission', PermissionGuardOptions<GuardHandlerContext<T, G>>>\n requireRole: ScopedGuard<T, G, 'role', RoleGuardOptions<GuardHandlerContext<T, G>>>\n requireRoleOrPermission: ScopedGuard<T, G, 'role_or_permission', RoleOrPermissionGuardOptions<GuardHandlerContext<T, G>>>\n canAny: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardHandlerContext<T, G>>>\n canAll: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardHandlerContext<T, G>>>\n}\n\n/** What `createGuards<T, G>()` returns: {@link Guards}, or {@link ScopedGuards} for a config with `guards`. */\nexport type GuardsFor<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> = T extends {\n guards: object\n}\n ? ScopedGuards<T, G>\n : Guards<T>\n\n/**\n * Builds the guards with shared defaults (e.g. a custom `onForbidden`).\n *\n * Pass the same type argument as `createRbac<AppTypes>()` (or `typeof rbac`) to check names at compile time:\n * `const { requirePermission } = createGuards<AppTypes>()`. With per-guard names, `G` is the guard of the requests\n * these guards run on: `createGuards<AppRbac, 'api'>()`.\n */\nexport function createGuards<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>,\n>(defaults: GuardHandlers<GuardHandlerContext<TypesOf<T>, G>> = {}): GuardsFor<TypesOf<T>, G> {\n // The typed handlers only narrow `rbac`; the implementation below works on any context.\n const shared = defaults as unknown as GuardHandlers\n\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: readonly (GuardNames | PermissionGuardOptions)[]): BeforeHandle {\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\n return createGuard(permissionRequirement(names, options), withDefaults(shared, options), options.guard)\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: readonly (GuardNames | RoleGuardOptions)[]): BeforeHandle {\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\n return createGuard(roleRequirement(names, options), withDefaults(shared, options), options.guard)\n }\n\n /** Passes with ANY of the names as a role OR a permission, like spatie's `role_or_permission:` middleware. */\n function requireRoleOrPermission(...args: readonly (GuardNames | RoleOrPermissionGuardOptions)[]): BeforeHandle {\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\n return createGuard(roleOrPermissionRequirement(names), withDefaults(shared, options), options.guard)\n }\n\n /** spatie v8.5 `canAny()`: passes with ANY of the listed permissions. */\n function canAny(...args: readonly (GuardNames | RouteGuardOptions)[]): BeforeHandle {\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(args)\n return requirePermission(...names, { ...options, any: true })\n }\n\n /** spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\". */\n function canAll(...args: readonly (GuardNames | RouteGuardOptions)[]): BeforeHandle {\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(args)\n return requirePermission(...names, { ...options, any: false })\n }\n\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } as unknown as GuardsFor<TypesOf<T>, G>\n}\n\nconst defaultGuards: Guards = createGuards()\n\nexport const requirePermission: Guard<string, PermissionGuardOptions> = defaultGuards.requirePermission\nexport const requireRole: Guard<string, RoleGuardOptions> = defaultGuards.requireRole\nexport const requireRoleOrPermission: Guard<string, RouteGuardOptions> = defaultGuards.requireRoleOrPermission\nexport const canAny: Guard<string, RouteGuardOptions> = defaultGuards.canAny\nexport const canAll: Guard<string, RouteGuardOptions> = defaultGuards.canAll\n\n"]}
@@ -0,0 +1,186 @@
1
+ import * as elysia from 'elysia';
2
+ import { Elysia } from 'elysia';
3
+ import { Rbac, RbacTypeConfig, DefaultRbacTypes, DefaultGuardName, SubjectRbac, ScopedGuardName, Subject, TeamId, GuardOptions, CheckGuard, RequirementNames, RequirementArgs, RequirementKind, PermissionName, RoleName, GuardRequirementArgs, GuardName } from '@anievo-id/rbac-evolution';
4
+
5
+ type MaybePromise<T> = T | Promise<T>;
6
+ /** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */
7
+ type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never;
8
+ /**
9
+ * The request context `rbacPlugin()` reads the subject from. Elysia's full context type depends on the app, so the
10
+ * plugin types only what every request has; read your own derived values (e.g. `user`) with a cast or from
11
+ * `request`, or resolve them before the plugin.
12
+ */
13
+ interface RbacRequestContext {
14
+ request: Request;
15
+ headers: Record<string, string | undefined>;
16
+ [key: string]: unknown;
17
+ }
18
+ /**
19
+ * What `rbacPlugin()` adds to the context of every route after it. `T` (a names type like `AppRbac`, or
20
+ * `typeof rbac`) types the names `rbac` accepts; with per-guard names, `G` is the guard of the subject.
21
+ */
22
+ type RbacContext<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>> = {
23
+ /** Roles & permissions of the current subject. `null` for guests. */
24
+ rbac: SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>> | null;
25
+ };
26
+ interface RbacPluginOptions<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> {
27
+ /** The RBAC engine created with `createRbac(...)`. Its typed names flow into the `rbac` context value. */
28
+ rbac: Rbac<T>;
29
+ /**
30
+ * Resolves the authenticated subject for this request (e.g. from a session cookie or a JWT payload).
31
+ * Return `null` / `undefined` for guests.
32
+ */
33
+ getSubject: (ctx: RbacRequestContext) => MaybePromise<Subject | null | undefined>;
34
+ /**
35
+ * Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. With per-guard names, it must be one
36
+ * of the typed guards, and the `rbac` context value gets its names.
37
+ */
38
+ guard?: G | undefined;
39
+ /** Resolves the current team (only when the engine was created with `teams: true`). */
40
+ team?: (ctx: RbacRequestContext) => MaybePromise<TeamId | undefined>;
41
+ /**
42
+ * Plugin name, used by Elysia to register it once. Default: `'rbac-evolution'`. Give each instance its own name
43
+ * when you register two (e.g. a `web` and an `api` guard).
44
+ */
45
+ name?: string | undefined;
46
+ }
47
+ /**
48
+ * Resolves the current subject and adds `rbac` (a `SubjectRbac`, or `null` for guests) to the context of every
49
+ * route registered after it.
50
+ *
51
+ * ```ts
52
+ * const app = new Elysia()
53
+ * .use(rbacPlugin({ rbac, getSubject: ({ headers }) => (headers['x-user'] ? { type: 'user', id: headers['x-user'] } : null) }))
54
+ * .get('/me', ({ rbac }) => rbac?.getRoleNames() ?? [])
55
+ * ```
56
+ */
57
+ declare function rbacPlugin<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>>(options: RbacPluginOptions<T, G> & (T extends {
58
+ guards: object;
59
+ } ? GuardOptions<CheckGuard<T, G>> : unknown)): Elysia<"", {
60
+ decorator: {};
61
+ store: {};
62
+ derive: {};
63
+ resolve: RbacContext<T, ScopedGuardName<T, G>>;
64
+ }, {
65
+ typebox: {};
66
+ error: {};
67
+ }, {
68
+ schema: {};
69
+ standaloneSchema: {};
70
+ macro: {};
71
+ macroFn: {};
72
+ parser: {};
73
+ response: elysia.ExtractErrorFromHandle<RbacContext<T, ScopedGuardName<T, G>>>;
74
+ }, {}, {
75
+ derive: {};
76
+ resolve: {};
77
+ schema: {};
78
+ standaloneSchema: {};
79
+ response: {};
80
+ }, {
81
+ derive: {};
82
+ resolve: {};
83
+ schema: {};
84
+ standaloneSchema: {};
85
+ response: {};
86
+ }>;
87
+
88
+ type GuardKind = RequirementKind;
89
+ /** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */
90
+ interface GuardContext {
91
+ kind: GuardKind;
92
+ /** Groups of names: every group must pass, a group passes when ANY of its names matches. */
93
+ requirements: string[][];
94
+ }
95
+ /**
96
+ * The context the handlers of `createGuards<T>()` get: the request context plus an `rbac` with the names of `T`
97
+ * (of guard `G` with per-guard names).
98
+ */
99
+ type GuardHandlerContext<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>> = RbacRequestContext & RbacContext<T, G>;
100
+ /**
101
+ * Returns the response to send (any value Elysia can send: a `Response`, an object, a string), or throws (e.g.
102
+ * Elysia's `status(403)` / an `error()`).
103
+ */
104
+ type GuardHandler<C = GuardHandlerContext> = (ctx: C, context: GuardContext) => unknown;
105
+ interface GuardHandlers<C = GuardHandlerContext> {
106
+ /** Called when there is no subject (`rbac` is `null`). Default: 401 JSON. */
107
+ onUnauthenticated?: GuardHandler<C> | undefined;
108
+ /** Called when the subject lacks access. Default: 403 JSON. */
109
+ onForbidden?: GuardHandler<C> | undefined;
110
+ /**
111
+ * Include the required roles/permissions in the default 403 body.
112
+ * Default: `false` (like spatie's `display_permission_in_exception`).
113
+ */
114
+ exposeRequirements?: boolean | undefined;
115
+ }
116
+ /** The options every guard takes: the handlers plus `guard` (check in another guard, like spatie's `role:admin,api`). */
117
+ interface RouteGuardOptions<C = GuardHandlerContext> extends GuardHandlers<C> {
118
+ /** Check in this guard instead of the request's (`subject.withScope({ guard })`). Default: the request's guard. */
119
+ guard?: string | undefined;
120
+ }
121
+ interface PermissionGuardOptions<C = GuardHandlerContext> extends RouteGuardOptions<C> {
122
+ /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */
123
+ any?: boolean | undefined;
124
+ }
125
+ interface RoleGuardOptions<C = GuardHandlerContext> extends RouteGuardOptions<C> {
126
+ /** Require ALL of the roles (instead of any). Default: `false`. */
127
+ all?: boolean | undefined;
128
+ }
129
+ type RoleOrPermissionGuardOptions<C = GuardHandlerContext> = RouteGuardOptions<C>;
130
+ /** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
131
+ type GuardNames = RequirementNames;
132
+ /**
133
+ * A guard, used as an Elysia `beforeHandle` hook: `app.get('/x', handler, { beforeHandle: requireRole('admin') })`
134
+ * or `app.guard({ beforeHandle: [...] }, (app) => ...)`. It returns nothing when the check passes, and the
135
+ * response of `onUnauthenticated` / `onForbidden` otherwise, which ends the request.
136
+ */
137
+ type BeforeHandle = (ctx: object) => Promise<unknown>;
138
+ declare class RbacPluginMissingError extends Error {
139
+ readonly code = "RBAC_PLUGIN_MISSING";
140
+ constructor();
141
+ }
142
+ /**
143
+ * A guard typed with the names `N` it accepts and its options `O`: `(...names, options?)`.
144
+ * Every name (each part of a `'a|b'` list, each array item) must be one of `N`; with `N = string`, any name is.
145
+ */
146
+ type Guard<N extends string, O> = <const A extends readonly (GuardNames | O)[]>(...args: A & RequirementArgs<A, N, O>) => BeforeHandle;
147
+ /** The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). */
148
+ interface Guards<T extends RbacTypeConfig = DefaultRbacTypes> {
149
+ requirePermission: Guard<PermissionName<T>, PermissionGuardOptions<GuardHandlerContext<T>>>;
150
+ requireRole: Guard<RoleName<T>, RoleGuardOptions<GuardHandlerContext<T>>>;
151
+ requireRoleOrPermission: Guard<PermissionName<T> | RoleName<T>, RoleOrPermissionGuardOptions<GuardHandlerContext<T>>>;
152
+ canAny: Guard<PermissionName<T>, RouteGuardOptions<GuardHandlerContext<T>>>;
153
+ canAll: Guard<PermissionName<T>, RouteGuardOptions<GuardHandlerContext<T>>>;
154
+ }
155
+ /**
156
+ * A guard of `createGuards<T, G>()` when `T` has per-guard names: the names are those of the guard the call checks
157
+ * in, its `{ guard }` option or else `G` (the guard of the request).
158
+ */
159
+ type ScopedGuard<T extends RbacTypeConfig, G extends string, K extends GuardKind, O> = <const A extends readonly (GuardNames | O)[]>(...args: A & GuardRequirementArgs<A, T, K, G, O>) => BeforeHandle;
160
+ /** The guards returned by `createGuards<T, G>()` when `T` has per-guard names. */
161
+ interface ScopedGuards<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> {
162
+ requirePermission: ScopedGuard<T, G, 'permission', PermissionGuardOptions<GuardHandlerContext<T, G>>>;
163
+ requireRole: ScopedGuard<T, G, 'role', RoleGuardOptions<GuardHandlerContext<T, G>>>;
164
+ requireRoleOrPermission: ScopedGuard<T, G, 'role_or_permission', RoleOrPermissionGuardOptions<GuardHandlerContext<T, G>>>;
165
+ canAny: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardHandlerContext<T, G>>>;
166
+ canAll: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardHandlerContext<T, G>>>;
167
+ }
168
+ /** What `createGuards<T, G>()` returns: {@link Guards}, or {@link ScopedGuards} for a config with `guards`. */
169
+ type GuardsFor<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> = T extends {
170
+ guards: object;
171
+ } ? ScopedGuards<T, G> : Guards<T>;
172
+ /**
173
+ * Builds the guards with shared defaults (e.g. a custom `onForbidden`).
174
+ *
175
+ * Pass the same type argument as `createRbac<AppTypes>()` (or `typeof rbac`) to check names at compile time:
176
+ * `const { requirePermission } = createGuards<AppTypes>()`. With per-guard names, `G` is the guard of the requests
177
+ * these guards run on: `createGuards<AppRbac, 'api'>()`.
178
+ */
179
+ declare function createGuards<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>>(defaults?: GuardHandlers<GuardHandlerContext<TypesOf<T>, G>>): GuardsFor<TypesOf<T>, G>;
180
+ declare const requirePermission: Guard<string, PermissionGuardOptions>;
181
+ declare const requireRole: Guard<string, RoleGuardOptions>;
182
+ declare const requireRoleOrPermission: Guard<string, RouteGuardOptions>;
183
+ declare const canAny: Guard<string, RouteGuardOptions>;
184
+ declare const canAll: Guard<string, RouteGuardOptions>;
185
+
186
+ export { type BeforeHandle, type Guard, type GuardContext, type GuardHandler, type GuardHandlerContext, type GuardHandlers, type GuardKind, type GuardNames, type Guards, type GuardsFor, type PermissionGuardOptions, type RbacContext, RbacPluginMissingError, type RbacPluginOptions, type RbacRequestContext, type RoleGuardOptions, type RoleOrPermissionGuardOptions, type RouteGuardOptions, type ScopedGuard, type ScopedGuards, type TypesOf, canAll, canAny, createGuards, rbacPlugin, requirePermission, requireRole, requireRoleOrPermission };
@@ -0,0 +1,186 @@
1
+ import * as elysia from 'elysia';
2
+ import { Elysia } from 'elysia';
3
+ import { Rbac, RbacTypeConfig, DefaultRbacTypes, DefaultGuardName, SubjectRbac, ScopedGuardName, Subject, TeamId, GuardOptions, CheckGuard, RequirementNames, RequirementArgs, RequirementKind, PermissionName, RoleName, GuardRequirementArgs, GuardName } from '@anievo-id/rbac-evolution';
4
+
5
+ type MaybePromise<T> = T | Promise<T>;
6
+ /** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */
7
+ type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never;
8
+ /**
9
+ * The request context `rbacPlugin()` reads the subject from. Elysia's full context type depends on the app, so the
10
+ * plugin types only what every request has; read your own derived values (e.g. `user`) with a cast or from
11
+ * `request`, or resolve them before the plugin.
12
+ */
13
+ interface RbacRequestContext {
14
+ request: Request;
15
+ headers: Record<string, string | undefined>;
16
+ [key: string]: unknown;
17
+ }
18
+ /**
19
+ * What `rbacPlugin()` adds to the context of every route after it. `T` (a names type like `AppRbac`, or
20
+ * `typeof rbac`) types the names `rbac` accepts; with per-guard names, `G` is the guard of the subject.
21
+ */
22
+ type RbacContext<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>> = {
23
+ /** Roles & permissions of the current subject. `null` for guests. */
24
+ rbac: SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>> | null;
25
+ };
26
+ interface RbacPluginOptions<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> {
27
+ /** The RBAC engine created with `createRbac(...)`. Its typed names flow into the `rbac` context value. */
28
+ rbac: Rbac<T>;
29
+ /**
30
+ * Resolves the authenticated subject for this request (e.g. from a session cookie or a JWT payload).
31
+ * Return `null` / `undefined` for guests.
32
+ */
33
+ getSubject: (ctx: RbacRequestContext) => MaybePromise<Subject | null | undefined>;
34
+ /**
35
+ * Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. With per-guard names, it must be one
36
+ * of the typed guards, and the `rbac` context value gets its names.
37
+ */
38
+ guard?: G | undefined;
39
+ /** Resolves the current team (only when the engine was created with `teams: true`). */
40
+ team?: (ctx: RbacRequestContext) => MaybePromise<TeamId | undefined>;
41
+ /**
42
+ * Plugin name, used by Elysia to register it once. Default: `'rbac-evolution'`. Give each instance its own name
43
+ * when you register two (e.g. a `web` and an `api` guard).
44
+ */
45
+ name?: string | undefined;
46
+ }
47
+ /**
48
+ * Resolves the current subject and adds `rbac` (a `SubjectRbac`, or `null` for guests) to the context of every
49
+ * route registered after it.
50
+ *
51
+ * ```ts
52
+ * const app = new Elysia()
53
+ * .use(rbacPlugin({ rbac, getSubject: ({ headers }) => (headers['x-user'] ? { type: 'user', id: headers['x-user'] } : null) }))
54
+ * .get('/me', ({ rbac }) => rbac?.getRoleNames() ?? [])
55
+ * ```
56
+ */
57
+ declare function rbacPlugin<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>>(options: RbacPluginOptions<T, G> & (T extends {
58
+ guards: object;
59
+ } ? GuardOptions<CheckGuard<T, G>> : unknown)): Elysia<"", {
60
+ decorator: {};
61
+ store: {};
62
+ derive: {};
63
+ resolve: RbacContext<T, ScopedGuardName<T, G>>;
64
+ }, {
65
+ typebox: {};
66
+ error: {};
67
+ }, {
68
+ schema: {};
69
+ standaloneSchema: {};
70
+ macro: {};
71
+ macroFn: {};
72
+ parser: {};
73
+ response: elysia.ExtractErrorFromHandle<RbacContext<T, ScopedGuardName<T, G>>>;
74
+ }, {}, {
75
+ derive: {};
76
+ resolve: {};
77
+ schema: {};
78
+ standaloneSchema: {};
79
+ response: {};
80
+ }, {
81
+ derive: {};
82
+ resolve: {};
83
+ schema: {};
84
+ standaloneSchema: {};
85
+ response: {};
86
+ }>;
87
+
88
+ type GuardKind = RequirementKind;
89
+ /** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */
90
+ interface GuardContext {
91
+ kind: GuardKind;
92
+ /** Groups of names: every group must pass, a group passes when ANY of its names matches. */
93
+ requirements: string[][];
94
+ }
95
+ /**
96
+ * The context the handlers of `createGuards<T>()` get: the request context plus an `rbac` with the names of `T`
97
+ * (of guard `G` with per-guard names).
98
+ */
99
+ type GuardHandlerContext<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>> = RbacRequestContext & RbacContext<T, G>;
100
+ /**
101
+ * Returns the response to send (any value Elysia can send: a `Response`, an object, a string), or throws (e.g.
102
+ * Elysia's `status(403)` / an `error()`).
103
+ */
104
+ type GuardHandler<C = GuardHandlerContext> = (ctx: C, context: GuardContext) => unknown;
105
+ interface GuardHandlers<C = GuardHandlerContext> {
106
+ /** Called when there is no subject (`rbac` is `null`). Default: 401 JSON. */
107
+ onUnauthenticated?: GuardHandler<C> | undefined;
108
+ /** Called when the subject lacks access. Default: 403 JSON. */
109
+ onForbidden?: GuardHandler<C> | undefined;
110
+ /**
111
+ * Include the required roles/permissions in the default 403 body.
112
+ * Default: `false` (like spatie's `display_permission_in_exception`).
113
+ */
114
+ exposeRequirements?: boolean | undefined;
115
+ }
116
+ /** The options every guard takes: the handlers plus `guard` (check in another guard, like spatie's `role:admin,api`). */
117
+ interface RouteGuardOptions<C = GuardHandlerContext> extends GuardHandlers<C> {
118
+ /** Check in this guard instead of the request's (`subject.withScope({ guard })`). Default: the request's guard. */
119
+ guard?: string | undefined;
120
+ }
121
+ interface PermissionGuardOptions<C = GuardHandlerContext> extends RouteGuardOptions<C> {
122
+ /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */
123
+ any?: boolean | undefined;
124
+ }
125
+ interface RoleGuardOptions<C = GuardHandlerContext> extends RouteGuardOptions<C> {
126
+ /** Require ALL of the roles (instead of any). Default: `false`. */
127
+ all?: boolean | undefined;
128
+ }
129
+ type RoleOrPermissionGuardOptions<C = GuardHandlerContext> = RouteGuardOptions<C>;
130
+ /** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
131
+ type GuardNames = RequirementNames;
132
+ /**
133
+ * A guard, used as an Elysia `beforeHandle` hook: `app.get('/x', handler, { beforeHandle: requireRole('admin') })`
134
+ * or `app.guard({ beforeHandle: [...] }, (app) => ...)`. It returns nothing when the check passes, and the
135
+ * response of `onUnauthenticated` / `onForbidden` otherwise, which ends the request.
136
+ */
137
+ type BeforeHandle = (ctx: object) => Promise<unknown>;
138
+ declare class RbacPluginMissingError extends Error {
139
+ readonly code = "RBAC_PLUGIN_MISSING";
140
+ constructor();
141
+ }
142
+ /**
143
+ * A guard typed with the names `N` it accepts and its options `O`: `(...names, options?)`.
144
+ * Every name (each part of a `'a|b'` list, each array item) must be one of `N`; with `N = string`, any name is.
145
+ */
146
+ type Guard<N extends string, O> = <const A extends readonly (GuardNames | O)[]>(...args: A & RequirementArgs<A, N, O>) => BeforeHandle;
147
+ /** The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). */
148
+ interface Guards<T extends RbacTypeConfig = DefaultRbacTypes> {
149
+ requirePermission: Guard<PermissionName<T>, PermissionGuardOptions<GuardHandlerContext<T>>>;
150
+ requireRole: Guard<RoleName<T>, RoleGuardOptions<GuardHandlerContext<T>>>;
151
+ requireRoleOrPermission: Guard<PermissionName<T> | RoleName<T>, RoleOrPermissionGuardOptions<GuardHandlerContext<T>>>;
152
+ canAny: Guard<PermissionName<T>, RouteGuardOptions<GuardHandlerContext<T>>>;
153
+ canAll: Guard<PermissionName<T>, RouteGuardOptions<GuardHandlerContext<T>>>;
154
+ }
155
+ /**
156
+ * A guard of `createGuards<T, G>()` when `T` has per-guard names: the names are those of the guard the call checks
157
+ * in, its `{ guard }` option or else `G` (the guard of the request).
158
+ */
159
+ type ScopedGuard<T extends RbacTypeConfig, G extends string, K extends GuardKind, O> = <const A extends readonly (GuardNames | O)[]>(...args: A & GuardRequirementArgs<A, T, K, G, O>) => BeforeHandle;
160
+ /** The guards returned by `createGuards<T, G>()` when `T` has per-guard names. */
161
+ interface ScopedGuards<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> {
162
+ requirePermission: ScopedGuard<T, G, 'permission', PermissionGuardOptions<GuardHandlerContext<T, G>>>;
163
+ requireRole: ScopedGuard<T, G, 'role', RoleGuardOptions<GuardHandlerContext<T, G>>>;
164
+ requireRoleOrPermission: ScopedGuard<T, G, 'role_or_permission', RoleOrPermissionGuardOptions<GuardHandlerContext<T, G>>>;
165
+ canAny: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardHandlerContext<T, G>>>;
166
+ canAll: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardHandlerContext<T, G>>>;
167
+ }
168
+ /** What `createGuards<T, G>()` returns: {@link Guards}, or {@link ScopedGuards} for a config with `guards`. */
169
+ type GuardsFor<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> = T extends {
170
+ guards: object;
171
+ } ? ScopedGuards<T, G> : Guards<T>;
172
+ /**
173
+ * Builds the guards with shared defaults (e.g. a custom `onForbidden`).
174
+ *
175
+ * Pass the same type argument as `createRbac<AppTypes>()` (or `typeof rbac`) to check names at compile time:
176
+ * `const { requirePermission } = createGuards<AppTypes>()`. With per-guard names, `G` is the guard of the requests
177
+ * these guards run on: `createGuards<AppRbac, 'api'>()`.
178
+ */
179
+ declare function createGuards<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>>(defaults?: GuardHandlers<GuardHandlerContext<TypesOf<T>, G>>): GuardsFor<TypesOf<T>, G>;
180
+ declare const requirePermission: Guard<string, PermissionGuardOptions>;
181
+ declare const requireRole: Guard<string, RoleGuardOptions>;
182
+ declare const requireRoleOrPermission: Guard<string, RouteGuardOptions>;
183
+ declare const canAny: Guard<string, RouteGuardOptions>;
184
+ declare const canAll: Guard<string, RouteGuardOptions>;
185
+
186
+ export { type BeforeHandle, type Guard, type GuardContext, type GuardHandler, type GuardHandlerContext, type GuardHandlers, type GuardKind, type GuardNames, type Guards, type GuardsFor, type PermissionGuardOptions, type RbacContext, RbacPluginMissingError, type RbacPluginOptions, type RbacRequestContext, type RoleGuardOptions, type RoleOrPermissionGuardOptions, type RouteGuardOptions, type ScopedGuard, type ScopedGuards, type TypesOf, canAll, canAny, createGuards, rbacPlugin, requirePermission, requireRole, requireRoleOrPermission };
package/dist/index.js ADDED
@@ -0,0 +1,92 @@
1
+ import { Elysia } from 'elysia';
2
+ import { splitRequirementArgs, permissionRequirement, roleRequirement, roleOrPermissionRequirement, satisfiesRequirement, REQUIREMENT_MESSAGES, UNAUTHENTICATED_MESSAGE } from '@anievo-id/rbac-evolution';
3
+
4
+ // src/plugin.ts
5
+ function rbacPlugin(options) {
6
+ const { getSubject, team } = options;
7
+ const guard = options.guard;
8
+ const rbac = options.rbac;
9
+ return new Elysia({ name: options.name ?? "rbac-evolution", seed: guard }).resolve(
10
+ { as: "global" },
11
+ async (ctx) => {
12
+ const subject = await getSubject(ctx);
13
+ if (!subject) return { rbac: null };
14
+ const teamId = team ? await team(ctx) : void 0;
15
+ const value = rbac.for(subject, {
16
+ ...guard !== void 0 && { guard },
17
+ ...teamId !== void 0 && { team: teamId }
18
+ });
19
+ return { rbac: value };
20
+ }
21
+ );
22
+ }
23
+ var RbacPluginMissingError = class extends Error {
24
+ code = "RBAC_PLUGIN_MISSING";
25
+ constructor() {
26
+ super("`rbac` is not set on the context. Register `rbacPlugin()` before the routes that use RBAC guards.");
27
+ this.name = "RbacPluginMissingError";
28
+ }
29
+ };
30
+ var json = (body, status) => Response.json(body, { status });
31
+ var defaultUnauthenticated = () => json({ error: "UNAUTHENTICATED", message: UNAUTHENTICATED_MESSAGE }, 401);
32
+ var defaultForbidden = (expose) => (_ctx, context) => json(
33
+ {
34
+ error: "FORBIDDEN",
35
+ reason: context.kind,
36
+ message: REQUIREMENT_MESSAGES[context.kind],
37
+ ...expose && { required: context.requirements }
38
+ },
39
+ 403
40
+ );
41
+ function createGuard(requirement, handlers, guard) {
42
+ const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated;
43
+ const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false);
44
+ const context = { kind: requirement.kind, requirements: requirement.requirements };
45
+ return async (ctx) => {
46
+ const rbac = ctx.rbac;
47
+ if (rbac === void 0) throw new RbacPluginMissingError();
48
+ const handlerCtx = ctx;
49
+ if (rbac === null) return onUnauthenticated(handlerCtx, context);
50
+ if (await satisfiesRequirement(guard === void 0 ? rbac : rbac.withScope({ guard }), requirement)) return void 0;
51
+ return onForbidden(handlerCtx, context);
52
+ };
53
+ }
54
+ function withDefaults(defaults, options) {
55
+ const merged = { ...defaults };
56
+ for (const [key, value] of Object.entries(options)) if (value !== void 0) merged[key] = value;
57
+ return merged;
58
+ }
59
+ function createGuards(defaults = {}) {
60
+ const shared = defaults;
61
+ function requirePermission2(...args) {
62
+ const { names, options = {} } = splitRequirementArgs(args);
63
+ return createGuard(permissionRequirement(names, options), withDefaults(shared, options), options.guard);
64
+ }
65
+ function requireRole2(...args) {
66
+ const { names, options = {} } = splitRequirementArgs(args);
67
+ return createGuard(roleRequirement(names, options), withDefaults(shared, options), options.guard);
68
+ }
69
+ function requireRoleOrPermission2(...args) {
70
+ const { names, options = {} } = splitRequirementArgs(args);
71
+ return createGuard(roleOrPermissionRequirement(names), withDefaults(shared, options), options.guard);
72
+ }
73
+ function canAny2(...args) {
74
+ const { names, options } = splitRequirementArgs(args);
75
+ return requirePermission2(...names, { ...options, any: true });
76
+ }
77
+ function canAll2(...args) {
78
+ const { names, options } = splitRequirementArgs(args);
79
+ return requirePermission2(...names, { ...options, any: false });
80
+ }
81
+ return { requirePermission: requirePermission2, requireRole: requireRole2, requireRoleOrPermission: requireRoleOrPermission2, canAny: canAny2, canAll: canAll2 };
82
+ }
83
+ var defaultGuards = createGuards();
84
+ var requirePermission = defaultGuards.requirePermission;
85
+ var requireRole = defaultGuards.requireRole;
86
+ var requireRoleOrPermission = defaultGuards.requireRoleOrPermission;
87
+ var canAny = defaultGuards.canAny;
88
+ var canAll = defaultGuards.canAll;
89
+
90
+ export { RbacPluginMissingError, canAll, canAny, createGuards, rbacPlugin, requirePermission, requireRole, requireRoleOrPermission };
91
+ //# sourceMappingURL=index.js.map
92
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugin.ts","../src/guards.ts"],"names":["requirePermission","requireRole","requireRoleOrPermission","canAny","canAll"],"mappings":";;;;AA0EO,SAAS,WACd,OAAA,EACA;AACA,EAAA,MAAM,EAAE,UAAA,EAAY,I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A,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,MAAM,CAAA;AAAA,EAC9D;AAGA,EAAA,SAASI,WAAU,IAAA,EAAiE;AAClF,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAI,qBAAwC,IAAI,CAAA;AACvE,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;AAEA,IAAM,gBAAwB,YAAA,EAAa;AAEpC,IAAM,oBAA2D,aAAA,CAAc;AAC/E,IAAM,cAA+C,aAAA,CAAc;AACnE,IAAM,0BAA4D,aAAA,CAAc;AAChF,IAAM,SAA2C,aAAA,CAAc;AAC/D,IAAM,SAA2C,aAAA,CAAc","file":"index.js","sourcesContent":["import type {\n CheckGuard,\n DefaultGuardName,\n DefaultRbacTypes,\n GuardOptions,\n Rbac,\n RbacTypeConfig,\n ScopedGuardName,\n Subject,\n SubjectRbac,\n TeamId,\n} from '@anievo-id/rbac-evolution'\nimport { Elysia } from 'elysia'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */\nexport type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never\n\n/**\n * The request context `rbacPlugin()` reads the subject from. Elysia's full context type depends on the app, so the\n * plugin types only what every request has; read your own derived values (e.g. `user`) with a cast or from\n * `request`, or resolve them before the plugin.\n */\nexport interface RbacRequestContext {\n request: Request\n headers: Record<string, string | undefined>\n [key: string]: unknown\n}\n\n/**\n * What `rbacPlugin()` adds to the context of every route after it. `T` (a names type like `AppRbac`, or\n * `typeof rbac`) types the names `rbac` accepts; with per-guard names, `G` is the guard of the subject.\n */\nexport type RbacContext<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends string = DefaultGuardName<TypesOf<T>>,\n> = {\n /** Roles & permissions of the current subject. `null` for guests. */\n rbac: SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>> | null\n}\n\nexport interface RbacPluginOptions<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> {\n /** The RBAC engine created with `createRbac(...)`. Its typed names flow into the `rbac` context value. */\n rbac: Rbac<T>\n /**\n * Resolves the authenticated subject for this request (e.g. from a session cookie or a JWT payload).\n * Return `null` / `undefined` for guests.\n */\n getSubject: (ctx: RbacRequestContext) => MaybePromise<Subject | null | undefined>\n /**\n * Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. With per-guard names, it must be one\n * of the typed guards, and the `rbac` context value gets its names.\n */\n guard?: G | undefined\n /** Resolves the current team (only when the engine was created with `teams: true`). */\n team?: (ctx: RbacRequestContext) => MaybePromise<TeamId | undefined>\n /**\n * Plugin name, used by Elysia to register it once. Default: `'rbac-evolution'`. Give each instance its own name\n * when you register two (e.g. a `web` and an `api` guard).\n */\n name?: string | undefined\n}\n\n/**\n * Resolves the current subject and adds `rbac` (a `SubjectRbac`, or `null` for guests) to the context of every\n * route registered after it.\n *\n * ```ts\n * const app = new Elysia()\n * .use(rbacPlugin({ rbac, getSubject: ({ headers }) => (headers['x-user'] ? { type: 'user', id: headers['x-user'] } : null) }))\n * .get('/me', ({ rbac }) => rbac?.getRoleNames() ?? [])\n * ```\n */\nexport function rbacPlugin<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>>(\n options: RbacPluginOptions<T, G> & (T extends { guards: object } ? GuardOptions<CheckGuard<T, G>> : unknown),\n) {\n const { getSubject, team } = options\n const guard: string | undefined = options.guard\n // `T` only narrows the names on `rbac`; the subject is the same object either way.\n const rbac = options.rbac as unknown as Rbac\n\n return new Elysia({ name: options.name ?? 'rbac-evolution', seed: guard }).resolve(\n { as: 'global' },\n async (ctx): Promise<RbacContext<T, ScopedGuardName<T, G>>> => {\n // Pass `ctx` itself: Elysia reads this function's source to decide which context fields to parse, and a\n // context handed to another function makes it parse them all (an alias would hide `headers` & co).\n const subject = await getSubject(ctx as unknown as RbacRequestContext)\n if (!subject) return { rbac: null }\n const teamId = team ? await team(ctx as unknown as RbacRequestContext) : undefined\n const value = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n return { rbac: value } as unknown as RbacContext<T, ScopedGuardName<T, G>>\n },\n )\n}\n","import {\n type DefaultGuardName,\n type DefaultRbacTypes,\n type GuardName,\n type GuardRequirementArgs,\n type PermissionName,\n permissionRequirement,\n type Rbac,\n type RbacRequirement,\n type RbacTypeConfig,\n type RequirementArgs,\n type RequirementKind,\n type RequirementNames,\n REQUIREMENT_MESSAGES,\n type RoleName,\n roleOrPermissionRequirement,\n roleRequirement,\n satisfiesRequirement,\n splitRequirementArgs,\n type SubjectRbac,\n UNAUTHENTICATED_MESSAGE,\n} from '@anievo-id/rbac-evolution'\nimport type { RbacContext, RbacRequestContext, TypesOf } from './plugin'\n\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/**\n * The context the handlers of `createGuards<T>()` get: the request context plus an `rbac` with the names of `T`\n * (of guard `G` with per-guard names).\n */\nexport type GuardHandlerContext<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends string = DefaultGuardName<TypesOf<T>>,\n> = RbacRequestContext & RbacContext<T, G>\n\n/**\n * Returns the response to send (any value Elysia can send: a `Response`, an object, a string), or throws (e.g.\n * Elysia's `status(403)` / an `error()`).\n */\nexport type GuardHandler<C = GuardHandlerContext> = (ctx: C, context: GuardContext) => unknown\n\nexport interface GuardHandlers<C = GuardHandlerContext> {\n /** Called when there is no subject (`rbac` is `null`). Default: 401 JSON. */\n onUnauthenticated?: GuardHandler<C> | undefined\n /** Called when the subject lacks access. Default: 403 JSON. */\n onForbidden?: GuardHandler<C> | undefined\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 | undefined\n}\n\n/** The options every guard takes: the handlers plus `guard` (check in another guard, like spatie's `role:admin,api`). */\nexport interface RouteGuardOptions<C = GuardHandlerContext> extends GuardHandlers<C> {\n /** Check in this guard instead of the request's (`subject.withScope({ guard })`). Default: the request's guard. */\n guard?: string | undefined\n}\n\nexport interface PermissionGuardOptions<C = GuardHandlerContext> extends RouteGuardOptions<C> {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean | undefined\n}\n\nexport interface RoleGuardOptions<C = GuardHandlerContext> extends RouteGuardOptions<C> {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean | undefined\n}\n\nexport type RoleOrPermissionGuardOptions<C = GuardHandlerContext> = RouteGuardOptions<C>\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = RequirementNames\n\n/**\n * A guard, used as an Elysia `beforeHandle` hook: `app.get('/x', handler, { beforeHandle: requireRole('admin') })`\n * or `app.guard({ beforeHandle: [...] }, (app) => ...)`. It returns nothing when the check passes, and the\n * response of `onUnauthenticated` / `onForbidden` otherwise, which ends the request.\n */\nexport type BeforeHandle = (ctx: object) => Promise<unknown>\n\nexport class RbacPluginMissingError extends Error {\n readonly code = 'RBAC_PLUGIN_MISSING'\n\n constructor() {\n super('`rbac` is not set on the context. Register `rbacPlugin()` before the routes that use RBAC guards.')\n this.name = 'RbacPluginMissingError'\n }\n}\n\nconst json = (body: unknown, status: number): Response => Response.json(body, { status })\n\nconst defaultUnauthenticated: GuardHandler = () => json({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }, 401)\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (_ctx, context) =>\n 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, guard: string | undefined): BeforeHandle {\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 (ctx) => {\n const rbac = (ctx as { rbac?: SubjectRbac | null }).rbac\n if (rbac === undefined) throw new RbacPluginMissingError()\n const handlerCtx = ctx as unknown as GuardHandlerContext\n if (rbac === null) return onUnauthenticated(handlerCtx, context)\n if (await satisfiesRequirement(guard === undefined ? rbac : rbac.withScope({ guard }), requirement)) return undefined\n return onForbidden(handlerCtx, context)\n }\n}\n\n/** `options` over `defaults`, where an option set to `undefined` keeps the default (as if left out). */\nfunction withDefaults(defaults: GuardHandlers, options: GuardHandlers): GuardHandlers {\n const merged: Record<string, unknown> = { ...defaults }\n for (const [key, value] of Object.entries(options)) if (value !== undefined) merged[key] = value\n return merged as GuardHandlers\n}\n\n/**\n * A guard typed with the names `N` it accepts and its options `O`: `(...names, options?)`.\n * Every name (each part of a `'a|b'` list, each array item) must be one of `N`; with `N = string`, any name is.\n */\nexport type Guard<N extends string, O> = <const A extends readonly (GuardNames | O)[]>(\n ...args: A & RequirementArgs<A, N, O>\n) => BeforeHandle\n\n/** The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). */\nexport interface Guards<T extends RbacTypeConfig = DefaultRbacTypes> {\n requirePermission: Guard<PermissionName<T>, PermissionGuardOptions<GuardHandlerContext<T>>>\n requireRole: Guard<RoleName<T>, RoleGuardOptions<GuardHandlerContext<T>>>\n requireRoleOrPermission: Guard<PermissionName<T> | RoleName<T>, RoleOrPermissionGuardOptions<GuardHandlerContext<T>>>\n canAny: Guard<PermissionName<T>, RouteGuardOptions<GuardHandlerContext<T>>>\n canAll: Guard<PermissionName<T>, RouteGuardOptions<GuardHandlerContext<T>>>\n}\n\n/**\n * A guard of `createGuards<T, G>()` when `T` has per-guard names: the names are those of the guard the call checks\n * in, its `{ guard }` option or else `G` (the guard of the request).\n */\nexport type ScopedGuard<T extends RbacTypeConfig, G extends string, K extends GuardKind, O> = <\n const A extends readonly (GuardNames | O)[],\n>(\n ...args: A & GuardRequirementArgs<A, T, K, G, O>\n) => BeforeHandle\n\n/** The guards returned by `createGuards<T, G>()` when `T` has per-guard names. */\nexport interface ScopedGuards<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> {\n requirePermission: ScopedGuard<T, G, 'permission', PermissionGuardOptions<GuardHandlerContext<T, G>>>\n requireRole: ScopedGuard<T, G, 'role', RoleGuardOptions<GuardHandlerContext<T, G>>>\n requireRoleOrPermission: ScopedGuard<T, G, 'role_or_permission', RoleOrPermissionGuardOptions<GuardHandlerContext<T, G>>>\n canAny: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardHandlerContext<T, G>>>\n canAll: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardHandlerContext<T, G>>>\n}\n\n/** What `createGuards<T, G>()` returns: {@link Guards}, or {@link ScopedGuards} for a config with `guards`. */\nexport type GuardsFor<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> = T extends {\n guards: object\n}\n ? ScopedGuards<T, G>\n : Guards<T>\n\n/**\n * Builds the guards with shared defaults (e.g. a custom `onForbidden`).\n *\n * Pass the same type argument as `createRbac<AppTypes>()` (or `typeof rbac`) to check names at compile time:\n * `const { requirePermission } = createGuards<AppTypes>()`. With per-guard names, `G` is the guard of the requests\n * these guards run on: `createGuards<AppRbac, 'api'>()`.\n */\nexport function createGuards<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>,\n>(defaults: GuardHandlers<GuardHandlerContext<TypesOf<T>, G>> = {}): GuardsFor<TypesOf<T>, G> {\n // The typed handlers only narrow `rbac`; the implementation below works on any context.\n const shared = defaults as unknown as GuardHandlers\n\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: readonly (GuardNames | PermissionGuardOptions)[]): BeforeHandle {\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\n return createGuard(permissionRequirement(names, options), withDefaults(shared, options), options.guard)\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: readonly (GuardNames | RoleGuardOptions)[]): BeforeHandle {\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\n return createGuard(roleRequirement(names, options), withDefaults(shared, options), options.guard)\n }\n\n /** Passes with ANY of the names as a role OR a permission, like spatie's `role_or_permission:` middleware. */\n function requireRoleOrPermission(...args: readonly (GuardNames | RoleOrPermissionGuardOptions)[]): BeforeHandle {\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\n return createGuard(roleOrPermissionRequirement(names), withDefaults(shared, options), options.guard)\n }\n\n /** spatie v8.5 `canAny()`: passes with ANY of the listed permissions. */\n function canAny(...args: readonly (GuardNames | RouteGuardOptions)[]): BeforeHandle {\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(args)\n return requirePermission(...names, { ...options, any: true })\n }\n\n /** spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\". */\n function canAll(...args: readonly (GuardNames | RouteGuardOptions)[]): BeforeHandle {\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(args)\n return requirePermission(...names, { ...options, any: false })\n }\n\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } as unknown as GuardsFor<TypesOf<T>, G>\n}\n\nconst defaultGuards: Guards = createGuards()\n\nexport const requirePermission: Guard<string, PermissionGuardOptions> = defaultGuards.requirePermission\nexport const requireRole: Guard<string, RoleGuardOptions> = defaultGuards.requireRole\nexport const requireRoleOrPermission: Guard<string, RouteGuardOptions> = defaultGuards.requireRoleOrPermission\nexport const canAny: Guard<string, RouteGuardOptions> = defaultGuards.canAny\nexport const canAll: Guard<string, RouteGuardOptions> = defaultGuards.canAll\n\n"]}
package/package.json CHANGED
@@ -1,11 +1,72 @@
1
1
  {
2
2
  "name": "@anievo-id/rbac-evolution-elysia",
3
- "version": "0.0.0",
4
- "description": "Placeholder for the first release of this package. Use 1.x.",
3
+ "version": "1.5.0",
4
+ "description": "Elysia plugin and beforeHandle guards for rbac-evolution — Bun-first, also on Node, Deno and Cloudflare Workers.",
5
5
  "license": "MIT",
6
+ "author": "AniEvo-ID (https://github.com/AniEvo-ID)",
7
+ "homepage": "https://creation.anievo.id/rbac-evolution/frameworks/elysia",
8
+ "bugs": {
9
+ "url": "https://github.com/AniEvo-ID/rbac-evolution/issues"
10
+ },
11
+ "type": "module",
6
12
  "repository": {
7
13
  "type": "git",
8
14
  "url": "git+https://github.com/AniEvo-ID/rbac-evolution.git",
9
15
  "directory": "packages/elysia"
16
+ },
17
+ "keywords": [
18
+ "rbac",
19
+ "permissions",
20
+ "roles",
21
+ "authorization",
22
+ "elysia",
23
+ "bun",
24
+ "plugin",
25
+ "middleware"
26
+ ],
27
+ "sideEffects": false,
28
+ "main": "./dist/index.cjs",
29
+ "module": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "import": {
34
+ "types": "./dist/index.d.ts",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "require": {
38
+ "types": "./dist/index.d.cts",
39
+ "default": "./dist/index.cjs"
40
+ }
41
+ },
42
+ "./package.json": "./package.json"
43
+ },
44
+ "files": [
45
+ "dist"
46
+ ],
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "dependencies": {
51
+ "@anievo-id/rbac-evolution": "^1.5.0"
52
+ },
53
+ "peerDependencies": {
54
+ "elysia": ">=1.2"
55
+ },
56
+ "devDependencies": {
57
+ "elysia": "^1.4.0",
58
+ "tsup": "^8.3.0",
59
+ "typescript": "^5.7.0",
60
+ "vitest": "^2.1.0"
61
+ },
62
+ "engines": {
63
+ "node": ">=20"
64
+ },
65
+ "scripts": {
66
+ "build": "tsup",
67
+ "dev": "tsup --watch",
68
+ "typecheck": "tsc --noEmit",
69
+ "test": "vitest run --passWithNoTests",
70
+ "clean": "rm -rf dist .turbo"
10
71
  }
11
72
  }