@anievo-id/rbac-evolution-nuxt 0.8.0 → 1.0.0-rc.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 +18 -63
- package/dist/server.d.ts +24 -7
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +15 -11
- package/dist/server.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,91 +1,46 @@
|
|
|
1
1
|
# @anievo-id/rbac-evolution-nuxt
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Nuxt 3 and 4 module for [RBAC Evolution](https://github.com/AniEvo-ID/rbac-evolution): the Vue directives and
|
|
4
|
+
components, the user's snapshot hydrated from SSR, `definePageMeta({ rbac })` route rules and Nitro helpers for
|
|
5
|
+
server-side checks.
|
|
4
6
|
|
|
5
|
-
|
|
6
|
-
(`v-can`, `v-role`, `<Can>`, `<HasRole>`, `$can`), hydrates the user's snapshot from SSR, auto-imports
|
|
7
|
-
`useRbac()` / `useCan()` & co., adds a route middleware for `definePageMeta({ rbac })`, and ships Nitro helpers
|
|
8
|
-
for server-side enforcement.
|
|
7
|
+
## Install
|
|
9
8
|
|
|
10
9
|
```bash
|
|
11
|
-
npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-nuxt
|
|
10
|
+
npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-nuxt nuxt vue
|
|
12
11
|
```
|
|
13
12
|
|
|
14
|
-
##
|
|
13
|
+
## Usage
|
|
15
14
|
|
|
16
15
|
```ts
|
|
17
16
|
// nuxt.config.ts
|
|
18
17
|
export default defineNuxtConfig({
|
|
19
18
|
modules: ['@anievo-id/rbac-evolution-nuxt'],
|
|
20
|
-
rbac: {
|
|
21
|
-
wildcard: true, // must mirror createRbac({ wildcard })
|
|
22
|
-
superAdminRoles: ['super-admin'],
|
|
23
|
-
unauthenticatedRedirect: '/login', // optional, otherwise a 401 error page
|
|
24
|
-
forbiddenRedirect: '/403', // optional, otherwise a 403 error page
|
|
25
|
-
},
|
|
19
|
+
rbac: { wildcard: true }, // must mirror createRbac({ wildcard })
|
|
26
20
|
})
|
|
27
21
|
```
|
|
28
22
|
|
|
29
|
-
Resolve the subject on the server — the module's plugin reads `event.context.rbac` during SSR and sends the
|
|
30
|
-
snapshot to the client through `useState`:
|
|
31
|
-
|
|
32
23
|
```ts
|
|
33
24
|
// server/utils/rbac.ts
|
|
34
25
|
import { createRbac } from '@anievo-id/rbac-evolution'
|
|
35
26
|
import { createRbacServer } from '@anievo-id/rbac-evolution-nuxt/server'
|
|
36
27
|
|
|
37
|
-
export const rbac = createRbac({ adapter: yourAdapter })
|
|
38
|
-
|
|
39
|
-
export const rbacServer = createRbacServer({
|
|
40
|
-
rbac,
|
|
41
|
-
getSubject: async (event) => {
|
|
42
|
-
const user = await getUserFromSession(event) // your auth
|
|
43
|
-
return user ? { type: 'user', id: user.id } : null
|
|
44
|
-
},
|
|
45
|
-
})
|
|
46
|
-
|
|
47
|
-
// server/middleware/rbac.ts
|
|
48
|
-
export default defineEventHandler((event) => rbacServer.resolve(event))
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
## Pages & components
|
|
28
|
+
export const rbac = createRbac({ adapter: yourAdapter, wildcard: true })
|
|
29
|
+
export const rbacServer = createRbacServer({ rbac, getSubject: (event) => getUserSubject(event) }) // yours
|
|
52
30
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
definePageMeta({ rbac: { permission: 'articles.edit' } })
|
|
56
|
-
|
|
57
|
-
const canPublish = useCan('articles.publish')
|
|
58
|
-
const rbac = useRbac()
|
|
59
|
-
</script>
|
|
60
|
-
|
|
61
|
-
<template>
|
|
62
|
-
<button v-if="canPublish">Publish</button>
|
|
63
|
-
<button v-can="'articles.delete'">Delete</button>
|
|
64
|
-
<HasRole role="admin">Admin tools</HasRole>
|
|
65
|
-
<p v-if="rbac.isGuest()">Please log in</p>
|
|
66
|
-
</template>
|
|
31
|
+
// server/middleware/rbac.ts: export default defineEventHandler((event) => rbacServer.resolve(event))
|
|
32
|
+
// server/api/articles/[id].delete.ts: await rbacServer.requirePermission(event, 'articles.delete')
|
|
67
33
|
```
|
|
68
34
|
|
|
69
|
-
|
|
70
|
-
`
|
|
71
|
-
|
|
72
|
-
After login or logout, update the client: `useRbac().setSnapshot(await $fetch('/api/me/permissions'))` or
|
|
73
|
-
`useRbac().setSnapshot(null)`.
|
|
35
|
+
In pages: `definePageMeta({ rbac: { permission: 'articles.edit' } })`, `useCan('articles.publish')`,
|
|
36
|
+
`v-can="'articles.delete'"` and `<HasRole role="admin">`.
|
|
74
37
|
|
|
75
|
-
|
|
38
|
+
> Client checks only decide what the UI shows. Enforce access in server routes with `rbacServer.require*()`.
|
|
76
39
|
|
|
77
|
-
|
|
40
|
+
## Documentation
|
|
78
41
|
|
|
79
|
-
|
|
80
|
-
// server/api/articles/[id].delete.ts
|
|
81
|
-
export default defineEventHandler(async (event) => {
|
|
82
|
-
const rbac = await rbacServer.requirePermission(event, 'articles.delete')
|
|
83
|
-
// ...
|
|
84
|
-
})
|
|
85
|
-
```
|
|
42
|
+
https://creation.anievo.id/rbac-evolution/frameworks/nuxt
|
|
86
43
|
|
|
87
|
-
|
|
88
|
-
Express body (`{ error, reason, message }`).
|
|
44
|
+
## License
|
|
89
45
|
|
|
90
|
-
|
|
91
|
-
`requirePermission(event, 'articles.edti')` is then a compile error. With an untyped engine, any string is accepted.
|
|
46
|
+
MIT
|
package/dist/server.d.ts
CHANGED
|
@@ -23,6 +23,20 @@ export interface RbacServerOptions<E extends RbacEvent = RbacEvent, T extends Rb
|
|
|
23
23
|
/** Include the required roles/permissions in the 403 body (`required`). Default: `false`. */
|
|
24
24
|
exposeRequirements?: boolean | undefined;
|
|
25
25
|
}
|
|
26
|
+
/** The options every `require*` / `can*` helper takes (last argument). */
|
|
27
|
+
export interface RequireGuardOptions {
|
|
28
|
+
/**
|
|
29
|
+
* Check in this guard instead of the server's (`subject.withScope({ guard })`), like spatie's
|
|
30
|
+
* `role:admin,api`. Default: the `guard` of `createRbacServer()`.
|
|
31
|
+
*/
|
|
32
|
+
guard?: string | undefined;
|
|
33
|
+
}
|
|
34
|
+
/** Options of `requirePermission()`: `{ any }` and `{ guard }`. */
|
|
35
|
+
export interface RequirePermissionOptions extends PermissionRequirementOptions, RequireGuardOptions {
|
|
36
|
+
}
|
|
37
|
+
/** Options of `requireRole()`: `{ all }` and `{ guard }`. */
|
|
38
|
+
export interface RequireRoleOptions extends RoleRequirementOptions, RequireGuardOptions {
|
|
39
|
+
}
|
|
26
40
|
/** The JSON body of a failed check — identical to `@anievo-id/rbac-evolution-express`. */
|
|
27
41
|
export type RbacErrorBody = {
|
|
28
42
|
error: 'UNAUTHENTICATED';
|
|
@@ -72,16 +86,19 @@ export interface RbacServer<E extends RbacEvent = RbacEvent, T extends RbacTypeC
|
|
|
72
86
|
resolve(event: E): Promise<SubjectRbac<T> | null>;
|
|
73
87
|
/** The current subject's `{ roles, permissions }`, or `null` for guests. */
|
|
74
88
|
snapshot(event: E): Promise<RbacSnapshot | null>;
|
|
75
|
-
/**
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
89
|
+
/**
|
|
90
|
+
* Like Express `requirePermission`: arguments are all required, pipes mean any, `{ any: true }`.
|
|
91
|
+
* With `{ guard: 'api' }` the check (and the returned subject) is in that guard.
|
|
92
|
+
*/
|
|
93
|
+
requirePermission<const A extends readonly (RequirementNames | RequirePermissionOptions)[]>(event: E, ...args: A & RequirementArgs<A, PermissionName<T>, RequirePermissionOptions>): Promise<SubjectRbac<T>>;
|
|
94
|
+
/** Like Express `requireRole`: any of the roles, `{ all: true }` for all, `{ guard: 'api' }` (spatie's `role:admin,api`). */
|
|
95
|
+
requireRole<const A extends readonly (RequirementNames | RequireRoleOptions)[]>(event: E, ...args: A & RequirementArgs<A, RoleName<T>, RequireRoleOptions>): Promise<SubjectRbac<T>>;
|
|
79
96
|
/** Like Express `requireRoleOrPermission`: any of the names as a role OR a permission. */
|
|
80
|
-
requireRoleOrPermission<const A extends readonly RequirementNames[]>(event: E, ...
|
|
97
|
+
requireRoleOrPermission<const A extends readonly (RequirementNames | RequireGuardOptions)[]>(event: E, ...args: A & RequirementArgs<A, PermissionName<T> | RoleName<T>, RequireGuardOptions>): Promise<SubjectRbac<T>>;
|
|
81
98
|
/** spatie v8.5 `canAny()`: requires ANY of the listed permissions. */
|
|
82
|
-
canAny<const A extends readonly RequirementNames[]>(event: E, ...
|
|
99
|
+
canAny<const A extends readonly (RequirementNames | RequireGuardOptions)[]>(event: E, ...args: A & RequirementArgs<A, PermissionName<T>, RequireGuardOptions>): Promise<SubjectRbac<T>>;
|
|
83
100
|
/** spatie v8.5 `canAll()`: requires EVERY listed entry; a `'a|b'` entry still means "a or b". */
|
|
84
|
-
canAll<const A extends readonly RequirementNames[]>(event: E, ...
|
|
101
|
+
canAll<const A extends readonly (RequirementNames | RequireGuardOptions)[]>(event: E, ...args: A & RequirementArgs<A, PermissionName<T>, RequireGuardOptions>): Promise<SubjectRbac<T>>;
|
|
85
102
|
}
|
|
86
103
|
/**
|
|
87
104
|
* Creates request helpers for Nitro event handlers.
|
package/dist/server.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EACV,gBAAgB,EAChB,cAAc,EACd,IAAI,EACJ,YAAY,EACZ,cAAc,EACd,QAAQ,EACR,OAAO,EACP,WAAW,EACX,MAAM,EACP,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAEL,KAAK,4BAA4B,EAEjC,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EAIrB,KAAK,sBAAsB,EAI5B,MAAM,2BAA2B,CAAA;AAElC,YAAY,EAAE,4BAA4B,EAAE,eAAe,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAA;AAExI,K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AC,GAAG,QAAQ,CAAC,CAAC,CAAC,EAAE,mBAAmB,CAAC,GACpF,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAA;IAC1B,sEAAsE;IACtE,MAAM,CAAC,KAAK,CAAC,CAAC,SAAS,SAAS,CAAC,gBAAgB,GAAG,mBAAmB,CAAC,EAAE,EACxE,KAAK,EAAE,CAAC,EACR,GAAG,IAAI,EAAE,CAAC,GAAG,eAAe,CAAC,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,EAAE,mBAAmB,CAAC,GACtE,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAA;IAC1B,iGAAiG;IACjG,MAAM,CAAC,KAAK,CAAC,CAAC,SAAS,SAAS,CAAC,gBAAgB,GAAG,mBAAmB,CAAC,EAAE,EACxE,KAAK,EAAE,CAAC,EACR,GAAG,IAAI,EAAE,CAAC,GAAG,eAAe,CAAC,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,EAAE,mBAAmB,CAAC,GACtE,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAA;CAC3B;AAeD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,EAAE,CAAC,SAAS,cAAc,GAAG,gBAAgB,EAC3G,OAAO,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,GAC/B,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,CAElB"}
|
package/dist/server.js
CHANGED
|
@@ -46,10 +46,11 @@ function buildRbacServer(options) {
|
|
|
46
46
|
if (context[CONTEXT_KEY] === void 0) context[CONTEXT_KEY] = result;
|
|
47
47
|
return result;
|
|
48
48
|
}
|
|
49
|
-
async function enforce(event, build) {
|
|
49
|
+
async function enforce(event, build, scope = {}) {
|
|
50
50
|
const requirement = build();
|
|
51
|
-
const
|
|
52
|
-
if (
|
|
51
|
+
const resolvedSubject = await resolve(event);
|
|
52
|
+
if (resolvedSubject === null) throw new RbacHttpError({ error: "UNAUTHENTICATED", message: UNAUTHENTICATED_MESSAGE });
|
|
53
|
+
const subject = scope.guard === void 0 ? resolvedSubject : resolvedSubject.withScope({ guard: scope.guard });
|
|
53
54
|
if (!await satisfiesRequirement(subject, requirement)) {
|
|
54
55
|
throw new RbacHttpError({
|
|
55
56
|
error: "FORBIDDEN",
|
|
@@ -68,20 +69,23 @@ function buildRbacServer(options) {
|
|
|
68
69
|
},
|
|
69
70
|
requirePermission(event, ...args) {
|
|
70
71
|
const { names, options: options2 } = splitRequirementArgs(args);
|
|
71
|
-
return enforce(event, () => permissionRequirement(names, options2));
|
|
72
|
+
return enforce(event, () => permissionRequirement(names, options2), options2);
|
|
72
73
|
},
|
|
73
74
|
requireRole(event, ...args) {
|
|
74
75
|
const { names, options: options2 } = splitRequirementArgs(args);
|
|
75
|
-
return enforce(event, () => roleRequirement(names, options2));
|
|
76
|
+
return enforce(event, () => roleRequirement(names, options2), options2);
|
|
76
77
|
},
|
|
77
|
-
requireRoleOrPermission(event, ...
|
|
78
|
-
|
|
78
|
+
requireRoleOrPermission(event, ...args) {
|
|
79
|
+
const { names, options: options2 } = splitRequirementArgs(args);
|
|
80
|
+
return enforce(event, () => roleOrPermissionRequirement(names), options2);
|
|
79
81
|
},
|
|
80
|
-
canAny(event, ...
|
|
81
|
-
|
|
82
|
+
canAny(event, ...args) {
|
|
83
|
+
const { names, options: options2 } = splitRequirementArgs(args);
|
|
84
|
+
return enforce(event, () => permissionRequirement(names, { any: true }), options2);
|
|
82
85
|
},
|
|
83
|
-
canAll(event, ...
|
|
84
|
-
|
|
86
|
+
canAll(event, ...args) {
|
|
87
|
+
const { names, options: options2 } = splitRequirementArgs(args);
|
|
88
|
+
return enforce(event, () => permissionRequirement(names), options2);
|
|
85
89
|
}
|
|
86
90
|
};
|
|
87
91
|
}
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts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AA,IAC1D;AAAA,GACF;AACF","file":"server.js","sourcesContent":["/**\n * @anievo-id/rbac-evolution-nuxt/server\n *\n * Server-side enforcement for Nitro / h3 event handlers. Runs on the server only.\n */\n\nimport type {\n DefaultRbacTypes,\n PermissionName,\n Rbac,\n RbacSnapshot,\n RbacTypeConfig,\n RoleName,\n Subject,\n SubjectRbac,\n TeamId,\n} from '@anievo-id/rbac-evolution'\nimport {\n permissionRequirement,\n type PermissionRequirementOptions,\n type RbacRequirement,\n type RequirementArgs,\n type RequirementKind,\n type RequirementNames,\n REQUIREMENT_MESSAGES,\n roleOrPermissionRequirement,\n roleRequirement,\n type RoleRequirementOptions,\n satisfiesRequirement,\n splitRequirementArgs,\n UNAUTHENTICATED_MESSAGE,\n} from '@anievo-id/rbac-evolution'\n\nexport type { PermissionRequirementOptions, RequirementKind, RequirementNames, RoleRequirementOptions } from '@anievo-id/rbac-evolution'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** The part of an h3 `H3Event` this helper uses. */\nexport interface RbacEvent {\n context: object\n}\n\nexport interface RbacServerOptions<E extends RbacEvent = RbacEvent, T extends RbacTypeConfig = DefaultRbacTypes> {\n /** The RBAC engine created with `createRbac(...)`. Its typed names flow into the `require*` / `can*` helpers. */\n rbac: Rbac<T>\n /** Resolves the authenticated subject for this request (e.g. from a session). `null` / `undefined` for guests. */\n getSubject: (event: 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?: (event: E) => MaybePromise<TeamId | undefined>\n /** Include the required roles/permissions in the 403 body (`required`). Default: `false`. */\n exposeRequirements?: boolean | undefined\n}\n\n/** The JSON body of a failed check — identical to `@anievo-id/rbac-evolution-express`. */\nexport type RbacErrorBody =\n | { error: 'UNAUTHENTICATED'; message: string }\n | { error: 'FORBIDDEN'; reason: RequirementKind; message: string; required?: string[][] }\n\n/**\n * Thrown by the `require*` helpers. h3 turns it into an error response with this `statusCode`\n * and the Express-style body under `data`.\n *\n * It is shaped like h3's `H3Error` (including the `__h3_error__` marker h3 checks), so h3 / Nitro\n * treat it as an expected HTTP error instead of logging it as an unhandled exception —\n * without this package depending on h3.\n */\nexport class RbacHttpError extends Error {\n static readonly __h3_error__ = true\n readonly statusCode: 401 | 403\n readonly statusMessage: string\n readonly data: RbacErrorBody\n readonly fatal = false\n readonly unhandled = false\n\n constructor(data: RbacErrorBody) {\n super(data.message)\n this.name = 'RbacHttpError'\n this.statusCode = data.error === 'UNAUTHENTICATED' ? 401 : 403\n this.statusMessage = data.error === 'UNAUTHENTICATED' ? 'Unauthorized' : 'Forbidden'\n this.data = data\n }\n\n /** Alias of `statusCode`. */\n get status(): 401 | 403 {\n return this.statusCode\n }\n\n toJSON() {\n return { message: this.message, statusCode: this.statusCode, statusMessage: this.statusMessage, data: this.data }\n }\n}\n\n/**\n * The helpers returned by `createRbacServer()`. `T` comes from the `rbac` option: with typed names, every\n * name (including each part of a `'a|b'` list) must be one of them; untyped, any string is accepted.\n * A call without names, or with options that are not the last argument, is a type error.\n */\nexport interface RbacServer<E extends RbacEvent = RbacEvent, T extends RbacTypeConfig = DefaultRbacTypes> {\n /**\n * Resolves the subject once per request (cached per helper instance) and stores it on\n * `event.context.rbac` (a `SubjectRbac`, or `null` for guests) unless another instance did\n * first. The Nuxt plugin reads it to hydrate the client.\n */\n resolve(event: E): Promise<SubjectRbac<T> | null>\n /** The current subject's `{ roles, permissions }`, or `null` for guests. */\n snapshot(event: E): Promise<RbacSnapshot | null>\n /** Like Express `requirePermission`: arguments are all required, pipes mean any, `{ any: true }`. */\n requirePermission<const A extends readonly (RequirementNames | PermissionRequirementOptions)[]>(\n event: E,\n ...args: A & RequirementArgs<A, PermissionName<T>, PermissionRequirementOptions>\n ): Promise<SubjectRbac<T>>\n /** Like Express `requireRole`: any of the roles, `{ all: true }` for all. */\n requireRole<const A extends readonly (RequirementNames | RoleRequirementOptions)[]>(\n event: E,\n ...args: A & RequirementArgs<A, RoleName<T>, RoleRequirementOptions>\n ): Promise<SubjectRbac<T>>\n /** Like Express `requireRoleOrPermission`: any of the names as a role OR a permission. */\n requireRoleOrPermission<const A extends readonly RequirementNames[]>(\n event: E,\n ...names: A & RequirementArgs<A, PermissionName<T> | RoleName<T>, never>\n ): Promise<SubjectRbac<T>>\n /** spatie v8.5 `canAny()`: requires ANY of the listed permissions. */\n canAny<const A extends readonly RequirementNames[]>(\n event: E,\n ...names: A & RequirementArgs<A, PermissionName<T>, never>\n ): Promise<SubjectRbac<T>>\n /** spatie v8.5 `canAll()`: requires EVERY listed entry; a `'a|b'` entry still means \"a or b\". */\n canAll<const A extends readonly RequirementNames[]>(\n event: E,\n ...names: A & RequirementArgs<A, PermissionName<T>, never>\n ): Promise<SubjectRbac<T>>\n}\n\n/** The untyped implementation behind `RbacServer` (plain `string` names, spread-friendly). */\ninterface UntypedRbacServer<E extends RbacEvent> {\n resolve(event: E): Promise<SubjectRbac | null>\n snapshot(event: E): Promise<RbacSnapshot | null>\n requirePermission(event: E, ...args: (RequirementNames | PermissionRequirementOptions)[]): Promise<SubjectRbac>\n requireRole(event: E, ...args: (RequirementNames | RoleRequirementOptions)[]): Promise<SubjectRbac>\n requireRoleOrPermission(event: E, ...names: RequirementNames[]): Promise<SubjectRbac>\n canAny(event: E, ...names: RequirementNames[]): Promise<SubjectRbac>\n canAll(event: E, ...names: RequirementNames[]): Promise<SubjectRbac>\n}\n\nconst CONTEXT_KEY = 'rbac'\n\n/**\n * Creates request helpers for Nitro event handlers.\n *\n * ```ts\n * // server/utils/rbac.ts\n * export const rbacServer = createRbacServer({\n * rbac,\n * getSubject: async (event) => {\n * const user = await getUserFromSession(event)\n * return user ? { type: 'user', id: user.id } : null\n * },\n * })\n *\n * // server/api/articles.post.ts\n * export default defineEventHandler(async (event) => {\n * await rbacServer.requirePermission(event, 'articles.create')\n * })\n * ```\n *\n * With a typed engine (`createRbac<AppTypes>(...)`), names are checked: `requirePermission(event, 'typo')` is a type error.\n */\nexport function createRbacServer<E extends RbacEvent = RbacEvent, T extends RbacTypeConfig = DefaultRbacTypes>(\n options: RbacServerOptions<E, T>,\n): RbacServer<E, T> {\n return buildRbacServer(options as unknown as RbacServerOptions<E>) as unknown as RbacServer<E, T>\n}\n\nfunction buildRbacServer<E extends RbacEvent>(options: RbacServerOptions<E>): UntypedRbacServer<E> {\n const { rbac, getSubject, guard, team, exposeRequirements = false } = options\n // Per instance, so a second server (e.g. guard 'api') never reuses another guard's subject.\n const resolved = new WeakMap<object, SubjectRbac | null>()\n\n async function resolve(event: E): Promise<SubjectRbac | null> {\n const context = event.context as Record<string, unknown>\n if (resolved.has(context)) return resolved.get(context)!\n\n const subject = await getSubject(event)\n let result: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(event) : undefined\n result = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n resolved.set(context, result)\n // The client plugin hydrates from `event.context.rbac`: the first instance to resolve fills it.\n if (context[CONTEXT_KEY] === undefined) context[CONTEXT_KEY] = result\n return result\n }\n\n // Async so an empty requirement (TypeError) rejects the returned promise instead of throwing synchronously.\n async function enforce(event: E, build: () => RbacRequirement): Promise<SubjectRbac> {\n const requirement = build()\n const subject = await resolve(event)\n if (subject === null) throw new RbacHttpError({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE })\n if (!(await satisfiesRequirement(subject, requirement))) {\n throw new RbacHttpError({\n error: 'FORBIDDEN',\n reason: requirement.kind,\n message: REQUIREMENT_MESSAGES[requirement.kind],\n ...(exposeRequirements && { required: requirement.requirements }),\n })\n }\n return subject\n }\n\n return {\n resolve,\n async snapshot(event) {\n const subject = await resolve(event)\n return subject ? subject.snapshot() : null\n },\n requirePermission(event, ...args) {\n const { names, options } = splitRequirementArgs<PermissionRequirementOptions>(args)\n return enforce(event, () => permissionRequirement(names, options))\n },\n requireRole(event, ...args) {\n const { names, options } = splitRequirementArgs<RoleRequirementOptions>(args)\n return enforce(event, () => roleRequirement(names, options))\n },\n requireRoleOrPermission(event, ...names) {\n return enforce(event, () => roleOrPermissionRequirement(names))\n },\n canAny(event, ...names) {\n return enforce(event, () => permissionRequirement(names, { any: true }))\n },\n canAll(event, ...names) {\n return enforce(event, () => permissionRequirement(names))\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"names":["options"],"mappings":";;;AAmFO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,OAAgB,YAAA,GAAe,IAAA;AAAA,EACtB,UAAA;AAAA,EACA,aAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA,GAAQ,KAAA;AAAA,EACR,SAAA,GAAY,KAAA;AAAA,EAErB,YAAY,IAAA,EAAqB;AAC/B,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AACZ,IAAA,IAAA,CAAK,UAAA,GAAa,IAAA,CAAK,KAAA,KAAU,iBAAA,GAAoB,GAAA,GAAM,GAAA;AAC3D,IAAA,IAAA,CAAK,aAAA,GAAgB,IAAA,CAAK,KAAA,KAAU,iBAAA,GAAoB,cAAA,GAAiB,WAAA;AACzE,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AAAA;AAAA,EAGA,IAAI,MAAA,GAAoB;AACtB,IAAA,OAAO,IAAA,CAAK,UAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAAS;AACP,IAAA,OAAO,EAAE,OAAA,EAAS,IAAA,CAAK,OAAA,EAAS,UAAA,EAAY,IAAA,CAAK,UAAA,EAAY,aAAA,EAAe,IAAA,CAAK,aAAA,EAAe,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK;AAAA,EAClH;AACF;AAyDA,IAAM,WAAA,GAAc,MAAA;AAuBb,SAAS,iBACd,OAAA,EACkB;AAClB,EAAA,OAAO,gBAAgB,OAA0C,CAAA;AACnE;AA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AAA,IACtE,CAAA;AAAA,IACA,uBAAA,CAAwB,UAAU,IAAA,EAAM;AACtC,MAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAAA,QAAAA,EAAQ,GAAI,qBAA0C,IAAI,CAAA;AACzE,MAAA,OAAO,QAAQ,KAAA,EAAO,MAAM,2BAAA,CAA4B,KAAK,GAAGA,QAAO,CAAA;AAAA,IACzE,CAAA;AAAA,IACA,MAAA,CAAO,UAAU,IAAA,EAAM;AACrB,MAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAAA,QAAAA,EAAQ,GAAI,qBAA0C,IAAI,CAAA;AACzE,MAAA,OAAO,OAAA,CAAQ,KAAA,EAAO,MAAM,qBAAA,CAAsB,KAAA,EAAO,EAAE,GAAA,EAAK,IAAA,EAAM,CAAA,EAAGA,QAAO,CAAA;AAAA,IAClF,CAAA;AAAA,IACA,MAAA,CAAO,UAAU,IAAA,EAAM;AACrB,MAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAAA,QAAAA,EAAQ,GAAI,qBAA0C,IAAI,CAAA;AACzE,MAAA,OAAO,QAAQ,KAAA,EAAO,MAAM,qBAAA,CAAsB,KAAK,GAAGA,QAAO,CAAA;AAAA,IACnE;AAAA,GACF;AACF","file":"server.js","sourcesContent":["/**\n * @anievo-id/rbac-evolution-nuxt/server\n *\n * Server-side enforcement for Nitro / h3 event handlers. Runs on the server only.\n */\n\nimport type {\n DefaultRbacTypes,\n PermissionName,\n Rbac,\n RbacSnapshot,\n RbacTypeConfig,\n RoleName,\n Subject,\n SubjectRbac,\n TeamId,\n} from '@anievo-id/rbac-evolution'\nimport {\n permissionRequirement,\n type PermissionRequirementOptions,\n type RbacRequirement,\n type RequirementArgs,\n type RequirementKind,\n type RequirementNames,\n REQUIREMENT_MESSAGES,\n roleOrPermissionRequirement,\n roleRequirement,\n type RoleRequirementOptions,\n satisfiesRequirement,\n splitRequirementArgs,\n UNAUTHENTICATED_MESSAGE,\n} from '@anievo-id/rbac-evolution'\n\nexport type { PermissionRequirementOptions, RequirementKind, RequirementNames, RoleRequirementOptions } from '@anievo-id/rbac-evolution'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** The part of an h3 `H3Event` this helper uses. */\nexport interface RbacEvent {\n context: object\n}\n\nexport interface RbacServerOptions<E extends RbacEvent = RbacEvent, T extends RbacTypeConfig = DefaultRbacTypes> {\n /** The RBAC engine created with `createRbac(...)`. Its typed names flow into the `require*` / `can*` helpers. */\n rbac: Rbac<T>\n /** Resolves the authenticated subject for this request (e.g. from a session). `null` / `undefined` for guests. */\n getSubject: (event: 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?: (event: E) => MaybePromise<TeamId | undefined>\n /** Include the required roles/permissions in the 403 body (`required`). Default: `false`. */\n exposeRequirements?: boolean | undefined\n}\n\n/** The options every `require*` / `can*` helper takes (last argument). */\nexport interface RequireGuardOptions {\n /**\n * Check in this guard instead of the server's (`subject.withScope({ guard })`), like spatie's\n * `role:admin,api`. Default: the `guard` of `createRbacServer()`.\n */\n guard?: string | undefined\n}\n\n/** Options of `requirePermission()`: `{ any }` and `{ guard }`. */\nexport interface RequirePermissionOptions extends PermissionRequirementOptions, RequireGuardOptions {}\n\n/** Options of `requireRole()`: `{ all }` and `{ guard }`. */\nexport interface RequireRoleOptions extends RoleRequirementOptions, RequireGuardOptions {}\n\n/** The JSON body of a failed check — identical to `@anievo-id/rbac-evolution-express`. */\nexport type RbacErrorBody =\n | { error: 'UNAUTHENTICATED'; message: string }\n | { error: 'FORBIDDEN'; reason: RequirementKind; message: string; required?: string[][] }\n\n/**\n * Thrown by the `require*` helpers. h3 turns it into an error response with this `statusCode`\n * and the Express-style body under `data`.\n *\n * It is shaped like h3's `H3Error` (including the `__h3_error__` marker h3 checks), so h3 / Nitro\n * treat it as an expected HTTP error instead of logging it as an unhandled exception —\n * without this package depending on h3.\n */\nexport class RbacHttpError extends Error {\n static readonly __h3_error__ = true\n readonly statusCode: 401 | 403\n readonly statusMessage: string\n readonly data: RbacErrorBody\n readonly fatal = false\n readonly unhandled = false\n\n constructor(data: RbacErrorBody) {\n super(data.message)\n this.name = 'RbacHttpError'\n this.statusCode = data.error === 'UNAUTHENTICATED' ? 401 : 403\n this.statusMessage = data.error === 'UNAUTHENTICATED' ? 'Unauthorized' : 'Forbidden'\n this.data = data\n }\n\n /** Alias of `statusCode`. */\n get status(): 401 | 403 {\n return this.statusCode\n }\n\n toJSON() {\n return { message: this.message, statusCode: this.statusCode, statusMessage: this.statusMessage, data: this.data }\n }\n}\n\n/**\n * The helpers returned by `createRbacServer()`. `T` comes from the `rbac` option: with typed names, every\n * name (including each part of a `'a|b'` list) must be one of them; untyped, any string is accepted.\n * A call without names, or with options that are not the last argument, is a type error.\n */\nexport interface RbacServer<E extends RbacEvent = RbacEvent, T extends RbacTypeConfig = DefaultRbacTypes> {\n /**\n * Resolves the subject once per request (cached per helper instance) and stores it on\n * `event.context.rbac` (a `SubjectRbac`, or `null` for guests) unless another instance did\n * first. The Nuxt plugin reads it to hydrate the client.\n */\n resolve(event: E): Promise<SubjectRbac<T> | null>\n /** The current subject's `{ roles, permissions }`, or `null` for guests. */\n snapshot(event: E): Promise<RbacSnapshot | null>\n /**\n * Like Express `requirePermission`: arguments are all required, pipes mean any, `{ any: true }`.\n * With `{ guard: 'api' }` the check (and the returned subject) is in that guard.\n */\n requirePermission<const A extends readonly (RequirementNames | RequirePermissionOptions)[]>(\n event: E,\n ...args: A & RequirementArgs<A, PermissionName<T>, RequirePermissionOptions>\n ): Promise<SubjectRbac<T>>\n /** Like Express `requireRole`: any of the roles, `{ all: true }` for all, `{ guard: 'api' }` (spatie's `role:admin,api`). */\n requireRole<const A extends readonly (RequirementNames | RequireRoleOptions)[]>(\n event: E,\n ...args: A & RequirementArgs<A, RoleName<T>, RequireRoleOptions>\n ): Promise<SubjectRbac<T>>\n /** Like Express `requireRoleOrPermission`: any of the names as a role OR a permission. */\n requireRoleOrPermission<const A extends readonly (RequirementNames | RequireGuardOptions)[]>(\n event: E,\n ...args: A & RequirementArgs<A, PermissionName<T> | RoleName<T>, RequireGuardOptions>\n ): Promise<SubjectRbac<T>>\n /** spatie v8.5 `canAny()`: requires ANY of the listed permissions. */\n canAny<const A extends readonly (RequirementNames | RequireGuardOptions)[]>(\n event: E,\n ...args: A & RequirementArgs<A, PermissionName<T>, RequireGuardOptions>\n ): Promise<SubjectRbac<T>>\n /** spatie v8.5 `canAll()`: requires EVERY listed entry; a `'a|b'` entry still means \"a or b\". */\n canAll<const A extends readonly (RequirementNames | RequireGuardOptions)[]>(\n event: E,\n ...args: A & RequirementArgs<A, PermissionName<T>, RequireGuardOptions>\n ): Promise<SubjectRbac<T>>\n}\n\n/** The untyped implementation behind `RbacServer` (plain `string` names, spread-friendly). */\ninterface UntypedRbacServer<E extends RbacEvent> {\n resolve(event: E): Promise<SubjectRbac | null>\n snapshot(event: E): Promise<RbacSnapshot | null>\n requirePermission(event: E, ...args: (RequirementNames | RequirePermissionOptions)[]): Promise<SubjectRbac>\n requireRole(event: E, ...args: (RequirementNames | RequireRoleOptions)[]): Promise<SubjectRbac>\n requireRoleOrPermission(event: E, ...args: (RequirementNames | RequireGuardOptions)[]): Promise<SubjectRbac>\n canAny(event: E, ...args: (RequirementNames | RequireGuardOptions)[]): Promise<SubjectRbac>\n canAll(event: E, ...args: (RequirementNames | RequireGuardOptions)[]): Promise<SubjectRbac>\n}\n\nconst CONTEXT_KEY = 'rbac'\n\n/**\n * Creates request helpers for Nitro event handlers.\n *\n * ```ts\n * // server/utils/rbac.ts\n * export const rbacServer = createRbacServer({\n * rbac,\n * getSubject: async (event) => {\n * const user = await getUserFromSession(event)\n * return user ? { type: 'user', id: user.id } : null\n * },\n * })\n *\n * // server/api/articles.post.ts\n * export default defineEventHandler(async (event) => {\n * await rbacServer.requirePermission(event, 'articles.create')\n * })\n * ```\n *\n * With a typed engine (`createRbac<AppTypes>(...)`), names are checked: `requirePermission(event, 'typo')` is a type error.\n */\nexport function createRbacServer<E extends RbacEvent = RbacEvent, T extends RbacTypeConfig = DefaultRbacTypes>(\n options: RbacServerOptions<E, T>,\n): RbacServer<E, T> {\n return buildRbacServer(options as unknown as RbacServerOptions<E>) as unknown as RbacServer<E, T>\n}\n\nfunction buildRbacServer<E extends RbacEvent>(options: RbacServerOptions<E>): UntypedRbacServer<E> {\n const { rbac, getSubject, guard, team, exposeRequirements = false } = options\n // Per instance, so a second server (e.g. guard 'api') never reuses another guard's subject.\n const resolved = new WeakMap<object, SubjectRbac | null>()\n\n async function resolve(event: E): Promise<SubjectRbac | null> {\n const context = event.context as Record<string, unknown>\n if (resolved.has(context)) return resolved.get(context)!\n\n const subject = await getSubject(event)\n let result: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(event) : undefined\n result = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n resolved.set(context, result)\n // The client plugin hydrates from `event.context.rbac`: the first instance to resolve fills it.\n if (context[CONTEXT_KEY] === undefined) context[CONTEXT_KEY] = result\n return result\n }\n\n // Async so an empty requirement (TypeError) rejects the returned promise instead of throwing synchronously.\n async function enforce(event: E, build: () => RbacRequirement, scope: RequireGuardOptions = {}): Promise<SubjectRbac> {\n const requirement = build()\n const resolvedSubject = await resolve(event)\n if (resolvedSubject === null) throw new RbacHttpError({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE })\n const subject = scope.guard === undefined ? resolvedSubject : resolvedSubject.withScope({ guard: scope.guard })\n if (!(await satisfiesRequirement(subject, requirement))) {\n throw new RbacHttpError({\n error: 'FORBIDDEN',\n reason: requirement.kind,\n message: REQUIREMENT_MESSAGES[requirement.kind],\n ...(exposeRequirements && { required: requirement.requirements }),\n })\n }\n return subject\n }\n\n return {\n resolve,\n async snapshot(event) {\n const subject = await resolve(event)\n return subject ? subject.snapshot() : null\n },\n requirePermission(event, ...args) {\n const { names, options } = splitRequirementArgs<RequirePermissionOptions>(args)\n return enforce(event, () => permissionRequirement(names, options), options)\n },\n requireRole(event, ...args) {\n const { names, options } = splitRequirementArgs<RequireRoleOptions>(args)\n return enforce(event, () => roleRequirement(names, options), options)\n },\n requireRoleOrPermission(event, ...args) {\n const { names, options } = splitRequirementArgs<RequireGuardOptions>(args)\n return enforce(event, () => roleOrPermissionRequirement(names), options)\n },\n canAny(event, ...args) {\n const { names, options } = splitRequirementArgs<RequireGuardOptions>(args)\n return enforce(event, () => permissionRequirement(names, { any: true }), options)\n },\n canAll(event, ...args) {\n const { names, options } = splitRequirementArgs<RequireGuardOptions>(args)\n return enforce(event, () => permissionRequirement(names), options)\n },\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anievo-id/rbac-evolution-nuxt",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0-rc.0",
|
|
4
4
|
"description": "Nuxt 3/4 module for rbac-evolution: SSR-hydrated permissions, auto-imported composables, route middleware & Nitro helpers.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "AniEvo-ID (https://github.com/AniEvo-ID)",
|
|
@@ -50,8 +50,8 @@
|
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
52
|
"@nuxt/kit": "^3.13.0 || ^4.0.0",
|
|
53
|
-
"@anievo-id/rbac-evolution
|
|
54
|
-
"@anievo-id/rbac-evolution": "^0.
|
|
53
|
+
"@anievo-id/rbac-evolution": "^1.0.0-rc.0",
|
|
54
|
+
"@anievo-id/rbac-evolution-vue": "^1.0.0-rc.0"
|
|
55
55
|
},
|
|
56
56
|
"peerDependencies": {
|
|
57
57
|
"nuxt": "^3.0.0 || ^4.0.0",
|