@anievo-id/rbac-evolution-hono 0.7.0 → 0.8.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/README.md +16 -0
- package/dist/index.cjs +8 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +36 -21
- package/dist/index.d.ts +36 -21
- package/dist/index.js +8 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -111,6 +111,22 @@ export const { requirePermission, requireRole, requireRoleOrPermission } = creat
|
|
|
111
111
|
})
|
|
112
112
|
```
|
|
113
113
|
|
|
114
|
+
## Typed names
|
|
115
|
+
|
|
116
|
+
Pass the type you gave `createRbac<AppRbac>()` to `createGuards()`, and a typo in a guard name is a compile error:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { createGuards } from '@anievo-id/rbac-evolution-hono'
|
|
120
|
+
import type { AppRbac } from './rbac' // the type you pass to createRbac<AppRbac>()
|
|
121
|
+
|
|
122
|
+
export const { requirePermission, requireRole } = createGuards<AppRbac>()
|
|
123
|
+
|
|
124
|
+
app.put('/articles/:id', requirePermission('edit articles|publish articles'), updateArticle)
|
|
125
|
+
app.delete('/articles/:id', requirePermission('delete artcles'), deleteArticle) // type error
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`createGuards<typeof rbac>()` works too. The guards exported by the package still accept any string.
|
|
129
|
+
|
|
114
130
|
## License
|
|
115
131
|
|
|
116
132
|
MIT
|
package/dist/index.cjs
CHANGED
|
@@ -52,18 +52,23 @@ function createGuard(requirement, handlers) {
|
|
|
52
52
|
return onForbidden(c, context);
|
|
53
53
|
};
|
|
54
54
|
}
|
|
55
|
+
function withDefaults(defaults, options) {
|
|
56
|
+
const merged = { ...defaults };
|
|
57
|
+
for (const [key, value] of Object.entries(options)) if (value !== void 0) merged[key] = value;
|
|
58
|
+
return merged;
|
|
59
|
+
}
|
|
55
60
|
function createGuards(defaults = {}) {
|
|
56
61
|
function requirePermission2(...args) {
|
|
57
62
|
const { names, options = {} } = rbacEvolution.splitRequirementArgs(args);
|
|
58
|
-
return createGuard(rbacEvolution.permissionRequirement(names, options),
|
|
63
|
+
return createGuard(rbacEvolution.permissionRequirement(names, options), withDefaults(defaults, options));
|
|
59
64
|
}
|
|
60
65
|
function requireRole2(...args) {
|
|
61
66
|
const { names, options = {} } = rbacEvolution.splitRequirementArgs(args);
|
|
62
|
-
return createGuard(rbacEvolution.roleRequirement(names, options),
|
|
67
|
+
return createGuard(rbacEvolution.roleRequirement(names, options), withDefaults(defaults, options));
|
|
63
68
|
}
|
|
64
69
|
function requireRoleOrPermission2(...args) {
|
|
65
70
|
const { names, options = {} } = rbacEvolution.splitRequirementArgs(args);
|
|
66
|
-
return createGuard(rbacEvolution.roleOrPermissionRequirement(names),
|
|
71
|
+
return createGuard(rbacEvolution.roleOrPermissionRequirement(names), withDefaults(defaults, options));
|
|
67
72
|
}
|
|
68
73
|
function canAny2(...args) {
|
|
69
74
|
const { names, options } = rbacEvolution.splitRequirementArgs(args);
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/middleware.ts","../src/guards.ts"],"names":["UNAUTHENTICATED_MESSAGE","REQUIREMENT_MESSAGES","satisfiesRequirement","requirePermission","splitRequirementArgs","permissionRequirement","requireRole","roleRequirement","requireRoleOrPermission","roleOrPermissionRequirement","canAny","canAll"],"mappings":";;;;;AAwCO,SAAS,eAAoC,OAAA,EAAmE;AACrH,EAAA,MAAM,EAAE,IAAA,EAAM,UAAA,EAAY,KAAA,EAAO,MAAK,GAAI,OAAA;AAE1C,EAAA,OAAO,OAAO,GAAG,IAAA,KAAS;AACxB,IAAA,MAAM,GAAA,GAAM,CAAA;AACZ,IAAA,MAAM,OAAA,GAAU,MAAM,UAAA,CAAW,GAAG,CAAA;AACpC,IAAA,IAAI,KAAA,GAA4B,IAAA;AAChC,IAAA,IAAI,OAAA,EAAS;AACX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GAAU,EAAC,EAAE,GAAIJ,mCAAmD,IAAI,CAAA;AACvF,IAAA,OAAO,WAAA,CAAYK,0CAA4B,KAAK,CAAA,EAAG,EAAE,GAAG,QAAA,EAAU,GAAG,OAAA,EAAS,CAAA;AAAA,EACpF;AAOA,EAAA,SAASC,WAAU,IAAA,EAAkE;AACnF,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAIN,mCAAoC,IAAI,CAAA;AACnE,IAAA,OAAOD,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,MAAM,CAAA;AAAA,EAC9D;AAOA,EAAA,SAASQ,WAAU,IAAA,EAAkE;AACnF,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAIP,mCAAoC,IAAI,CAAA;AACnE,IAAA,OAAOD,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,OAAO,CAAA;AAAA,EAC/D;AAEA,EAAA,OAAO,EAAE,iBAAA,EAAAA,kBAAAA,EAAmB,WAAA,EAAAG,YAAAA,EAAa,yBAAAE,wBAAAA,EAAyB,MAAA,EAAAE,OAAAA,EAAQ,MAAA,EAAAC,OAAAA,EAAO;AACnF;AAEO,IAAM,EAAE,iBAAA,EAAmB,WAAA,EAAa,yBAAyB,MAAA,EAAQ,MAAA,KAAW,YAAA","file":"index.cjs","sourcesContent":["import type { Rbac, Subject, SubjectRbac, TeamId } from '@anievo-id/rbac-evolution'\nimport type { Context, Env, MiddlewareHandler } from 'hono'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** Context variables set by `rbacMiddleware()`. */\nexport type RbacVariables = {\n /** Roles & permissions of the current subject. `null` for guests. */\n rbac: SubjectRbac | null\n}\n\n/**\n * Hono env for apps using `rbacMiddleware()`: `new Hono<RbacEnv>()` types `c.var.rbac`.\n * Combine it with your own variables: `new Hono<{ Variables: RbacVariables & { user: User } }>()`.\n */\nexport type RbacEnv = {\n Variables: RbacVariables\n}\n\nexport interface RbacMiddlewareOptions<E extends Env = Env> {\n /** The RBAC engine created with `createRbac(...)`. */\n rbac: Rbac\n /**\n * Resolves the authenticated subject for this request (e.g. from `c.var.user` or a JWT payload).\n * Return `null` / `undefined` for guests.\n */\n getSubject: (c: Context<E>) => MaybePromise<Subject | null | undefined>\n /** Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. */\n guard?: string\n /** Resolves the current team (only when the engine was created with `teams: true`). */\n team?: (c: Context<E>) => MaybePromise<TeamId | undefined>\n}\n\n/**\n * Resolves the current subject and sets `c.var.rbac` (a `SubjectRbac`, or `null` for guests).\n *\n * ```ts\n * app.use(rbacMiddleware({ rbac, getSubject: (c) => (c.var.user ? { type: 'user', id: c.var.user.id } : null) }))\n * ```\n */\nexport function rbacMiddleware<E extends Env = Env>(options: RbacMiddlewareOptions<E>): MiddlewareHandler<E & RbacEnv> {\n const { rbac, getSubject, guard, team } = options\n\n return async (c, next) => {\n const ctx = c as unknown as Context<E>\n const subject = await getSubject(ctx)\n let value: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(ctx) : undefined\n value = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n ;(c as unknown as Context<RbacEnv>).set('rbac', value)\n await next()\n }\n}\n","import {\n permissionRequirement,\n type RbacRequirement,\n type RequirementKind,\n type RequirementNames,\n REQUIREMENT_MESSAGES,\n roleOrPermissionRequirement,\n roleRequirement,\n satisfiesRequirement,\n splitRequirementArgs,\n type SubjectRbac,\n UNAUTHENTICATED_MESSAGE,\n} from '@anievo-id/rbac-evolution'\nimport type { Context, MiddlewareHandler } from 'hono'\nimport type { RbacEnv } from './middleware'\n\nexport type GuardKind = RequirementKind\n\n/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */\nexport interface GuardContext {\n kind: GuardKind\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\n requirements: string[][]\n}\n\n/** Returns the response to send (or throws, e.g. an `HTTPException`). */\nexport type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>\n\nexport interface GuardHandlers {\n /** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */\n onUnauthenticated?: GuardHandler\n /** Called when the subject lacks access. Default: 403 JSON. */\n onForbidden?: GuardHandler\n /**\n * Include the required roles/permissions in the default 403 body.\n * Default: `false` (like spatie's `display_permission_in_exception`).\n */\n exposeRequirements?: boolean\n}\n\nexport interface PermissionGuardOptions extends GuardHandlers {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean\n}\n\nexport interface RoleGuardOptions extends GuardHandlers {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean\n}\n\nexport type RoleOrPermissionGuardOptions = GuardHandlers\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = RequirementNames\n\nexport class RbacMiddlewareMissingError extends Error {\n readonly code = 'RBAC_MIDDLEWARE_MISSING'\n\n constructor() {\n super('`c.var.rbac` is not set. Register `rbacMiddleware()` before using RBAC guards.')\n this.name = 'RbacMiddlewareMissingError'\n }\n}\n\nconst defaultUnauthenticated: GuardHandler = (c) =>\n c.json({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }, 401)\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (c, context) =>\n c.json(\n {\n error: 'FORBIDDEN',\n reason: context.kind,\n message: REQUIREMENT_MESSAGES[context.kind],\n ...(expose && { required: context.requirements }),\n },\n 403,\n )\n\nfunction createGuard(requirement: RbacRequirement, handlers: GuardHandlers): MiddlewareHandler<RbacEnv> {\n const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated\n const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false)\n const context: GuardContext = { kind: requirement.kind, requirements: requirement.requirements }\n\n return async (c, next) => {\n const rbac = c.get('rbac') as SubjectRbac | null | undefined\n if (rbac === undefined) throw new RbacMiddlewareMissingError()\n if (rbac === null) return onUnauthenticated(c, context)\n if (await satisfiesRequirement(rbac, requirement)) {\n await next()\n return\n }\n return onForbidden(c, context)\n }\n}\n\n/** Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page). */\nexport function createGuards(defaults: GuardHandlers = {}) {\n /**\n * Requires permissions, like spatie's `permission:` middleware.\n *\n * - `requirePermission('edit articles')`\n * - `requirePermission('edit articles|delete articles')` — any of them\n * - `requirePermission('edit articles', 'publish articles')` — all of them\n * - `requirePermission('a', 'b', { any: true })` — any of them\n */\n function requirePermission(...args: (GuardNames | PermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\n return createGuard(permissionRequirement(names, options), { ...defaults, ...options })\n }\n\n /**\n * Requires roles, like spatie's `role:` middleware.\n *\n * - `requireRole('admin')`, `requireRole('admin|editor')`, `requireRole('admin', 'editor')` — any of them\n * - `requireRole('admin', 'editor', { all: true })` — all of them\n */\n function requireRole(...args: (GuardNames | RoleGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\n return createGuard(roleRequirement(names, options), { ...defaults, ...options })\n }\n\n /**\n * Passes when the subject has ANY of the names as a role OR as a permission,\n * like spatie's `role_or_permission:` middleware.\n *\n * - `requireRoleOrPermission('admin|edit articles')`\n */\n function requireRoleOrPermission(...args: (GuardNames | RoleOrPermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\n return createGuard(roleOrPermissionRequirement(names), { ...defaults, ...options })\n }\n\n /**\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `canAny('edit articles', 'publish articles')`, `canAny(['edit articles', 'publish articles'])`\n */\n function canAny(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: true })\n }\n\n /**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `canAll('edit articles', 'publish articles')`, `canAll(['edit articles', 'publish|review'])`\n */\n function canAll(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: false })\n }\n\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll }\n}\n\nexport const { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } = createGuards()\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/middleware.ts","../src/guards.ts"],"names":["UNAUTHENTICATED_MESSAGE","REQUIREMENT_MESSAGES","satisfiesRequirement","requirePermission","splitRequirementArgs","permissionRequirement","requireRole","roleRequirement","requireRoleOrPermission","roleOrPermissionRequirement","canAny","canAll"],"mappings":";;;;;AAwCO,SAAS,eAAoC,OAAA,EAAmE;AACrH,EAAA,MAAM,EAAE,IAAA,EAAM,UAAA,EAAY,KAAA,EAAO,MAAK,GAAI,OAAA;AAE1C,EAAA,OAAO,OAAO,GAAG,IAAA,KAAS;AACxB,IAAA,MAAM,GAAA,GAAM,CAAA;AACZ,IAAA,MAAM,OAAA,GAAU,MAAM,UAAA,CAAW,GAAG,CAAA;AACpC,IAAA,IAAI,KAAA,GAA4B,IAAA;AAChC,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,MAAM,MAAA,GAAS,IAAA,GAAO,MAAM,IAAA,CAAK,GAAG,CAAA,GAAI,MAAA;AACxC,MAAA,KAAA,GAAQ,IAAA,CAAK,IAAI,OAAA,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,CAA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AAI,CAAA;AACvF,IAAA,OAAO,YAAYK,yCAAA,CAA4B,KAAK,GAAG,YAAA,CAAa,QAAA,EAAU,OAAO,CAAC,CAAA;AAAA,EACxF;AAOA,EAAA,SAASC,WAAU,IAAA,EAA2E;AAC5F,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAIN,mCAAoC,IAAI,CAAA;AACnE,IAAA,OAAOD,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,MAAM,CAAA;AAAA,EAC9D;AAOA,EAAA,SAASQ,WAAU,IAAA,EAA2E;AAC5F,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAIP,mCAAoC,IAAI,CAAA;AACnE,IAAA,OAAOD,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,OAAO,CAAA;AAAA,EAC/D;AAIA,EAAA,OAAO,EAAE,iBAAA,EAAAA,kBAAAA,EAAmB,WAAA,EAAAG,YAAAA,EAAa,yBAAAE,wBAAAA,EAAyB,MAAA,EAAAE,OAAAA,EAAQ,MAAA,EAAAC,OAAAA,EAAO;AACnF;AAEO,IAAM,EAAE,iBAAA,EAAmB,WAAA,EAAa,yBAAyB,MAAA,EAAQ,MAAA,KAAW,YAAA","file":"index.cjs","sourcesContent":["import type { Rbac, Subject, SubjectRbac, TeamId } from '@anievo-id/rbac-evolution'\nimport type { Context, Env, MiddlewareHandler } from 'hono'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** Context variables set by `rbacMiddleware()`. */\nexport type RbacVariables = {\n /** Roles & permissions of the current subject. `null` for guests. */\n rbac: SubjectRbac | null\n}\n\n/**\n * Hono env for apps using `rbacMiddleware()`: `new Hono<RbacEnv>()` types `c.var.rbac`.\n * Combine it with your own variables: `new Hono<{ Variables: RbacVariables & { user: User } }>()`.\n */\nexport type RbacEnv = {\n Variables: RbacVariables\n}\n\nexport interface RbacMiddlewareOptions<E extends Env = Env> {\n /** The RBAC engine created with `createRbac(...)`. */\n rbac: Rbac\n /**\n * Resolves the authenticated subject for this request (e.g. from `c.var.user` or a JWT payload).\n * Return `null` / `undefined` for guests.\n */\n getSubject: (c: Context<E>) => MaybePromise<Subject | null | undefined>\n /** Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. */\n guard?: string | undefined\n /** Resolves the current team (only when the engine was created with `teams: true`). */\n team?: (c: Context<E>) => MaybePromise<TeamId | undefined>\n}\n\n/**\n * Resolves the current subject and sets `c.var.rbac` (a `SubjectRbac`, or `null` for guests).\n *\n * ```ts\n * app.use(rbacMiddleware({ rbac, getSubject: (c) => (c.var.user ? { type: 'user', id: c.var.user.id } : null) }))\n * ```\n */\nexport function rbacMiddleware<E extends Env = Env>(options: RbacMiddlewareOptions<E>): MiddlewareHandler<E & RbacEnv> {\n const { rbac, getSubject, guard, team } = options\n\n return async (c, next) => {\n const ctx = c as unknown as Context<E>\n const subject = await getSubject(ctx)\n let value: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(ctx) : undefined\n value = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n ;(c as unknown as Context<RbacEnv>).set('rbac', value)\n await next()\n }\n}\n","import {\n type DefaultRbacTypes,\n type PermissionName,\n permissionRequirement,\n type Rbac,\n type RbacTypeConfig,\n type RbacRequirement,\n type RequirementKind,\n type RequirementArgs,\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 { Context, MiddlewareHandler } from 'hono'\nimport type { RbacEnv } from './middleware'\n\nexport type GuardKind = RequirementKind\n\n/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */\nexport interface GuardContext {\n kind: GuardKind\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\n requirements: string[][]\n}\n\n/** Returns the response to send (or throws, e.g. an `HTTPException`). */\nexport type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>\n\nexport interface GuardHandlers {\n /** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */\n onUnauthenticated?: GuardHandler | undefined\n /** Called when the subject lacks access. Default: 403 JSON. */\n onForbidden?: GuardHandler | 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\nexport interface PermissionGuardOptions extends GuardHandlers {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean | undefined\n}\n\nexport interface RoleGuardOptions extends GuardHandlers {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean | undefined\n}\n\nexport type RoleOrPermissionGuardOptions = GuardHandlers\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = RequirementNames\n\nexport class RbacMiddlewareMissingError extends Error {\n readonly code = 'RBAC_MIDDLEWARE_MISSING'\n\n constructor() {\n super('`c.var.rbac` is not set. Register `rbacMiddleware()` before using RBAC guards.')\n this.name = 'RbacMiddlewareMissingError'\n }\n}\n\nconst defaultUnauthenticated: GuardHandler = (c) =>\n c.json({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }, 401)\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (c, context) =>\n c.json(\n {\n error: 'FORBIDDEN',\n reason: context.kind,\n message: REQUIREMENT_MESSAGES[context.kind],\n ...(expose && { required: context.requirements }),\n },\n 403,\n )\n\nfunction createGuard(requirement: RbacRequirement, handlers: GuardHandlers): MiddlewareHandler<RbacEnv> {\n const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated\n const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false)\n const context: GuardContext = { kind: requirement.kind, requirements: requirement.requirements }\n\n return async (c, next) => {\n const rbac = c.get('rbac') as SubjectRbac | null | undefined\n if (rbac === undefined) throw new RbacMiddlewareMissingError()\n if (rbac === null) return onUnauthenticated(c, context)\n if (await satisfiesRequirement(rbac, requirement)) {\n await next()\n return\n }\n return onForbidden(c, context)\n }\n}\n\n/** `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 * A call without names, or with options that are not the last argument, is a type error.\n */\nexport type Guard<N extends string, O> = <const A extends readonly (GuardNames | O)[]>(\n ...args: A & RequirementArgs<A, N, O>\n) => MiddlewareHandler<RbacEnv>\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>\n requireRole: Guard<RoleName<T>, RoleGuardOptions>\n requireRoleOrPermission: Guard<PermissionName<T> | RoleName<T>, RoleOrPermissionGuardOptions>\n canAny: Guard<PermissionName<T>, GuardHandlers>\n canAll: Guard<PermissionName<T>, GuardHandlers>\n}\n\n/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */\ntype TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never\n\n/**\n * Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page).\n *\n * Pass the same type argument as `createRbac<AppTypes>()` (or `typeof rbac`) to check names at compile time:\n * `const { requirePermission } = createGuards<AppTypes>()`.\n */\nexport function createGuards<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes>(\n defaults: GuardHandlers = {},\n): Guards<TypesOf<T>> {\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)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\n return createGuard(permissionRequirement(names, options), withDefaults(defaults, options))\n }\n\n /**\n * Requires roles, like spatie's `role:` middleware.\n *\n * - `requireRole('admin')`, `requireRole('admin|editor')`, `requireRole('admin', 'editor')` — any of them\n * - `requireRole('admin', 'editor', { all: true })` — all of them\n */\n function requireRole(...args: readonly (GuardNames | RoleGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\n return createGuard(roleRequirement(names, options), withDefaults(defaults, options))\n }\n\n /**\n * Passes when the subject has ANY of the names as a role OR as a permission,\n * like spatie's `role_or_permission:` middleware.\n *\n * - `requireRoleOrPermission('admin|edit articles')`\n */\n function requireRoleOrPermission(...args: readonly (GuardNames | RoleOrPermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\n return createGuard(roleOrPermissionRequirement(names), withDefaults(defaults, options))\n }\n\n /**\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `canAny('edit articles', 'publish articles')`, `canAny(['edit articles', 'publish articles'])`\n */\n function canAny(...args: readonly (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: true })\n }\n\n /**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `canAll('edit articles', 'publish articles')`, `canAll(['edit articles', 'publish|review'])`\n */\n function canAll(...args: readonly (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: false })\n }\n\n // The untyped functions above take any spread of names (`canAny` passes `...names` on); the typed signature\n // is only the public face, so a cast is enough. No runtime change.\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } as Guards<TypesOf<T>>\n}\n\nexport const { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } = createGuards()\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SubjectRbac, Rbac, Subject, TeamId, RequirementKind,
|
|
1
|
+
import { SubjectRbac, Rbac, Subject, TeamId, RequirementNames, RequirementArgs, RequirementKind, RbacTypeConfig, DefaultRbacTypes, PermissionName, RoleName } from '@anievo-id/rbac-evolution';
|
|
2
2
|
import { Env, Context, MiddlewareHandler } from 'hono';
|
|
3
3
|
|
|
4
4
|
type MaybePromise<T> = T | Promise<T>;
|
|
@@ -23,7 +23,7 @@ interface RbacMiddlewareOptions<E extends Env = Env> {
|
|
|
23
23
|
*/
|
|
24
24
|
getSubject: (c: Context<E>) => MaybePromise<Subject | null | undefined>;
|
|
25
25
|
/** Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. */
|
|
26
|
-
guard?: string;
|
|
26
|
+
guard?: string | undefined;
|
|
27
27
|
/** Resolves the current team (only when the engine was created with `teams: true`). */
|
|
28
28
|
team?: (c: Context<E>) => MaybePromise<TeamId | undefined>;
|
|
29
29
|
}
|
|
@@ -47,22 +47,22 @@ interface GuardContext {
|
|
|
47
47
|
type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>;
|
|
48
48
|
interface GuardHandlers {
|
|
49
49
|
/** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */
|
|
50
|
-
onUnauthenticated?: GuardHandler;
|
|
50
|
+
onUnauthenticated?: GuardHandler | undefined;
|
|
51
51
|
/** Called when the subject lacks access. Default: 403 JSON. */
|
|
52
|
-
onForbidden?: GuardHandler;
|
|
52
|
+
onForbidden?: GuardHandler | undefined;
|
|
53
53
|
/**
|
|
54
54
|
* Include the required roles/permissions in the default 403 body.
|
|
55
55
|
* Default: `false` (like spatie's `display_permission_in_exception`).
|
|
56
56
|
*/
|
|
57
|
-
exposeRequirements?: boolean;
|
|
57
|
+
exposeRequirements?: boolean | undefined;
|
|
58
58
|
}
|
|
59
59
|
interface PermissionGuardOptions extends GuardHandlers {
|
|
60
60
|
/** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */
|
|
61
|
-
any?: boolean;
|
|
61
|
+
any?: boolean | undefined;
|
|
62
62
|
}
|
|
63
63
|
interface RoleGuardOptions extends GuardHandlers {
|
|
64
64
|
/** Require ALL of the roles (instead of any). Default: `false`. */
|
|
65
|
-
all?: boolean;
|
|
65
|
+
all?: boolean | undefined;
|
|
66
66
|
}
|
|
67
67
|
type RoleOrPermissionGuardOptions = GuardHandlers;
|
|
68
68
|
/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
|
|
@@ -71,18 +71,33 @@ declare class RbacMiddlewareMissingError extends Error {
|
|
|
71
71
|
readonly code = "RBAC_MIDDLEWARE_MISSING";
|
|
72
72
|
constructor();
|
|
73
73
|
}
|
|
74
|
-
/**
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
74
|
+
/**
|
|
75
|
+
* A guard typed with the names `N` it accepts and its options `O`: `(...names, options?)`.
|
|
76
|
+
* Every name (each part of a `'a|b'` list, each array item) must be one of `N`; with `N = string`, any name is.
|
|
77
|
+
* A call without names, or with options that are not the last argument, is a type error.
|
|
78
|
+
*/
|
|
79
|
+
type Guard<N extends string, O> = <const A extends readonly (GuardNames | O)[]>(...args: A & RequirementArgs<A, N, O>) => MiddlewareHandler<RbacEnv>;
|
|
80
|
+
/** The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). */
|
|
81
|
+
interface Guards<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
82
|
+
requirePermission: Guard<PermissionName<T>, PermissionGuardOptions>;
|
|
83
|
+
requireRole: Guard<RoleName<T>, RoleGuardOptions>;
|
|
84
|
+
requireRoleOrPermission: Guard<PermissionName<T> | RoleName<T>, RoleOrPermissionGuardOptions>;
|
|
85
|
+
canAny: Guard<PermissionName<T>, GuardHandlers>;
|
|
86
|
+
canAll: Guard<PermissionName<T>, GuardHandlers>;
|
|
87
|
+
}
|
|
88
|
+
/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */
|
|
89
|
+
type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never;
|
|
90
|
+
/**
|
|
91
|
+
* Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page).
|
|
92
|
+
*
|
|
93
|
+
* Pass the same type argument as `createRbac<AppTypes>()` (or `typeof rbac`) to check names at compile time:
|
|
94
|
+
* `const { requirePermission } = createGuards<AppTypes>()`.
|
|
95
|
+
*/
|
|
96
|
+
declare function createGuards<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes>(defaults?: GuardHandlers): Guards<TypesOf<T>>;
|
|
97
|
+
declare const requirePermission: Guard<string, PermissionGuardOptions>;
|
|
98
|
+
declare const requireRole: Guard<string, RoleGuardOptions>;
|
|
99
|
+
declare const requireRoleOrPermission: Guard<string, GuardHandlers>;
|
|
100
|
+
declare const canAny: Guard<string, GuardHandlers>;
|
|
101
|
+
declare const canAll: Guard<string, GuardHandlers>;
|
|
87
102
|
|
|
88
|
-
export { type GuardContext, type GuardHandler, type GuardHandlers, type GuardKind, type GuardNames, type PermissionGuardOptions, type RbacEnv, RbacMiddlewareMissingError, type RbacMiddlewareOptions, type RbacVariables, type RoleGuardOptions, type RoleOrPermissionGuardOptions, canAll, canAny, createGuards, rbacMiddleware, requirePermission, requireRole, requireRoleOrPermission };
|
|
103
|
+
export { type Guard, type GuardContext, type GuardHandler, type GuardHandlers, type GuardKind, type GuardNames, type Guards, type PermissionGuardOptions, type RbacEnv, RbacMiddlewareMissingError, type RbacMiddlewareOptions, type RbacVariables, type RoleGuardOptions, type RoleOrPermissionGuardOptions, canAll, canAny, createGuards, rbacMiddleware, requirePermission, requireRole, requireRoleOrPermission };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SubjectRbac, Rbac, Subject, TeamId, RequirementKind,
|
|
1
|
+
import { SubjectRbac, Rbac, Subject, TeamId, RequirementNames, RequirementArgs, RequirementKind, RbacTypeConfig, DefaultRbacTypes, PermissionName, RoleName } from '@anievo-id/rbac-evolution';
|
|
2
2
|
import { Env, Context, MiddlewareHandler } from 'hono';
|
|
3
3
|
|
|
4
4
|
type MaybePromise<T> = T | Promise<T>;
|
|
@@ -23,7 +23,7 @@ interface RbacMiddlewareOptions<E extends Env = Env> {
|
|
|
23
23
|
*/
|
|
24
24
|
getSubject: (c: Context<E>) => MaybePromise<Subject | null | undefined>;
|
|
25
25
|
/** Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. */
|
|
26
|
-
guard?: string;
|
|
26
|
+
guard?: string | undefined;
|
|
27
27
|
/** Resolves the current team (only when the engine was created with `teams: true`). */
|
|
28
28
|
team?: (c: Context<E>) => MaybePromise<TeamId | undefined>;
|
|
29
29
|
}
|
|
@@ -47,22 +47,22 @@ interface GuardContext {
|
|
|
47
47
|
type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>;
|
|
48
48
|
interface GuardHandlers {
|
|
49
49
|
/** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */
|
|
50
|
-
onUnauthenticated?: GuardHandler;
|
|
50
|
+
onUnauthenticated?: GuardHandler | undefined;
|
|
51
51
|
/** Called when the subject lacks access. Default: 403 JSON. */
|
|
52
|
-
onForbidden?: GuardHandler;
|
|
52
|
+
onForbidden?: GuardHandler | undefined;
|
|
53
53
|
/**
|
|
54
54
|
* Include the required roles/permissions in the default 403 body.
|
|
55
55
|
* Default: `false` (like spatie's `display_permission_in_exception`).
|
|
56
56
|
*/
|
|
57
|
-
exposeRequirements?: boolean;
|
|
57
|
+
exposeRequirements?: boolean | undefined;
|
|
58
58
|
}
|
|
59
59
|
interface PermissionGuardOptions extends GuardHandlers {
|
|
60
60
|
/** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */
|
|
61
|
-
any?: boolean;
|
|
61
|
+
any?: boolean | undefined;
|
|
62
62
|
}
|
|
63
63
|
interface RoleGuardOptions extends GuardHandlers {
|
|
64
64
|
/** Require ALL of the roles (instead of any). Default: `false`. */
|
|
65
|
-
all?: boolean;
|
|
65
|
+
all?: boolean | undefined;
|
|
66
66
|
}
|
|
67
67
|
type RoleOrPermissionGuardOptions = GuardHandlers;
|
|
68
68
|
/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
|
|
@@ -71,18 +71,33 @@ declare class RbacMiddlewareMissingError extends Error {
|
|
|
71
71
|
readonly code = "RBAC_MIDDLEWARE_MISSING";
|
|
72
72
|
constructor();
|
|
73
73
|
}
|
|
74
|
-
/**
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
74
|
+
/**
|
|
75
|
+
* A guard typed with the names `N` it accepts and its options `O`: `(...names, options?)`.
|
|
76
|
+
* Every name (each part of a `'a|b'` list, each array item) must be one of `N`; with `N = string`, any name is.
|
|
77
|
+
* A call without names, or with options that are not the last argument, is a type error.
|
|
78
|
+
*/
|
|
79
|
+
type Guard<N extends string, O> = <const A extends readonly (GuardNames | O)[]>(...args: A & RequirementArgs<A, N, O>) => MiddlewareHandler<RbacEnv>;
|
|
80
|
+
/** The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). */
|
|
81
|
+
interface Guards<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
82
|
+
requirePermission: Guard<PermissionName<T>, PermissionGuardOptions>;
|
|
83
|
+
requireRole: Guard<RoleName<T>, RoleGuardOptions>;
|
|
84
|
+
requireRoleOrPermission: Guard<PermissionName<T> | RoleName<T>, RoleOrPermissionGuardOptions>;
|
|
85
|
+
canAny: Guard<PermissionName<T>, GuardHandlers>;
|
|
86
|
+
canAll: Guard<PermissionName<T>, GuardHandlers>;
|
|
87
|
+
}
|
|
88
|
+
/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */
|
|
89
|
+
type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never;
|
|
90
|
+
/**
|
|
91
|
+
* Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page).
|
|
92
|
+
*
|
|
93
|
+
* Pass the same type argument as `createRbac<AppTypes>()` (or `typeof rbac`) to check names at compile time:
|
|
94
|
+
* `const { requirePermission } = createGuards<AppTypes>()`.
|
|
95
|
+
*/
|
|
96
|
+
declare function createGuards<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes>(defaults?: GuardHandlers): Guards<TypesOf<T>>;
|
|
97
|
+
declare const requirePermission: Guard<string, PermissionGuardOptions>;
|
|
98
|
+
declare const requireRole: Guard<string, RoleGuardOptions>;
|
|
99
|
+
declare const requireRoleOrPermission: Guard<string, GuardHandlers>;
|
|
100
|
+
declare const canAny: Guard<string, GuardHandlers>;
|
|
101
|
+
declare const canAll: Guard<string, GuardHandlers>;
|
|
87
102
|
|
|
88
|
-
export { type GuardContext, type GuardHandler, type GuardHandlers, type GuardKind, type GuardNames, type PermissionGuardOptions, type RbacEnv, RbacMiddlewareMissingError, type RbacMiddlewareOptions, type RbacVariables, type RoleGuardOptions, type RoleOrPermissionGuardOptions, canAll, canAny, createGuards, rbacMiddleware, requirePermission, requireRole, requireRoleOrPermission };
|
|
103
|
+
export { type Guard, type GuardContext, type GuardHandler, type GuardHandlers, type GuardKind, type GuardNames, type Guards, type PermissionGuardOptions, type RbacEnv, RbacMiddlewareMissingError, type RbacMiddlewareOptions, type RbacVariables, type RoleGuardOptions, type RoleOrPermissionGuardOptions, canAll, canAny, createGuards, rbacMiddleware, requirePermission, requireRole, requireRoleOrPermission };
|
package/dist/index.js
CHANGED
|
@@ -50,18 +50,23 @@ function createGuard(requirement, handlers) {
|
|
|
50
50
|
return onForbidden(c, context);
|
|
51
51
|
};
|
|
52
52
|
}
|
|
53
|
+
function withDefaults(defaults, options) {
|
|
54
|
+
const merged = { ...defaults };
|
|
55
|
+
for (const [key, value] of Object.entries(options)) if (value !== void 0) merged[key] = value;
|
|
56
|
+
return merged;
|
|
57
|
+
}
|
|
53
58
|
function createGuards(defaults = {}) {
|
|
54
59
|
function requirePermission2(...args) {
|
|
55
60
|
const { names, options = {} } = splitRequirementArgs(args);
|
|
56
|
-
return createGuard(permissionRequirement(names, options),
|
|
61
|
+
return createGuard(permissionRequirement(names, options), withDefaults(defaults, options));
|
|
57
62
|
}
|
|
58
63
|
function requireRole2(...args) {
|
|
59
64
|
const { names, options = {} } = splitRequirementArgs(args);
|
|
60
|
-
return createGuard(roleRequirement(names, options),
|
|
65
|
+
return createGuard(roleRequirement(names, options), withDefaults(defaults, options));
|
|
61
66
|
}
|
|
62
67
|
function requireRoleOrPermission2(...args) {
|
|
63
68
|
const { names, options = {} } = splitRequirementArgs(args);
|
|
64
|
-
return createGuard(roleOrPermissionRequirement(names),
|
|
69
|
+
return createGuard(roleOrPermissionRequirement(names), withDefaults(defaults, options));
|
|
65
70
|
}
|
|
66
71
|
function canAny2(...args) {
|
|
67
72
|
const { names, options } = splitRequirementArgs(args);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/middleware.ts","../src/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AW,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 {\n permissionRequirement,\n type RbacRequirement,\n type RequirementKind,\n type RequirementNames,\n REQUIREMENT_MESSAGES,\n roleOrPermissionRequirement,\n roleRequirement,\n satisfiesRequirement,\n splitRequirementArgs,\n type SubjectRbac,\n UNAUTHENTICATED_MESSAGE,\n} from '@anievo-id/rbac-evolution'\nimport type { Context, MiddlewareHandler } from 'hono'\nimport type { RbacEnv } from './middleware'\n\nexport type GuardKind = RequirementKind\n\n/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */\nexport interface GuardContext {\n kind: GuardKind\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\n requirements: string[][]\n}\n\n/** Returns the response to send (or throws, e.g. an `HTTPException`). */\nexport type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>\n\nexport interface GuardHandlers {\n /** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */\n onUnauthenticated?: GuardHandler\n /** Called when the subject lacks access. Default: 403 JSON. */\n onForbidden?: GuardHandler\n /**\n * Include the required roles/permissions in the default 403 body.\n * Default: `false` (like spatie's `display_permission_in_exception`).\n */\n exposeRequirements?: boolean\n}\n\nexport interface PermissionGuardOptions extends GuardHandlers {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean\n}\n\nexport interface RoleGuardOptions extends GuardHandlers {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean\n}\n\nexport type RoleOrPermissionGuardOptions = GuardHandlers\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = RequirementNames\n\nexport class RbacMiddlewareMissingError extends Error {\n readonly code = 'RBAC_MIDDLEWARE_MISSING'\n\n constructor() {\n super('`c.var.rbac` is not set. Register `rbacMiddleware()` before using RBAC guards.')\n this.name = 'RbacMiddlewareMissingError'\n }\n}\n\nconst defaultUnauthenticated: GuardHandler = (c) =>\n c.json({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }, 401)\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (c, context) =>\n c.json(\n {\n error: 'FORBIDDEN',\n reason: context.kind,\n message: REQUIREMENT_MESSAGES[context.kind],\n ...(expose && { required: context.requirements }),\n },\n 403,\n )\n\nfunction createGuard(requirement: RbacRequirement, handlers: GuardHandlers): MiddlewareHandler<RbacEnv> {\n const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated\n const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false)\n const context: GuardContext = { kind: requirement.kind, requirements: requirement.requirements }\n\n return async (c, next) => {\n const rbac = c.get('rbac') as SubjectRbac | null | undefined\n if (rbac === undefined) throw new RbacMiddlewareMissingError()\n if (rbac === null) return onUnauthenticated(c, context)\n if (await satisfiesRequirement(rbac, requirement)) {\n await next()\n return\n }\n return onForbidden(c, context)\n }\n}\n\n/** Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page). */\nexport function createGuards(defaults: GuardHandlers = {}) {\n /**\n * Requires permissions, like spatie's `permission:` middleware.\n *\n * - `requirePermission('edit articles')`\n * - `requirePermission('edit articles|delete articles')` — any of them\n * - `requirePermission('edit articles', 'publish articles')` — all of them\n * - `requirePermission('a', 'b', { any: true })` — any of them\n */\n function requirePermission(...args: (GuardNames | PermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\n return createGuard(permissionRequirement(names, options), { ...defaults, ...options })\n }\n\n /**\n * Requires roles, like spatie's `role:` middleware.\n *\n * - `requireRole('admin')`, `requireRole('admin|editor')`, `requireRole('admin', 'editor')` — any of them\n * - `requireRole('admin', 'editor', { all: true })` — all of them\n */\n function requireRole(...args: (GuardNames | RoleGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\n return createGuard(roleRequirement(names, options), { ...defaults, ...options })\n }\n\n /**\n * Passes when the subject has ANY of the names as a role OR as a permission,\n * like spatie's `role_or_permission:` middleware.\n *\n * - `requireRoleOrPermission('admin|edit articles')`\n */\n function requireRoleOrPermission(...args: (GuardNames | RoleOrPermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\n return createGuard(roleOrPermissionRequirement(names), { ...defaults, ...options })\n }\n\n /**\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `canAny('edit articles', 'publish articles')`, `canAny(['edit articles', 'publish articles'])`\n */\n function canAny(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: true })\n }\n\n /**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `canAll('edit articles', 'publish articles')`, `canAll(['edit articles', 'publish|review'])`\n */\n function canAll(...args: (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: false })\n }\n\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll }\n}\n\nexport const { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } = createGuards()\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/middleware.ts","../src/guards.ts"],"names":["requirePermission","requireRole","requireRoleOrPermission","canAny","canAll"],"mappings":";;;AAwCO,SAAS,eAAoC,OAAA,EAAmE;AACrH,EAAA,MAAM,EAAE,IAAA,EAAM,UAAA,EAAY,KAAA,EAAO,MAAK,GAAI,OAAA;AAE1C,EAAA,OAAO,OAAO,GAAG,IAAA,KAAS;AACxB,IAAA,MAAM,GAAA,GAAM,CAAA;AACZ,IAAA,MAAM,OAAA,GAAU,MAAM,UAAA,CAAW,GAAG,CAAA;AACpC,IAAA,IAAI,KAAA,GAA4B,IAAA;AAChC,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,MAAM,MAAA,GAAS,IAAA,GAA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,qBAAuC,IAAI,CAAA;AAC3E,IAAA,OAAO,WAAA,CAAY,gBAAgB,KAAA,EAAO,OAAO,GAAG,YAAA,CAAa,QAAA,EAAU,OAAO,CAAC,CAAA;AAAA,EACrF;AAQA,EAAA,SAASC,4BAA2B,IAAA,EAA0F;AAC5H,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,GAAU,EAAC,EAAE,GAAI,qBAAmD,IAAI,CAAA;AACvF,IAAA,OAAO,YAAY,2BAAA,CAA4B,KAAK,GAAG,YAAA,CAAa,QAAA,EAAU,OAAO,CAAC,CAAA;AAAA,EACxF;AAOA,EAAA,SAASC,WAAU,IAAA,EAA2E;AAC5F,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAI,qBAAoC,IAAI,CAAA;AACnE,IAAA,OAAOH,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,MAAM,CAAA;AAAA,EAC9D;AAOA,EAAA,SAASI,WAAU,IAAA,EAA2E;AAC5F,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAI,qBAAoC,IAAI,CAAA;AACnE,IAAA,OAAOJ,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,OAAO,CAAA;AAAA,EAC/D;AAIA,EAAA,OAAO,EAAE,iBAAA,EAAAA,kBAAAA,EAAmB,WAAA,EAAAC,YAAAA,EAAa,yBAAAC,wBAAAA,EAAyB,MAAA,EAAAC,OAAAA,EAAQ,MAAA,EAAAC,OAAAA,EAAO;AACnF;AAEO,IAAM,EAAE,iBAAA,EAAmB,WAAA,EAAa,yBAAyB,MAAA,EAAQ,MAAA,KAAW,YAAA","file":"index.js","sourcesContent":["import type { Rbac, Subject, SubjectRbac, TeamId } from '@anievo-id/rbac-evolution'\nimport type { Context, Env, MiddlewareHandler } from 'hono'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** Context variables set by `rbacMiddleware()`. */\nexport type RbacVariables = {\n /** Roles & permissions of the current subject. `null` for guests. */\n rbac: SubjectRbac | null\n}\n\n/**\n * Hono env for apps using `rbacMiddleware()`: `new Hono<RbacEnv>()` types `c.var.rbac`.\n * Combine it with your own variables: `new Hono<{ Variables: RbacVariables & { user: User } }>()`.\n */\nexport type RbacEnv = {\n Variables: RbacVariables\n}\n\nexport interface RbacMiddlewareOptions<E extends Env = Env> {\n /** The RBAC engine created with `createRbac(...)`. */\n rbac: Rbac\n /**\n * Resolves the authenticated subject for this request (e.g. from `c.var.user` or a JWT payload).\n * Return `null` / `undefined` for guests.\n */\n getSubject: (c: Context<E>) => MaybePromise<Subject | null | undefined>\n /** Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. */\n guard?: string | undefined\n /** Resolves the current team (only when the engine was created with `teams: true`). */\n team?: (c: Context<E>) => MaybePromise<TeamId | undefined>\n}\n\n/**\n * Resolves the current subject and sets `c.var.rbac` (a `SubjectRbac`, or `null` for guests).\n *\n * ```ts\n * app.use(rbacMiddleware({ rbac, getSubject: (c) => (c.var.user ? { type: 'user', id: c.var.user.id } : null) }))\n * ```\n */\nexport function rbacMiddleware<E extends Env = Env>(options: RbacMiddlewareOptions<E>): MiddlewareHandler<E & RbacEnv> {\n const { rbac, getSubject, guard, team } = options\n\n return async (c, next) => {\n const ctx = c as unknown as Context<E>\n const subject = await getSubject(ctx)\n let value: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(ctx) : undefined\n value = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n ;(c as unknown as Context<RbacEnv>).set('rbac', value)\n await next()\n }\n}\n","import {\n type DefaultRbacTypes,\n type PermissionName,\n permissionRequirement,\n type Rbac,\n type RbacTypeConfig,\n type RbacRequirement,\n type RequirementKind,\n type RequirementArgs,\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 { Context, MiddlewareHandler } from 'hono'\nimport type { RbacEnv } from './middleware'\n\nexport type GuardKind = RequirementKind\n\n/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */\nexport interface GuardContext {\n kind: GuardKind\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\n requirements: string[][]\n}\n\n/** Returns the response to send (or throws, e.g. an `HTTPException`). */\nexport type GuardHandler = (c: Context, context: GuardContext) => Response | Promise<Response>\n\nexport interface GuardHandlers {\n /** Called when there is no subject (`c.var.rbac` is `null`). Default: 401 JSON. */\n onUnauthenticated?: GuardHandler | undefined\n /** Called when the subject lacks access. Default: 403 JSON. */\n onForbidden?: GuardHandler | 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\nexport interface PermissionGuardOptions extends GuardHandlers {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean | undefined\n}\n\nexport interface RoleGuardOptions extends GuardHandlers {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean | undefined\n}\n\nexport type RoleOrPermissionGuardOptions = GuardHandlers\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = RequirementNames\n\nexport class RbacMiddlewareMissingError extends Error {\n readonly code = 'RBAC_MIDDLEWARE_MISSING'\n\n constructor() {\n super('`c.var.rbac` is not set. Register `rbacMiddleware()` before using RBAC guards.')\n this.name = 'RbacMiddlewareMissingError'\n }\n}\n\nconst defaultUnauthenticated: GuardHandler = (c) =>\n c.json({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }, 401)\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (c, context) =>\n c.json(\n {\n error: 'FORBIDDEN',\n reason: context.kind,\n message: REQUIREMENT_MESSAGES[context.kind],\n ...(expose && { required: context.requirements }),\n },\n 403,\n )\n\nfunction createGuard(requirement: RbacRequirement, handlers: GuardHandlers): MiddlewareHandler<RbacEnv> {\n const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated\n const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false)\n const context: GuardContext = { kind: requirement.kind, requirements: requirement.requirements }\n\n return async (c, next) => {\n const rbac = c.get('rbac') as SubjectRbac | null | undefined\n if (rbac === undefined) throw new RbacMiddlewareMissingError()\n if (rbac === null) return onUnauthenticated(c, context)\n if (await satisfiesRequirement(rbac, requirement)) {\n await next()\n return\n }\n return onForbidden(c, context)\n }\n}\n\n/** `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 * A call without names, or with options that are not the last argument, is a type error.\n */\nexport type Guard<N extends string, O> = <const A extends readonly (GuardNames | O)[]>(\n ...args: A & RequirementArgs<A, N, O>\n) => MiddlewareHandler<RbacEnv>\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>\n requireRole: Guard<RoleName<T>, RoleGuardOptions>\n requireRoleOrPermission: Guard<PermissionName<T> | RoleName<T>, RoleOrPermissionGuardOptions>\n canAny: Guard<PermissionName<T>, GuardHandlers>\n canAll: Guard<PermissionName<T>, GuardHandlers>\n}\n\n/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */\ntype TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never\n\n/**\n * Builds the guards with shared defaults (e.g. a custom `onForbidden` that renders an HTML page).\n *\n * Pass the same type argument as `createRbac<AppTypes>()` (or `typeof rbac`) to check names at compile time:\n * `const { requirePermission } = createGuards<AppTypes>()`.\n */\nexport function createGuards<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes>(\n defaults: GuardHandlers = {},\n): Guards<TypesOf<T>> {\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)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\n return createGuard(permissionRequirement(names, options), withDefaults(defaults, options))\n }\n\n /**\n * Requires roles, like spatie's `role:` middleware.\n *\n * - `requireRole('admin')`, `requireRole('admin|editor')`, `requireRole('admin', 'editor')` — any of them\n * - `requireRole('admin', 'editor', { all: true })` — all of them\n */\n function requireRole(...args: readonly (GuardNames | RoleGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\n return createGuard(roleRequirement(names, options), withDefaults(defaults, options))\n }\n\n /**\n * Passes when the subject has ANY of the names as a role OR as a permission,\n * like spatie's `role_or_permission:` middleware.\n *\n * - `requireRoleOrPermission('admin|edit articles')`\n */\n function requireRoleOrPermission(...args: readonly (GuardNames | RoleOrPermissionGuardOptions)[]): MiddlewareHandler<RbacEnv> {\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\n return createGuard(roleOrPermissionRequirement(names), withDefaults(defaults, options))\n }\n\n /**\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `canAny('edit articles', 'publish articles')`, `canAny(['edit articles', 'publish articles'])`\n */\n function canAny(...args: readonly (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: true })\n }\n\n /**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `canAll('edit articles', 'publish articles')`, `canAll(['edit articles', 'publish|review'])`\n */\n function canAll(...args: readonly (GuardNames | GuardHandlers)[]): MiddlewareHandler<RbacEnv> {\n const { names, options } = splitRequirementArgs<GuardHandlers>(args)\n return requirePermission(...names, { ...options, any: false })\n }\n\n // The untyped functions above take any spread of names (`canAny` passes `...names` on); the typed signature\n // is only the public face, so a cast is enough. No runtime change.\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } as Guards<TypesOf<T>>\n}\n\nexport const { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } = createGuards()\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anievo-id/rbac-evolution-hono",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Hono middleware for rbac-evolution — runs on Node, Bun, Deno, Cloudflare Workers and other edge runtimes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "AniEvo-ID (https://github.com/AniEvo-ID)",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"access": "public"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@anievo-id/rbac-evolution": "^0.
|
|
52
|
+
"@anievo-id/rbac-evolution": "^0.8.0"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"hono": ">=4"
|