@anievo-id/rbac-evolution-next 0.0.0-stage → 0.1.1
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 +233 -2
- package/dist/chunk-QGRA2JHH.js +116 -0
- package/dist/chunk-QGRA2JHH.js.map +1 -0
- package/dist/index.cjs +280 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +99 -0
- package/dist/index.d.ts +99 -0
- package/dist/index.js +159 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware-entry-Bh8jQj1L.d.cts +105 -0
- package/dist/middleware-entry-Bh8jQj1L.d.ts +105 -0
- package/dist/middleware.cjs +121 -0
- package/dist/middleware.cjs.map +1 -0
- package/dist/middleware.d.cts +2 -0
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.js +3 -0
- package/dist/middleware.js.map +1 -0
- package/package.json +82 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var navigation = require('next/navigation');
|
|
4
|
+
var rbacEvolution = require('@anievo-id/rbac-evolution');
|
|
5
|
+
|
|
6
|
+
// src/server.ts
|
|
7
|
+
|
|
8
|
+
// src/errors.ts
|
|
9
|
+
var RbacUnauthorizedError = class extends Error {
|
|
10
|
+
/** `unauthenticated` (no subject) or `unauthorized` (missing role/permission). */
|
|
11
|
+
reason;
|
|
12
|
+
/** HTTP-style status: `401` or `403`. */
|
|
13
|
+
status;
|
|
14
|
+
constructor(reason, message) {
|
|
15
|
+
super(message ?? (reason === "unauthenticated" ? "Unauthenticated." : "This action is unauthorized."));
|
|
16
|
+
this.name = "RbacUnauthorizedError";
|
|
17
|
+
this.reason = reason;
|
|
18
|
+
this.status = reason === "unauthenticated" ? 401 : 403;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// src/server.ts
|
|
23
|
+
function forbiddenMessage(requirement) {
|
|
24
|
+
if (requirement.permission !== void 0) return "User does not have the right permissions.";
|
|
25
|
+
if (requirement.role !== void 0) return "User does not have the right roles.";
|
|
26
|
+
return "User does not have any of the necessary access rights.";
|
|
27
|
+
}
|
|
28
|
+
var EMPTY_SNAPSHOT = { roles: [], permissions: [] };
|
|
29
|
+
function createNextRbac(options) {
|
|
30
|
+
const { rbac } = options;
|
|
31
|
+
async function getSubject() {
|
|
32
|
+
return await options.getSubject() ?? null;
|
|
33
|
+
}
|
|
34
|
+
async function resolveScope(scope = {}) {
|
|
35
|
+
const guard = scope.guard ?? options.guard;
|
|
36
|
+
let team = scope.team;
|
|
37
|
+
if (team === void 0) {
|
|
38
|
+
team = typeof options.team === "function" ? await options.team() : options.team;
|
|
39
|
+
}
|
|
40
|
+
const out = {};
|
|
41
|
+
if (guard !== void 0) out.guard = guard;
|
|
42
|
+
if (team !== void 0 && team !== null) out.team = team;
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
async function forSubject(subject, scope) {
|
|
46
|
+
return rbac.for(subject, await resolveScope(scope));
|
|
47
|
+
}
|
|
48
|
+
async function satisfies(subject, requirement, scope) {
|
|
49
|
+
const s = await forSubject(subject, scope);
|
|
50
|
+
if (requirement.permission !== void 0) return s.canAny(requirement.permission);
|
|
51
|
+
if (requirement.role !== void 0) return s.hasAnyRole(requirement.role);
|
|
52
|
+
const items = requirement.roleOrPermission;
|
|
53
|
+
return await s.hasAnyRole(items) || await s.canAny(items);
|
|
54
|
+
}
|
|
55
|
+
async function authorize(requirement, scope) {
|
|
56
|
+
const subject = await getSubject();
|
|
57
|
+
if (!subject) return { ok: false, reason: "unauthenticated", subject: null };
|
|
58
|
+
if (!await satisfies(subject, requirement, scope)) return { ok: false, reason: "unauthorized", subject };
|
|
59
|
+
return { ok: true, subject };
|
|
60
|
+
}
|
|
61
|
+
function fail(reason, opts) {
|
|
62
|
+
if (reason === "unauthenticated") {
|
|
63
|
+
const handler = opts.onUnauthenticated ?? options.onUnauthenticated;
|
|
64
|
+
if (handler) handler();
|
|
65
|
+
else {
|
|
66
|
+
const loginUrl = opts.loginUrl ?? options.loginUrl;
|
|
67
|
+
if (loginUrl !== void 0) navigation.redirect(loginUrl);
|
|
68
|
+
navigation.notFound();
|
|
69
|
+
}
|
|
70
|
+
} else {
|
|
71
|
+
const handler = opts.onUnauthorized ?? options.onUnauthorized;
|
|
72
|
+
if (handler) handler();
|
|
73
|
+
else navigation.notFound();
|
|
74
|
+
}
|
|
75
|
+
throw new RbacUnauthorizedError(reason);
|
|
76
|
+
}
|
|
77
|
+
async function enforce(requirement, opts = {}) {
|
|
78
|
+
const result = await authorize(requirement, opts);
|
|
79
|
+
if (!result.ok) fail(result.reason, opts);
|
|
80
|
+
return result.subject;
|
|
81
|
+
}
|
|
82
|
+
function guardAction(requirement, action, scope) {
|
|
83
|
+
return async (...args) => {
|
|
84
|
+
const result = await authorize(requirement, scope);
|
|
85
|
+
if (!result.ok) throw new RbacUnauthorizedError(result.reason);
|
|
86
|
+
return action(...args);
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
rbac,
|
|
91
|
+
getSubject,
|
|
92
|
+
authorize,
|
|
93
|
+
/** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */
|
|
94
|
+
async getSnapshot(scope) {
|
|
95
|
+
const subject = await getSubject();
|
|
96
|
+
if (!subject) return { roles: [...EMPTY_SNAPSHOT.roles], permissions: [...EMPTY_SNAPSHOT.permissions] };
|
|
97
|
+
return (await forSubject(subject, scope)).snapshot();
|
|
98
|
+
},
|
|
99
|
+
async can(permission, scope) {
|
|
100
|
+
const subject = await getSubject();
|
|
101
|
+
return subject ? (await forSubject(subject, scope)).can(permission) : false;
|
|
102
|
+
},
|
|
103
|
+
async canAny(permissions, scope) {
|
|
104
|
+
const subject = await getSubject();
|
|
105
|
+
return subject ? (await forSubject(subject, scope)).canAny(permissions) : false;
|
|
106
|
+
},
|
|
107
|
+
async canAll(permissions, scope) {
|
|
108
|
+
const subject = await getSubject();
|
|
109
|
+
return subject ? (await forSubject(subject, scope)).canAll(permissions) : false;
|
|
110
|
+
},
|
|
111
|
+
/** `true` if the user has the role — or ANY of the roles when given an array. */
|
|
112
|
+
async hasRole(role, scope) {
|
|
113
|
+
const subject = await getSubject();
|
|
114
|
+
return subject ? (await forSubject(subject, scope)).hasAnyRole(role) : false;
|
|
115
|
+
},
|
|
116
|
+
async hasAllRoles(roles, scope) {
|
|
117
|
+
const subject = await getSubject();
|
|
118
|
+
return subject ? (await forSubject(subject, scope)).hasAllRoles(roles) : false;
|
|
119
|
+
},
|
|
120
|
+
/**
|
|
121
|
+
* Ensures the user has the permission (or ANY of the permissions). Returns the subject.
|
|
122
|
+
* Guests: `redirect(loginUrl)` or `notFound()`. Missing permission: `notFound()`. Both configurable.
|
|
123
|
+
*/
|
|
124
|
+
requirePermission(permission, opts) {
|
|
125
|
+
return enforce({ permission }, opts);
|
|
126
|
+
},
|
|
127
|
+
/** Ensures the user has the role (or ANY of the roles). Returns the subject. */
|
|
128
|
+
requireRole(role, opts) {
|
|
129
|
+
return enforce({ role }, opts);
|
|
130
|
+
},
|
|
131
|
+
/** Ensures the user has ANY of the given roles or permissions. Returns the subject. */
|
|
132
|
+
requireRoleOrPermission(items, opts) {
|
|
133
|
+
return enforce({ roleOrPermission: items }, opts);
|
|
134
|
+
},
|
|
135
|
+
/** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */
|
|
136
|
+
withPermission(permission, action, scope) {
|
|
137
|
+
return guardAction({ permission }, action, scope);
|
|
138
|
+
},
|
|
139
|
+
/** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */
|
|
140
|
+
withRole(role, action, scope) {
|
|
141
|
+
return guardAction({ role }, action, scope);
|
|
142
|
+
},
|
|
143
|
+
/**
|
|
144
|
+
* Wraps a route handler. Responds `401` (guest) or `403` (missing role/permission) with a JSON body.
|
|
145
|
+
* Mirrors spatie's `permission`, `role` and `role_or_permission` middleware.
|
|
146
|
+
*/
|
|
147
|
+
withRbac(handler, options2) {
|
|
148
|
+
const { guard, team, ...requirement } = options2;
|
|
149
|
+
const scope = {};
|
|
150
|
+
if (guard !== void 0) scope.guard = guard;
|
|
151
|
+
if (team !== void 0) scope.team = team;
|
|
152
|
+
return async (...args) => {
|
|
153
|
+
const result = await authorize(requirement, scope);
|
|
154
|
+
if (result.ok) return handler(...args);
|
|
155
|
+
return result.reason === "unauthenticated" ? Response.json({ error: "Unauthenticated", message: "Unauthenticated." }, { status: 401 }) : Response.json({ error: "Forbidden", message: forbiddenMessage(requirement) }, { status: 403 });
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// src/matcher.ts
|
|
162
|
+
var cache = /* @__PURE__ */ new Map();
|
|
163
|
+
var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
164
|
+
function compilePathPattern(pattern) {
|
|
165
|
+
const hit = cache.get(pattern);
|
|
166
|
+
if (hit) return hit;
|
|
167
|
+
let source = "";
|
|
168
|
+
for (const segment of pattern.split("/")) {
|
|
169
|
+
if (segment === "") continue;
|
|
170
|
+
const param = /^:[A-Za-z_][A-Za-z0-9_]*([*+?])?$/.exec(segment);
|
|
171
|
+
if (!param) {
|
|
172
|
+
source += `/${escape(segment)}`;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
switch (param[1]) {
|
|
176
|
+
case "*":
|
|
177
|
+
source += "(?:/[^/]+)*";
|
|
178
|
+
break;
|
|
179
|
+
case "+":
|
|
180
|
+
source += "(?:/[^/]+)+";
|
|
181
|
+
break;
|
|
182
|
+
case "?":
|
|
183
|
+
source += "(?:/[^/]+)?";
|
|
184
|
+
break;
|
|
185
|
+
default:
|
|
186
|
+
source += "/[^/]+";
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const regex = new RegExp(`^${source}/?$`);
|
|
190
|
+
cache.set(pattern, regex);
|
|
191
|
+
return regex;
|
|
192
|
+
}
|
|
193
|
+
function matchPath(matcher, pathname) {
|
|
194
|
+
if (typeof matcher === "string") return compilePathPattern(matcher).test(pathname || "/");
|
|
195
|
+
if (matcher instanceof RegExp) return matcher.test(pathname);
|
|
196
|
+
return matcher.some((m) => matchPath(m, pathname));
|
|
197
|
+
}
|
|
198
|
+
var toList = (value) => typeof value === "string" ? [value] : value;
|
|
199
|
+
function safeImplies(granted, required) {
|
|
200
|
+
try {
|
|
201
|
+
return rbacEvolution.wildcardImplies(granted, required);
|
|
202
|
+
} catch {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function snapshotSatisfies(snapshot, requirement, options = {}) {
|
|
207
|
+
const roles = new Set(snapshot.roles);
|
|
208
|
+
const isSuperAdmin = (options.superAdminRoles ?? []).some((r) => roles.has(r));
|
|
209
|
+
const hasRole = (role) => roles.has(role.trim());
|
|
210
|
+
const can = (permission) => {
|
|
211
|
+
if (isSuperAdmin) return true;
|
|
212
|
+
const name = permission.trim();
|
|
213
|
+
if (name === "") return false;
|
|
214
|
+
if (snapshot.permissions.includes(name)) return true;
|
|
215
|
+
return (options.wildcard ?? false) && snapshot.permissions.some((g) => safeImplies(g, name));
|
|
216
|
+
};
|
|
217
|
+
if (requirement.permission !== void 0) return toList(requirement.permission).some(can);
|
|
218
|
+
if (requirement.role !== void 0) return toList(requirement.role).some(hasRole);
|
|
219
|
+
const items = toList(requirement.roleOrPermission);
|
|
220
|
+
return items.some(hasRole) || items.some(can);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// src/middleware.ts
|
|
224
|
+
function ruleRequirements(rule) {
|
|
225
|
+
const out = [];
|
|
226
|
+
if (rule.permission !== void 0) out.push({ permission: rule.permission });
|
|
227
|
+
if (rule.role !== void 0) out.push({ role: rule.role });
|
|
228
|
+
if (rule.roleOrPermission !== void 0) out.push({ roleOrPermission: rule.roleOrPermission });
|
|
229
|
+
return out;
|
|
230
|
+
}
|
|
231
|
+
var json = (status, error, message) => new Response(JSON.stringify({ error, message }), { status, headers: { "content-type": "application/json" } });
|
|
232
|
+
function createRbacMiddleware(options) {
|
|
233
|
+
async function loadSnapshot(req) {
|
|
234
|
+
if (options.rbac === void 0) {
|
|
235
|
+
const snapshot = await options.getSnapshot(req) ?? null;
|
|
236
|
+
return snapshot && { snapshot, wildcard: options.wildcard ?? false };
|
|
237
|
+
}
|
|
238
|
+
const subject = await options.getSubject(req) ?? null;
|
|
239
|
+
if (!subject) return null;
|
|
240
|
+
const scope = {};
|
|
241
|
+
if (options.guard !== void 0) scope.guard = options.guard;
|
|
242
|
+
const team = typeof options.team === "function" ? await options.team(req) : options.team;
|
|
243
|
+
if (team !== void 0 && team !== null) scope.team = team;
|
|
244
|
+
return { snapshot: await options.rbac.for(subject, scope).snapshot(), wildcard: options.rbac.wildcard };
|
|
245
|
+
}
|
|
246
|
+
return async (req) => {
|
|
247
|
+
const pathname = req.nextUrl?.pathname ?? new URL(req.url).pathname;
|
|
248
|
+
const matching = options.rules.filter((rule) => matchPath(rule.matcher, pathname));
|
|
249
|
+
if (matching.length === 0) return void 0;
|
|
250
|
+
const loaded = await loadSnapshot(req);
|
|
251
|
+
if (!loaded) {
|
|
252
|
+
const rule = matching[0];
|
|
253
|
+
if (options.onUnauthenticated) return options.onUnauthenticated(req, rule);
|
|
254
|
+
if (options.loginUrl !== void 0) {
|
|
255
|
+
const target = typeof options.loginUrl === "function" ? options.loginUrl(req) : options.loginUrl;
|
|
256
|
+
return Response.redirect(new URL(target, req.url), 307);
|
|
257
|
+
}
|
|
258
|
+
return json(401, "Unauthenticated", "Unauthenticated.");
|
|
259
|
+
}
|
|
260
|
+
const checkOptions = options.rbac === void 0 && options.superAdminRoles ? { wildcard: loaded.wildcard, superAdminRoles: options.superAdminRoles } : { wildcard: loaded.wildcard };
|
|
261
|
+
for (const rule of matching) {
|
|
262
|
+
const passes = ruleRequirements(rule).every((r) => snapshotSatisfies(loaded.snapshot, r, checkOptions));
|
|
263
|
+
if (!passes) {
|
|
264
|
+
if (options.onUnauthorized) return options.onUnauthorized(req, rule);
|
|
265
|
+
return json(403, "Forbidden", "User does not have the right roles or permissions.");
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return void 0;
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
exports.RbacUnauthorizedError = RbacUnauthorizedError;
|
|
273
|
+
exports.compilePathPattern = compilePathPattern;
|
|
274
|
+
exports.createNextRbac = createNextRbac;
|
|
275
|
+
exports.createRbacMiddleware = createRbacMiddleware;
|
|
276
|
+
exports.forbiddenMessage = forbiddenMessage;
|
|
277
|
+
exports.matchPath = matchPath;
|
|
278
|
+
exports.snapshotSatisfies = snapshotSatisfies;
|
|
279
|
+
//# sourceMappingURL=index.cjs.map
|
|
280
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/server.ts","../src/matcher.ts","../src/snapshot.ts","../src/middleware.ts"],"names":["redirect","notFound","options","wildcardImplies"],"mappings":";;;;;;;;AAGO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA;AAAA,EAEtC,MAAA;AAAA;AAAA,EAEA,MAAA;AAAA,EAET,WAAA,CAAY,QAAuB,OAAA,EAAkB;AACnD,IAAA,KAAA,CAAM,OAAA,KAAY,MAAA,KAAW,iBAAA,GAAoB,kBAAA,GAAqB,8BAAA,CAA+B,CAAA;AACrG,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA,KAAW,iBAAA,GAAoB,GAAA,GAAM,GAAA;AAAA,EACrD;AACF;;;ACsBO,SAAS,iBAAiB,WAAA,EAAkC;AACjE,EAAA,IAAI,WAAA,CAAY,UAAA,KAAe,MAAA,EAA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AC,CAAA,KAAM,iBAAA,CAAkB,MAAA,CAAO,QAAA,EAAU,CAAA,EAAG,YAAY,CAAC,CAAA;AACtG,MAAA,IAAI,CAAC,MAAA,EAAQ;AACX,QAAA,IAAI,QAAQ,cAAA,EAAgB,OAAO,OAAA,CAAQ,cAAA,CAAe,KAAK,IAAI,CAAA;AACnE,QAAA,OAAO,IAAA,CAAK,GAAA,EAAK,WAAA,EAAa,oDAAoD,CAAA;AAAA,MACpF;AAAA,IACF;AACA,IAAA,OAAO,MAAA;AAAA,EACT,CAAA;AACF","file":"index.cjs","sourcesContent":["import type { FailureReason } from './types'\n\n/** Thrown by `withPermission()` / `withRole()` wrapped server actions when access is denied. */\nexport class RbacUnauthorizedError extends Error {\n /** `unauthenticated` (no subject) or `unauthorized` (missing role/permission). */\n readonly reason: FailureReason\n /** HTTP-style status: `401` or `403`. */\n readonly status: 401 | 403\n\n constructor(reason: FailureReason, message?: string) {\n super(message ?? (reason === 'unauthenticated' ? 'Unauthenticated.' : 'This action is unauthorized.'))\n this.name = 'RbacUnauthorizedError'\n this.reason = reason\n this.status = reason === 'unauthenticated' ? 401 : 403\n }\n}\n","import { notFound, redirect } from 'next/navigation'\nimport type { Many, Rbac, RbacSnapshot, ScopeOptions, Subject, TeamId } from '@anievo-id/rbac-evolution'\nimport { RbacUnauthorizedError } from './errors'\nimport type { FailureReason, MaybePromise, Requirement } from './types'\n\nexport interface NextRbacOptions {\n /** Your `createRbac(...)` instance. */\n rbac: Rbac\n /** Resolves the current user (e.g. from Auth.js `auth()`). Return `null` for guests. */\n getSubject: () => MaybePromise<Subject | null | undefined>\n /** Default guard for every check. Default: the rbac instance's `defaultGuard`. */\n guard?: string\n /** Default team for every check — a value, or a function (e.g. reading the current tenant). */\n team?: TeamId | (() => MaybePromise<TeamId | undefined>)\n /** Where `require*()` redirects guests. Without it, guests get `notFound()`. */\n loginUrl?: string\n /** Replaces the default guest handling of `require*()` (must throw, e.g. `() => redirect('/login')`). */\n onUnauthenticated?: () => never\n /** Replaces the default `notFound()` of `require*()` (must throw, e.g. `() => forbidden()`). */\n onUnauthorized?: () => never\n}\n\n/** Per-call options for `require*()`. */\nexport interface RequireOptions extends ScopeOptions {\n loginUrl?: string\n onUnauthenticated?: () => never\n onUnauthorized?: () => never\n}\n\nexport type AuthorizeResult =\n | { ok: true; subject: Subject }\n | { ok: false; reason: 'unauthenticated'; subject: null }\n | { ok: false; reason: 'unauthorized'; subject: Subject }\n\nexport type WithRbacOptions = Requirement & ScopeOptions\n\n/** Like spatie, the message names the kind of requirement but not the role/permission names. */\nexport function forbiddenMessage(requirement: Requirement): string {\n if (requirement.permission !== undefined) return 'User does not have the right permissions.'\n if (requirement.role !== undefined) return 'User does not have the right roles.'\n return 'User does not have any of the necessary access rights.'\n}\n\nconst EMPTY_SNAPSHOT: RbacSnapshot = { roles: [], permissions: [] }\n\n\n\n/**\n * Server-side helpers for the Next.js App Router (server components, server actions, route handlers).\n *\n * ```ts\n * // lib/rbac.ts\n * export const { getSnapshot, can, requirePermission, withPermission, withRbac } = createNextRbac({\n * rbac,\n * getSubject: async () => {\n * const session = await auth()\n * return session?.user ? { type: 'user', id: session.user.id } : null\n * },\n * })\n * ```\n */\nexport function createNextRbac(options: NextRbacOptions) {\n const { rbac } = options\n\n async function getSubject(): Promise<Subject | null> {\n return (await options.getSubject()) ?? null\n }\n\n async function resolveScope(scope: ScopeOptions = {}): Promise<ScopeOptions> {\n const guard = scope.guard ?? options.guard\n let team: TeamId | undefined = scope.team\n if (team === undefined) {\n team = typeof options.team === 'function' ? await options.team() : options.team\n }\n const out: ScopeOptions = {}\n if (guard !== undefined) out.guard = guard\n if (team !== undefined && team !== null) out.team = team\n return out\n }\n\n async function forSubject(subject: Subject, scope?: ScopeOptions) {\n return rbac.for(subject, await resolveScope(scope))\n }\n\n async function satisfies(subject: Subject, requirement: Requirement, scope?: ScopeOptions): Promise<boolean> {\n const s = await forSubject(subject, scope)\n if (requirement.permission !== undefined) return s.canAny(requirement.permission)\n if (requirement.role !== undefined) return s.hasAnyRole(requirement.role)\n const items = requirement.roleOrPermission\n return (await s.hasAnyRole(items)) || (await s.canAny(items))\n }\n\n /** Non-throwing check: who is the user and do they meet the requirement? */\n async function authorize(requirement: Requirement, scope?: ScopeOptions): Promise<AuthorizeResult> {\n const subject = await getSubject()\n if (!subject) return { ok: false, reason: 'unauthenticated', subject: null }\n if (!(await satisfies(subject, requirement, scope))) return { ok: false, reason: 'unauthorized', subject }\n return { ok: true, subject }\n }\n\n function fail(reason: FailureReason, opts: RequireOptions): never {\n if (reason === 'unauthenticated') {\n const handler = opts.onUnauthenticated ?? options.onUnauthenticated\n if (handler) handler()\n else {\n const loginUrl = opts.loginUrl ?? options.loginUrl\n if (loginUrl !== undefined) redirect(loginUrl)\n notFound()\n }\n } else {\n const handler = opts.onUnauthorized ?? options.onUnauthorized\n if (handler) handler()\n else notFound()\n }\n // Safety net in case a custom handler returned instead of throwing.\n throw new RbacUnauthorizedError(reason)\n }\n\n async function enforce(requirement: Requirement, opts: RequireOptions = {}): Promise<Subject> {\n const result = await authorize(requirement, opts)\n if (!result.ok) fail(result.reason, opts)\n return result.subject\n }\n\n function guardAction<Args extends unknown[], R>(\n requirement: Requirement,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions,\n ): (...args: Args) => Promise<R> {\n return async (...args: Args): Promise<R> => {\n const result = await authorize(requirement, scope)\n if (!result.ok) throw new RbacUnauthorizedError(result.reason)\n return action(...args)\n }\n }\n\n return {\n rbac,\n getSubject,\n authorize,\n\n /** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */\n async getSnapshot(scope?: ScopeOptions): Promise<RbacSnapshot> {\n const subject = await getSubject()\n if (!subject) return { roles: [...EMPTY_SNAPSHOT.roles], permissions: [...EMPTY_SNAPSHOT.permissions] }\n return (await forSubject(subject, scope)).snapshot()\n },\n\n async can(permission: string, scope?: ScopeOptions): Promise<boolean> {\n const subject = await getSubject()\n return subject ? (await forSubject(subject, scope)).can(permission) : false\n },\n\n async canAny(permissions: Many<string>, scope?: ScopeOptions): Promise<boolean> {\n const subject = await getSubject()\n return subject ? (await forSubject(subject, scope)).canAny(permissions) : false\n },\n\n async canAll(permissions: Many<string>, scope?: ScopeOptions): Promise<boolean> {\n const subject = await getSubject()\n return subject ? (await forSubject(subject, scope)).canAll(permissions) : false\n },\n\n /** `true` if the user has the role — or ANY of the roles when given an array. */\n async hasRole(role: Many<string>, scope?: ScopeOptions): Promise<boolean> {\n const subject = await getSubject()\n return subject ? (await forSubject(subject, scope)).hasAnyRole(role) : false\n },\n\n async hasAllRoles(roles: Many<string>, scope?: ScopeOptions): Promise<boolean> {\n const subject = await getSubject()\n return subject ? (await forSubject(subject, scope)).hasAllRoles(roles) : false\n },\n\n /**\n * Ensures the user has the permission (or ANY of the permissions). Returns the subject.\n * Guests: `redirect(loginUrl)` or `notFound()`. Missing permission: `notFound()`. Both configurable.\n */\n requirePermission(permission: Many<string>, opts?: RequireOptions): Promise<Subject> {\n return enforce({ permission }, opts)\n },\n\n /** Ensures the user has the role (or ANY of the roles). Returns the subject. */\n requireRole(role: Many<string>, opts?: RequireOptions): Promise<Subject> {\n return enforce({ role }, opts)\n },\n\n /** Ensures the user has ANY of the given roles or permissions. Returns the subject. */\n requireRoleOrPermission(items: Many<string>, opts?: RequireOptions): Promise<Subject> {\n return enforce({ roleOrPermission: items }, opts)\n },\n\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */\n withPermission<Args extends unknown[], R>(\n permission: Many<string>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions,\n ): (...args: Args) => Promise<R> {\n return guardAction({ permission }, action, scope)\n },\n\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */\n withRole<Args extends unknown[], R>(\n role: Many<string>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions,\n ): (...args: Args) => Promise<R> {\n return guardAction({ role }, action, scope)\n },\n\n /**\n * Wraps a route handler. Responds `401` (guest) or `403` (missing role/permission) with a JSON body.\n * Mirrors spatie's `permission`, `role` and `role_or_permission` middleware.\n */\n withRbac<Args extends unknown[]>(\n handler: (...args: Args) => MaybePromise<Response>,\n options: WithRbacOptions,\n ): (...args: Args) => Promise<Response> {\n const { guard, team, ...requirement } = options\n const scope: ScopeOptions = {}\n if (guard !== undefined) scope.guard = guard\n if (team !== undefined) scope.team = team\n return async (...args: Args): Promise<Response> => {\n const result = await authorize(requirement as Requirement, scope)\n if (result.ok) return handler(...args)\n return result.reason === 'unauthenticated'\n ? Response.json({ error: 'Unauthenticated', message: 'Unauthenticated.' }, { status: 401 })\n : Response.json({ error: 'Forbidden', message: forbiddenMessage(requirement as Requirement) }, { status: 403 })\n }\n },\n }\n}\n\nexport type NextRbac = ReturnType<typeof createNextRbac>\n","const cache = new Map<string, RegExp>()\n\nconst escape = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n/**\n * Compiles a Next.js-style path pattern to a RegExp.\n *\n * - `/admin` matches `/admin` (and `/admin/`)\n * - `/users/:id` matches one segment\n * - `/admin/:path*` matches `/admin`, `/admin/a`, `/admin/a/b`\n * - `/admin/:path+` matches `/admin/a`, `/admin/a/b` (not `/admin`)\n * - `/blog/:slug?` matches `/blog` and `/blog/x`\n */\nexport function compilePathPattern(pattern: string): RegExp {\n const hit = cache.get(pattern)\n if (hit) return hit\n\n let source = ''\n for (const segment of pattern.split('/')) {\n if (segment === '') continue\n const param = /^:[A-Za-z_][A-Za-z0-9_]*([*+?])?$/.exec(segment)\n if (!param) {\n source += `/${escape(segment)}`\n continue\n }\n switch (param[1]) {\n case '*':\n source += '(?:/[^/]+)*'\n break\n case '+':\n source += '(?:/[^/]+)+'\n break\n case '?':\n source += '(?:/[^/]+)?'\n break\n default:\n source += '/[^/]+'\n }\n }\n const regex = new RegExp(`^${source}/?$`)\n cache.set(pattern, regex)\n return regex\n}\n\nexport type PathMatcher = string | RegExp | readonly (string | RegExp)[]\n\n/** `true` if the pathname matches the pattern (or any of the patterns). */\nexport function matchPath(matcher: PathMatcher, pathname: string): boolean {\n if (typeof matcher === 'string') return compilePathPattern(matcher).test(pathname || '/')\n if (matcher instanceof RegExp) return matcher.test(pathname)\n return matcher.some((m) => matchPath(m, pathname))\n}\n","import { wildcardImplies } from '@anievo-id/rbac-evolution'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\nimport type { Requirement } from './types'\n\nexport interface SnapshotCheckOptions {\n /** Treat granted permissions as wildcard patterns. */\n wildcard?: boolean\n /** Roles that pass every permission check. */\n superAdminRoles?: readonly string[]\n}\n\nconst toList = (value: Many<string>): readonly string[] => (typeof value === 'string' ? [value] : value)\n\nfunction safeImplies(granted: string, required: string): boolean {\n try {\n return wildcardImplies(granted, required)\n } catch {\n return false\n }\n}\n\n/** Synchronously checks a requirement against a snapshot. Arrays mean \"any of\". */\nexport function snapshotSatisfies(\n snapshot: RbacSnapshot,\n requirement: Requirement,\n options: SnapshotCheckOptions = {},\n): boolean {\n const roles = new Set(snapshot.roles)\n const isSuperAdmin = (options.superAdminRoles ?? []).some((r) => roles.has(r))\n const hasRole = (role: string): boolean => roles.has(role.trim())\n const can = (permission: string): boolean => {\n if (isSuperAdmin) return true\n const name = permission.trim()\n if (name === '') return false\n if (snapshot.permissions.includes(name)) return true\n return (options.wildcard ?? false) && snapshot.permissions.some((g) => safeImplies(g, name))\n }\n\n if (requirement.permission !== undefined) return toList(requirement.permission).some(can)\n if (requirement.role !== undefined) return toList(requirement.role).some(hasRole)\n const items = toList(requirement.roleOrPermission)\n return items.some(hasRole) || items.some(can)\n}\n","import type { Many, Rbac, RbacSnapshot, ScopeOptions, Subject, TeamId } from '@anievo-id/rbac-evolution'\nimport { matchPath } from './matcher'\nimport type { PathMatcher } from './matcher'\nimport { snapshotSatisfies } from './snapshot'\nimport type { MaybePromise, Requirement } from './types'\n\nexport interface RbacMiddlewareRule {\n /** Path pattern(s): `/admin`, `/users/:id`, `/admin/:path*`, or a RegExp. */\n matcher: PathMatcher\n /** Requires the permission (or ANY of them). */\n permission?: Many<string>\n /** Requires the role (or ANY of them). */\n role?: Many<string>\n /** Requires ANY of the given roles or permissions. */\n roleOrPermission?: Many<string>\n // A rule with none of the above only requires an authenticated user.\n}\n\n/** The request as seen by middleware. `NextRequest` fits; `nextUrl.pathname` is preferred (it excludes `basePath`). */\nexport type MiddlewareRequest = Request & { nextUrl?: { pathname: string } }\n\ninterface BaseOptions<Req extends MiddlewareRequest> {\n /** Every matching rule must pass. Requests matching no rule pass through. */\n rules: readonly RbacMiddlewareRule[]\n /** Redirect guests here (relative to the request URL). Without it, guests get a `401` JSON response. */\n loginUrl?: string | ((req: Req) => string | URL)\n /** Custom response for guests. */\n onUnauthenticated?: (req: Req, rule: RbacMiddlewareRule) => MaybePromise<Response>\n /** Custom response for users missing a role/permission. Default: `403` JSON response. */\n onUnauthorized?: (req: Req, rule: RbacMiddlewareRule) => MaybePromise<Response>\n}\n\n/** Loads roles & permissions through an `Rbac` instance (DB adapters need the Node.js middleware runtime). */\nexport interface RbacMiddlewareWithRbac<Req extends MiddlewareRequest> extends BaseOptions<Req> {\n rbac: Rbac\n getSubject: (req: Req) => MaybePromise<Subject | null | undefined>\n guard?: string\n team?: TeamId | ((req: Req) => MaybePromise<TeamId | undefined>)\n getSnapshot?: never\n}\n\n/** Reads roles & permissions from somewhere cheap, e.g. the session/JWT. Works in the Edge runtime. */\nexport interface RbacMiddlewareWithSnapshot<Req extends MiddlewareRequest> extends BaseOptions<Req> {\n /** Return `null` for guests. */\n getSnapshot: (req: Req) => MaybePromise<RbacSnapshot | null | undefined>\n /** Must match the server's `wildcard` setting. Default: `false`. */\n wildcard?: boolean\n /** Roles that pass every permission check. */\n superAdminRoles?: readonly string[]\n rbac?: never\n getSubject?: never\n}\n\nexport type RbacMiddlewareOptions<Req extends MiddlewareRequest = MiddlewareRequest> =\n | RbacMiddlewareWithRbac<Req>\n | RbacMiddlewareWithSnapshot<Req>\n\nfunction ruleRequirements(rule: RbacMiddlewareRule): Requirement[] {\n const out: Requirement[] = []\n if (rule.permission !== undefined) out.push({ permission: rule.permission })\n if (rule.role !== undefined) out.push({ role: rule.role })\n if (rule.roleOrPermission !== undefined) out.push({ roleOrPermission: rule.roleOrPermission })\n return out\n}\n\nconst json = (status: number, error: string, message: string): Response =>\n new Response(JSON.stringify({ error, message }), { status, headers: { 'content-type': 'application/json' } })\n\n/**\n * Route protection for `middleware.ts`, like spatie's route middleware.\n * Returns a `Response` when access is denied, or `undefined` to let the request through.\n *\n * ```ts\n * export default createRbacMiddleware({\n * rules: [{ matcher: '/admin/:path*', role: 'admin' }],\n * getSnapshot: async (req) => (await getToken({ req }))?.rbac ?? null,\n * })\n * ```\n */\nexport function createRbacMiddleware<Req extends MiddlewareRequest = MiddlewareRequest>(\n options: RbacMiddlewareOptions<Req>,\n): (req: Req) => Promise<Response | undefined> {\n async function loadSnapshot(req: Req): Promise<{ snapshot: RbacSnapshot; wildcard: boolean } | null> {\n if (options.rbac === undefined) {\n const snapshot = (await options.getSnapshot(req)) ?? null\n return snapshot && { snapshot, wildcard: options.wildcard ?? false }\n }\n const subject = (await options.getSubject(req)) ?? null\n if (!subject) return null\n const scope: ScopeOptions = {}\n if (options.guard !== undefined) scope.guard = options.guard\n const team = typeof options.team === 'function' ? await options.team(req) : options.team\n if (team !== undefined && team !== null) scope.team = team\n return { snapshot: await options.rbac.for(subject, scope).snapshot(), wildcard: options.rbac.wildcard }\n }\n\n return async (req: Req): Promise<Response | undefined> => {\n const pathname = req.nextUrl?.pathname ?? new URL(req.url).pathname\n const matching = options.rules.filter((rule) => matchPath(rule.matcher, pathname))\n if (matching.length === 0) return undefined\n\n const loaded = await loadSnapshot(req)\n if (!loaded) {\n const rule = matching[0]!\n if (options.onUnauthenticated) return options.onUnauthenticated(req, rule)\n if (options.loginUrl !== undefined) {\n const target = typeof options.loginUrl === 'function' ? options.loginUrl(req) : options.loginUrl\n return Response.redirect(new URL(target, req.url), 307)\n }\n return json(401, 'Unauthenticated', 'Unauthenticated.')\n }\n\n const checkOptions =\n options.rbac === undefined && options.superAdminRoles\n ? { wildcard: loaded.wildcard, superAdminRoles: options.superAdminRoles }\n : { wildcard: loaded.wildcard }\n\n for (const rule of matching) {\n const passes = ruleRequirements(rule).every((r) => snapshotSatisfies(loaded.snapshot, r, checkOptions))\n if (!passes) {\n if (options.onUnauthorized) return options.onUnauthorized(req, rule)\n return json(403, 'Forbidden', 'User does not have the right roles or permissions.')\n }\n }\n return undefined\n }\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import * as _anievo_id_rbac_evolution from '@anievo-id/rbac-evolution';
|
|
2
|
+
import { Subject, Rbac, TeamId, ScopeOptions, RbacSnapshot, Many } from '@anievo-id/rbac-evolution';
|
|
3
|
+
import { M as MaybePromise, R as Requirement, F as FailureReason } from './middleware-entry-Bh8jQj1L.cjs';
|
|
4
|
+
export { a as MiddlewareRequest, P as PathMatcher, b as RbacMiddlewareOptions, c as RbacMiddlewareRule, d as RbacMiddlewareWithRbac, e as RbacMiddlewareWithSnapshot, S as SnapshotCheckOptions, f as compilePathPattern, g as createRbacMiddleware, m as matchPath, s as snapshotSatisfies } from './middleware-entry-Bh8jQj1L.cjs';
|
|
5
|
+
|
|
6
|
+
interface NextRbacOptions {
|
|
7
|
+
/** Your `createRbac(...)` instance. */
|
|
8
|
+
rbac: Rbac;
|
|
9
|
+
/** Resolves the current user (e.g. from Auth.js `auth()`). Return `null` for guests. */
|
|
10
|
+
getSubject: () => MaybePromise<Subject | null | undefined>;
|
|
11
|
+
/** Default guard for every check. Default: the rbac instance's `defaultGuard`. */
|
|
12
|
+
guard?: string;
|
|
13
|
+
/** Default team for every check — a value, or a function (e.g. reading the current tenant). */
|
|
14
|
+
team?: TeamId | (() => MaybePromise<TeamId | undefined>);
|
|
15
|
+
/** Where `require*()` redirects guests. Without it, guests get `notFound()`. */
|
|
16
|
+
loginUrl?: string;
|
|
17
|
+
/** Replaces the default guest handling of `require*()` (must throw, e.g. `() => redirect('/login')`). */
|
|
18
|
+
onUnauthenticated?: () => never;
|
|
19
|
+
/** Replaces the default `notFound()` of `require*()` (must throw, e.g. `() => forbidden()`). */
|
|
20
|
+
onUnauthorized?: () => never;
|
|
21
|
+
}
|
|
22
|
+
/** Per-call options for `require*()`. */
|
|
23
|
+
interface RequireOptions extends ScopeOptions {
|
|
24
|
+
loginUrl?: string;
|
|
25
|
+
onUnauthenticated?: () => never;
|
|
26
|
+
onUnauthorized?: () => never;
|
|
27
|
+
}
|
|
28
|
+
type AuthorizeResult = {
|
|
29
|
+
ok: true;
|
|
30
|
+
subject: Subject;
|
|
31
|
+
} | {
|
|
32
|
+
ok: false;
|
|
33
|
+
reason: 'unauthenticated';
|
|
34
|
+
subject: null;
|
|
35
|
+
} | {
|
|
36
|
+
ok: false;
|
|
37
|
+
reason: 'unauthorized';
|
|
38
|
+
subject: Subject;
|
|
39
|
+
};
|
|
40
|
+
type WithRbacOptions = Requirement & ScopeOptions;
|
|
41
|
+
/** Like spatie, the message names the kind of requirement but not the role/permission names. */
|
|
42
|
+
declare function forbiddenMessage(requirement: Requirement): string;
|
|
43
|
+
/**
|
|
44
|
+
* Server-side helpers for the Next.js App Router (server components, server actions, route handlers).
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* // lib/rbac.ts
|
|
48
|
+
* export const { getSnapshot, can, requirePermission, withPermission, withRbac } = createNextRbac({
|
|
49
|
+
* rbac,
|
|
50
|
+
* getSubject: async () => {
|
|
51
|
+
* const session = await auth()
|
|
52
|
+
* return session?.user ? { type: 'user', id: session.user.id } : null
|
|
53
|
+
* },
|
|
54
|
+
* })
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
declare function createNextRbac(options: NextRbacOptions): {
|
|
58
|
+
rbac: Rbac<_anievo_id_rbac_evolution.DefaultRbacTypes>;
|
|
59
|
+
getSubject: () => Promise<Subject | null>;
|
|
60
|
+
authorize: (requirement: Requirement, scope?: ScopeOptions) => Promise<AuthorizeResult>;
|
|
61
|
+
/** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */
|
|
62
|
+
getSnapshot(scope?: ScopeOptions): Promise<RbacSnapshot>;
|
|
63
|
+
can(permission: string, scope?: ScopeOptions): Promise<boolean>;
|
|
64
|
+
canAny(permissions: Many<string>, scope?: ScopeOptions): Promise<boolean>;
|
|
65
|
+
canAll(permissions: Many<string>, scope?: ScopeOptions): Promise<boolean>;
|
|
66
|
+
/** `true` if the user has the role — or ANY of the roles when given an array. */
|
|
67
|
+
hasRole(role: Many<string>, scope?: ScopeOptions): Promise<boolean>;
|
|
68
|
+
hasAllRoles(roles: Many<string>, scope?: ScopeOptions): Promise<boolean>;
|
|
69
|
+
/**
|
|
70
|
+
* Ensures the user has the permission (or ANY of the permissions). Returns the subject.
|
|
71
|
+
* Guests: `redirect(loginUrl)` or `notFound()`. Missing permission: `notFound()`. Both configurable.
|
|
72
|
+
*/
|
|
73
|
+
requirePermission(permission: Many<string>, opts?: RequireOptions): Promise<Subject>;
|
|
74
|
+
/** Ensures the user has the role (or ANY of the roles). Returns the subject. */
|
|
75
|
+
requireRole(role: Many<string>, opts?: RequireOptions): Promise<Subject>;
|
|
76
|
+
/** Ensures the user has ANY of the given roles or permissions. Returns the subject. */
|
|
77
|
+
requireRoleOrPermission(items: Many<string>, opts?: RequireOptions): Promise<Subject>;
|
|
78
|
+
/** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */
|
|
79
|
+
withPermission<Args extends unknown[], R>(permission: Many<string>, action: (...args: Args) => MaybePromise<R>, scope?: ScopeOptions): (...args: Args) => Promise<R>;
|
|
80
|
+
/** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */
|
|
81
|
+
withRole<Args extends unknown[], R>(role: Many<string>, action: (...args: Args) => MaybePromise<R>, scope?: ScopeOptions): (...args: Args) => Promise<R>;
|
|
82
|
+
/**
|
|
83
|
+
* Wraps a route handler. Responds `401` (guest) or `403` (missing role/permission) with a JSON body.
|
|
84
|
+
* Mirrors spatie's `permission`, `role` and `role_or_permission` middleware.
|
|
85
|
+
*/
|
|
86
|
+
withRbac<Args extends unknown[]>(handler: (...args: Args) => MaybePromise<Response>, options: WithRbacOptions): (...args: Args) => Promise<Response>;
|
|
87
|
+
};
|
|
88
|
+
type NextRbac = ReturnType<typeof createNextRbac>;
|
|
89
|
+
|
|
90
|
+
/** Thrown by `withPermission()` / `withRole()` wrapped server actions when access is denied. */
|
|
91
|
+
declare class RbacUnauthorizedError extends Error {
|
|
92
|
+
/** `unauthenticated` (no subject) or `unauthorized` (missing role/permission). */
|
|
93
|
+
readonly reason: FailureReason;
|
|
94
|
+
/** HTTP-style status: `401` or `403`. */
|
|
95
|
+
readonly status: 401 | 403;
|
|
96
|
+
constructor(reason: FailureReason, message?: string);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export { type AuthorizeResult, FailureReason, MaybePromise, type NextRbac, type NextRbacOptions, RbacUnauthorizedError, type RequireOptions, Requirement, type WithRbacOptions, createNextRbac, forbiddenMessage };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import * as _anievo_id_rbac_evolution from '@anievo-id/rbac-evolution';
|
|
2
|
+
import { Subject, Rbac, TeamId, ScopeOptions, RbacSnapshot, Many } from '@anievo-id/rbac-evolution';
|
|
3
|
+
import { M as MaybePromise, R as Requirement, F as FailureReason } from './middleware-entry-Bh8jQj1L.js';
|
|
4
|
+
export { a as MiddlewareRequest, P as PathMatcher, b as RbacMiddlewareOptions, c as RbacMiddlewareRule, d as RbacMiddlewareWithRbac, e as RbacMiddlewareWithSnapshot, S as SnapshotCheckOptions, f as compilePathPattern, g as createRbacMiddleware, m as matchPath, s as snapshotSatisfies } from './middleware-entry-Bh8jQj1L.js';
|
|
5
|
+
|
|
6
|
+
interface NextRbacOptions {
|
|
7
|
+
/** Your `createRbac(...)` instance. */
|
|
8
|
+
rbac: Rbac;
|
|
9
|
+
/** Resolves the current user (e.g. from Auth.js `auth()`). Return `null` for guests. */
|
|
10
|
+
getSubject: () => MaybePromise<Subject | null | undefined>;
|
|
11
|
+
/** Default guard for every check. Default: the rbac instance's `defaultGuard`. */
|
|
12
|
+
guard?: string;
|
|
13
|
+
/** Default team for every check — a value, or a function (e.g. reading the current tenant). */
|
|
14
|
+
team?: TeamId | (() => MaybePromise<TeamId | undefined>);
|
|
15
|
+
/** Where `require*()` redirects guests. Without it, guests get `notFound()`. */
|
|
16
|
+
loginUrl?: string;
|
|
17
|
+
/** Replaces the default guest handling of `require*()` (must throw, e.g. `() => redirect('/login')`). */
|
|
18
|
+
onUnauthenticated?: () => never;
|
|
19
|
+
/** Replaces the default `notFound()` of `require*()` (must throw, e.g. `() => forbidden()`). */
|
|
20
|
+
onUnauthorized?: () => never;
|
|
21
|
+
}
|
|
22
|
+
/** Per-call options for `require*()`. */
|
|
23
|
+
interface RequireOptions extends ScopeOptions {
|
|
24
|
+
loginUrl?: string;
|
|
25
|
+
onUnauthenticated?: () => never;
|
|
26
|
+
onUnauthorized?: () => never;
|
|
27
|
+
}
|
|
28
|
+
type AuthorizeResult = {
|
|
29
|
+
ok: true;
|
|
30
|
+
subject: Subject;
|
|
31
|
+
} | {
|
|
32
|
+
ok: false;
|
|
33
|
+
reason: 'unauthenticated';
|
|
34
|
+
subject: null;
|
|
35
|
+
} | {
|
|
36
|
+
ok: false;
|
|
37
|
+
reason: 'unauthorized';
|
|
38
|
+
subject: Subject;
|
|
39
|
+
};
|
|
40
|
+
type WithRbacOptions = Requirement & ScopeOptions;
|
|
41
|
+
/** Like spatie, the message names the kind of requirement but not the role/permission names. */
|
|
42
|
+
declare function forbiddenMessage(requirement: Requirement): string;
|
|
43
|
+
/**
|
|
44
|
+
* Server-side helpers for the Next.js App Router (server components, server actions, route handlers).
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* // lib/rbac.ts
|
|
48
|
+
* export const { getSnapshot, can, requirePermission, withPermission, withRbac } = createNextRbac({
|
|
49
|
+
* rbac,
|
|
50
|
+
* getSubject: async () => {
|
|
51
|
+
* const session = await auth()
|
|
52
|
+
* return session?.user ? { type: 'user', id: session.user.id } : null
|
|
53
|
+
* },
|
|
54
|
+
* })
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
declare function createNextRbac(options: NextRbacOptions): {
|
|
58
|
+
rbac: Rbac<_anievo_id_rbac_evolution.DefaultRbacTypes>;
|
|
59
|
+
getSubject: () => Promise<Subject | null>;
|
|
60
|
+
authorize: (requirement: Requirement, scope?: ScopeOptions) => Promise<AuthorizeResult>;
|
|
61
|
+
/** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */
|
|
62
|
+
getSnapshot(scope?: ScopeOptions): Promise<RbacSnapshot>;
|
|
63
|
+
can(permission: string, scope?: ScopeOptions): Promise<boolean>;
|
|
64
|
+
canAny(permissions: Many<string>, scope?: ScopeOptions): Promise<boolean>;
|
|
65
|
+
canAll(permissions: Many<string>, scope?: ScopeOptions): Promise<boolean>;
|
|
66
|
+
/** `true` if the user has the role — or ANY of the roles when given an array. */
|
|
67
|
+
hasRole(role: Many<string>, scope?: ScopeOptions): Promise<boolean>;
|
|
68
|
+
hasAllRoles(roles: Many<string>, scope?: ScopeOptions): Promise<boolean>;
|
|
69
|
+
/**
|
|
70
|
+
* Ensures the user has the permission (or ANY of the permissions). Returns the subject.
|
|
71
|
+
* Guests: `redirect(loginUrl)` or `notFound()`. Missing permission: `notFound()`. Both configurable.
|
|
72
|
+
*/
|
|
73
|
+
requirePermission(permission: Many<string>, opts?: RequireOptions): Promise<Subject>;
|
|
74
|
+
/** Ensures the user has the role (or ANY of the roles). Returns the subject. */
|
|
75
|
+
requireRole(role: Many<string>, opts?: RequireOptions): Promise<Subject>;
|
|
76
|
+
/** Ensures the user has ANY of the given roles or permissions. Returns the subject. */
|
|
77
|
+
requireRoleOrPermission(items: Many<string>, opts?: RequireOptions): Promise<Subject>;
|
|
78
|
+
/** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */
|
|
79
|
+
withPermission<Args extends unknown[], R>(permission: Many<string>, action: (...args: Args) => MaybePromise<R>, scope?: ScopeOptions): (...args: Args) => Promise<R>;
|
|
80
|
+
/** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */
|
|
81
|
+
withRole<Args extends unknown[], R>(role: Many<string>, action: (...args: Args) => MaybePromise<R>, scope?: ScopeOptions): (...args: Args) => Promise<R>;
|
|
82
|
+
/**
|
|
83
|
+
* Wraps a route handler. Responds `401` (guest) or `403` (missing role/permission) with a JSON body.
|
|
84
|
+
* Mirrors spatie's `permission`, `role` and `role_or_permission` middleware.
|
|
85
|
+
*/
|
|
86
|
+
withRbac<Args extends unknown[]>(handler: (...args: Args) => MaybePromise<Response>, options: WithRbacOptions): (...args: Args) => Promise<Response>;
|
|
87
|
+
};
|
|
88
|
+
type NextRbac = ReturnType<typeof createNextRbac>;
|
|
89
|
+
|
|
90
|
+
/** Thrown by `withPermission()` / `withRole()` wrapped server actions when access is denied. */
|
|
91
|
+
declare class RbacUnauthorizedError extends Error {
|
|
92
|
+
/** `unauthenticated` (no subject) or `unauthorized` (missing role/permission). */
|
|
93
|
+
readonly reason: FailureReason;
|
|
94
|
+
/** HTTP-style status: `401` or `403`. */
|
|
95
|
+
readonly status: 401 | 403;
|
|
96
|
+
constructor(reason: FailureReason, message?: string);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export { type AuthorizeResult, FailureReason, MaybePromise, type NextRbac, type NextRbacOptions, RbacUnauthorizedError, type RequireOptions, Requirement, type WithRbacOptions, createNextRbac, forbiddenMessage };
|