@anievo-id/rbac-evolution-trpc 0.0.0-stage → 1.4.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 -0
- package/README.md +53 -3
- package/dist/index.cjs +138 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +276 -0
- package/dist/index.d.ts +276 -0
- package/dist/index.js +126 -0
- package/dist/index.js.map +1 -0
- package/package.json +70 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AniEvo-ID
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
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
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var rbacEvolution = require('@anievo-id/rbac-evolution');
|
|
4
|
+
var server = require('@trpc/server');
|
|
5
|
+
|
|
6
|
+
// src/context.ts
|
|
7
|
+
function createRbacContext(options) {
|
|
8
|
+
const { getSubject, team } = options;
|
|
9
|
+
const guard = options.guard;
|
|
10
|
+
const rbac = options.rbac;
|
|
11
|
+
return async (input) => {
|
|
12
|
+
const subject = await getSubject(input);
|
|
13
|
+
let value = null;
|
|
14
|
+
if (subject) {
|
|
15
|
+
const teamId = team ? await team(input) : void 0;
|
|
16
|
+
value = rbac.for(subject, {
|
|
17
|
+
...guard !== void 0 && { guard },
|
|
18
|
+
...teamId !== void 0 && { team: teamId }
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
return { rbac: value };
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
var RbacAccessError = class extends Error {
|
|
25
|
+
code = "RBAC_ACCESS_DENIED";
|
|
26
|
+
/** The 401 / 403 body of the other integrations. */
|
|
27
|
+
body;
|
|
28
|
+
/** HTTP-style status: `401` (no subject) or `403` (missing role/permission). */
|
|
29
|
+
status;
|
|
30
|
+
constructor(body) {
|
|
31
|
+
super(body.message);
|
|
32
|
+
this.name = "RbacAccessError";
|
|
33
|
+
this.body = body;
|
|
34
|
+
this.status = body.error === "UNAUTHENTICATED" ? 401 : 403;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
var RbacContextMissingError = class extends Error {
|
|
38
|
+
code = "RBAC_CONTEXT_MISSING";
|
|
39
|
+
constructor() {
|
|
40
|
+
super(
|
|
41
|
+
"`ctx.rbac` is not set. Return it from `createContext` (see `createRbacContext()`), or pass `resolve` to `createGuards()`."
|
|
42
|
+
);
|
|
43
|
+
this.name = "RbacContextMissingError";
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
function unauthenticatedError() {
|
|
47
|
+
const body = { error: "UNAUTHENTICATED", message: rbacEvolution.UNAUTHENTICATED_MESSAGE };
|
|
48
|
+
return new server.TRPCError({ code: "UNAUTHORIZED", message: body.message, cause: new RbacAccessError(body) });
|
|
49
|
+
}
|
|
50
|
+
function forbiddenError(kind, requirements) {
|
|
51
|
+
const body = {
|
|
52
|
+
error: "FORBIDDEN",
|
|
53
|
+
reason: kind,
|
|
54
|
+
message: rbacEvolution.REQUIREMENT_MESSAGES[kind],
|
|
55
|
+
...requirements !== void 0 && { required: requirements }
|
|
56
|
+
};
|
|
57
|
+
return new server.TRPCError({ code: "FORBIDDEN", message: body.message, cause: new RbacAccessError(body) });
|
|
58
|
+
}
|
|
59
|
+
var isAccessError = (value) => value instanceof Error && value.code === "RBAC_ACCESS_DENIED" && typeof value.body === "object";
|
|
60
|
+
function getRbacErrorBody(error) {
|
|
61
|
+
if (isAccessError(error)) return error.body;
|
|
62
|
+
if (error instanceof Error && isAccessError(error.cause)) return error.cause.body;
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
function rbacErrorFormatter(opts) {
|
|
66
|
+
const { shape, error } = opts;
|
|
67
|
+
return { ...shape, data: { ...shape.data, rbac: getRbacErrorBody(error) } };
|
|
68
|
+
}
|
|
69
|
+
var fromContext = ({ ctx }) => {
|
|
70
|
+
const rbac = ctx?.rbac;
|
|
71
|
+
if (rbac === void 0) throw new RbacContextMissingError();
|
|
72
|
+
return rbac;
|
|
73
|
+
};
|
|
74
|
+
var defaultUnauthenticated = () => unauthenticatedError();
|
|
75
|
+
var defaultForbidden = (expose) => (_opts, context) => forbiddenError(context.kind, expose ? context.requirements : void 0);
|
|
76
|
+
function createGuard(requirement, handlers, guard, resolve) {
|
|
77
|
+
const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated;
|
|
78
|
+
const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false);
|
|
79
|
+
const context = { kind: requirement.kind, requirements: requirement.requirements };
|
|
80
|
+
return async (opts) => {
|
|
81
|
+
const call = { ctx: opts.ctx, path: opts.path, type: opts.type };
|
|
82
|
+
const rbac = await resolve(call) ?? null;
|
|
83
|
+
if (rbac === null) throw await onUnauthenticated({ ...call, rbac }, context);
|
|
84
|
+
if (await rbacEvolution.satisfiesRequirement(guard === void 0 ? rbac : rbac.withScope({ guard }), requirement)) {
|
|
85
|
+
return opts.next({ ctx: { rbac } });
|
|
86
|
+
}
|
|
87
|
+
throw await onForbidden({ ...call, rbac }, context);
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function withDefaults(defaults, options) {
|
|
91
|
+
const merged = { ...defaults };
|
|
92
|
+
for (const [key, value] of Object.entries(options)) if (value !== void 0) merged[key] = value;
|
|
93
|
+
return merged;
|
|
94
|
+
}
|
|
95
|
+
function createGuards(options = {}) {
|
|
96
|
+
const { resolve = fromContext, ...shared } = options;
|
|
97
|
+
function requirePermission2(...args) {
|
|
98
|
+
const { names, options: options2 = {} } = rbacEvolution.splitRequirementArgs(args);
|
|
99
|
+
return createGuard(rbacEvolution.permissionRequirement(names, options2), withDefaults(shared, options2), options2.guard, resolve);
|
|
100
|
+
}
|
|
101
|
+
function requireRole2(...args) {
|
|
102
|
+
const { names, options: options2 = {} } = rbacEvolution.splitRequirementArgs(args);
|
|
103
|
+
return createGuard(rbacEvolution.roleRequirement(names, options2), withDefaults(shared, options2), options2.guard, resolve);
|
|
104
|
+
}
|
|
105
|
+
function requireRoleOrPermission2(...args) {
|
|
106
|
+
const { names, options: options2 = {} } = rbacEvolution.splitRequirementArgs(args);
|
|
107
|
+
return createGuard(rbacEvolution.roleOrPermissionRequirement(names), withDefaults(shared, options2), options2.guard, resolve);
|
|
108
|
+
}
|
|
109
|
+
function canAny2(...args) {
|
|
110
|
+
const { names, options: options2 } = rbacEvolution.splitRequirementArgs(args);
|
|
111
|
+
return requirePermission2(...names, { ...options2, any: true });
|
|
112
|
+
}
|
|
113
|
+
function canAll2(...args) {
|
|
114
|
+
const { names, options: options2 } = rbacEvolution.splitRequirementArgs(args);
|
|
115
|
+
return requirePermission2(...names, { ...options2, any: false });
|
|
116
|
+
}
|
|
117
|
+
return { requirePermission: requirePermission2, requireRole: requireRole2, requireRoleOrPermission: requireRoleOrPermission2, canAny: canAny2, canAll: canAll2 };
|
|
118
|
+
}
|
|
119
|
+
var defaultGuards = createGuards();
|
|
120
|
+
var requirePermission = defaultGuards.requirePermission;
|
|
121
|
+
var requireRole = defaultGuards.requireRole;
|
|
122
|
+
var requireRoleOrPermission = defaultGuards.requireRoleOrPermission;
|
|
123
|
+
var canAny = defaultGuards.canAny;
|
|
124
|
+
var canAll = defaultGuards.canAll;
|
|
125
|
+
|
|
126
|
+
exports.RbacAccessError = RbacAccessError;
|
|
127
|
+
exports.RbacContextMissingError = RbacContextMissingError;
|
|
128
|
+
exports.canAll = canAll;
|
|
129
|
+
exports.canAny = canAny;
|
|
130
|
+
exports.createGuards = createGuards;
|
|
131
|
+
exports.createRbacContext = createRbacContext;
|
|
132
|
+
exports.getRbacErrorBody = getRbacErrorBody;
|
|
133
|
+
exports.rbacErrorFormatter = rbacErrorFormatter;
|
|
134
|
+
exports.requirePermission = requirePermission;
|
|
135
|
+
exports.requireRole = requireRole;
|
|
136
|
+
exports.requireRoleOrPermission = requireRoleOrPermission;
|
|
137
|
+
//# sourceMappingURL=index.cjs.map
|
|
138
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +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,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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,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"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { RbacTypeConfig, Rbac, DefaultRbacTypes, DefaultGuardName, SubjectRbac, ScopedGuardName, Subject, TeamId, GuardOptions, CheckGuard, RequirementKind, RequirementNames, RequirementArgs, PermissionName, RoleName, GuardRequirementArgs, GuardName } from '@anievo-id/rbac-evolution';
|
|
2
|
+
import { TRPCProcedureType } from '@trpc/server';
|
|
3
|
+
import { MiddlewareFunction } from '@trpc/server/unstable-core-do-not-import';
|
|
4
|
+
|
|
5
|
+
type MaybePromise$1<T> = T | Promise<T>;
|
|
6
|
+
/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */
|
|
7
|
+
type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never;
|
|
8
|
+
/**
|
|
9
|
+
* The subject the guards of `createGuards<T, G>()` work with: a `SubjectRbac` with the names of `T` (of guard `G`
|
|
10
|
+
* with per-guard names), or an untyped `SubjectRbac` without `T`.
|
|
11
|
+
*/
|
|
12
|
+
type GuardSubject<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>> = SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>>;
|
|
13
|
+
/**
|
|
14
|
+
* The part of the tRPC context this package reads and writes: `ctx.rbac`, a `SubjectRbac` for the current subject
|
|
15
|
+
* or `null` for guests. Spread it into what `createContext` returns (see `createRbacContext()`), or type your
|
|
16
|
+
* context with it: `type Context = RbacContext<typeof rbac> & { user: User | null }`.
|
|
17
|
+
*
|
|
18
|
+
* `T` (a names type like `AppRbac`, or `typeof rbac`) types the names `ctx.rbac` accepts; without it, any name.
|
|
19
|
+
* With per-guard names, `G` is the guard of the subject: the default guard's names by default.
|
|
20
|
+
*/
|
|
21
|
+
type RbacContext<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>> = {
|
|
22
|
+
/** Roles & permissions of the current subject. `null` for guests. */
|
|
23
|
+
rbac: GuardSubject<T, G> | null;
|
|
24
|
+
};
|
|
25
|
+
interface RbacContextOptions<I = unknown, T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> {
|
|
26
|
+
/** The RBAC engine created with `createRbac(...)`. Its typed names flow into `ctx.rbac`. */
|
|
27
|
+
rbac: Rbac<T>;
|
|
28
|
+
/**
|
|
29
|
+
* Resolves the authenticated subject from what you pass to the returned function (your user, the request, the
|
|
30
|
+
* `createContext` options, ...). Return `null` / `undefined` for guests.
|
|
31
|
+
*/
|
|
32
|
+
getSubject: (input: I) => MaybePromise$1<Subject | null | undefined>;
|
|
33
|
+
/**
|
|
34
|
+
* Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. With per-guard names, it must be one
|
|
35
|
+
* of the typed guards, and `ctx.rbac` gets its names.
|
|
36
|
+
*/
|
|
37
|
+
guard?: G | undefined;
|
|
38
|
+
/** Resolves the current team (only when the engine was created with `teams: true`). */
|
|
39
|
+
team?: ((input: I) => MaybePromise$1<TeamId | undefined>) | undefined;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Builds the `rbac` part of your tRPC context: returns a function that resolves the subject from its argument and
|
|
43
|
+
* gives `{ rbac }` (a `SubjectRbac`, or `null` for guests). Spread it into what `createContext` returns.
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* const rbacContext = createRbacContext({
|
|
47
|
+
* rbac,
|
|
48
|
+
* getSubject: (user: User | null) => (user ? { type: 'user', id: user.id } : null),
|
|
49
|
+
* })
|
|
50
|
+
*
|
|
51
|
+
* export async function createContext({ req }: FetchCreateContextFnOptions) {
|
|
52
|
+
* const user = await getUser(req)
|
|
53
|
+
* return { user, ...(await rbacContext(user)) }
|
|
54
|
+
* }
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* With a typed engine (`createRbac<AppRbac>()`), `ctx.rbac` is typed with its names. With per-guard names, the
|
|
58
|
+
* `guard` option picks the names of `ctx.rbac`.
|
|
59
|
+
*/
|
|
60
|
+
declare function createRbacContext<I = unknown, T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>>(options: RbacContextOptions<I, T, G> & (T extends {
|
|
61
|
+
guards: object;
|
|
62
|
+
} ? GuardOptions<CheckGuard<T, G>> : unknown)): (input: I) => Promise<RbacContext<T, G>>;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Why a guard denied a call: the same body the other integrations send with their 401 / 403 responses
|
|
66
|
+
* (`error`, `reason`, `message`, and `required` only with `exposeRequirements: true`).
|
|
67
|
+
*/
|
|
68
|
+
type RbacErrorBody = {
|
|
69
|
+
error: 'UNAUTHENTICATED';
|
|
70
|
+
message: string;
|
|
71
|
+
} | {
|
|
72
|
+
error: 'FORBIDDEN';
|
|
73
|
+
reason: RequirementKind;
|
|
74
|
+
message: string;
|
|
75
|
+
required?: string[][];
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* The `cause` of the `TRPCError` a guard throws by default. It carries the {@link RbacErrorBody}, which
|
|
79
|
+
* `rbacErrorFormatter` (or `getRbacErrorBody()`) puts where clients can read it.
|
|
80
|
+
*/
|
|
81
|
+
declare class RbacAccessError extends Error {
|
|
82
|
+
readonly code = "RBAC_ACCESS_DENIED";
|
|
83
|
+
/** The 401 / 403 body of the other integrations. */
|
|
84
|
+
readonly body: RbacErrorBody;
|
|
85
|
+
/** HTTP-style status: `401` (no subject) or `403` (missing role/permission). */
|
|
86
|
+
readonly status: 401 | 403;
|
|
87
|
+
constructor(body: RbacErrorBody);
|
|
88
|
+
}
|
|
89
|
+
/** Thrown when a guard runs without a subject resolver: `ctx.rbac` is `undefined` and `createGuards()` has no `resolve`. */
|
|
90
|
+
declare class RbacContextMissingError extends Error {
|
|
91
|
+
readonly code = "RBAC_CONTEXT_MISSING";
|
|
92
|
+
constructor();
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The {@link RbacErrorBody} of an error thrown by a guard (the `TRPCError`, or its `RbacAccessError` cause), or
|
|
96
|
+
* `null` for any other error.
|
|
97
|
+
*/
|
|
98
|
+
declare function getRbacErrorBody(error: unknown): RbacErrorBody | null;
|
|
99
|
+
/**
|
|
100
|
+
* An `errorFormatter` that adds the guard's {@link RbacErrorBody} to the error shape as `data.rbac` (`null` for
|
|
101
|
+
* other errors), so clients can read `error.data.rbac.reason`:
|
|
102
|
+
*
|
|
103
|
+
* ```ts
|
|
104
|
+
* const t = initTRPC.context<Context>().create({ errorFormatter: rbacErrorFormatter })
|
|
105
|
+
* ```
|
|
106
|
+
*
|
|
107
|
+
* To combine it with your own formatter, call it first and extend what it returns.
|
|
108
|
+
*/
|
|
109
|
+
declare function rbacErrorFormatter<S extends {
|
|
110
|
+
data: object;
|
|
111
|
+
}>(opts: {
|
|
112
|
+
shape: S;
|
|
113
|
+
error: unknown;
|
|
114
|
+
}): S & {
|
|
115
|
+
data: S['data'] & {
|
|
116
|
+
rbac: RbacErrorBody | null;
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
121
|
+
type GuardKind = RequirementKind;
|
|
122
|
+
/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */
|
|
123
|
+
interface GuardContext {
|
|
124
|
+
kind: GuardKind;
|
|
125
|
+
/** Groups of names: every group must pass, a group passes when ANY of its names matches. */
|
|
126
|
+
requirements: string[][];
|
|
127
|
+
}
|
|
128
|
+
/** The call a guard runs in, as `onUnauthenticated` / `onForbidden` and `resolve` get it. */
|
|
129
|
+
interface GuardCallOptions {
|
|
130
|
+
/** The procedure's context (after the middlewares that ran before the guard). */
|
|
131
|
+
ctx: any;
|
|
132
|
+
/** The procedure's path, such as `post.byId`. */
|
|
133
|
+
path: string;
|
|
134
|
+
type: TRPCProcedureType;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* What `onUnauthenticated` / `onForbidden` get: the call, plus the subject the guard checked (`null` in
|
|
138
|
+
* `onUnauthenticated`). `R` is that subject's type: `SubjectRbac` with the names of `T` in `createGuards<T>()`.
|
|
139
|
+
*/
|
|
140
|
+
interface GuardHandlerOptions<R = SubjectRbac> extends GuardCallOptions {
|
|
141
|
+
rbac: R | null;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Returns the error to throw (or throws it), e.g. a `TRPCError` with another code. Anything that is not a
|
|
145
|
+
* `TRPCError` reaches the client as an `INTERNAL_SERVER_ERROR`.
|
|
146
|
+
*/
|
|
147
|
+
type GuardHandler<R = SubjectRbac> = (opts: GuardHandlerOptions<R>, context: GuardContext) => MaybePromise<Error>;
|
|
148
|
+
interface GuardHandlers<R = SubjectRbac> {
|
|
149
|
+
/** Called when there is no subject (`ctx.rbac` is `null`). Default: a `TRPCError` `UNAUTHORIZED`. */
|
|
150
|
+
onUnauthenticated?: GuardHandler<R> | undefined;
|
|
151
|
+
/** Called when the subject lacks access. Default: a `TRPCError` `FORBIDDEN`. */
|
|
152
|
+
onForbidden?: GuardHandler<R> | undefined;
|
|
153
|
+
/**
|
|
154
|
+
* Include the required roles/permissions in the default error (`required` in its body).
|
|
155
|
+
* Default: `false` (like spatie's `display_permission_in_exception`).
|
|
156
|
+
*/
|
|
157
|
+
exposeRequirements?: boolean | undefined;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Reads the subject of a call, instead of `ctx.rbac`: `({ ctx }) => (ctx.user ? rbac.for(ctx.user) : null)`.
|
|
161
|
+
* Return `null` / `undefined` for guests.
|
|
162
|
+
*/
|
|
163
|
+
type RbacResolver<R = SubjectRbac> = (opts: GuardCallOptions) => MaybePromise<R | null | undefined>;
|
|
164
|
+
/** The options of `createGuards()`: the shared handlers, plus a `resolve` that replaces `ctx.rbac`. */
|
|
165
|
+
interface CreateGuardsOptions<R = SubjectRbac> extends GuardHandlers<R> {
|
|
166
|
+
/**
|
|
167
|
+
* Reads the subject of each call. Default: `ctx.rbac`, as `createRbacContext()` sets it. With `resolve`, the
|
|
168
|
+
* procedures don't need `rbac` in their context. It runs once per guard and call.
|
|
169
|
+
*/
|
|
170
|
+
resolve?: RbacResolver<R> | undefined;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* The options every guard takes: the handlers plus `guard`.
|
|
174
|
+
*
|
|
175
|
+
* `guard` is per guard only (like spatie's `role:admin,api`), not a `createGuards()` default: the subject's guard
|
|
176
|
+
* comes from `createRbacContext()` (or `resolve`). With per-guard names, tell the types which guard the subjects
|
|
177
|
+
* have with `createGuards<AppRbac, 'api'>()`.
|
|
178
|
+
*/
|
|
179
|
+
interface RouteGuardOptions<R = SubjectRbac> extends GuardHandlers<R> {
|
|
180
|
+
/**
|
|
181
|
+
* Check in this guard instead of the subject's (`subject.withScope({ guard })`), like spatie's
|
|
182
|
+
* `role:admin,api`. Default: the guard of the subject.
|
|
183
|
+
*/
|
|
184
|
+
guard?: string | undefined;
|
|
185
|
+
}
|
|
186
|
+
interface PermissionGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {
|
|
187
|
+
/** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */
|
|
188
|
+
any?: boolean | undefined;
|
|
189
|
+
}
|
|
190
|
+
interface RoleGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {
|
|
191
|
+
/** Require ALL of the roles (instead of any). Default: `false`. */
|
|
192
|
+
all?: boolean | undefined;
|
|
193
|
+
}
|
|
194
|
+
type RoleOrPermissionGuardOptions<R = SubjectRbac> = RouteGuardOptions<R>;
|
|
195
|
+
/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
|
|
196
|
+
type GuardNames = RequirementNames;
|
|
197
|
+
/**
|
|
198
|
+
* The context a guard needs: `ctx.rbac`, a `SubjectRbac` or `null` (see `createRbacContext()`). A procedure
|
|
199
|
+
* whose context has no `rbac` can't `.use()` the guard (unless `createGuards()` got a `resolve`).
|
|
200
|
+
*/
|
|
201
|
+
interface RbacProcedureContext {
|
|
202
|
+
rbac: SubjectRbac<any, any> | null;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* The middleware a guard returns, for `t.procedure.use(...)`. After it, `ctx.rbac` is `R`: the subject, never
|
|
206
|
+
* `null`. `C` is the context it needs: {@link RbacProcedureContext} by default.
|
|
207
|
+
*/
|
|
208
|
+
type RbacMiddleware<R = SubjectRbac, C = RbacProcedureContext> = MiddlewareFunction<C, any, any, {
|
|
209
|
+
rbac: R;
|
|
210
|
+
}, any>;
|
|
211
|
+
/**
|
|
212
|
+
* A guard typed with the names `N` it accepts and its options `O`: `(...names, options?)`.
|
|
213
|
+
* Every name (each part of a `'a|b'` list, each array item) must be one of `N`; with `N = string`, any name is.
|
|
214
|
+
* A call without names, or with options that are not the last argument, is a type error.
|
|
215
|
+
* The middleware narrows `ctx.rbac` to `R`, and needs the context `C`.
|
|
216
|
+
*/
|
|
217
|
+
type Guard<N extends string, O, R = SubjectRbac, C = RbacProcedureContext> = <const A extends readonly (GuardNames | O)[]>(...args: A & RequirementArgs<A, N, O>) => RbacMiddleware<R, C>;
|
|
218
|
+
/**
|
|
219
|
+
* The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). After them,
|
|
220
|
+
* `ctx.rbac` is a `SubjectRbac` with the names of `T`.
|
|
221
|
+
*/
|
|
222
|
+
interface Guards<T extends RbacTypeConfig = DefaultRbacTypes, C = RbacProcedureContext> {
|
|
223
|
+
requirePermission: Guard<PermissionName<T>, PermissionGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>;
|
|
224
|
+
requireRole: Guard<RoleName<T>, RoleGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>;
|
|
225
|
+
requireRoleOrPermission: Guard<PermissionName<T> | RoleName<T>, RoleOrPermissionGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>;
|
|
226
|
+
canAny: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>;
|
|
227
|
+
canAll: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* A guard of `createGuards<T, G>()` when `T` has per-guard names (`RbacTypeConfig['guards']`): like
|
|
231
|
+
* {@link Guard}, but the names are those of the guard the call checks in, its `{ guard }` option or else `G`
|
|
232
|
+
* (the guard of the subject). `requirePermission('orders.read', { guard: 'api' })` takes the `api` names.
|
|
233
|
+
*/
|
|
234
|
+
type ScopedGuard<T extends RbacTypeConfig, G extends string, K extends GuardKind, O, C = RbacProcedureContext> = <const A extends readonly (GuardNames | O)[]>(...args: A & GuardRequirementArgs<A, T, K, G, O>) => RbacMiddleware<GuardSubject<T, G>, C>;
|
|
235
|
+
/**
|
|
236
|
+
* The guards returned by `createGuards<T, G>()` when `T` has per-guard names: names follow the guard each call
|
|
237
|
+
* checks in (see {@link ScopedGuard}), and `ctx.rbac` is in guard `G` after them.
|
|
238
|
+
*/
|
|
239
|
+
interface ScopedGuards<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>, C = RbacProcedureContext> {
|
|
240
|
+
requirePermission: ScopedGuard<T, G, 'permission', PermissionGuardOptions<GuardSubject<T, G>>, C>;
|
|
241
|
+
requireRole: ScopedGuard<T, G, 'role', RoleGuardOptions<GuardSubject<T, G>>, C>;
|
|
242
|
+
requireRoleOrPermission: ScopedGuard<T, G, 'role_or_permission', RoleOrPermissionGuardOptions<GuardSubject<T, G>>, C>;
|
|
243
|
+
canAny: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>;
|
|
244
|
+
canAll: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* What `createGuards<T, G>()` returns: {@link Guards} for a config without per-guard names, and
|
|
248
|
+
* {@link ScopedGuards} for one with `guards`.
|
|
249
|
+
*/
|
|
250
|
+
type GuardsFor<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>, C = RbacProcedureContext> = T extends {
|
|
251
|
+
guards: object;
|
|
252
|
+
} ? ScopedGuards<T, G, C> : Guards<T, C>;
|
|
253
|
+
/**
|
|
254
|
+
* Builds the guards with shared options: handlers (e.g. an `onForbidden` that throws `NOT_FOUND`), and a `resolve`
|
|
255
|
+
* that reads the subject of a call instead of `ctx.rbac`.
|
|
256
|
+
*
|
|
257
|
+
* Pass the same type argument as `createRbac<AppRbac>()` (or `typeof rbac`) to check names at compile time:
|
|
258
|
+
* `const { requirePermission } = createGuards<AppRbac>()`. After a guard, `ctx.rbac` has the same names and is
|
|
259
|
+
* never `null`.
|
|
260
|
+
*
|
|
261
|
+
* With per-guard names (`RbacTypeConfig['guards']`), `G` is the guard of the subjects these guards check (the
|
|
262
|
+
* `guard` of `createRbacContext()`; default: the default guard): `createGuards<AppRbac, 'api'>()`. Names are
|
|
263
|
+
* checked in that guard, or in a procedure's `{ guard }`. It is a type only; the subject's guard still decides
|
|
264
|
+
* at runtime.
|
|
265
|
+
*/
|
|
266
|
+
declare function createGuards<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>>(options: CreateGuardsOptions<GuardSubject<T, G>> & {
|
|
267
|
+
resolve: RbacResolver<GuardSubject<T, G>>;
|
|
268
|
+
}): GuardsFor<TypesOf<T>, G, any>;
|
|
269
|
+
declare function createGuards<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>>(defaults?: GuardHandlers<GuardSubject<T, G>>): GuardsFor<TypesOf<T>, G>;
|
|
270
|
+
declare const requirePermission: Guard<string, PermissionGuardOptions>;
|
|
271
|
+
declare const requireRole: Guard<string, RoleGuardOptions>;
|
|
272
|
+
declare const requireRoleOrPermission: Guard<string, RouteGuardOptions>;
|
|
273
|
+
declare const canAny: Guard<string, RouteGuardOptions>;
|
|
274
|
+
declare const canAll: Guard<string, RouteGuardOptions>;
|
|
275
|
+
|
|
276
|
+
export { type CreateGuardsOptions, type Guard, type GuardCallOptions, type GuardContext, type GuardHandler, type GuardHandlerOptions, type GuardHandlers, type GuardKind, type GuardNames, type GuardSubject, type Guards, type GuardsFor, type PermissionGuardOptions, RbacAccessError, type RbacContext, RbacContextMissingError, type RbacContextOptions, type RbacErrorBody, type RbacMiddleware, type RbacProcedureContext, type RbacResolver, type RoleGuardOptions, type RoleOrPermissionGuardOptions, type RouteGuardOptions, type ScopedGuard, type ScopedGuards, type TypesOf, canAll, canAny, createGuards, createRbacContext, getRbacErrorBody, rbacErrorFormatter, requirePermission, requireRole, requireRoleOrPermission };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { RbacTypeConfig, Rbac, DefaultRbacTypes, DefaultGuardName, SubjectRbac, ScopedGuardName, Subject, TeamId, GuardOptions, CheckGuard, RequirementKind, RequirementNames, RequirementArgs, PermissionName, RoleName, GuardRequirementArgs, GuardName } from '@anievo-id/rbac-evolution';
|
|
2
|
+
import { TRPCProcedureType } from '@trpc/server';
|
|
3
|
+
import { MiddlewareFunction } from '@trpc/server/unstable-core-do-not-import';
|
|
4
|
+
|
|
5
|
+
type MaybePromise$1<T> = T | Promise<T>;
|
|
6
|
+
/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine. */
|
|
7
|
+
type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never;
|
|
8
|
+
/**
|
|
9
|
+
* The subject the guards of `createGuards<T, G>()` work with: a `SubjectRbac` with the names of `T` (of guard `G`
|
|
10
|
+
* with per-guard names), or an untyped `SubjectRbac` without `T`.
|
|
11
|
+
*/
|
|
12
|
+
type GuardSubject<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>> = SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>>;
|
|
13
|
+
/**
|
|
14
|
+
* The part of the tRPC context this package reads and writes: `ctx.rbac`, a `SubjectRbac` for the current subject
|
|
15
|
+
* or `null` for guests. Spread it into what `createContext` returns (see `createRbacContext()`), or type your
|
|
16
|
+
* context with it: `type Context = RbacContext<typeof rbac> & { user: User | null }`.
|
|
17
|
+
*
|
|
18
|
+
* `T` (a names type like `AppRbac`, or `typeof rbac`) types the names `ctx.rbac` accepts; without it, any name.
|
|
19
|
+
* With per-guard names, `G` is the guard of the subject: the default guard's names by default.
|
|
20
|
+
*/
|
|
21
|
+
type RbacContext<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>> = {
|
|
22
|
+
/** Roles & permissions of the current subject. `null` for guests. */
|
|
23
|
+
rbac: GuardSubject<T, G> | null;
|
|
24
|
+
};
|
|
25
|
+
interface RbacContextOptions<I = unknown, T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> {
|
|
26
|
+
/** The RBAC engine created with `createRbac(...)`. Its typed names flow into `ctx.rbac`. */
|
|
27
|
+
rbac: Rbac<T>;
|
|
28
|
+
/**
|
|
29
|
+
* Resolves the authenticated subject from what you pass to the returned function (your user, the request, the
|
|
30
|
+
* `createContext` options, ...). Return `null` / `undefined` for guests.
|
|
31
|
+
*/
|
|
32
|
+
getSubject: (input: I) => MaybePromise$1<Subject | null | undefined>;
|
|
33
|
+
/**
|
|
34
|
+
* Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. With per-guard names, it must be one
|
|
35
|
+
* of the typed guards, and `ctx.rbac` gets its names.
|
|
36
|
+
*/
|
|
37
|
+
guard?: G | undefined;
|
|
38
|
+
/** Resolves the current team (only when the engine was created with `teams: true`). */
|
|
39
|
+
team?: ((input: I) => MaybePromise$1<TeamId | undefined>) | undefined;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Builds the `rbac` part of your tRPC context: returns a function that resolves the subject from its argument and
|
|
43
|
+
* gives `{ rbac }` (a `SubjectRbac`, or `null` for guests). Spread it into what `createContext` returns.
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* const rbacContext = createRbacContext({
|
|
47
|
+
* rbac,
|
|
48
|
+
* getSubject: (user: User | null) => (user ? { type: 'user', id: user.id } : null),
|
|
49
|
+
* })
|
|
50
|
+
*
|
|
51
|
+
* export async function createContext({ req }: FetchCreateContextFnOptions) {
|
|
52
|
+
* const user = await getUser(req)
|
|
53
|
+
* return { user, ...(await rbacContext(user)) }
|
|
54
|
+
* }
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* With a typed engine (`createRbac<AppRbac>()`), `ctx.rbac` is typed with its names. With per-guard names, the
|
|
58
|
+
* `guard` option picks the names of `ctx.rbac`.
|
|
59
|
+
*/
|
|
60
|
+
declare function createRbacContext<I = unknown, T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>>(options: RbacContextOptions<I, T, G> & (T extends {
|
|
61
|
+
guards: object;
|
|
62
|
+
} ? GuardOptions<CheckGuard<T, G>> : unknown)): (input: I) => Promise<RbacContext<T, G>>;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Why a guard denied a call: the same body the other integrations send with their 401 / 403 responses
|
|
66
|
+
* (`error`, `reason`, `message`, and `required` only with `exposeRequirements: true`).
|
|
67
|
+
*/
|
|
68
|
+
type RbacErrorBody = {
|
|
69
|
+
error: 'UNAUTHENTICATED';
|
|
70
|
+
message: string;
|
|
71
|
+
} | {
|
|
72
|
+
error: 'FORBIDDEN';
|
|
73
|
+
reason: RequirementKind;
|
|
74
|
+
message: string;
|
|
75
|
+
required?: string[][];
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* The `cause` of the `TRPCError` a guard throws by default. It carries the {@link RbacErrorBody}, which
|
|
79
|
+
* `rbacErrorFormatter` (or `getRbacErrorBody()`) puts where clients can read it.
|
|
80
|
+
*/
|
|
81
|
+
declare class RbacAccessError extends Error {
|
|
82
|
+
readonly code = "RBAC_ACCESS_DENIED";
|
|
83
|
+
/** The 401 / 403 body of the other integrations. */
|
|
84
|
+
readonly body: RbacErrorBody;
|
|
85
|
+
/** HTTP-style status: `401` (no subject) or `403` (missing role/permission). */
|
|
86
|
+
readonly status: 401 | 403;
|
|
87
|
+
constructor(body: RbacErrorBody);
|
|
88
|
+
}
|
|
89
|
+
/** Thrown when a guard runs without a subject resolver: `ctx.rbac` is `undefined` and `createGuards()` has no `resolve`. */
|
|
90
|
+
declare class RbacContextMissingError extends Error {
|
|
91
|
+
readonly code = "RBAC_CONTEXT_MISSING";
|
|
92
|
+
constructor();
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The {@link RbacErrorBody} of an error thrown by a guard (the `TRPCError`, or its `RbacAccessError` cause), or
|
|
96
|
+
* `null` for any other error.
|
|
97
|
+
*/
|
|
98
|
+
declare function getRbacErrorBody(error: unknown): RbacErrorBody | null;
|
|
99
|
+
/**
|
|
100
|
+
* An `errorFormatter` that adds the guard's {@link RbacErrorBody} to the error shape as `data.rbac` (`null` for
|
|
101
|
+
* other errors), so clients can read `error.data.rbac.reason`:
|
|
102
|
+
*
|
|
103
|
+
* ```ts
|
|
104
|
+
* const t = initTRPC.context<Context>().create({ errorFormatter: rbacErrorFormatter })
|
|
105
|
+
* ```
|
|
106
|
+
*
|
|
107
|
+
* To combine it with your own formatter, call it first and extend what it returns.
|
|
108
|
+
*/
|
|
109
|
+
declare function rbacErrorFormatter<S extends {
|
|
110
|
+
data: object;
|
|
111
|
+
}>(opts: {
|
|
112
|
+
shape: S;
|
|
113
|
+
error: unknown;
|
|
114
|
+
}): S & {
|
|
115
|
+
data: S['data'] & {
|
|
116
|
+
rbac: RbacErrorBody | null;
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
121
|
+
type GuardKind = RequirementKind;
|
|
122
|
+
/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */
|
|
123
|
+
interface GuardContext {
|
|
124
|
+
kind: GuardKind;
|
|
125
|
+
/** Groups of names: every group must pass, a group passes when ANY of its names matches. */
|
|
126
|
+
requirements: string[][];
|
|
127
|
+
}
|
|
128
|
+
/** The call a guard runs in, as `onUnauthenticated` / `onForbidden` and `resolve` get it. */
|
|
129
|
+
interface GuardCallOptions {
|
|
130
|
+
/** The procedure's context (after the middlewares that ran before the guard). */
|
|
131
|
+
ctx: any;
|
|
132
|
+
/** The procedure's path, such as `post.byId`. */
|
|
133
|
+
path: string;
|
|
134
|
+
type: TRPCProcedureType;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* What `onUnauthenticated` / `onForbidden` get: the call, plus the subject the guard checked (`null` in
|
|
138
|
+
* `onUnauthenticated`). `R` is that subject's type: `SubjectRbac` with the names of `T` in `createGuards<T>()`.
|
|
139
|
+
*/
|
|
140
|
+
interface GuardHandlerOptions<R = SubjectRbac> extends GuardCallOptions {
|
|
141
|
+
rbac: R | null;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Returns the error to throw (or throws it), e.g. a `TRPCError` with another code. Anything that is not a
|
|
145
|
+
* `TRPCError` reaches the client as an `INTERNAL_SERVER_ERROR`.
|
|
146
|
+
*/
|
|
147
|
+
type GuardHandler<R = SubjectRbac> = (opts: GuardHandlerOptions<R>, context: GuardContext) => MaybePromise<Error>;
|
|
148
|
+
interface GuardHandlers<R = SubjectRbac> {
|
|
149
|
+
/** Called when there is no subject (`ctx.rbac` is `null`). Default: a `TRPCError` `UNAUTHORIZED`. */
|
|
150
|
+
onUnauthenticated?: GuardHandler<R> | undefined;
|
|
151
|
+
/** Called when the subject lacks access. Default: a `TRPCError` `FORBIDDEN`. */
|
|
152
|
+
onForbidden?: GuardHandler<R> | undefined;
|
|
153
|
+
/**
|
|
154
|
+
* Include the required roles/permissions in the default error (`required` in its body).
|
|
155
|
+
* Default: `false` (like spatie's `display_permission_in_exception`).
|
|
156
|
+
*/
|
|
157
|
+
exposeRequirements?: boolean | undefined;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Reads the subject of a call, instead of `ctx.rbac`: `({ ctx }) => (ctx.user ? rbac.for(ctx.user) : null)`.
|
|
161
|
+
* Return `null` / `undefined` for guests.
|
|
162
|
+
*/
|
|
163
|
+
type RbacResolver<R = SubjectRbac> = (opts: GuardCallOptions) => MaybePromise<R | null | undefined>;
|
|
164
|
+
/** The options of `createGuards()`: the shared handlers, plus a `resolve` that replaces `ctx.rbac`. */
|
|
165
|
+
interface CreateGuardsOptions<R = SubjectRbac> extends GuardHandlers<R> {
|
|
166
|
+
/**
|
|
167
|
+
* Reads the subject of each call. Default: `ctx.rbac`, as `createRbacContext()` sets it. With `resolve`, the
|
|
168
|
+
* procedures don't need `rbac` in their context. It runs once per guard and call.
|
|
169
|
+
*/
|
|
170
|
+
resolve?: RbacResolver<R> | undefined;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* The options every guard takes: the handlers plus `guard`.
|
|
174
|
+
*
|
|
175
|
+
* `guard` is per guard only (like spatie's `role:admin,api`), not a `createGuards()` default: the subject's guard
|
|
176
|
+
* comes from `createRbacContext()` (or `resolve`). With per-guard names, tell the types which guard the subjects
|
|
177
|
+
* have with `createGuards<AppRbac, 'api'>()`.
|
|
178
|
+
*/
|
|
179
|
+
interface RouteGuardOptions<R = SubjectRbac> extends GuardHandlers<R> {
|
|
180
|
+
/**
|
|
181
|
+
* Check in this guard instead of the subject's (`subject.withScope({ guard })`), like spatie's
|
|
182
|
+
* `role:admin,api`. Default: the guard of the subject.
|
|
183
|
+
*/
|
|
184
|
+
guard?: string | undefined;
|
|
185
|
+
}
|
|
186
|
+
interface PermissionGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {
|
|
187
|
+
/** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */
|
|
188
|
+
any?: boolean | undefined;
|
|
189
|
+
}
|
|
190
|
+
interface RoleGuardOptions<R = SubjectRbac> extends RouteGuardOptions<R> {
|
|
191
|
+
/** Require ALL of the roles (instead of any). Default: `false`. */
|
|
192
|
+
all?: boolean | undefined;
|
|
193
|
+
}
|
|
194
|
+
type RoleOrPermissionGuardOptions<R = SubjectRbac> = RouteGuardOptions<R>;
|
|
195
|
+
/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
|
|
196
|
+
type GuardNames = RequirementNames;
|
|
197
|
+
/**
|
|
198
|
+
* The context a guard needs: `ctx.rbac`, a `SubjectRbac` or `null` (see `createRbacContext()`). A procedure
|
|
199
|
+
* whose context has no `rbac` can't `.use()` the guard (unless `createGuards()` got a `resolve`).
|
|
200
|
+
*/
|
|
201
|
+
interface RbacProcedureContext {
|
|
202
|
+
rbac: SubjectRbac<any, any> | null;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* The middleware a guard returns, for `t.procedure.use(...)`. After it, `ctx.rbac` is `R`: the subject, never
|
|
206
|
+
* `null`. `C` is the context it needs: {@link RbacProcedureContext} by default.
|
|
207
|
+
*/
|
|
208
|
+
type RbacMiddleware<R = SubjectRbac, C = RbacProcedureContext> = MiddlewareFunction<C, any, any, {
|
|
209
|
+
rbac: R;
|
|
210
|
+
}, any>;
|
|
211
|
+
/**
|
|
212
|
+
* A guard typed with the names `N` it accepts and its options `O`: `(...names, options?)`.
|
|
213
|
+
* Every name (each part of a `'a|b'` list, each array item) must be one of `N`; with `N = string`, any name is.
|
|
214
|
+
* A call without names, or with options that are not the last argument, is a type error.
|
|
215
|
+
* The middleware narrows `ctx.rbac` to `R`, and needs the context `C`.
|
|
216
|
+
*/
|
|
217
|
+
type Guard<N extends string, O, R = SubjectRbac, C = RbacProcedureContext> = <const A extends readonly (GuardNames | O)[]>(...args: A & RequirementArgs<A, N, O>) => RbacMiddleware<R, C>;
|
|
218
|
+
/**
|
|
219
|
+
* The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). After them,
|
|
220
|
+
* `ctx.rbac` is a `SubjectRbac` with the names of `T`.
|
|
221
|
+
*/
|
|
222
|
+
interface Guards<T extends RbacTypeConfig = DefaultRbacTypes, C = RbacProcedureContext> {
|
|
223
|
+
requirePermission: Guard<PermissionName<T>, PermissionGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>;
|
|
224
|
+
requireRole: Guard<RoleName<T>, RoleGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>;
|
|
225
|
+
requireRoleOrPermission: Guard<PermissionName<T> | RoleName<T>, RoleOrPermissionGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>;
|
|
226
|
+
canAny: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>;
|
|
227
|
+
canAll: Guard<PermissionName<T>, RouteGuardOptions<GuardSubject<T>>, GuardSubject<T>, C>;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* A guard of `createGuards<T, G>()` when `T` has per-guard names (`RbacTypeConfig['guards']`): like
|
|
231
|
+
* {@link Guard}, but the names are those of the guard the call checks in, its `{ guard }` option or else `G`
|
|
232
|
+
* (the guard of the subject). `requirePermission('orders.read', { guard: 'api' })` takes the `api` names.
|
|
233
|
+
*/
|
|
234
|
+
type ScopedGuard<T extends RbacTypeConfig, G extends string, K extends GuardKind, O, C = RbacProcedureContext> = <const A extends readonly (GuardNames | O)[]>(...args: A & GuardRequirementArgs<A, T, K, G, O>) => RbacMiddleware<GuardSubject<T, G>, C>;
|
|
235
|
+
/**
|
|
236
|
+
* The guards returned by `createGuards<T, G>()` when `T` has per-guard names: names follow the guard each call
|
|
237
|
+
* checks in (see {@link ScopedGuard}), and `ctx.rbac` is in guard `G` after them.
|
|
238
|
+
*/
|
|
239
|
+
interface ScopedGuards<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>, C = RbacProcedureContext> {
|
|
240
|
+
requirePermission: ScopedGuard<T, G, 'permission', PermissionGuardOptions<GuardSubject<T, G>>, C>;
|
|
241
|
+
requireRole: ScopedGuard<T, G, 'role', RoleGuardOptions<GuardSubject<T, G>>, C>;
|
|
242
|
+
requireRoleOrPermission: ScopedGuard<T, G, 'role_or_permission', RoleOrPermissionGuardOptions<GuardSubject<T, G>>, C>;
|
|
243
|
+
canAny: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>;
|
|
244
|
+
canAll: ScopedGuard<T, G, 'permission', RouteGuardOptions<GuardSubject<T, G>>, C>;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* What `createGuards<T, G>()` returns: {@link Guards} for a config without per-guard names, and
|
|
248
|
+
* {@link ScopedGuards} for one with `guards`.
|
|
249
|
+
*/
|
|
250
|
+
type GuardsFor<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>, C = RbacProcedureContext> = T extends {
|
|
251
|
+
guards: object;
|
|
252
|
+
} ? ScopedGuards<T, G, C> : Guards<T, C>;
|
|
253
|
+
/**
|
|
254
|
+
* Builds the guards with shared options: handlers (e.g. an `onForbidden` that throws `NOT_FOUND`), and a `resolve`
|
|
255
|
+
* that reads the subject of a call instead of `ctx.rbac`.
|
|
256
|
+
*
|
|
257
|
+
* Pass the same type argument as `createRbac<AppRbac>()` (or `typeof rbac`) to check names at compile time:
|
|
258
|
+
* `const { requirePermission } = createGuards<AppRbac>()`. After a guard, `ctx.rbac` has the same names and is
|
|
259
|
+
* never `null`.
|
|
260
|
+
*
|
|
261
|
+
* With per-guard names (`RbacTypeConfig['guards']`), `G` is the guard of the subjects these guards check (the
|
|
262
|
+
* `guard` of `createRbacContext()`; default: the default guard): `createGuards<AppRbac, 'api'>()`. Names are
|
|
263
|
+
* checked in that guard, or in a procedure's `{ guard }`. It is a type only; the subject's guard still decides
|
|
264
|
+
* at runtime.
|
|
265
|
+
*/
|
|
266
|
+
declare function createGuards<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>>(options: CreateGuardsOptions<GuardSubject<T, G>> & {
|
|
267
|
+
resolve: RbacResolver<GuardSubject<T, G>>;
|
|
268
|
+
}): GuardsFor<TypesOf<T>, G, any>;
|
|
269
|
+
declare function createGuards<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>>(defaults?: GuardHandlers<GuardSubject<T, G>>): GuardsFor<TypesOf<T>, G>;
|
|
270
|
+
declare const requirePermission: Guard<string, PermissionGuardOptions>;
|
|
271
|
+
declare const requireRole: Guard<string, RoleGuardOptions>;
|
|
272
|
+
declare const requireRoleOrPermission: Guard<string, RouteGuardOptions>;
|
|
273
|
+
declare const canAny: Guard<string, RouteGuardOptions>;
|
|
274
|
+
declare const canAll: Guard<string, RouteGuardOptions>;
|
|
275
|
+
|
|
276
|
+
export { type CreateGuardsOptions, type Guard, type GuardCallOptions, type GuardContext, type GuardHandler, type GuardHandlerOptions, type GuardHandlers, type GuardKind, type GuardNames, type GuardSubject, type Guards, type GuardsFor, type PermissionGuardOptions, RbacAccessError, type RbacContext, RbacContextMissingError, type RbacContextOptions, type RbacErrorBody, type RbacMiddleware, type RbacProcedureContext, type RbacResolver, type RoleGuardOptions, type RoleOrPermissionGuardOptions, type RouteGuardOptions, type ScopedGuard, type ScopedGuards, type TypesOf, canAll, canAny, createGuards, createRbacContext, getRbacErrorBody, rbacErrorFormatter, requirePermission, requireRole, requireRoleOrPermission };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { splitRequirementArgs, roleOrPermissionRequirement, roleRequirement, permissionRequirement, satisfiesRequirement, UNAUTHENTICATED_MESSAGE, REQUIREMENT_MESSAGES } from '@anievo-id/rbac-evolution';
|
|
2
|
+
import { TRPCError } from '@trpc/server';
|
|
3
|
+
|
|
4
|
+
// src/context.ts
|
|
5
|
+
function createRbacContext(options) {
|
|
6
|
+
const { getSubject, team } = options;
|
|
7
|
+
const guard = options.guard;
|
|
8
|
+
const rbac = options.rbac;
|
|
9
|
+
return async (input) => {
|
|
10
|
+
const subject = await getSubject(input);
|
|
11
|
+
let value = null;
|
|
12
|
+
if (subject) {
|
|
13
|
+
const teamId = team ? await team(input) : void 0;
|
|
14
|
+
value = rbac.for(subject, {
|
|
15
|
+
...guard !== void 0 && { guard },
|
|
16
|
+
...teamId !== void 0 && { team: teamId }
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
return { rbac: value };
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
var RbacAccessError = class extends Error {
|
|
23
|
+
code = "RBAC_ACCESS_DENIED";
|
|
24
|
+
/** The 401 / 403 body of the other integrations. */
|
|
25
|
+
body;
|
|
26
|
+
/** HTTP-style status: `401` (no subject) or `403` (missing role/permission). */
|
|
27
|
+
status;
|
|
28
|
+
constructor(body) {
|
|
29
|
+
super(body.message);
|
|
30
|
+
this.name = "RbacAccessError";
|
|
31
|
+
this.body = body;
|
|
32
|
+
this.status = body.error === "UNAUTHENTICATED" ? 401 : 403;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
var RbacContextMissingError = class extends Error {
|
|
36
|
+
code = "RBAC_CONTEXT_MISSING";
|
|
37
|
+
constructor() {
|
|
38
|
+
super(
|
|
39
|
+
"`ctx.rbac` is not set. Return it from `createContext` (see `createRbacContext()`), or pass `resolve` to `createGuards()`."
|
|
40
|
+
);
|
|
41
|
+
this.name = "RbacContextMissingError";
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
function unauthenticatedError() {
|
|
45
|
+
const body = { error: "UNAUTHENTICATED", message: UNAUTHENTICATED_MESSAGE };
|
|
46
|
+
return new TRPCError({ code: "UNAUTHORIZED", message: body.message, cause: new RbacAccessError(body) });
|
|
47
|
+
}
|
|
48
|
+
function forbiddenError(kind, requirements) {
|
|
49
|
+
const body = {
|
|
50
|
+
error: "FORBIDDEN",
|
|
51
|
+
reason: kind,
|
|
52
|
+
message: REQUIREMENT_MESSAGES[kind],
|
|
53
|
+
...requirements !== void 0 && { required: requirements }
|
|
54
|
+
};
|
|
55
|
+
return new TRPCError({ code: "FORBIDDEN", message: body.message, cause: new RbacAccessError(body) });
|
|
56
|
+
}
|
|
57
|
+
var isAccessError = (value) => value instanceof Error && value.code === "RBAC_ACCESS_DENIED" && typeof value.body === "object";
|
|
58
|
+
function getRbacErrorBody(error) {
|
|
59
|
+
if (isAccessError(error)) return error.body;
|
|
60
|
+
if (error instanceof Error && isAccessError(error.cause)) return error.cause.body;
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
function rbacErrorFormatter(opts) {
|
|
64
|
+
const { shape, error } = opts;
|
|
65
|
+
return { ...shape, data: { ...shape.data, rbac: getRbacErrorBody(error) } };
|
|
66
|
+
}
|
|
67
|
+
var fromContext = ({ ctx }) => {
|
|
68
|
+
const rbac = ctx?.rbac;
|
|
69
|
+
if (rbac === void 0) throw new RbacContextMissingError();
|
|
70
|
+
return rbac;
|
|
71
|
+
};
|
|
72
|
+
var defaultUnauthenticated = () => unauthenticatedError();
|
|
73
|
+
var defaultForbidden = (expose) => (_opts, context) => forbiddenError(context.kind, expose ? context.requirements : void 0);
|
|
74
|
+
function createGuard(requirement, handlers, guard, resolve) {
|
|
75
|
+
const onUnauthenticated = handlers.onUnauthenticated ?? defaultUnauthenticated;
|
|
76
|
+
const onForbidden = handlers.onForbidden ?? defaultForbidden(handlers.exposeRequirements ?? false);
|
|
77
|
+
const context = { kind: requirement.kind, requirements: requirement.requirements };
|
|
78
|
+
return async (opts) => {
|
|
79
|
+
const call = { ctx: opts.ctx, path: opts.path, type: opts.type };
|
|
80
|
+
const rbac = await resolve(call) ?? null;
|
|
81
|
+
if (rbac === null) throw await onUnauthenticated({ ...call, rbac }, context);
|
|
82
|
+
if (await satisfiesRequirement(guard === void 0 ? rbac : rbac.withScope({ guard }), requirement)) {
|
|
83
|
+
return opts.next({ ctx: { rbac } });
|
|
84
|
+
}
|
|
85
|
+
throw await onForbidden({ ...call, rbac }, context);
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function withDefaults(defaults, options) {
|
|
89
|
+
const merged = { ...defaults };
|
|
90
|
+
for (const [key, value] of Object.entries(options)) if (value !== void 0) merged[key] = value;
|
|
91
|
+
return merged;
|
|
92
|
+
}
|
|
93
|
+
function createGuards(options = {}) {
|
|
94
|
+
const { resolve = fromContext, ...shared } = options;
|
|
95
|
+
function requirePermission2(...args) {
|
|
96
|
+
const { names, options: options2 = {} } = splitRequirementArgs(args);
|
|
97
|
+
return createGuard(permissionRequirement(names, options2), withDefaults(shared, options2), options2.guard, resolve);
|
|
98
|
+
}
|
|
99
|
+
function requireRole2(...args) {
|
|
100
|
+
const { names, options: options2 = {} } = splitRequirementArgs(args);
|
|
101
|
+
return createGuard(roleRequirement(names, options2), withDefaults(shared, options2), options2.guard, resolve);
|
|
102
|
+
}
|
|
103
|
+
function requireRoleOrPermission2(...args) {
|
|
104
|
+
const { names, options: options2 = {} } = splitRequirementArgs(args);
|
|
105
|
+
return createGuard(roleOrPermissionRequirement(names), withDefaults(shared, options2), options2.guard, resolve);
|
|
106
|
+
}
|
|
107
|
+
function canAny2(...args) {
|
|
108
|
+
const { names, options: options2 } = splitRequirementArgs(args);
|
|
109
|
+
return requirePermission2(...names, { ...options2, any: true });
|
|
110
|
+
}
|
|
111
|
+
function canAll2(...args) {
|
|
112
|
+
const { names, options: options2 } = splitRequirementArgs(args);
|
|
113
|
+
return requirePermission2(...names, { ...options2, any: false });
|
|
114
|
+
}
|
|
115
|
+
return { requirePermission: requirePermission2, requireRole: requireRole2, requireRoleOrPermission: requireRoleOrPermission2, canAny: canAny2, canAll: canAll2 };
|
|
116
|
+
}
|
|
117
|
+
var defaultGuards = createGuards();
|
|
118
|
+
var requirePermission = defaultGuards.requirePermission;
|
|
119
|
+
var requireRole = defaultGuards.requireRole;
|
|
120
|
+
var requireRoleOrPermission = defaultGuards.requireRoleOrPermission;
|
|
121
|
+
var canAny = defaultGuards.canAny;
|
|
122
|
+
var canAll = defaultGuards.canAll;
|
|
123
|
+
|
|
124
|
+
export { RbacAccessError, RbacContextMissingError, canAll, canAny, createGuards, createRbacContext, getRbacErrorBody, rbacErrorFormatter, requirePermission, requireRole, requireRoleOrPermission };
|
|
125
|
+
//# sourceMappingURL=index.js.map
|
|
126
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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,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,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ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AAE,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 {\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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,73 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anievo-id/rbac-evolution-trpc",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.4.0",
|
|
4
|
+
"description": "tRPC middleware for rbac-evolution — permission and role guards for procedures, with a narrowed ctx.rbac.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "AniEvo-ID (https://github.com/AniEvo-ID)",
|
|
7
|
+
"homepage": "https://creation.anievo.id/rbac-evolution/frameworks/trpc",
|
|
8
|
+
"bugs": {
|
|
9
|
+
"url": "https://github.com/AniEvo-ID/rbac-evolution/issues"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/AniEvo-ID/rbac-evolution.git",
|
|
15
|
+
"directory": "packages/trpc"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"rbac",
|
|
19
|
+
"permissions",
|
|
20
|
+
"roles",
|
|
21
|
+
"authorization",
|
|
22
|
+
"trpc",
|
|
23
|
+
"middleware",
|
|
24
|
+
"procedure",
|
|
25
|
+
"nextjs"
|
|
26
|
+
],
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"main": "./dist/index.cjs",
|
|
29
|
+
"module": "./dist/index.js",
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"import": {
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"default": "./dist/index.js"
|
|
36
|
+
},
|
|
37
|
+
"require": {
|
|
38
|
+
"types": "./dist/index.d.cts",
|
|
39
|
+
"default": "./dist/index.cjs"
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"./package.json": "./package.json"
|
|
43
|
+
},
|
|
44
|
+
"files": [
|
|
45
|
+
"dist"
|
|
46
|
+
],
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"@anievo-id/rbac-evolution": "^1.4.0"
|
|
52
|
+
},
|
|
53
|
+
"peerDependencies": {
|
|
54
|
+
"@trpc/server": ">=11"
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@trpc/client": "~11.26.0",
|
|
58
|
+
"@trpc/server": "~11.26.0",
|
|
59
|
+
"tsup": "^8.3.0",
|
|
60
|
+
"typescript": "^5.7.0",
|
|
61
|
+
"vitest": "^2.1.0"
|
|
62
|
+
},
|
|
63
|
+
"engines": {
|
|
64
|
+
"node": ">=20"
|
|
65
|
+
},
|
|
66
|
+
"scripts": {
|
|
67
|
+
"build": "tsup",
|
|
68
|
+
"dev": "tsup --watch",
|
|
69
|
+
"typecheck": "tsc --noEmit",
|
|
70
|
+
"test": "vitest run --passWithNoTests",
|
|
71
|
+
"clean": "rm -rf dist .turbo"
|
|
72
|
+
}
|
|
6
73
|
}
|