@anievo-id/rbac-evolution-trpc 1.4.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +53 -53
- package/dist/index.cjs.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 AniEvo-ID
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AniEvo-ID
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,53 +1,53 @@
|
|
|
1
|
-
# @anievo-id/rbac-evolution-trpc
|
|
2
|
-
|
|
3
|
-
[tRPC](https://trpc.io) middleware for [RBAC Evolution](https://github.com/AniEvo-ID/rbac-evolution): permission and
|
|
4
|
-
role guards for procedures, with a typed, non-null `ctx.rbac` after them.
|
|
5
|
-
|
|
6
|
-
## Install
|
|
7
|
-
|
|
8
|
-
```bash
|
|
9
|
-
npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-trpc @trpc/server
|
|
10
|
-
```
|
|
11
|
-
|
|
12
|
-
## Usage
|
|
13
|
-
|
|
14
|
-
```ts
|
|
15
|
-
import { initTRPC } from '@trpc/server'
|
|
16
|
-
import { createRbac, MemoryAdapter } from '@anievo-id/rbac-evolution'
|
|
17
|
-
import { createGuards, createRbacContext, rbacErrorFormatter } from '@anievo-id/rbac-evolution-trpc'
|
|
18
|
-
|
|
19
|
-
const rbac = createRbac<AppRbac>({ adapter: new MemoryAdapter() })
|
|
20
|
-
const rbacContext = createRbacContext({
|
|
21
|
-
rbac,
|
|
22
|
-
getSubject: (user: User | null) => (user ? { type: 'user', id: user.id } : null),
|
|
23
|
-
})
|
|
24
|
-
|
|
25
|
-
export async function createContext({ req }: { req: Request }) {
|
|
26
|
-
const user = await getUser(req) // yours
|
|
27
|
-
return { user, ...(await rbacContext(user)) } // ctx.rbac: SubjectRbac | null
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
const t = initTRPC.context<Awaited<ReturnType<typeof createContext>>>().create({ errorFormatter: rbacErrorFormatter })
|
|
31
|
-
const { requirePermission, requireRole } = createGuards<typeof rbac>()
|
|
32
|
-
|
|
33
|
-
export const appRouter = t.router({
|
|
34
|
-
publish: t.procedure.use(requirePermission('posts.publish')).mutation(async ({ ctx }) => {
|
|
35
|
-
await ctx.rbac.can('posts.delete') // ctx.rbac is never null here, and the names are typed
|
|
36
|
-
}),
|
|
37
|
-
stats: t.procedure.use(requireRole('admin|editor')).query(() => getStats()),
|
|
38
|
-
})
|
|
39
|
-
```
|
|
40
|
-
|
|
41
|
-
- Guests get a `TRPCError` `UNAUTHORIZED`, users without access a `TRPCError` `FORBIDDEN`. With
|
|
42
|
-
`rbacErrorFormatter`, clients read `{ error, reason, message }` from `error.data.rbac`. The required names are
|
|
43
|
-
only added with `exposeRequirements: true`. Leave it off in production.
|
|
44
|
-
- `createGuards<AppRbac>()` checks names at compile time; `createGuards<AppRbac, 'api'>()` with names per guard.
|
|
45
|
-
- `createGuards({ resolve: ({ ctx }) => ... })` reads the subject from the call instead of `ctx.rbac`.
|
|
46
|
-
|
|
47
|
-
## Documentation
|
|
48
|
-
|
|
49
|
-
https://creation.anievo.id/rbac-evolution/frameworks/trpc
|
|
50
|
-
|
|
51
|
-
## License
|
|
52
|
-
|
|
53
|
-
MIT
|
|
1
|
+
# @anievo-id/rbac-evolution-trpc
|
|
2
|
+
|
|
3
|
+
[tRPC](https://trpc.io) middleware for [RBAC Evolution](https://github.com/AniEvo-ID/rbac-evolution): permission and
|
|
4
|
+
role guards for procedures, with a typed, non-null `ctx.rbac` after them.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-trpc @trpc/server
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Usage
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { initTRPC } from '@trpc/server'
|
|
16
|
+
import { createRbac, MemoryAdapter } from '@anievo-id/rbac-evolution'
|
|
17
|
+
import { createGuards, createRbacContext, rbacErrorFormatter } from '@anievo-id/rbac-evolution-trpc'
|
|
18
|
+
|
|
19
|
+
const rbac = createRbac<AppRbac>({ adapter: new MemoryAdapter() })
|
|
20
|
+
const rbacContext = createRbacContext({
|
|
21
|
+
rbac,
|
|
22
|
+
getSubject: (user: User | null) => (user ? { type: 'user', id: user.id } : null),
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
export async function createContext({ req }: { req: Request }) {
|
|
26
|
+
const user = await getUser(req) // yours
|
|
27
|
+
return { user, ...(await rbacContext(user)) } // ctx.rbac: SubjectRbac | null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const t = initTRPC.context<Awaited<ReturnType<typeof createContext>>>().create({ errorFormatter: rbacErrorFormatter })
|
|
31
|
+
const { requirePermission, requireRole } = createGuards<typeof rbac>()
|
|
32
|
+
|
|
33
|
+
export const appRouter = t.router({
|
|
34
|
+
publish: t.procedure.use(requirePermission('posts.publish')).mutation(async ({ ctx }) => {
|
|
35
|
+
await ctx.rbac.can('posts.delete') // ctx.rbac is never null here, and the names are typed
|
|
36
|
+
}),
|
|
37
|
+
stats: t.procedure.use(requireRole('admin|editor')).query(() => getStats()),
|
|
38
|
+
})
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- Guests get a `TRPCError` `UNAUTHORIZED`, users without access a `TRPCError` `FORBIDDEN`. With
|
|
42
|
+
`rbacErrorFormatter`, clients read `{ error, reason, message }` from `error.data.rbac`. The required names are
|
|
43
|
+
only added with `exposeRequirements: true`. Leave it off in production.
|
|
44
|
+
- `createGuards<AppRbac>()` checks names at compile time; `createGuards<AppRbac, 'api'>()` with names per guard.
|
|
45
|
+
- `createGuards({ resolve: ({ ctx }) => ... })` reads the subject from the call instead of `ctx.rbac`.
|
|
46
|
+
|
|
47
|
+
## Documentation
|
|
48
|
+
|
|
49
|
+
https://creation.anievo.id/rbac-evolution/frameworks/trpc
|
|
50
|
+
|
|
51
|
+
## License
|
|
52
|
+
|
|
53
|
+
MIT
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context.ts","../src/errors.ts","../src/guards.ts"],"names":["UNAUTHENTICATED_MESSAGE","TRPCError","REQUIREMENT_MESSAGES","satisfiesRequirement","requirePermission","options","splitRequirementArgs","permissionRequirement","requireRole","roleRequirement","requireRoleOrPermission","roleOrPermissionRequirement","canAny","canAll"],"mappings":";;;;;;AAmFO,SAAS,kBAKd,OAAA,EAC0C;AAC1C,EAAA,MAAM,EAAE,UAAA,EAAY,IAAA,EAAK,GAAI,OAAA;AAC7B,EAAA,MAAM,QAA4B,OAAA,CAAQ,KAAA;AAE1C,EAAA,MAAM,OAAO,OAAA,CAAQ,IAAA;AAErB,EAAA,OAAO,OAAO,KAAA,KAAU;AACtB,IAAA,MAAM,OAAA,GAAU,MAAM,UAAA,CAAW,KAAK,CAAA;AACtC,IAAA,IAAI,KAAA,GAA4B,IAAA;AAChC,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,MAAM,MAAA,GAAS,IAAA,GAAO,MAAM,IAAA,CAAK,KAAK,CAAA,GAAI,MAAA;AAC1C,MAAA,KA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9G;AAOA,EAAA,SAASO,WAAU,IAAA,EAAkE;AACnF,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAAP,QAAAA,EAAQ,GAAIC,mCAAwC,IAAI,CAAA;AACvE,IAAA,OAAOF,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAGC,QAAAA,EAAS,GAAA,EAAK,MAAM,CAAA;AAAA,EAC9D;AAOA,EAAA,SAASQ,WAAU,IAAA,EAAkE;AACnF,IAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAAR,QAAAA,EAAQ,GAAIC,mCAAwC,IAAI,CAAA;AACvE,IAAA,OAAOF,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAGC,QAAAA,EAAS,GAAA,EAAK,OAAO,CAAA;AAAA,EAC/D;AAIA,EAAA,OAAO,EAAE,iBAAA,EAAAD,kBAAAA,EAAmB,WAAA,EAAAI,YAAAA,EAAa,yBAAAE,wBAAAA,EAAyB,MAAA,EAAAE,OAAAA,EAAQ,MAAA,EAAAC,OAAAA,EAAO;AACnF;AAEA,IAAM,gBAAwB,YAAA,EAAa;AAGpC,IAAM,oBAA2D,aAAA,CAAc;AAC/E,IAAM,cAA+C,aAAA,CAAc;AACnE,IAAM,0BAA4D,aAAA,CAAc;AAChF,IAAM,SAA2C,aAAA,CAAc;AAC/D,IAAM,SAA2C,aAAA,CAAc","file":"index.cjs","sourcesContent":["import type {\r\n CheckGuard,\r\n DefaultGuardName,\r\n DefaultRbacTypes,\r\n GuardOptions,\r\n Rbac,\r\n RbacTypeConfig,\r\n ScopedGuardName,\r\n Subject,\r\n SubjectRbac,\r\n TeamId,\r\n} from '@anievo-id/rbac-evolution'\r\n\r\ntype MaybePromise<T> = T | Promise<T>\r\n\r\n/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */\r\nexport type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never\r\n\r\n/**\r\n * The subject the guards of `createGuards<T, G>()` work with: a `SubjectRbac` with the names of `T` (of guard `G`\r\n * with per-guard names), or an untyped `SubjectRbac` without `T`.\r\n */\r\nexport type GuardSubject<\r\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\r\n G extends string = DefaultGuardName<TypesOf<T>>,\r\n> = SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>>\r\n\r\n/**\r\n * The part of the tRPC context this package reads and writes: `ctx.rbac`, a `SubjectRbac` for the current subject\r\n * or `null` for guests. Spread it into what `createContext` returns (see `createRbacContext()`), or type your\r\n * context with it: `type Context = RbacContext<typeof rbac> & { user: User | null }`.\r\n *\r\n * `T` (a names type like `AppRbac`, or `typeof rbac`) types the names `ctx.rbac` accepts; without it, any name.\r\n * With per-guard names, `G` is the guard of the subject: the default guard's names by default.\r\n */\r\nexport type RbacContext<\r\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\r\n G extends string = DefaultGuardName<TypesOf<T>>,\r\n> = {\r\n /** Roles & permissions of the current subject. `null` for guests. */\r\n rbac: GuardSubject<T, G> | null\r\n}\r\n\r\nexport interface RbacContextOptions<\r\n I = unknown,\r\n T extends RbacTypeConfig = DefaultRbacTypes,\r\n G extends string = DefaultGuardName<T>,\r\n> {\r\n /** The RBAC engine created with `createRbac(...)`. Its typed names flow into `ctx.rbac`. */\r\n rbac: Rbac<T>\r\n /**\r\n * Resolves the authenticated subject from what you pass to the returned function (your user, the request, the\r\n * `createContext` options, ...). Return `null` / `undefined` for guests.\r\n */\r\n getSubject: (input: I) => MaybePromise<Subject | null | undefined>\r\n /**\r\n * Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. With per-guard names, it must be one\r\n * of the typed guards, and `ctx.rbac` gets its names.\r\n */\r\n guard?: G | undefined\r\n /** Resolves the current team (only when the engine was created with `teams: true`). */\r\n team?: ((input: I) => MaybePromise<TeamId | undefined>) | undefined\r\n}\r\n\r\n/**\r\n * Builds the `rbac` part of your tRPC context: returns a function that resolves the subject from its argument and\r\n * gives `{ rbac }` (a `SubjectRbac`, or `null` for guests). Spread it into what `createContext` returns.\r\n *\r\n * ```ts\r\n * const rbacContext = createRbacContext({\r\n * rbac,\r\n * getSubject: (user: User | null) => (user ? { type: 'user', id: user.id } : null),\r\n * })\r\n *\r\n * export async function createContext({ req }: FetchCreateContextFnOptions) {\r\n * const user = await getUser(req)\r\n * return { user, ...(await rbacContext(user)) }\r\n * }\r\n * ```\r\n *\r\n * With a typed engine (`createRbac<AppRbac>()`), `ctx.rbac` is typed with its names. With per-guard names, the\r\n * `guard` option picks the names of `ctx.rbac`.\r\n */\r\nexport function createRbacContext<\r\n I = unknown,\r\n T extends RbacTypeConfig = DefaultRbacTypes,\r\n G extends string = DefaultGuardName<T>,\r\n>(\r\n options: RbacContextOptions<I, T, G> & (T extends { guards: object } ? GuardOptions<CheckGuard<T, G>> : unknown),\r\n): (input: I) => Promise<RbacContext<T, G>> {\r\n const { getSubject, team } = options\r\n const guard: string | undefined = options.guard\r\n // `T` only narrows the names on `ctx.rbac`; the subject is the same object either way.\r\n const rbac = options.rbac as unknown as Rbac\r\n\r\n return async (input) => {\r\n const subject = await getSubject(input)\r\n let value: SubjectRbac | null = null\r\n if (subject) {\r\n const teamId = team ? await team(input) : undefined\r\n value = rbac.for(subject, {\r\n ...(guard !== undefined && { guard }),\r\n ...(teamId !== undefined && { team: teamId }),\r\n })\r\n }\r\n return { rbac: value } as unknown as RbacContext<T, G>\r\n }\r\n}\r\n","import {\r\n REQUIREMENT_MESSAGES,\r\n type RequirementKind,\r\n UNAUTHENTICATED_MESSAGE,\r\n} from '@anievo-id/rbac-evolution'\r\nimport { TRPCError } from '@trpc/server'\r\n\r\n/**\r\n * Why a guard denied a call: the same body the other integrations send with their 401 / 403 responses\r\n * (`error`, `reason`, `message`, and `required` only with `exposeRequirements: true`).\r\n */\r\nexport type RbacErrorBody =\r\n | { error: 'UNAUTHENTICATED'; message: string }\r\n | { error: 'FORBIDDEN'; reason: RequirementKind; message: string; required?: string[][] }\r\n\r\n/**\r\n * The `cause` of the `TRPCError` a guard throws by default. It carries the {@link RbacErrorBody}, which\r\n * `rbacErrorFormatter` (or `getRbacErrorBody()`) puts where clients can read it.\r\n */\r\nexport class RbacAccessError extends Error {\r\n readonly code = 'RBAC_ACCESS_DENIED'\r\n /** The 401 / 403 body of the other integrations. */\r\n readonly body: RbacErrorBody\r\n /** HTTP-style status: `401` (no subject) or `403` (missing role/permission). */\r\n readonly status: 401 | 403\r\n\r\n constructor(body: RbacErrorBody) {\r\n super(body.message)\r\n this.name = 'RbacAccessError'\r\n this.body = body\r\n this.status = body.error === 'UNAUTHENTICATED' ? 401 : 403\r\n }\r\n}\r\n\r\n/** Thrown when a guard runs without a subject resolver: `ctx.rbac` is `undefined` and `createGuards()` has no `resolve`. */\r\nexport class RbacContextMissingError extends Error {\r\n readonly code = 'RBAC_CONTEXT_MISSING'\r\n\r\n constructor() {\r\n super(\r\n '`ctx.rbac` is not set. Return it from `createContext` (see `createRbacContext()`), or pass `resolve` to `createGuards()`.',\r\n )\r\n this.name = 'RbacContextMissingError'\r\n }\r\n}\r\n\r\n/** The default error for a call without a subject: `TRPCError` `UNAUTHORIZED`. */\r\nexport function unauthenticatedError(): TRPCError {\r\n const body: RbacErrorBody = { error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }\r\n return new TRPCError({ code: 'UNAUTHORIZED', message: body.message, cause: new RbacAccessError(body) })\r\n}\r\n\r\n/** The default error for a subject without access: `TRPCError` `FORBIDDEN`. */\r\nexport function forbiddenError(kind: RequirementKind, requirements?: string[][]): TRPCError {\r\n const body: RbacErrorBody = {\r\n error: 'FORBIDDEN',\r\n reason: kind,\r\n message: REQUIREMENT_MESSAGES[kind],\r\n ...(requirements !== undefined && { required: requirements }),\r\n }\r\n return new TRPCError({ code: 'FORBIDDEN', message: body.message, cause: new RbacAccessError(body) })\r\n}\r\n\r\n/** Duck-typed, so it also works when two copies of this package are installed. */\r\nconst isAccessError = (value: unknown): value is RbacAccessError =>\r\n value instanceof Error &&\r\n (value as { code?: unknown }).code === 'RBAC_ACCESS_DENIED' &&\r\n typeof (value as { body?: unknown }).body === 'object'\r\n\r\n/**\r\n * The {@link RbacErrorBody} of an error thrown by a guard (the `TRPCError`, or its `RbacAccessError` cause), or\r\n * `null` for any other error.\r\n */\r\nexport function getRbacErrorBody(error: unknown): RbacErrorBody | null {\r\n if (isAccessError(error)) return error.body\r\n if (error instanceof Error && isAccessError(error.cause)) return error.cause.body\r\n return null\r\n}\r\n\r\n/**\r\n * An `errorFormatter` that adds the guard's {@link RbacErrorBody} to the error shape as `data.rbac` (`null` for\r\n * other errors), so clients can read `error.data.rbac.reason`:\r\n *\r\n * ```ts\r\n * const t = initTRPC.context<Context>().create({ errorFormatter: rbacErrorFormatter })\r\n * ```\r\n *\r\n * To combine it with your own formatter, call it first and extend what it returns.\r\n */\r\nexport function rbacErrorFormatter<S extends { data: object }>(opts: {\r\n shape: S\r\n error: unknown\r\n}): S & { data: S['data'] & { rbac: RbacErrorBody | null } } {\r\n const { shape, error } = opts\r\n return { ...shape, data: { ...shape.data, rbac: getRbacErrorBody(error) } }\r\n}\r\n","import {\r\n type DefaultGuardName,\r\n type DefaultRbacTypes,\r\n type GuardName,\r\n type GuardRequirementArgs,\r\n type PermissionName,\r\n permissionRequirement,\r\n type Rbac,\r\n type RbacTypeConfig,\r\n type RbacRequirement,\r\n type RequirementKind,\r\n type RequirementArgs,\r\n type RequirementNames,\r\n type RoleName,\r\n roleOrPermissionRequirement,\r\n roleRequirement,\r\n satisfiesRequirement,\r\n splitRequirementArgs,\r\n type SubjectRbac,\r\n} from '@anievo-id/rbac-evolution'\r\nimport type { TRPCProcedureType } from '@trpc/server'\r\n// Type-only. The main entry exports it as `TRPCMiddlewareFunction` in later 11.x releases, but not in 11.0.0;\r\n// this entry has it in every 11.x.\r\nimport type { MiddlewareFunction } from '@trpc/server/unstable-core-do-not-import'\r\nimport type { GuardSubject, TypesOf } from './context'\r\nimport { forbiddenError, RbacContextMissingError, unauthenticatedError } from './errors'\r\n\r\ntype MaybePromise<T> = T | Promise<T>\r\n\r\nexport type GuardKind = RequirementKind\r\n\r\n/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */\r\nexport interface GuardContext {\r\n kind: GuardKind\r\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\r\n requirements: string[][]\r\n}\r\n\r\n/** The call a guard runs in, as `onUnauthenticated` / `onForbidden` and `resolve` get it. */\r\nexport interface GuardCallOptions {\r\n /** The procedure's context (after the middlewares that ran before the guard). */\r\n ctx: any\r\n /** The procedure's path, such as `post.byId`. */\r\n path: string\r\n type: TRPCProcedureType\r\n}\r\n\r\n/**\r\n * What `onUnauthenticated` / `onForbidden` get: the call, plus the subject the guard checked (`null` in\r\n * `onUnauthenticated`). `R` is that subject's type: `SubjectRbac` with the names of `T` in `createGuards<T>()`.\r\n */\r\nexport interface GuardHandlerOptions<R = SubjectRbac> extends GuardCallOptions {\r\n rbac: R | null\r\n}\r\n\r\n/**\r\n * Returns the error to throw (or throws it), e.g. a `TRPCError` with another code. Anything that is not a\r\n * `TRPCError` reaches the client as an `INTERNAL_SERVER_ERROR`.\r\n */\r\nexport type GuardHandler<R = SubjectRbac> = (opts: GuardHandlerOptions<R>, context: GuardContext) => MaybePromise<Error>\r\n\r\nexport interface GuardHandlers<R = SubjectRbac> {\r\n /** Called when there is no subject (`ctx.rbac` is `null`). Default: a `TRPCError` `UNAUTHORIZED`. */\r\n onUnauthenticated?: GuardHandler<R> | undefined\r\n /** Called when the subject lacks access. Default: a `TRPCError` `FORBIDDEN`. */\r\n onForbidden?: GuardHandler<R> | undefined\r\n /**\r\n * Include the required roles/permissions in the default error (`required` in its body).\r\n * Default: `false` (like spatie's `display_permission_in_exception`).\r\n */\r\n exposeRequirements?: boolean | undefined\r\n}\r\n\r\n/**\r\n * Reads the subject of a call, instead of `ctx.rbac`: `({ ctx }) => (ctx.user ? rbac.for(ctx.user) : null)`.\r\n * Return `null` / `undefined` for guests.\r\n */\r\nexport type RbacResolver<R = SubjectRbac> = (opts: GuardCallOptions) => MaybePromise<R | null | undefined>\r\n\r\n/** The options of `createGuards()`: the shared handlers, plus a `resolve` that replaces `ctx.rbac`. */\r\nexport interface CreateGuardsOptions<R = SubjectRbac> extends GuardHandlers<R> {\r\n /**\r\n * Reads the subject of each call. Default: `ctx.rbac`, as `createRbacContext()` sets it. With `resolve`, the\r\n * procedures don't need `rbac` in their context. It runs once per guard and call.\r\n */\r\n resolve?: RbacResolver<R> | undefined\r\n}\r\n\r\n/**\r\n * The options every guard takes: the handlers plus `guard`.\r\n *\r\n * `guard` is per guard only (like spatie's `role:admin,api`), not a `createGuards()` default: the subject's guard\r\n * comes from `createRbacContext()` (or `resolve`). With per-guard names, tell the types which guard the subjects\r\n * have with `createGuards<AppRbac, 'api'>()`.\r\n */\r\nexport interface RouteGuardOptions<R = SubjectRbac> extends GuardHandlers<R> {\r\n /**\r\n * Check in this guard instead of the subject's (`subject.withScope({ guard })`), like spatie's\r\n * `role:admin,api`. Default: the guard of the subject.\r\n */\r\n guard?: string | undefined\r\n}\r\n\r\nexport interface PermissionGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {\r\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\r\n any?: boolean | undefined\r\n}\r\n\r\nexport interface RoleGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {\r\n /** Require ALL of the roles (instead of any). Default: `false`. */\r\n all?: boolean | undefined\r\n}\r\n\r\nexport type RoleOrPermissionGuardOptions<R = SubjectRbac> = RouteGuardOptions<R>\r\n\r\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\r\nexport type GuardNames = RequirementNames\r\n\r\n/**\r\n * The context a guard needs: `ctx.rbac`, a `SubjectRbac` or `null` (see `createRbacContext()`). A procedure\r\n * whose context has no `rbac` can't `.use()` the guard (unless `createGuards()` got a `resolve`).\r\n */\r\nexport interface RbacProcedureContext {\r\n rbac: SubjectRbac<any, any> | null\r\n}\r\n\r\n/**\r\n * The middleware a guard returns, for `t.procedure.use(...)`. After it, `ctx.rbac` is `R`: the subject, never\r\n * `null`. `C` is the context it needs: {@link RbacProcedureContext} by default.\r\n */\r\nexport type RbacMiddleware<R = SubjectRbac, C = RbacProcedureContext> = MiddlewareFunction<\r\n C,\r\n any,\r\n any,\r\n { rbac: R },\r\n any\r\n>\r\n\r\n/**\r\n * A guard typed with the names `N` it accepts and its options `O`: `(...names, options?)`.\r\n * Every name (each part of a `'a|b'` list, each array item) must be one of `N`; with `N = string`, any name is.\r\n * A call without names, or with options that are not the last argument, is a type error.\r\n * The middleware narrows `ctx.rbac` to `R`, and needs the context `C`.\r\n */\r\nexport type Guard<N extends string, O, R = SubjectRbac, C = RbacProcedureContext> = <\r\n const A extends readonly (GuardNames | O)[],\r\n>(\r\n ...args: A & RequirementArgs<A, N, O>\r\n) => RbacMiddleware<R, C>\r\n\r\n/**\r\n * The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). After them,\r\n * `ctx.rbac` is a `SubjectRbac` with the names of `T`.\r\n */\r\nexport interface Guards<T extends RbacTypeConfig = DefaultRbacTypes, C = RbacProcedureContext> {\r\n requirePermission: Guard<PermissionName<T>, PermissionGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\r\n requireRole: Guard<RoleName<T>, RoleGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\r\n requireRoleOrPermission: Guard<\r\n PermissionName<T> | RoleName<T>,\r\n RoleOrPermissionGuardOptions<GuardSubject<T>>,\r\n GuardSubject<T>,\r\n C\r\n >\r\n canAny: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\r\n canAll: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\r\n}\r\n\r\n/**\r\n * A guard of `createGuards<T, G>()` when `T` has per-guard names (`RbacTypeConfig['guards']`): like\r\n * {@link Guard}, but the names are those of the guard the call checks in, its `{ guard }` option or else `G`\r\n * (the guard of the subject). `requirePermission('orders.read', { guard: 'api' })` takes the `api` names.\r\n */\r\nexport type ScopedGuard<T extends RbacTypeConfig, G extends string, K extends GuardKind, O, C = RbacProcedureContext> = <\r\n const A extends readonly (GuardNames | O)[],\r\n>(\r\n ...args: A & GuardRequirementArgs<A, T, K, G, O>\r\n) => RbacMiddleware<GuardSubject<T, G>, C>\r\n\r\n/**\r\n * The guards returned by `createGuards<T, G>()` when `T` has per-guard names: names follow the guard each call\r\n * checks in (see {@link ScopedGuard}), and `ctx.rbac` is in guard `G` after them.\r\n */\r\nexport interface ScopedGuards<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>, C = RbacProcedureContext> {\r\n requirePermission: ScopedGuard<T, G, 'permission', PermissionGuardOptions<GuardSubject<T, G>>, C>\r\n requireRole: ScopedGuard<T, G, 'role', RoleGuardOptions<GuardSubject<T, G>>, C>\r\n requireRoleOrPermission: ScopedGuard<T, G, 'role_or_permission', RoleOrPermissionGuardOptions<GuardSubject<T, G>>, C>\r\n canAny: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>\r\n canAll: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>\r\n}\r\n\r\n/**\r\n * What `createGuards<T, G>()` returns: {@link Guards} for a config without per-guard names, and\r\n * {@link ScopedGuards} for one with `guards`.\r\n */\r\nexport type GuardsFor<\r\n T extends RbacTypeConfig = DefaultRbacTypes,\r\n G extends string = DefaultGuardName<T>,\r\n C = RbacProcedureContext,\r\n> = T extends { guards: object } ? ScopedGuards<T, G, C> : Guards<T, C>\r\n\r\n// ------------------------------------------------------------------------------------------ runtime\r\n\r\n/** The untyped middleware the guards build; the public types above are only its face. */\r\ntype AnyMiddleware = (opts: GuardCallOptions & { next: (opts: { ctx: object }) => Promise<unknown> }) => Promise<unknown>\r\n\r\nconst fromContext: RbacResolver = ({ ctx }) => {\r\n const rbac = (ctx as { rbac?: SubjectRbac | null } | undefined)?.rbac\r\n if (rbac === undefined) throw new RbacContextMissingError()\r\n return rbac\r\n}\r\n\r\nconst defaultUnauthenticated: GuardHandler = () => unauthenticatedError()\r\n\r\nconst defaultForbidden =\r\n (expose: boolean): GuardHandler =>\r\n (_opts, context) =>\r\n forbiddenError(context.kind, expose ? context.requirements : undefined)\r\n\r\nfunction createGuard(\r\n requirement: RbacRequirement,\r\n handlers: GuardHandlers,\r\n guard: string | undefined,\r\n resolve: RbacResolver,\r\n): AnyMiddleware {\r\n const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated\r\n const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false)\r\n const context: GuardContext = { kind: requirement.kind, requirements: requirement.requirements }\r\n\r\n return async (opts) => {\r\n const call: GuardCallOptions = { ctx: opts.ctx, path: opts.path, type: opts.type }\r\n const rbac = (await resolve(call)) ?? null\r\n if (rbac === null) throw await onUnauthenticated({ ...call, rbac }, context)\r\n if (await satisfiesRequirement(guard === undefined ? rbac : rbac.withScope({ guard }), requirement)) {\r\n return opts.next({ ctx: { rbac } })\r\n }\r\n throw await onForbidden({ ...call, rbac }, context)\r\n }\r\n}\r\n\r\n/** `options` over `defaults`, where an option set to `undefined` keeps the default (as if left out). */\r\nfunction withDefaults(defaults: GuardHandlers, options: GuardHandlers): GuardHandlers {\r\n const merged: Record<string, unknown> = { ...defaults }\r\n for (const [key, value] of Object.entries(options)) if (value !== undefined) merged[key] = value\r\n return merged as GuardHandlers\r\n}\r\n\r\n/**\r\n * Builds the guards with shared options: handlers (e.g. an `onForbidden` that throws `NOT_FOUND`), and a `resolve`\r\n * that reads the subject of a call instead of `ctx.rbac`.\r\n *\r\n * Pass the same type argument as `createRbac<AppRbac>()` (or `typeof rbac`) to check names at compile time:\r\n * `const { requirePermission } = createGuards<AppRbac>()`. After a guard, `ctx.rbac` has the same names and is\r\n * never `null`.\r\n *\r\n * With per-guard names (`RbacTypeConfig['guards']`), `G` is the guard of the subjects these guards check (the\r\n * `guard` of `createRbacContext()`; default: the default guard): `createGuards<AppRbac, 'api'>()`. Names are\r\n * checked in that guard, or in a procedure's `{ guard }`. It is a type only; the subject's guard still decides\r\n * at runtime.\r\n */\r\nexport function createGuards<\r\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\r\n G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>,\r\n>(\r\n options: CreateGuardsOptions<GuardSubject<T, G>> & { resolve: RbacResolver<GuardSubject<T, G>> },\r\n): GuardsFor<TypesOf<T>, G, any>\r\nexport function createGuards<\r\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\r\n G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>,\r\n>(defaults?: GuardHandlers<GuardSubject<T, G>>): GuardsFor<TypesOf<T>, G>\r\nexport function createGuards(options: CreateGuardsOptions = {}): GuardsFor {\r\n const { resolve = fromContext, ...shared } = options\r\n\r\n /**\r\n * Requires permissions, like spatie's `permission:` middleware.\r\n *\r\n * - `requirePermission('edit articles')`\r\n * - `requirePermission('edit articles|delete articles')` — any of them\r\n * - `requirePermission('edit articles', 'publish articles')` — all of them\r\n * - `requirePermission('a', 'b', { any: true })` — any of them\r\n */\r\n function requirePermission(...args: readonly (GuardNames | PermissionGuardOptions)[]): AnyMiddleware {\r\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\r\n return createGuard(permissionRequirement(names, options), withDefaults(shared, options), options.guard, resolve)\r\n }\r\n\r\n /**\r\n * Requires roles, like spatie's `role:` middleware.\r\n *\r\n * - `requireRole('admin')`, `requireRole('admin|editor')`, `requireRole('admin', 'editor')` — any of them\r\n * - `requireRole('admin', 'editor', { all: true })` — all of them\r\n */\r\n function requireRole(...args: readonly (GuardNames | RoleGuardOptions)[]): AnyMiddleware {\r\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\r\n return createGuard(roleRequirement(names, options), withDefaults(shared, options), options.guard, resolve)\r\n }\r\n\r\n /**\r\n * Passes when the subject has ANY of the names as a role OR as a permission,\r\n * like spatie's `role_or_permission:` middleware.\r\n *\r\n * - `requireRoleOrPermission('admin|edit articles')`\r\n */\r\n function requireRoleOrPermission(...args: readonly (GuardNames | RoleOrPermissionGuardOptions)[]): AnyMiddleware {\r\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\r\n return createGuard(roleOrPermissionRequirement(names), withDefaults(shared, options), options.guard, resolve)\r\n }\r\n\r\n /**\r\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\r\n *\r\n * - `canAny('edit articles', 'publish articles')`, `canAny(['edit articles', 'publish articles'])`\r\n */\r\n function canAny(...args: readonly (GuardNames | RouteGuardOptions)[]): AnyMiddleware {\r\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(args)\r\n return requirePermission(...names, { ...options, any: true })\r\n }\r\n\r\n /**\r\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\r\n *\r\n * - `canAll('edit articles', 'publish articles')`, `canAll(['edit articles', 'publish|review'])`\r\n */\r\n function canAll(...args: readonly (GuardNames | RouteGuardOptions)[]): AnyMiddleware {\r\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(args)\r\n return requirePermission(...names, { ...options, any: false })\r\n }\r\n\r\n // The untyped functions above take any spread of names (`canAny` passes `...names` on); the typed signature\r\n // is only the public face, so a cast is enough. No runtime change.\r\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } as unknown as GuardsFor\r\n}\r\n\r\nconst defaultGuards: Guards = createGuards()\r\n\r\n// Spelled out, so the declarations keep these types (`Guard<string, PermissionGuardOptions>`, ...).\r\nexport const requirePermission: Guard<string, PermissionGuardOptions> = defaultGuards.requirePermission\r\nexport const requireRole: Guard<string, RoleGuardOptions> = defaultGuards.requireRole\r\nexport const requireRoleOrPermission: Guard<string, RouteGuardOptions> = defaultGuards.requireRoleOrPermission\r\nexport const canAny: Guard<string, RouteGuardOptions> = defaultGuards.canAny\r\nexport const canAll: Guard<string, RouteGuardOptions> = defaultGuards.canAll\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/context.ts","../src/errors.ts","../src/guards.ts"],"names":["UNAUTHENTICATED_MESSAGE","TRPCError","REQUIREMENT_MESSAGES","satisfiesRequirement","requirePermission","options","splitRequirementArgs","permissionRequirement","requireRole","roleRequirement","requireRoleOrPermission","roleOrPermissionRequirement","canAny","canAll"],"mappings":";;;;;;AAmFO,SAAS,kBAKd,OAAA,EAC0C;AAC1C,EAAA,MAAM,EAAE,UAAA,EAAY,IAAA,EAAK,GAAI,OAAA;AAC7B,EAAA,MAAM,QAA4B,OAAA,CAAQ,KAAA;AAE1C,EAAA,MAAM,OAAO,OAAA,CAAQ,IAAA;AAErB,EAAA,OAAO,OAAO,KAAA,KAAU;AACtB,IAAA,MAAM,OAAA,GAAU,MAAM,UAAA,CAAW,KAAK,CAAA;AACtC,IAAA,IAAI,KAAA,GAA4B,IAAA;AAChC,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,MAAM,MAAA,GAAS,IAAA,GAAO,MAAM,IAAA,CAAK,KAAK,CAAA,GAAI,MAAA;AAC1C,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;AACA,IAAA,OAAO,EAAE,MAAM,KAAA,EAAM;AAAA,EACvB,CAAA;AACF;ACxFO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EAChC,IAAA,GAAO,oBAAA;AAAA;AAAA,EAEP,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA,EAET,YAAY,IAAA,EAAqB;AAC/B,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AG,KAAA,EAAO,EAAE,GAAGC,QAAAA,EAAS,GAAA,EAAK,OAAO,CAAA;AAAA,EAC/D;AAIA,EAAA,OAAO,EAAE,iBAAA,EAAAD,kBAAAA,EAAmB,WAAA,EAAAI,YAAAA,EAAa,yBAAAE,wBAAAA,EAAyB,MAAA,EAAAE,OAAAA,EAAQ,MAAA,EAAAC,OAAAA,EAAO;AACnF;AAEA,IAAM,gBAAwB,YAAA,EAAa;AAGpC,IAAM,oBAA2D,aAAA,CAAc;AAC/E,IAAM,cAA+C,aAAA,CAAc;AACnE,IAAM,0BAA4D,aAAA,CAAc;AAChF,IAAM,SAA2C,aAAA,CAAc;AAC/D,IAAM,SAA2C,aAAA,CAAc","file":"index.cjs","sourcesContent":["import type {\n CheckGuard,\n DefaultGuardName,\n DefaultRbacTypes,\n GuardOptions,\n Rbac,\n RbacTypeConfig,\n ScopedGuardName,\n Subject,\n SubjectRbac,\n TeamId,\n} from '@anievo-id/rbac-evolution'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */\nexport type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never\n\n/**\n * The subject the guards of `createGuards<T, G>()` work with: a `SubjectRbac` with the names of `T` (of guard `G`\n * with per-guard names), or an untyped `SubjectRbac` without `T`.\n */\nexport type GuardSubject<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends string = DefaultGuardName<TypesOf<T>>,\n> = SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>>\n\n/**\n * The part of the tRPC context this package reads and writes: `ctx.rbac`, a `SubjectRbac` for the current subject\n * or `null` for guests. Spread it into what `createContext` returns (see `createRbacContext()`), or type your\n * context with it: `type Context = RbacContext<typeof rbac> & { user: User | null }`.\n *\n * `T` (a names type like `AppRbac`, or `typeof rbac`) types the names `ctx.rbac` accepts; without it, any name.\n * With per-guard names, `G` is the guard of the subject: the default guard's names by default.\n */\nexport type RbacContext<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends string = DefaultGuardName<TypesOf<T>>,\n> = {\n /** Roles & permissions of the current subject. `null` for guests. */\n rbac: GuardSubject<T, G> | null\n}\n\nexport interface RbacContextOptions<\n I = unknown,\n T extends RbacTypeConfig = DefaultRbacTypes,\n G extends string = DefaultGuardName<T>,\n> {\n /** The RBAC engine created with `createRbac(...)`. Its typed names flow into `ctx.rbac`. */\n rbac: Rbac<T>\n /**\n * Resolves the authenticated subject from what you pass to the returned function (your user, the request, the\n * `createContext` options, ...). Return `null` / `undefined` for guests.\n */\n getSubject: (input: I) => MaybePromise<Subject | null | undefined>\n /**\n * Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. With per-guard names, it must be one\n * of the typed guards, and `ctx.rbac` gets its names.\n */\n guard?: G | undefined\n /** Resolves the current team (only when the engine was created with `teams: true`). */\n team?: ((input: I) => MaybePromise<TeamId | undefined>) | undefined\n}\n\n/**\n * Builds the `rbac` part of your tRPC context: returns a function that resolves the subject from its argument and\n * gives `{ rbac }` (a `SubjectRbac`, or `null` for guests). Spread it into what `createContext` returns.\n *\n * ```ts\n * const rbacContext = createRbacContext({\n * rbac,\n * getSubject: (user: User | null) => (user ? { type: 'user', id: user.id } : null),\n * })\n *\n * export async function createContext({ req }: FetchCreateContextFnOptions) {\n * const user = await getUser(req)\n * return { user, ...(await rbacContext(user)) }\n * }\n * ```\n *\n * With a typed engine (`createRbac<AppRbac>()`), `ctx.rbac` is typed with its names. With per-guard names, the\n * `guard` option picks the names of `ctx.rbac`.\n */\nexport function createRbacContext<\n I = unknown,\n T extends RbacTypeConfig = DefaultRbacTypes,\n G extends string = DefaultGuardName<T>,\n>(\n options: RbacContextOptions<I, T, G> & (T extends { guards: object } ? GuardOptions<CheckGuard<T, G>> : unknown),\n): (input: I) => Promise<RbacContext<T, G>> {\n const { getSubject, team } = options\n const guard: string | undefined = options.guard\n // `T` only narrows the names on `ctx.rbac`; the subject is the same object either way.\n const rbac = options.rbac as unknown as Rbac\n\n return async (input) => {\n const subject = await getSubject(input)\n let value: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(input) : undefined\n value = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n return { rbac: value } as unknown as RbacContext<T, G>\n }\n}\n","import {\n REQUIREMENT_MESSAGES,\n type RequirementKind,\n UNAUTHENTICATED_MESSAGE,\n} from '@anievo-id/rbac-evolution'\nimport { TRPCError } from '@trpc/server'\n\n/**\n * Why a guard denied a call: the same body the other integrations send with their 401 / 403 responses\n * (`error`, `reason`, `message`, and `required` only with `exposeRequirements: true`).\n */\nexport type RbacErrorBody =\n | { error: 'UNAUTHENTICATED'; message: string }\n | { error: 'FORBIDDEN'; reason: RequirementKind; message: string; required?: string[][] }\n\n/**\n * The `cause` of the `TRPCError` a guard throws by default. It carries the {@link RbacErrorBody}, which\n * `rbacErrorFormatter` (or `getRbacErrorBody()`) puts where clients can read it.\n */\nexport class RbacAccessError extends Error {\n readonly code = 'RBAC_ACCESS_DENIED'\n /** The 401 / 403 body of the other integrations. */\n readonly body: RbacErrorBody\n /** HTTP-style status: `401` (no subject) or `403` (missing role/permission). */\n readonly status: 401 | 403\n\n constructor(body: RbacErrorBody) {\n super(body.message)\n this.name = 'RbacAccessError'\n this.body = body\n this.status = body.error === 'UNAUTHENTICATED' ? 401 : 403\n }\n}\n\n/** Thrown when a guard runs without a subject resolver: `ctx.rbac` is `undefined` and `createGuards()` has no `resolve`. */\nexport class RbacContextMissingError extends Error {\n readonly code = 'RBAC_CONTEXT_MISSING'\n\n constructor() {\n super(\n '`ctx.rbac` is not set. Return it from `createContext` (see `createRbacContext()`), or pass `resolve` to `createGuards()`.',\n )\n this.name = 'RbacContextMissingError'\n }\n}\n\n/** The default error for a call without a subject: `TRPCError` `UNAUTHORIZED`. */\nexport function unauthenticatedError(): TRPCError {\n const body: RbacErrorBody = { error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }\n return new TRPCError({ code: 'UNAUTHORIZED', message: body.message, cause: new RbacAccessError(body) })\n}\n\n/** The default error for a subject without access: `TRPCError` `FORBIDDEN`. */\nexport function forbiddenError(kind: RequirementKind, requirements?: string[][]): TRPCError {\n const body: RbacErrorBody = {\n error: 'FORBIDDEN',\n reason: kind,\n message: REQUIREMENT_MESSAGES[kind],\n ...(requirements !== undefined && { required: requirements }),\n }\n return new TRPCError({ code: 'FORBIDDEN', message: body.message, cause: new RbacAccessError(body) })\n}\n\n/** Duck-typed, so it also works when two copies of this package are installed. */\nconst isAccessError = (value: unknown): value is RbacAccessError =>\n value instanceof Error &&\n (value as { code?: unknown }).code === 'RBAC_ACCESS_DENIED' &&\n typeof (value as { body?: unknown }).body === 'object'\n\n/**\n * The {@link RbacErrorBody} of an error thrown by a guard (the `TRPCError`, or its `RbacAccessError` cause), or\n * `null` for any other error.\n */\nexport function getRbacErrorBody(error: unknown): RbacErrorBody | null {\n if (isAccessError(error)) return error.body\n if (error instanceof Error && isAccessError(error.cause)) return error.cause.body\n return null\n}\n\n/**\n * An `errorFormatter` that adds the guard's {@link RbacErrorBody} to the error shape as `data.rbac` (`null` for\n * other errors), so clients can read `error.data.rbac.reason`:\n *\n * ```ts\n * const t = initTRPC.context<Context>().create({ errorFormatter: rbacErrorFormatter })\n * ```\n *\n * To combine it with your own formatter, call it first and extend what it returns.\n */\nexport function rbacErrorFormatter<S extends { data: object }>(opts: {\n shape: S\n error: unknown\n}): S & { data: S['data'] & { rbac: RbacErrorBody | null } } {\n const { shape, error } = opts\n return { ...shape, data: { ...shape.data, rbac: getRbacErrorBody(error) } }\n}\n","import {\n type DefaultGuardName,\n type DefaultRbacTypes,\n type GuardName,\n type GuardRequirementArgs,\n type PermissionName,\n permissionRequirement,\n type Rbac,\n type RbacTypeConfig,\n type RbacRequirement,\n type RequirementKind,\n type RequirementArgs,\n type RequirementNames,\n type RoleName,\n roleOrPermissionRequirement,\n roleRequirement,\n satisfiesRequirement,\n splitRequirementArgs,\n type SubjectRbac,\n} from '@anievo-id/rbac-evolution'\nimport type { TRPCProcedureType } from '@trpc/server'\n// Type-only. The main entry exports it as `TRPCMiddlewareFunction` in later 11.x releases, but not in 11.0.0;\n// this entry has it in every 11.x.\nimport type { MiddlewareFunction } from '@trpc/server/unstable-core-do-not-import'\nimport type { GuardSubject, TypesOf } from './context'\nimport { forbiddenError, RbacContextMissingError, unauthenticatedError } from './errors'\n\ntype MaybePromise<T> = T | Promise<T>\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/** The call a guard runs in, as `onUnauthenticated` / `onForbidden` and `resolve` get it. */\nexport interface GuardCallOptions {\n /** The procedure's context (after the middlewares that ran before the guard). */\n ctx: any\n /** The procedure's path, such as `post.byId`. */\n path: string\n type: TRPCProcedureType\n}\n\n/**\n * What `onUnauthenticated` / `onForbidden` get: the call, plus the subject the guard checked (`null` in\n * `onUnauthenticated`). `R` is that subject's type: `SubjectRbac` with the names of `T` in `createGuards<T>()`.\n */\nexport interface GuardHandlerOptions<R = SubjectRbac> extends GuardCallOptions {\n rbac: R | null\n}\n\n/**\n * Returns the error to throw (or throws it), e.g. a `TRPCError` with another code. Anything that is not a\n * `TRPCError` reaches the client as an `INTERNAL_SERVER_ERROR`.\n */\nexport type GuardHandler<R = SubjectRbac> = (opts: GuardHandlerOptions<R>, context: GuardContext) => MaybePromise<Error>\n\nexport interface GuardHandlers<R = SubjectRbac> {\n /** Called when there is no subject (`ctx.rbac` is `null`). Default: a `TRPCError` `UNAUTHORIZED`. */\n onUnauthenticated?: GuardHandler<R> | undefined\n /** Called when the subject lacks access. Default: a `TRPCError` `FORBIDDEN`. */\n onForbidden?: GuardHandler<R> | undefined\n /**\n * Include the required roles/permissions in the default error (`required` in its body).\n * Default: `false` (like spatie's `display_permission_in_exception`).\n */\n exposeRequirements?: boolean | undefined\n}\n\n/**\n * Reads the subject of a call, instead of `ctx.rbac`: `({ ctx }) => (ctx.user ? rbac.for(ctx.user) : null)`.\n * Return `null` / `undefined` for guests.\n */\nexport type RbacResolver<R = SubjectRbac> = (opts: GuardCallOptions) => MaybePromise<R | null | undefined>\n\n/** The options of `createGuards()`: the shared handlers, plus a `resolve` that replaces `ctx.rbac`. */\nexport interface CreateGuardsOptions<R = SubjectRbac> extends GuardHandlers<R> {\n /**\n * Reads the subject of each call. Default: `ctx.rbac`, as `createRbacContext()` sets it. With `resolve`, the\n * procedures don't need `rbac` in their context. It runs once per guard and call.\n */\n resolve?: RbacResolver<R> | undefined\n}\n\n/**\n * The options every guard takes: the handlers plus `guard`.\n *\n * `guard` is per guard only (like spatie's `role:admin,api`), not a `createGuards()` default: the subject's guard\n * comes from `createRbacContext()` (or `resolve`). With per-guard names, tell the types which guard the subjects\n * have with `createGuards<AppRbac, 'api'>()`.\n */\nexport interface RouteGuardOptions<R = SubjectRbac> extends GuardHandlers<R> {\n /**\n * Check in this guard instead of the subject's (`subject.withScope({ guard })`), like spatie's\n * `role:admin,api`. Default: the guard of the subject.\n */\n guard?: string | undefined\n}\n\nexport interface PermissionGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean | undefined\n}\n\nexport interface RoleGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean | undefined\n}\n\nexport type RoleOrPermissionGuardOptions<R = SubjectRbac> = RouteGuardOptions<R>\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = RequirementNames\n\n/**\n * The context a guard needs: `ctx.rbac`, a `SubjectRbac` or `null` (see `createRbacContext()`). A procedure\n * whose context has no `rbac` can't `.use()` the guard (unless `createGuards()` got a `resolve`).\n */\nexport interface RbacProcedureContext {\n rbac: SubjectRbac<any, any> | null\n}\n\n/**\n * The middleware a guard returns, for `t.procedure.use(...)`. After it, `ctx.rbac` is `R`: the subject, never\n * `null`. `C` is the context it needs: {@link RbacProcedureContext} by default.\n */\nexport type RbacMiddleware<R = SubjectRbac, C = RbacProcedureContext> = MiddlewareFunction<\n C,\n any,\n any,\n { rbac: R },\n any\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 * The middleware narrows `ctx.rbac` to `R`, and needs the context `C`.\n */\nexport type Guard<N extends string, O, R = SubjectRbac, C = RbacProcedureContext> = <\n const A extends readonly (GuardNames | O)[],\n>(\n ...args: A & RequirementArgs<A, N, O>\n) => RbacMiddleware<R, C>\n\n/**\n * The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). After them,\n * `ctx.rbac` is a `SubjectRbac` with the names of `T`.\n */\nexport interface Guards<T extends RbacTypeConfig = DefaultRbacTypes, C = RbacProcedureContext> {\n requirePermission: Guard<PermissionName<T>, PermissionGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\n requireRole: Guard<RoleName<T>, RoleGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\n requireRoleOrPermission: Guard<\n PermissionName<T> | RoleName<T>,\n RoleOrPermissionGuardOptions<GuardSubject<T>>,\n GuardSubject<T>,\n C\n >\n canAny: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\n canAll: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\n}\n\n/**\n * A guard of `createGuards<T, G>()` when `T` has per-guard names (`RbacTypeConfig['guards']`): like\n * {@link Guard}, but the names are those of the guard the call checks in, its `{ guard }` option or else `G`\n * (the guard of the subject). `requirePermission('orders.read', { guard: 'api' })` takes the `api` names.\n */\nexport type ScopedGuard<T extends RbacTypeConfig, G extends string, K extends GuardKind, O, C = RbacProcedureContext> = <\n const A extends readonly (GuardNames | O)[],\n>(\n ...args: A & GuardRequirementArgs<A, T, K, G, O>\n) => RbacMiddleware<GuardSubject<T, G>, C>\n\n/**\n * The guards returned by `createGuards<T, G>()` when `T` has per-guard names: names follow the guard each call\n * checks in (see {@link ScopedGuard}), and `ctx.rbac` is in guard `G` after them.\n */\nexport interface ScopedGuards<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>, C = RbacProcedureContext> {\n requirePermission: ScopedGuard<T, G, 'permission', PermissionGuardOptions<GuardSubject<T, G>>, C>\n requireRole: ScopedGuard<T, G, 'role', RoleGuardOptions<GuardSubject<T, G>>, C>\n requireRoleOrPermission: ScopedGuard<T, G, 'role_or_permission', RoleOrPermissionGuardOptions<GuardSubject<T, G>>, C>\n canAny: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>\n canAll: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>\n}\n\n/**\n * What `createGuards<T, G>()` returns: {@link Guards} for a config without per-guard names, and\n * {@link ScopedGuards} for one with `guards`.\n */\nexport type GuardsFor<\n T extends RbacTypeConfig = DefaultRbacTypes,\n G extends string = DefaultGuardName<T>,\n C = RbacProcedureContext,\n> = T extends { guards: object } ? ScopedGuards<T, G, C> : Guards<T, C>\n\n// ------------------------------------------------------------------------------------------ runtime\n\n/** The untyped middleware the guards build; the public types above are only its face. */\ntype AnyMiddleware = (opts: GuardCallOptions & { next: (opts: { ctx: object }) => Promise<unknown> }) => Promise<unknown>\n\nconst fromContext: RbacResolver = ({ ctx }) => {\n const rbac = (ctx as { rbac?: SubjectRbac | null } | undefined)?.rbac\n if (rbac === undefined) throw new RbacContextMissingError()\n return rbac\n}\n\nconst defaultUnauthenticated: GuardHandler = () => unauthenticatedError()\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (_opts, context) =>\n forbiddenError(context.kind, expose ? context.requirements : undefined)\n\nfunction createGuard(\n requirement: RbacRequirement,\n handlers: GuardHandlers,\n guard: string | undefined,\n resolve: RbacResolver,\n): AnyMiddleware {\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 (opts) => {\n const call: GuardCallOptions = { ctx: opts.ctx, path: opts.path, type: opts.type }\n const rbac = (await resolve(call)) ?? null\n if (rbac === null) throw await onUnauthenticated({ ...call, rbac }, context)\n if (await satisfiesRequirement(guard === undefined ? rbac : rbac.withScope({ guard }), requirement)) {\n return opts.next({ ctx: { rbac } })\n }\n throw await onForbidden({ ...call, rbac }, 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 * Builds the guards with shared options: handlers (e.g. an `onForbidden` that throws `NOT_FOUND`), and a `resolve`\n * that reads the subject of a call instead of `ctx.rbac`.\n *\n * Pass the same type argument as `createRbac<AppRbac>()` (or `typeof rbac`) to check names at compile time:\n * `const { requirePermission } = createGuards<AppRbac>()`. After a guard, `ctx.rbac` has the same names and is\n * never `null`.\n *\n * With per-guard names (`RbacTypeConfig['guards']`), `G` is the guard of the subjects these guards check (the\n * `guard` of `createRbacContext()`; default: the default guard): `createGuards<AppRbac, 'api'>()`. Names are\n * checked in that guard, or in a procedure's `{ guard }`. It is a type only; the subject's guard still decides\n * at runtime.\n */\nexport function createGuards<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>,\n>(\n options: CreateGuardsOptions<GuardSubject<T, G>> & { resolve: RbacResolver<GuardSubject<T, G>> },\n): GuardsFor<TypesOf<T>, G, any>\nexport function createGuards<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>,\n>(defaults?: GuardHandlers<GuardSubject<T, G>>): GuardsFor<TypesOf<T>, G>\nexport function createGuards(options: CreateGuardsOptions = {}): GuardsFor {\n const { resolve = fromContext, ...shared } = options\n\n /**\n * Requires permissions, like spatie's `permission:` middleware.\n *\n * - `requirePermission('edit articles')`\n * - `requirePermission('edit articles|delete articles')` — any of them\n * - `requirePermission('edit articles', 'publish articles')` — all of them\n * - `requirePermission('a', 'b', { any: true })` — any of them\n */\n function requirePermission(...args: readonly (GuardNames | PermissionGuardOptions)[]): AnyMiddleware {\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\n return createGuard(permissionRequirement(names, options), withDefaults(shared, options), options.guard, resolve)\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)[]): AnyMiddleware {\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\n return createGuard(roleRequirement(names, options), withDefaults(shared, options), options.guard, resolve)\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)[]): AnyMiddleware {\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\n return createGuard(roleOrPermissionRequirement(names), withDefaults(shared, options), options.guard, resolve)\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 | RouteGuardOptions)[]): AnyMiddleware {\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(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 | RouteGuardOptions)[]): AnyMiddleware {\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(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 unknown as GuardsFor\n}\n\nconst defaultGuards: Guards = createGuards()\n\n// Spelled out, so the declarations keep these types (`Guard<string, PermissionGuardOptions>`, ...).\nexport const requirePermission: Guard<string, PermissionGuardOptions> = defaultGuards.requirePermission\nexport const requireRole: Guard<string, RoleGuardOptions> = defaultGuards.requireRole\nexport const requireRoleOrPermission: Guard<string, RouteGuardOptions> = defaultGuards.requireRoleOrPermission\nexport const canAny: Guard<string, RouteGuardOptions> = defaultGuards.canAny\nexport const canAll: Guard<string, RouteGuardOptions> = defaultGuards.canAll\n"]}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context.ts","../src/errors.ts","../src/guards.ts"],"names":["requirePermission","options","requireRole","requireRoleOrPermission","canAny","canAll"],"mappings":";;;;AAmFO,SAAS,kBAKd,OAAA,EAC0C;AAC1C,EAAA,MAAM,EAAE,UAAA,EAAY,IAAA,EAAK,GAAI,OAAA;AAC7B,EAAA,MAAM,QAA4B,OAAA,CAAQ,KAAA;AAE1C,EAAA,MAAM,OAAO,OAAA,CAAQ,IAAA;AAErB,E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\n SubjectRbac,\r\n TeamId,\r\n} from '@anievo-id/rbac-evolution'\r\n\r\ntype MaybePromise<T> = T | Promise<T>\r\n\r\n/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */\r\nexport type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never\r\n\r\n/**\r\n * The subject the guards of `createGuards<T, G>()` work with: a `SubjectRbac` with the names of `T` (of guard `G`\r\n * with per-guard names), or an untyped `SubjectRbac` without `T`.\r\n */\r\nexport type GuardSubject<\r\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\r\n G extends string = DefaultGuardName<TypesOf<T>>,\r\n> = SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>>\r\n\r\n/**\r\n * The part of the tRPC context this package reads and writes: `ctx.rbac`, a `SubjectRbac` for the current subject\r\n * or `null` for guests. Spread it into what `createContext` returns (see `createRbacContext()`), or type your\r\n * context with it: `type Context = RbacContext<typeof rbac> & { user: User | null }`.\r\n *\r\n * `T` (a names type like `AppRbac`, or `typeof rbac`) types the names `ctx.rbac` accepts; without it, any name.\r\n * With per-guard names, `G` is the guard of the subject: the default guard's names by default.\r\n */\r\nexport type RbacContext<\r\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\r\n G extends string = DefaultGuardName<TypesOf<T>>,\r\n> = {\r\n /** Roles & permissions of the current subject. `null` for guests. */\r\n rbac: GuardSubject<T, G> | null\r\n}\r\n\r\nexport interface RbacContextOptions<\r\n I = unknown,\r\n T extends RbacTypeConfig = DefaultRbacTypes,\r\n G extends string = DefaultGuardName<T>,\r\n> {\r\n /** The RBAC engine created with `createRbac(...)`. Its typed names flow into `ctx.rbac`. */\r\n rbac: Rbac<T>\r\n /**\r\n * Resolves the authenticated subject from what you pass to the returned function (your user, the request, the\r\n * `createContext` options, ...). Return `null` / `undefined` for guests.\r\n */\r\n getSubject: (input: I) => MaybePromise<Subject | null | undefined>\r\n /**\r\n * Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. With per-guard names, it must be one\r\n * of the typed guards, and `ctx.rbac` gets its names.\r\n */\r\n guard?: G | undefined\r\n /** Resolves the current team (only when the engine was created with `teams: true`). */\r\n team?: ((input: I) => MaybePromise<TeamId | undefined>) | undefined\r\n}\r\n\r\n/**\r\n * Builds the `rbac` part of your tRPC context: returns a function that resolves the subject from its argument and\r\n * gives `{ rbac }` (a `SubjectRbac`, or `null` for guests). Spread it into what `createContext` returns.\r\n *\r\n * ```ts\r\n * const rbacContext = createRbacContext({\r\n * rbac,\r\n * getSubject: (user: User | null) => (user ? { type: 'user', id: user.id } : null),\r\n * })\r\n *\r\n * export async function createContext({ req }: FetchCreateContextFnOptions) {\r\n * const user = await getUser(req)\r\n * return { user, ...(await rbacContext(user)) }\r\n * }\r\n * ```\r\n *\r\n * With a typed engine (`createRbac<AppRbac>()`), `ctx.rbac` is typed with its names. With per-guard names, the\r\n * `guard` option picks the names of `ctx.rbac`.\r\n */\r\nexport function createRbacContext<\r\n I = unknown,\r\n T extends RbacTypeConfig = DefaultRbacTypes,\r\n G extends string = DefaultGuardName<T>,\r\n>(\r\n options: RbacContextOptions<I, T, G> & (T extends { guards: object } ? GuardOptions<CheckGuard<T, G>> : unknown),\r\n): (input: I) => Promise<RbacContext<T, G>> {\r\n const { getSubject, team } = options\r\n const guard: string | undefined = options.guard\r\n // `T` only narrows the names on `ctx.rbac`; the subject is the same object either way.\r\n const rbac = options.rbac as unknown as Rbac\r\n\r\n return async (input) => {\r\n const subject = await getSubject(input)\r\n let value: SubjectRbac | null = null\r\n if (subject) {\r\n const teamId = team ? await team(input) : undefined\r\n value = rbac.for(subject, {\r\n ...(guard !== undefined && { guard }),\r\n ...(teamId !== undefined && { team: teamId }),\r\n })\r\n }\r\n return { rbac: value } as unknown as RbacContext<T, G>\r\n }\r\n}\r\n","import {\r\n REQUIREMENT_MESSAGES,\r\n type RequirementKind,\r\n UNAUTHENTICATED_MESSAGE,\r\n} from '@anievo-id/rbac-evolution'\r\nimport { TRPCError } from '@trpc/server'\r\n\r\n/**\r\n * Why a guard denied a call: the same body the other integrations send with their 401 / 403 responses\r\n * (`error`, `reason`, `message`, and `required` only with `exposeRequirements: true`).\r\n */\r\nexport type RbacErrorBody =\r\n | { error: 'UNAUTHENTICATED'; message: string }\r\n | { error: 'FORBIDDEN'; reason: RequirementKind; message: string; required?: string[][] }\r\n\r\n/**\r\n * The `cause` of the `TRPCError` a guard throws by default. It carries the {@link RbacErrorBody}, which\r\n * `rbacErrorFormatter` (or `getRbacErrorBody()`) puts where clients can read it.\r\n */\r\nexport class RbacAccessError extends Error {\r\n readonly code = 'RBAC_ACCESS_DENIED'\r\n /** The 401 / 403 body of the other integrations. */\r\n readonly body: RbacErrorBody\r\n /** HTTP-style status: `401` (no subject) or `403` (missing role/permission). */\r\n readonly status: 401 | 403\r\n\r\n constructor(body: RbacErrorBody) {\r\n super(body.message)\r\n this.name = 'RbacAccessError'\r\n this.body = body\r\n this.status = body.error === 'UNAUTHENTICATED' ? 401 : 403\r\n }\r\n}\r\n\r\n/** Thrown when a guard runs without a subject resolver: `ctx.rbac` is `undefined` and `createGuards()` has no `resolve`. */\r\nexport class RbacContextMissingError extends Error {\r\n readonly code = 'RBAC_CONTEXT_MISSING'\r\n\r\n constructor() {\r\n super(\r\n '`ctx.rbac` is not set. Return it from `createContext` (see `createRbacContext()`), or pass `resolve` to `createGuards()`.',\r\n )\r\n this.name = 'RbacContextMissingError'\r\n }\r\n}\r\n\r\n/** The default error for a call without a subject: `TRPCError` `UNAUTHORIZED`. */\r\nexport function unauthenticatedError(): TRPCError {\r\n const body: RbacErrorBody = { error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }\r\n return new TRPCError({ code: 'UNAUTHORIZED', message: body.message, cause: new RbacAccessError(body) })\r\n}\r\n\r\n/** The default error for a subject without access: `TRPCError` `FORBIDDEN`. */\r\nexport function forbiddenError(kind: RequirementKind, requirements?: string[][]): TRPCError {\r\n const body: RbacErrorBody = {\r\n error: 'FORBIDDEN',\r\n reason: kind,\r\n message: REQUIREMENT_MESSAGES[kind],\r\n ...(requirements !== undefined && { required: requirements }),\r\n }\r\n return new TRPCError({ code: 'FORBIDDEN', message: body.message, cause: new RbacAccessError(body) })\r\n}\r\n\r\n/** Duck-typed, so it also works when two copies of this package are installed. */\r\nconst isAccessError = (value: unknown): value is RbacAccessError =>\r\n value instanceof Error &&\r\n (value as { code?: unknown }).code === 'RBAC_ACCESS_DENIED' &&\r\n typeof (value as { body?: unknown }).body === 'object'\r\n\r\n/**\r\n * The {@link RbacErrorBody} of an error thrown by a guard (the `TRPCError`, or its `RbacAccessError` cause), or\r\n * `null` for any other error.\r\n */\r\nexport function getRbacErrorBody(error: unknown): RbacErrorBody | null {\r\n if (isAccessError(error)) return error.body\r\n if (error instanceof Error && isAccessError(error.cause)) return error.cause.body\r\n return null\r\n}\r\n\r\n/**\r\n * An `errorFormatter` that adds the guard's {@link RbacErrorBody} to the error shape as `data.rbac` (`null` for\r\n * other errors), so clients can read `error.data.rbac.reason`:\r\n *\r\n * ```ts\r\n * const t = initTRPC.context<Context>().create({ errorFormatter: rbacErrorFormatter })\r\n * ```\r\n *\r\n * To combine it with your own formatter, call it first and extend what it returns.\r\n */\r\nexport function rbacErrorFormatter<S extends { data: object }>(opts: {\r\n shape: S\r\n error: unknown\r\n}): S & { data: S['data'] & { rbac: RbacErrorBody | null } } {\r\n const { shape, error } = opts\r\n return { ...shape, data: { ...shape.data, rbac: getRbacErrorBody(error) } }\r\n}\r\n","import {\r\n type DefaultGuardName,\r\n type DefaultRbacTypes,\r\n type GuardName,\r\n type GuardRequirementArgs,\r\n type PermissionName,\r\n permissionRequirement,\r\n type Rbac,\r\n type RbacTypeConfig,\r\n type RbacRequirement,\r\n type RequirementKind,\r\n type RequirementArgs,\r\n type RequirementNames,\r\n type RoleName,\r\n roleOrPermissionRequirement,\r\n roleRequirement,\r\n satisfiesRequirement,\r\n splitRequirementArgs,\r\n type SubjectRbac,\r\n} from '@anievo-id/rbac-evolution'\r\nimport type { TRPCProcedureType } from '@trpc/server'\r\n// Type-only. The main entry exports it as `TRPCMiddlewareFunction` in later 11.x releases, but not in 11.0.0;\r\n// this entry has it in every 11.x.\r\nimport type { MiddlewareFunction } from '@trpc/server/unstable-core-do-not-import'\r\nimport type { GuardSubject, TypesOf } from './context'\r\nimport { forbiddenError, RbacContextMissingError, unauthenticatedError } from './errors'\r\n\r\ntype MaybePromise<T> = T | Promise<T>\r\n\r\nexport type GuardKind = RequirementKind\r\n\r\n/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */\r\nexport interface GuardContext {\r\n kind: GuardKind\r\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\r\n requirements: string[][]\r\n}\r\n\r\n/** The call a guard runs in, as `onUnauthenticated` / `onForbidden` and `resolve` get it. */\r\nexport interface GuardCallOptions {\r\n /** The procedure's context (after the middlewares that ran before the guard). */\r\n ctx: any\r\n /** The procedure's path, such as `post.byId`. */\r\n path: string\r\n type: TRPCProcedureType\r\n}\r\n\r\n/**\r\n * What `onUnauthenticated` / `onForbidden` get: the call, plus the subject the guard checked (`null` in\r\n * `onUnauthenticated`). `R` is that subject's type: `SubjectRbac` with the names of `T` in `createGuards<T>()`.\r\n */\r\nexport interface GuardHandlerOptions<R = SubjectRbac> extends GuardCallOptions {\r\n rbac: R | null\r\n}\r\n\r\n/**\r\n * Returns the error to throw (or throws it), e.g. a `TRPCError` with another code. Anything that is not a\r\n * `TRPCError` reaches the client as an `INTERNAL_SERVER_ERROR`.\r\n */\r\nexport type GuardHandler<R = SubjectRbac> = (opts: GuardHandlerOptions<R>, context: GuardContext) => MaybePromise<Error>\r\n\r\nexport interface GuardHandlers<R = SubjectRbac> {\r\n /** Called when there is no subject (`ctx.rbac` is `null`). Default: a `TRPCError` `UNAUTHORIZED`. */\r\n onUnauthenticated?: GuardHandler<R> | undefined\r\n /** Called when the subject lacks access. Default: a `TRPCError` `FORBIDDEN`. */\r\n onForbidden?: GuardHandler<R> | undefined\r\n /**\r\n * Include the required roles/permissions in the default error (`required` in its body).\r\n * Default: `false` (like spatie's `display_permission_in_exception`).\r\n */\r\n exposeRequirements?: boolean | undefined\r\n}\r\n\r\n/**\r\n * Reads the subject of a call, instead of `ctx.rbac`: `({ ctx }) => (ctx.user ? rbac.for(ctx.user) : null)`.\r\n * Return `null` / `undefined` for guests.\r\n */\r\nexport type RbacResolver<R = SubjectRbac> = (opts: GuardCallOptions) => MaybePromise<R | null | undefined>\r\n\r\n/** The options of `createGuards()`: the shared handlers, plus a `resolve` that replaces `ctx.rbac`. */\r\nexport interface CreateGuardsOptions<R = SubjectRbac> extends GuardHandlers<R> {\r\n /**\r\n * Reads the subject of each call. Default: `ctx.rbac`, as `createRbacContext()` sets it. With `resolve`, the\r\n * procedures don't need `rbac` in their context. It runs once per guard and call.\r\n */\r\n resolve?: RbacResolver<R> | undefined\r\n}\r\n\r\n/**\r\n * The options every guard takes: the handlers plus `guard`.\r\n *\r\n * `guard` is per guard only (like spatie's `role:admin,api`), not a `createGuards()` default: the subject's guard\r\n * comes from `createRbacContext()` (or `resolve`). With per-guard names, tell the types which guard the subjects\r\n * have with `createGuards<AppRbac, 'api'>()`.\r\n */\r\nexport interface RouteGuardOptions<R = SubjectRbac> extends GuardHandlers<R> {\r\n /**\r\n * Check in this guard instead of the subject's (`subject.withScope({ guard })`), like spatie's\r\n * `role:admin,api`. Default: the guard of the subject.\r\n */\r\n guard?: string | undefined\r\n}\r\n\r\nexport interface PermissionGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {\r\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\r\n any?: boolean | undefined\r\n}\r\n\r\nexport interface RoleGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {\r\n /** Require ALL of the roles (instead of any). Default: `false`. */\r\n all?: boolean | undefined\r\n}\r\n\r\nexport type RoleOrPermissionGuardOptions<R = SubjectRbac> = RouteGuardOptions<R>\r\n\r\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\r\nexport type GuardNames = RequirementNames\r\n\r\n/**\r\n * The context a guard needs: `ctx.rbac`, a `SubjectRbac` or `null` (see `createRbacContext()`). A procedure\r\n * whose context has no `rbac` can't `.use()` the guard (unless `createGuards()` got a `resolve`).\r\n */\r\nexport interface RbacProcedureContext {\r\n rbac: SubjectRbac<any, any> | null\r\n}\r\n\r\n/**\r\n * The middleware a guard returns, for `t.procedure.use(...)`. After it, `ctx.rbac` is `R`: the subject, never\r\n * `null`. `C` is the context it needs: {@link RbacProcedureContext} by default.\r\n */\r\nexport type RbacMiddleware<R = SubjectRbac, C = RbacProcedureContext> = MiddlewareFunction<\r\n C,\r\n any,\r\n any,\r\n { rbac: R },\r\n any\r\n>\r\n\r\n/**\r\n * A guard typed with the names `N` it accepts and its options `O`: `(...names, options?)`.\r\n * Every name (each part of a `'a|b'` list, each array item) must be one of `N`; with `N = string`, any name is.\r\n * A call without names, or with options that are not the last argument, is a type error.\r\n * The middleware narrows `ctx.rbac` to `R`, and needs the context `C`.\r\n */\r\nexport type Guard<N extends string, O, R = SubjectRbac, C = RbacProcedureContext> = <\r\n const A extends readonly (GuardNames | O)[],\r\n>(\r\n ...args: A & RequirementArgs<A, N, O>\r\n) => RbacMiddleware<R, C>\r\n\r\n/**\r\n * The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). After them,\r\n * `ctx.rbac` is a `SubjectRbac` with the names of `T`.\r\n */\r\nexport interface Guards<T extends RbacTypeConfig = DefaultRbacTypes, C = RbacProcedureContext> {\r\n requirePermission: Guard<PermissionName<T>, PermissionGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\r\n requireRole: Guard<RoleName<T>, RoleGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\r\n requireRoleOrPermission: Guard<\r\n PermissionName<T> | RoleName<T>,\r\n RoleOrPermissionGuardOptions<GuardSubject<T>>,\r\n GuardSubject<T>,\r\n C\r\n >\r\n canAny: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\r\n canAll: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\r\n}\r\n\r\n/**\r\n * A guard of `createGuards<T, G>()` when `T` has per-guard names (`RbacTypeConfig['guards']`): like\r\n * {@link Guard}, but the names are those of the guard the call checks in, its `{ guard }` option or else `G`\r\n * (the guard of the subject). `requirePermission('orders.read', { guard: 'api' })` takes the `api` names.\r\n */\r\nexport type ScopedGuard<T extends RbacTypeConfig, G extends string, K extends GuardKind, O, C = RbacProcedureContext> = <\r\n const A extends readonly (GuardNames | O)[],\r\n>(\r\n ...args: A & GuardRequirementArgs<A, T, K, G, O>\r\n) => RbacMiddleware<GuardSubject<T, G>, C>\r\n\r\n/**\r\n * The guards returned by `createGuards<T, G>()` when `T` has per-guard names: names follow the guard each call\r\n * checks in (see {@link ScopedGuard}), and `ctx.rbac` is in guard `G` after them.\r\n */\r\nexport interface ScopedGuards<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>, C = RbacProcedureContext> {\r\n requirePermission: ScopedGuard<T, G, 'permission', PermissionGuardOptions<GuardSubject<T, G>>, C>\r\n requireRole: ScopedGuard<T, G, 'role', RoleGuardOptions<GuardSubject<T, G>>, C>\r\n requireRoleOrPermission: ScopedGuard<T, G, 'role_or_permission', RoleOrPermissionGuardOptions<GuardSubject<T, G>>, C>\r\n canAny: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>\r\n canAll: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>\r\n}\r\n\r\n/**\r\n * What `createGuards<T, G>()` returns: {@link Guards} for a config without per-guard names, and\r\n * {@link ScopedGuards} for one with `guards`.\r\n */\r\nexport type GuardsFor<\r\n T extends RbacTypeConfig = DefaultRbacTypes,\r\n G extends string = DefaultGuardName<T>,\r\n C = RbacProcedureContext,\r\n> = T extends { guards: object } ? ScopedGuards<T, G, C> : Guards<T, C>\r\n\r\n// ------------------------------------------------------------------------------------------ runtime\r\n\r\n/** The untyped middleware the guards build; the public types above are only its face. */\r\ntype AnyMiddleware = (opts: GuardCallOptions & { next: (opts: { ctx: object }) => Promise<unknown> }) => Promise<unknown>\r\n\r\nconst fromContext: RbacResolver = ({ ctx }) => {\r\n const rbac = (ctx as { rbac?: SubjectRbac | null } | undefined)?.rbac\r\n if (rbac === undefined) throw new RbacContextMissingError()\r\n return rbac\r\n}\r\n\r\nconst defaultUnauthenticated: GuardHandler = () => unauthenticatedError()\r\n\r\nconst defaultForbidden =\r\n (expose: boolean): GuardHandler =>\r\n (_opts, context) =>\r\n forbiddenError(context.kind, expose ? context.requirements : undefined)\r\n\r\nfunction createGuard(\r\n requirement: RbacRequirement,\r\n handlers: GuardHandlers,\r\n guard: string | undefined,\r\n resolve: RbacResolver,\r\n): AnyMiddleware {\r\n const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated\r\n const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false)\r\n const context: GuardContext = { kind: requirement.kind, requirements: requirement.requirements }\r\n\r\n return async (opts) => {\r\n const call: GuardCallOptions = { ctx: opts.ctx, path: opts.path, type: opts.type }\r\n const rbac = (await resolve(call)) ?? null\r\n if (rbac === null) throw await onUnauthenticated({ ...call, rbac }, context)\r\n if (await satisfiesRequirement(guard === undefined ? rbac : rbac.withScope({ guard }), requirement)) {\r\n return opts.next({ ctx: { rbac } })\r\n }\r\n throw await onForbidden({ ...call, rbac }, context)\r\n }\r\n}\r\n\r\n/** `options` over `defaults`, where an option set to `undefined` keeps the default (as if left out). */\r\nfunction withDefaults(defaults: GuardHandlers, options: GuardHandlers): GuardHandlers {\r\n const merged: Record<string, unknown> = { ...defaults }\r\n for (const [key, value] of Object.entries(options)) if (value !== undefined) merged[key] = value\r\n return merged as GuardHandlers\r\n}\r\n\r\n/**\r\n * Builds the guards with shared options: handlers (e.g. an `onForbidden` that throws `NOT_FOUND`), and a `resolve`\r\n * that reads the subject of a call instead of `ctx.rbac`.\r\n *\r\n * Pass the same type argument as `createRbac<AppRbac>()` (or `typeof rbac`) to check names at compile time:\r\n * `const { requirePermission } = createGuards<AppRbac>()`. After a guard, `ctx.rbac` has the same names and is\r\n * never `null`.\r\n *\r\n * With per-guard names (`RbacTypeConfig['guards']`), `G` is the guard of the subjects these guards check (the\r\n * `guard` of `createRbacContext()`; default: the default guard): `createGuards<AppRbac, 'api'>()`. Names are\r\n * checked in that guard, or in a procedure's `{ guard }`. It is a type only; the subject's guard still decides\r\n * at runtime.\r\n */\r\nexport function createGuards<\r\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\r\n G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>,\r\n>(\r\n options: CreateGuardsOptions<GuardSubject<T, G>> & { resolve: RbacResolver<GuardSubject<T, G>> },\r\n): GuardsFor<TypesOf<T>, G, any>\r\nexport function createGuards<\r\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\r\n G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>,\r\n>(defaults?: GuardHandlers<GuardSubject<T, G>>): GuardsFor<TypesOf<T>, G>\r\nexport function createGuards(options: CreateGuardsOptions = {}): GuardsFor {\r\n const { resolve = fromContext, ...shared } = options\r\n\r\n /**\r\n * Requires permissions, like spatie's `permission:` middleware.\r\n *\r\n * - `requirePermission('edit articles')`\r\n * - `requirePermission('edit articles|delete articles')` — any of them\r\n * - `requirePermission('edit articles', 'publish articles')` — all of them\r\n * - `requirePermission('a', 'b', { any: true })` — any of them\r\n */\r\n function requirePermission(...args: readonly (GuardNames | PermissionGuardOptions)[]): AnyMiddleware {\r\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\r\n return createGuard(permissionRequirement(names, options), withDefaults(shared, options), options.guard, resolve)\r\n }\r\n\r\n /**\r\n * Requires roles, like spatie's `role:` middleware.\r\n *\r\n * - `requireRole('admin')`, `requireRole('admin|editor')`, `requireRole('admin', 'editor')` — any of them\r\n * - `requireRole('admin', 'editor', { all: true })` — all of them\r\n */\r\n function requireRole(...args: readonly (GuardNames | RoleGuardOptions)[]): AnyMiddleware {\r\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\r\n return createGuard(roleRequirement(names, options), withDefaults(shared, options), options.guard, resolve)\r\n }\r\n\r\n /**\r\n * Passes when the subject has ANY of the names as a role OR as a permission,\r\n * like spatie's `role_or_permission:` middleware.\r\n *\r\n * - `requireRoleOrPermission('admin|edit articles')`\r\n */\r\n function requireRoleOrPermission(...args: readonly (GuardNames | RoleOrPermissionGuardOptions)[]): AnyMiddleware {\r\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\r\n return createGuard(roleOrPermissionRequirement(names), withDefaults(shared, options), options.guard, resolve)\r\n }\r\n\r\n /**\r\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\r\n *\r\n * - `canAny('edit articles', 'publish articles')`, `canAny(['edit articles', 'publish articles'])`\r\n */\r\n function canAny(...args: readonly (GuardNames | RouteGuardOptions)[]): AnyMiddleware {\r\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(args)\r\n return requirePermission(...names, { ...options, any: true })\r\n }\r\n\r\n /**\r\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\r\n *\r\n * - `canAll('edit articles', 'publish articles')`, `canAll(['edit articles', 'publish|review'])`\r\n */\r\n function canAll(...args: readonly (GuardNames | RouteGuardOptions)[]): AnyMiddleware {\r\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(args)\r\n return requirePermission(...names, { ...options, any: false })\r\n }\r\n\r\n // The untyped functions above take any spread of names (`canAny` passes `...names` on); the typed signature\r\n // is only the public face, so a cast is enough. No runtime change.\r\n return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll } as unknown as GuardsFor\r\n}\r\n\r\nconst defaultGuards: Guards = createGuards()\r\n\r\n// Spelled out, so the declarations keep these types (`Guard<string, PermissionGuardOptions>`, ...).\r\nexport const requirePermission: Guard<string, PermissionGuardOptions> = defaultGuards.requirePermission\r\nexport const requireRole: Guard<string, RoleGuardOptions> = defaultGuards.requireRole\r\nexport const requireRoleOrPermission: Guard<string, RouteGuardOptions> = defaultGuards.requireRoleOrPermission\r\nexport const canAny: Guard<string, RouteGuardOptions> = defaultGuards.canAny\r\nexport const canAll: Guard<string, RouteGuardOptions> = defaultGuards.canAll\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/context.ts","../src/errors.ts","../src/guards.ts"],"names":["requirePermission","options","requireRole","requireRoleOrPermission","canAny","canAll"],"mappings":";;;;AAmFO,SAAS,kBAKd,OAAA,EAC0C;AAC1C,EAAA,MAAM,EAAE,UAAA,EAAY,IAAA,EAAK,GAAI,OAAA;AAC7B,EAAA,MAAM,QAA4B,OAAA,CAAQ,KAAA;AAE1C,EAAA,MAAM,OAAO,OAAA,CAAQ,IAAA;AAErB,EAAA,OAAO,OAAO,KAAA,KAAU;AACtB,IAAA,MAAM,OAAA,GAAU,MAAM,UAAA,CAAW,KAAK,CAAA;AACtC,IAAA,IAAI,KAAA,GAA4B,IAAA;AAChC,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,MAAM,MAAA,GAAS,IAAA,GAAO,MAAM,IAAA,CAAK,KAAK,CAAA,GAAI,MAAA;AAC1C,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;AACA,IAAA,OAAO,EAAE,MAAM,KAAA,EAAM;AAAA,EACvB,CAAA;AACF;ACxFO,IAAM,eAAA,GAAN,cAA8B,K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,EAAE,KAAA,EAAO,OAAA,EAAAJ,QAAAA,EAAQ,GAAI,qBAAwC,IAAI,CAAA;AACvE,IAAA,OAAOD,kBAAAA,CAAkB,GAAG,KAAA,EAAO,EAAE,GAAGC,QAAAA,EAAS,GAAA,EAAK,OAAO,CAAA;AAAA,EAC/D;AAIA,EAAA,OAAO,EAAE,iBAAA,EAAAD,kBAAAA,EAAmB,WAAA,EAAAE,YAAAA,EAAa,yBAAAC,wBAAAA,EAAyB,MAAA,EAAAC,OAAAA,EAAQ,MAAA,EAAAC,OAAAA,EAAO;AACnF;AAEA,IAAM,gBAAwB,YAAA,EAAa;AAGpC,IAAM,oBAA2D,aAAA,CAAc;AAC/E,IAAM,cAA+C,aAAA,CAAc;AACnE,IAAM,0BAA4D,aAAA,CAAc;AAChF,IAAM,SAA2C,aAAA,CAAc;AAC/D,IAAM,SAA2C,aAAA,CAAc","file":"index.js","sourcesContent":["import type {\n CheckGuard,\n DefaultGuardName,\n DefaultRbacTypes,\n GuardOptions,\n Rbac,\n RbacTypeConfig,\n ScopedGuardName,\n Subject,\n SubjectRbac,\n TeamId,\n} from '@anievo-id/rbac-evolution'\n\ntype MaybePromise<T> = T | Promise<T>\n\n/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */\nexport type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never\n\n/**\n * The subject the guards of `createGuards<T, G>()` work with: a `SubjectRbac` with the names of `T` (of guard `G`\n * with per-guard names), or an untyped `SubjectRbac` without `T`.\n */\nexport type GuardSubject<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends string = DefaultGuardName<TypesOf<T>>,\n> = SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>>\n\n/**\n * The part of the tRPC context this package reads and writes: `ctx.rbac`, a `SubjectRbac` for the current subject\n * or `null` for guests. Spread it into what `createContext` returns (see `createRbacContext()`), or type your\n * context with it: `type Context = RbacContext<typeof rbac> & { user: User | null }`.\n *\n * `T` (a names type like `AppRbac`, or `typeof rbac`) types the names `ctx.rbac` accepts; without it, any name.\n * With per-guard names, `G` is the guard of the subject: the default guard's names by default.\n */\nexport type RbacContext<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends string = DefaultGuardName<TypesOf<T>>,\n> = {\n /** Roles & permissions of the current subject. `null` for guests. */\n rbac: GuardSubject<T, G> | null\n}\n\nexport interface RbacContextOptions<\n I = unknown,\n T extends RbacTypeConfig = DefaultRbacTypes,\n G extends string = DefaultGuardName<T>,\n> {\n /** The RBAC engine created with `createRbac(...)`. Its typed names flow into `ctx.rbac`. */\n rbac: Rbac<T>\n /**\n * Resolves the authenticated subject from what you pass to the returned function (your user, the request, the\n * `createContext` options, ...). Return `null` / `undefined` for guests.\n */\n getSubject: (input: I) => MaybePromise<Subject | null | undefined>\n /**\n * Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. With per-guard names, it must be one\n * of the typed guards, and `ctx.rbac` gets its names.\n */\n guard?: G | undefined\n /** Resolves the current team (only when the engine was created with `teams: true`). */\n team?: ((input: I) => MaybePromise<TeamId | undefined>) | undefined\n}\n\n/**\n * Builds the `rbac` part of your tRPC context: returns a function that resolves the subject from its argument and\n * gives `{ rbac }` (a `SubjectRbac`, or `null` for guests). Spread it into what `createContext` returns.\n *\n * ```ts\n * const rbacContext = createRbacContext({\n * rbac,\n * getSubject: (user: User | null) => (user ? { type: 'user', id: user.id } : null),\n * })\n *\n * export async function createContext({ req }: FetchCreateContextFnOptions) {\n * const user = await getUser(req)\n * return { user, ...(await rbacContext(user)) }\n * }\n * ```\n *\n * With a typed engine (`createRbac<AppRbac>()`), `ctx.rbac` is typed with its names. With per-guard names, the\n * `guard` option picks the names of `ctx.rbac`.\n */\nexport function createRbacContext<\n I = unknown,\n T extends RbacTypeConfig = DefaultRbacTypes,\n G extends string = DefaultGuardName<T>,\n>(\n options: RbacContextOptions<I, T, G> & (T extends { guards: object } ? GuardOptions<CheckGuard<T, G>> : unknown),\n): (input: I) => Promise<RbacContext<T, G>> {\n const { getSubject, team } = options\n const guard: string | undefined = options.guard\n // `T` only narrows the names on `ctx.rbac`; the subject is the same object either way.\n const rbac = options.rbac as unknown as Rbac\n\n return async (input) => {\n const subject = await getSubject(input)\n let value: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(input) : undefined\n value = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n return { rbac: value } as unknown as RbacContext<T, G>\n }\n}\n","import {\n REQUIREMENT_MESSAGES,\n type RequirementKind,\n UNAUTHENTICATED_MESSAGE,\n} from '@anievo-id/rbac-evolution'\nimport { TRPCError } from '@trpc/server'\n\n/**\n * Why a guard denied a call: the same body the other integrations send with their 401 / 403 responses\n * (`error`, `reason`, `message`, and `required` only with `exposeRequirements: true`).\n */\nexport type RbacErrorBody =\n | { error: 'UNAUTHENTICATED'; message: string }\n | { error: 'FORBIDDEN'; reason: RequirementKind; message: string; required?: string[][] }\n\n/**\n * The `cause` of the `TRPCError` a guard throws by default. It carries the {@link RbacErrorBody}, which\n * `rbacErrorFormatter` (or `getRbacErrorBody()`) puts where clients can read it.\n */\nexport class RbacAccessError extends Error {\n readonly code = 'RBAC_ACCESS_DENIED'\n /** The 401 / 403 body of the other integrations. */\n readonly body: RbacErrorBody\n /** HTTP-style status: `401` (no subject) or `403` (missing role/permission). */\n readonly status: 401 | 403\n\n constructor(body: RbacErrorBody) {\n super(body.message)\n this.name = 'RbacAccessError'\n this.body = body\n this.status = body.error === 'UNAUTHENTICATED' ? 401 : 403\n }\n}\n\n/** Thrown when a guard runs without a subject resolver: `ctx.rbac` is `undefined` and `createGuards()` has no `resolve`. */\nexport class RbacContextMissingError extends Error {\n readonly code = 'RBAC_CONTEXT_MISSING'\n\n constructor() {\n super(\n '`ctx.rbac` is not set. Return it from `createContext` (see `createRbacContext()`), or pass `resolve` to `createGuards()`.',\n )\n this.name = 'RbacContextMissingError'\n }\n}\n\n/** The default error for a call without a subject: `TRPCError` `UNAUTHORIZED`. */\nexport function unauthenticatedError(): TRPCError {\n const body: RbacErrorBody = { error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE }\n return new TRPCError({ code: 'UNAUTHORIZED', message: body.message, cause: new RbacAccessError(body) })\n}\n\n/** The default error for a subject without access: `TRPCError` `FORBIDDEN`. */\nexport function forbiddenError(kind: RequirementKind, requirements?: string[][]): TRPCError {\n const body: RbacErrorBody = {\n error: 'FORBIDDEN',\n reason: kind,\n message: REQUIREMENT_MESSAGES[kind],\n ...(requirements !== undefined && { required: requirements }),\n }\n return new TRPCError({ code: 'FORBIDDEN', message: body.message, cause: new RbacAccessError(body) })\n}\n\n/** Duck-typed, so it also works when two copies of this package are installed. */\nconst isAccessError = (value: unknown): value is RbacAccessError =>\n value instanceof Error &&\n (value as { code?: unknown }).code === 'RBAC_ACCESS_DENIED' &&\n typeof (value as { body?: unknown }).body === 'object'\n\n/**\n * The {@link RbacErrorBody} of an error thrown by a guard (the `TRPCError`, or its `RbacAccessError` cause), or\n * `null` for any other error.\n */\nexport function getRbacErrorBody(error: unknown): RbacErrorBody | null {\n if (isAccessError(error)) return error.body\n if (error instanceof Error && isAccessError(error.cause)) return error.cause.body\n return null\n}\n\n/**\n * An `errorFormatter` that adds the guard's {@link RbacErrorBody} to the error shape as `data.rbac` (`null` for\n * other errors), so clients can read `error.data.rbac.reason`:\n *\n * ```ts\n * const t = initTRPC.context<Context>().create({ errorFormatter: rbacErrorFormatter })\n * ```\n *\n * To combine it with your own formatter, call it first and extend what it returns.\n */\nexport function rbacErrorFormatter<S extends { data: object }>(opts: {\n shape: S\n error: unknown\n}): S & { data: S['data'] & { rbac: RbacErrorBody | null } } {\n const { shape, error } = opts\n return { ...shape, data: { ...shape.data, rbac: getRbacErrorBody(error) } }\n}\n","import {\n type DefaultGuardName,\n type DefaultRbacTypes,\n type GuardName,\n type GuardRequirementArgs,\n type PermissionName,\n permissionRequirement,\n type Rbac,\n type RbacTypeConfig,\n type RbacRequirement,\n type RequirementKind,\n type RequirementArgs,\n type RequirementNames,\n type RoleName,\n roleOrPermissionRequirement,\n roleRequirement,\n satisfiesRequirement,\n splitRequirementArgs,\n type SubjectRbac,\n} from '@anievo-id/rbac-evolution'\nimport type { TRPCProcedureType } from '@trpc/server'\n// Type-only. The main entry exports it as `TRPCMiddlewareFunction` in later 11.x releases, but not in 11.0.0;\n// this entry has it in every 11.x.\nimport type { MiddlewareFunction } from '@trpc/server/unstable-core-do-not-import'\nimport type { GuardSubject, TypesOf } from './context'\nimport { forbiddenError, RbacContextMissingError, unauthenticatedError } from './errors'\n\ntype MaybePromise<T> = T | Promise<T>\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/** The call a guard runs in, as `onUnauthenticated` / `onForbidden` and `resolve` get it. */\nexport interface GuardCallOptions {\n /** The procedure's context (after the middlewares that ran before the guard). */\n ctx: any\n /** The procedure's path, such as `post.byId`. */\n path: string\n type: TRPCProcedureType\n}\n\n/**\n * What `onUnauthenticated` / `onForbidden` get: the call, plus the subject the guard checked (`null` in\n * `onUnauthenticated`). `R` is that subject's type: `SubjectRbac` with the names of `T` in `createGuards<T>()`.\n */\nexport interface GuardHandlerOptions<R = SubjectRbac> extends GuardCallOptions {\n rbac: R | null\n}\n\n/**\n * Returns the error to throw (or throws it), e.g. a `TRPCError` with another code. Anything that is not a\n * `TRPCError` reaches the client as an `INTERNAL_SERVER_ERROR`.\n */\nexport type GuardHandler<R = SubjectRbac> = (opts: GuardHandlerOptions<R>, context: GuardContext) => MaybePromise<Error>\n\nexport interface GuardHandlers<R = SubjectRbac> {\n /** Called when there is no subject (`ctx.rbac` is `null`). Default: a `TRPCError` `UNAUTHORIZED`. */\n onUnauthenticated?: GuardHandler<R> | undefined\n /** Called when the subject lacks access. Default: a `TRPCError` `FORBIDDEN`. */\n onForbidden?: GuardHandler<R> | undefined\n /**\n * Include the required roles/permissions in the default error (`required` in its body).\n * Default: `false` (like spatie's `display_permission_in_exception`).\n */\n exposeRequirements?: boolean | undefined\n}\n\n/**\n * Reads the subject of a call, instead of `ctx.rbac`: `({ ctx }) => (ctx.user ? rbac.for(ctx.user) : null)`.\n * Return `null` / `undefined` for guests.\n */\nexport type RbacResolver<R = SubjectRbac> = (opts: GuardCallOptions) => MaybePromise<R | null | undefined>\n\n/** The options of `createGuards()`: the shared handlers, plus a `resolve` that replaces `ctx.rbac`. */\nexport interface CreateGuardsOptions<R = SubjectRbac> extends GuardHandlers<R> {\n /**\n * Reads the subject of each call. Default: `ctx.rbac`, as `createRbacContext()` sets it. With `resolve`, the\n * procedures don't need `rbac` in their context. It runs once per guard and call.\n */\n resolve?: RbacResolver<R> | undefined\n}\n\n/**\n * The options every guard takes: the handlers plus `guard`.\n *\n * `guard` is per guard only (like spatie's `role:admin,api`), not a `createGuards()` default: the subject's guard\n * comes from `createRbacContext()` (or `resolve`). With per-guard names, tell the types which guard the subjects\n * have with `createGuards<AppRbac, 'api'>()`.\n */\nexport interface RouteGuardOptions<R = SubjectRbac> extends GuardHandlers<R> {\n /**\n * Check in this guard instead of the subject's (`subject.withScope({ guard })`), like spatie's\n * `role:admin,api`. Default: the guard of the subject.\n */\n guard?: string | undefined\n}\n\nexport interface PermissionGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean | undefined\n}\n\nexport interface RoleGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean | undefined\n}\n\nexport type RoleOrPermissionGuardOptions<R = SubjectRbac> = RouteGuardOptions<R>\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type GuardNames = RequirementNames\n\n/**\n * The context a guard needs: `ctx.rbac`, a `SubjectRbac` or `null` (see `createRbacContext()`). A procedure\n * whose context has no `rbac` can't `.use()` the guard (unless `createGuards()` got a `resolve`).\n */\nexport interface RbacProcedureContext {\n rbac: SubjectRbac<any, any> | null\n}\n\n/**\n * The middleware a guard returns, for `t.procedure.use(...)`. After it, `ctx.rbac` is `R`: the subject, never\n * `null`. `C` is the context it needs: {@link RbacProcedureContext} by default.\n */\nexport type RbacMiddleware<R = SubjectRbac, C = RbacProcedureContext> = MiddlewareFunction<\n C,\n any,\n any,\n { rbac: R },\n any\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 * The middleware narrows `ctx.rbac` to `R`, and needs the context `C`.\n */\nexport type Guard<N extends string, O, R = SubjectRbac, C = RbacProcedureContext> = <\n const A extends readonly (GuardNames | O)[],\n>(\n ...args: A & RequirementArgs<A, N, O>\n) => RbacMiddleware<R, C>\n\n/**\n * The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). After them,\n * `ctx.rbac` is a `SubjectRbac` with the names of `T`.\n */\nexport interface Guards<T extends RbacTypeConfig = DefaultRbacTypes, C = RbacProcedureContext> {\n requirePermission: Guard<PermissionName<T>, PermissionGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\n requireRole: Guard<RoleName<T>, RoleGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\n requireRoleOrPermission: Guard<\n PermissionName<T> | RoleName<T>,\n RoleOrPermissionGuardOptions<GuardSubject<T>>,\n GuardSubject<T>,\n C\n >\n canAny: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\n canAll: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>\n}\n\n/**\n * A guard of `createGuards<T, G>()` when `T` has per-guard names (`RbacTypeConfig['guards']`): like\n * {@link Guard}, but the names are those of the guard the call checks in, its `{ guard }` option or else `G`\n * (the guard of the subject). `requirePermission('orders.read', { guard: 'api' })` takes the `api` names.\n */\nexport type ScopedGuard<T extends RbacTypeConfig, G extends string, K extends GuardKind, O, C = RbacProcedureContext> = <\n const A extends readonly (GuardNames | O)[],\n>(\n ...args: A & GuardRequirementArgs<A, T, K, G, O>\n) => RbacMiddleware<GuardSubject<T, G>, C>\n\n/**\n * The guards returned by `createGuards<T, G>()` when `T` has per-guard names: names follow the guard each call\n * checks in (see {@link ScopedGuard}), and `ctx.rbac` is in guard `G` after them.\n */\nexport interface ScopedGuards<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>, C = RbacProcedureContext> {\n requirePermission: ScopedGuard<T, G, 'permission', PermissionGuardOptions<GuardSubject<T, G>>, C>\n requireRole: ScopedGuard<T, G, 'role', RoleGuardOptions<GuardSubject<T, G>>, C>\n requireRoleOrPermission: ScopedGuard<T, G, 'role_or_permission', RoleOrPermissionGuardOptions<GuardSubject<T, G>>, C>\n canAny: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>\n canAll: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>\n}\n\n/**\n * What `createGuards<T, G>()` returns: {@link Guards} for a config without per-guard names, and\n * {@link ScopedGuards} for one with `guards`.\n */\nexport type GuardsFor<\n T extends RbacTypeConfig = DefaultRbacTypes,\n G extends string = DefaultGuardName<T>,\n C = RbacProcedureContext,\n> = T extends { guards: object } ? ScopedGuards<T, G, C> : Guards<T, C>\n\n// ------------------------------------------------------------------------------------------ runtime\n\n/** The untyped middleware the guards build; the public types above are only its face. */\ntype AnyMiddleware = (opts: GuardCallOptions & { next: (opts: { ctx: object }) => Promise<unknown> }) => Promise<unknown>\n\nconst fromContext: RbacResolver = ({ ctx }) => {\n const rbac = (ctx as { rbac?: SubjectRbac | null } | undefined)?.rbac\n if (rbac === undefined) throw new RbacContextMissingError()\n return rbac\n}\n\nconst defaultUnauthenticated: GuardHandler = () => unauthenticatedError()\n\nconst defaultForbidden =\n (expose: boolean): GuardHandler =>\n (_opts, context) =>\n forbiddenError(context.kind, expose ? context.requirements : undefined)\n\nfunction createGuard(\n requirement: RbacRequirement,\n handlers: GuardHandlers,\n guard: string | undefined,\n resolve: RbacResolver,\n): AnyMiddleware {\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 (opts) => {\n const call: GuardCallOptions = { ctx: opts.ctx, path: opts.path, type: opts.type }\n const rbac = (await resolve(call)) ?? null\n if (rbac === null) throw await onUnauthenticated({ ...call, rbac }, context)\n if (await satisfiesRequirement(guard === undefined ? rbac : rbac.withScope({ guard }), requirement)) {\n return opts.next({ ctx: { rbac } })\n }\n throw await onForbidden({ ...call, rbac }, 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 * Builds the guards with shared options: handlers (e.g. an `onForbidden` that throws `NOT_FOUND`), and a `resolve`\n * that reads the subject of a call instead of `ctx.rbac`.\n *\n * Pass the same type argument as `createRbac<AppRbac>()` (or `typeof rbac`) to check names at compile time:\n * `const { requirePermission } = createGuards<AppRbac>()`. After a guard, `ctx.rbac` has the same names and is\n * never `null`.\n *\n * With per-guard names (`RbacTypeConfig['guards']`), `G` is the guard of the subjects these guards check (the\n * `guard` of `createRbacContext()`; default: the default guard): `createGuards<AppRbac, 'api'>()`. Names are\n * checked in that guard, or in a procedure's `{ guard }`. It is a type only; the subject's guard still decides\n * at runtime.\n */\nexport function createGuards<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>,\n>(\n options: CreateGuardsOptions<GuardSubject<T, G>> & { resolve: RbacResolver<GuardSubject<T, G>> },\n): GuardsFor<TypesOf<T>, G, any>\nexport function createGuards<\n T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes,\n G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>,\n>(defaults?: GuardHandlers<GuardSubject<T, G>>): GuardsFor<TypesOf<T>, G>\nexport function createGuards(options: CreateGuardsOptions = {}): GuardsFor {\n const { resolve = fromContext, ...shared } = options\n\n /**\n * Requires permissions, like spatie's `permission:` middleware.\n *\n * - `requirePermission('edit articles')`\n * - `requirePermission('edit articles|delete articles')` — any of them\n * - `requirePermission('edit articles', 'publish articles')` — all of them\n * - `requirePermission('a', 'b', { any: true })` — any of them\n */\n function requirePermission(...args: readonly (GuardNames | PermissionGuardOptions)[]): AnyMiddleware {\n const { names, options = {} } = splitRequirementArgs<PermissionGuardOptions>(args)\n return createGuard(permissionRequirement(names, options), withDefaults(shared, options), options.guard, resolve)\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)[]): AnyMiddleware {\n const { names, options = {} } = splitRequirementArgs<RoleGuardOptions>(args)\n return createGuard(roleRequirement(names, options), withDefaults(shared, options), options.guard, resolve)\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)[]): AnyMiddleware {\n const { names, options = {} } = splitRequirementArgs<RoleOrPermissionGuardOptions>(args)\n return createGuard(roleOrPermissionRequirement(names), withDefaults(shared, options), options.guard, resolve)\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 | RouteGuardOptions)[]): AnyMiddleware {\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(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 | RouteGuardOptions)[]): AnyMiddleware {\n const { names, options } = splitRequirementArgs<RouteGuardOptions>(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 unknown as GuardsFor\n}\n\nconst defaultGuards: Guards = createGuards()\n\n// Spelled out, so the declarations keep these types (`Guard<string, PermissionGuardOptions>`, ...).\nexport const requirePermission: Guard<string, PermissionGuardOptions> = defaultGuards.requirePermission\nexport const requireRole: Guard<string, RoleGuardOptions> = defaultGuards.requireRole\nexport const requireRoleOrPermission: Guard<string, RouteGuardOptions> = defaultGuards.requireRoleOrPermission\nexport const canAny: Guard<string, RouteGuardOptions> = defaultGuards.canAny\nexport const canAll: Guard<string, RouteGuardOptions> = defaultGuards.canAll\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anievo-id/rbac-evolution-trpc",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"description": "tRPC middleware for rbac-evolution — permission and role guards for procedures, with a narrowed ctx.rbac.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "AniEvo-ID (https://github.com/AniEvo-ID)",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@anievo-id/rbac-evolution": "^1.
|
|
51
|
+
"@anievo-id/rbac-evolution": "^1.6.0"
|
|
52
52
|
},
|
|
53
53
|
"peerDependencies": {
|
|
54
54
|
"@trpc/server": ">=11"
|