@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/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,234 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @anievo-id/rbac-evolution-next
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Next.js (App Router) helpers for [rbac-evolution](../core): guards for server components, server actions and route
|
|
4
|
+
handlers, plus route protection in `middleware.ts` — the Next.js counterpart of spatie/laravel-permission's
|
|
5
|
+
`permission`, `role` and `role_or_permission` middleware.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-next
|
|
9
|
+
# for client-side <Can> / useCan():
|
|
10
|
+
npm i @anievo-id/rbac-evolution-react
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
`next` (14+) and `react` are peer dependencies. This package is server-only; it does not re-export the React bindings.
|
|
14
|
+
|
|
15
|
+
## Setup
|
|
16
|
+
|
|
17
|
+
You resolve the session yourself (Auth.js, Clerk, Lucia, iron-session, ...) and tell rbac-evolution who the
|
|
18
|
+
current subject is:
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
// lib/rbac.ts
|
|
22
|
+
import { createRbac } from '@anievo-id/rbac-evolution'
|
|
23
|
+
import { createNextRbac } from '@anievo-id/rbac-evolution-next'
|
|
24
|
+
import { PrismaAdapter } from '@anievo-id/rbac-evolution-prisma'
|
|
25
|
+
import { auth } from '@/auth'
|
|
26
|
+
import { prisma } from '@/lib/prisma'
|
|
27
|
+
|
|
28
|
+
export const rbac = createRbac({ adapter: new PrismaAdapter(prisma), wildcard: true })
|
|
29
|
+
|
|
30
|
+
export const {
|
|
31
|
+
getSnapshot,
|
|
32
|
+
can,
|
|
33
|
+
hasRole,
|
|
34
|
+
requirePermission,
|
|
35
|
+
requireRole,
|
|
36
|
+
withPermission,
|
|
37
|
+
withRbac,
|
|
38
|
+
} = createNextRbac({
|
|
39
|
+
rbac,
|
|
40
|
+
getSubject: async () => {
|
|
41
|
+
const session = await auth()
|
|
42
|
+
return session?.user?.id ? { type: 'user', id: session.user.id } : null
|
|
43
|
+
},
|
|
44
|
+
loginUrl: '/login', // optional: where require*() sends guests
|
|
45
|
+
// guard: 'web', // optional default guard
|
|
46
|
+
// team: async () => (await cookies()).get('team')?.value, // optional default team
|
|
47
|
+
})
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Server components → `RbacProvider` → `<Can>`
|
|
51
|
+
|
|
52
|
+
```tsx
|
|
53
|
+
// app/layout.tsx (server component)
|
|
54
|
+
import { RbacProvider } from '@anievo-id/rbac-evolution-react'
|
|
55
|
+
import { getSnapshot, rbac } from '@/lib/rbac'
|
|
56
|
+
|
|
57
|
+
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
|
58
|
+
return (
|
|
59
|
+
<html lang="en">
|
|
60
|
+
<body>
|
|
61
|
+
{/* guests get { roles: [], permissions: [] } */}
|
|
62
|
+
<RbacProvider snapshot={await getSnapshot()} wildcard={rbac.wildcard}>
|
|
63
|
+
{children}
|
|
64
|
+
</RbacProvider>
|
|
65
|
+
</body>
|
|
66
|
+
</html>
|
|
67
|
+
)
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```tsx
|
|
72
|
+
// app/articles/[id]/toolbar.tsx (client component)
|
|
73
|
+
'use client'
|
|
74
|
+
|
|
75
|
+
import { Can } from '@anievo-id/rbac-evolution-react'
|
|
76
|
+
|
|
77
|
+
export function Toolbar() {
|
|
78
|
+
return (
|
|
79
|
+
<Can permission="articles.edit" fallback={<span>Read only</span>}>
|
|
80
|
+
<button>Edit</button>
|
|
81
|
+
</Can>
|
|
82
|
+
)
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`<Can>` only hides UI. The page, actions and APIs below must still be protected on the server:
|
|
87
|
+
|
|
88
|
+
## Protecting pages
|
|
89
|
+
|
|
90
|
+
```tsx
|
|
91
|
+
// app/admin/page.tsx
|
|
92
|
+
import { requireRole } from '@/lib/rbac'
|
|
93
|
+
|
|
94
|
+
export default async function AdminPage() {
|
|
95
|
+
const user = await requireRole('admin') // returns the subject when allowed
|
|
96
|
+
return <h1>Admin</h1>
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`requirePermission(permission | permissions[], opts?)`, `requireRole(role | roles[], opts?)` and
|
|
101
|
+
`requireRoleOrPermission(items, opts?)` — arrays mean "any of" (like spatie's `permission:a|b`).
|
|
102
|
+
|
|
103
|
+
On failure (both configurable per factory or per call):
|
|
104
|
+
|
|
105
|
+
| Case | Default | Option |
|
|
106
|
+
| ------------------------------ | ----------------------------------------------------------- | ------------------- |
|
|
107
|
+
| Guest (`getSubject()` → null) | `redirect(loginUrl)` if `loginUrl` is set, else `notFound()` | `onUnauthenticated` |
|
|
108
|
+
| Missing role/permission | `notFound()` (does not reveal the page exists) | `onUnauthorized` |
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
import { redirect } from 'next/navigation'
|
|
112
|
+
|
|
113
|
+
await requirePermission('billing.view', {
|
|
114
|
+
onUnauthorized: () => redirect('/403'),
|
|
115
|
+
// or, with `experimental.authInterrupts` (Next 15.1+): onUnauthorized: () => forbidden(),
|
|
116
|
+
})
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Use `can()`, `canAny()`, `canAll()`, `hasRole()`, `hasAllRoles()` for plain boolean checks, and
|
|
120
|
+
`authorize(requirement)` for a non-throwing `{ ok, reason, subject }` result.
|
|
121
|
+
|
|
122
|
+
## Server actions
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
// app/articles/actions.ts
|
|
126
|
+
'use server'
|
|
127
|
+
|
|
128
|
+
import { withPermission } from '@/lib/rbac'
|
|
129
|
+
|
|
130
|
+
export const deleteArticle = withPermission('articles.delete', async (id: string) => {
|
|
131
|
+
await db.article.delete({ where: { id } })
|
|
132
|
+
})
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
When access is denied the wrapped action throws `RbacUnauthorizedError` (`reason: 'unauthenticated' | 'unauthorized'`,
|
|
136
|
+
`status: 401 | 403`) before running. `withRole(role, action)` works the same. Note that Next.js hides error details
|
|
137
|
+
from the client in production; if the UI needs to react, catch it in the action and return a value instead.
|
|
138
|
+
|
|
139
|
+
## Route handlers
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
// app/api/articles/[id]/route.ts
|
|
143
|
+
import { withRbac } from '@/lib/rbac'
|
|
144
|
+
|
|
145
|
+
export const DELETE = withRbac(
|
|
146
|
+
async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
|
|
147
|
+
const { id } = await params
|
|
148
|
+
// ...
|
|
149
|
+
return Response.json({ deleted: id })
|
|
150
|
+
},
|
|
151
|
+
{ permission: 'articles.delete' }, // or { role: 'admin' } or { roleOrPermission: ['admin', 'articles.delete'] }
|
|
152
|
+
)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Guests get `401 { "error": "Unauthenticated" }`, users without access get `403 { "error": "Forbidden" }`.
|
|
156
|
+
`withRbac` also accepts `guard` and `team`.
|
|
157
|
+
|
|
158
|
+
## Guards & teams
|
|
159
|
+
|
|
160
|
+
Every helper accepts `{ guard, team }` (passed to `rbac.for(subject, { guard, team })`). Defaults come from the
|
|
161
|
+
`guard` / `team` options of `createNextRbac`; `team` may be a function so it can read the current tenant per request.
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
await can('invoices.view', { team: params.teamId })
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Middleware
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
// middleware.ts
|
|
171
|
+
import type { NextRequest } from 'next/server'
|
|
172
|
+
import { createRbacMiddleware } from '@anievo-id/rbac-evolution-next/middleware'
|
|
173
|
+
|
|
174
|
+
export default createRbacMiddleware<NextRequest>({
|
|
175
|
+
rules: [
|
|
176
|
+
{ matcher: '/admin/:path*', role: 'admin' },
|
|
177
|
+
{ matcher: '/articles/:id/edit', permission: 'articles.edit' },
|
|
178
|
+
{ matcher: '/reports/:path*', roleOrPermission: ['manager', 'reports.view'] },
|
|
179
|
+
{ matcher: '/dashboard/:path*' }, // logged in only
|
|
180
|
+
],
|
|
181
|
+
// Snapshot stored in the session/JWT (see below) — works in the Edge runtime:
|
|
182
|
+
getSnapshot: async (req) => readSessionSnapshot(req), // RbacSnapshot | null
|
|
183
|
+
wildcard: true,
|
|
184
|
+
loginUrl: (req) => `/login?callbackUrl=${encodeURIComponent(req.nextUrl.pathname)}`,
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
export const config = { matcher: ['/admin/:path*', '/articles/:path*', '/reports/:path*', '/dashboard/:path*'] }
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
- Matchers support `/exact`, `:param` (one segment), `:path*` (zero or more), `:path+` (one or more), `:param?`,
|
|
191
|
+
a `RegExp`, or an array of these. Trailing slashes are ignored.
|
|
192
|
+
- Every matching rule must pass; a rule may combine `permission`, `role` and `roleOrPermission` (all must hold).
|
|
193
|
+
- Requests matching no rule pass through (the middleware returns `undefined`), so you can compose it:
|
|
194
|
+
`const res = await rbacMiddleware(req); if (res) return res`.
|
|
195
|
+
- Defaults: guests → redirect to `loginUrl`, or `401` JSON without it; missing access → `403` JSON.
|
|
196
|
+
Override with `onUnauthenticated(req, rule)` / `onUnauthorized(req, rule)` returning a `Response`
|
|
197
|
+
(e.g. `NextResponse.rewrite(new URL('/403', req.url))`).
|
|
198
|
+
- Import from `@anievo-id/rbac-evolution-next/middleware`: this entry does not import `next/navigation`.
|
|
199
|
+
|
|
200
|
+
### Where the roles come from in middleware
|
|
201
|
+
|
|
202
|
+
Middleware runs on every matched request, so database lookups there are costly — and **database adapters (Prisma,
|
|
203
|
+
Drizzle, ...) do not work in the Edge runtime**, which was the only middleware runtime before Next.js 15.5. Two options:
|
|
204
|
+
|
|
205
|
+
1. **Snapshot in the session/JWT (recommended).** Store `await rbac.for(user).snapshot()` in the token when the
|
|
206
|
+
user signs in (e.g. Auth.js `jwt` callback) and return it from `getSnapshot(req)`. Remember to refresh the token
|
|
207
|
+
when roles change; the server-side guards above still read live data.
|
|
208
|
+
2. **Use the `rbac` instance with the Node.js middleware runtime** (Next.js 15.5+):
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
import type { NextRequest } from 'next/server'
|
|
212
|
+
import { createRbacMiddleware } from '@anievo-id/rbac-evolution-next/middleware'
|
|
213
|
+
import { rbac } from '@/lib/rbac'
|
|
214
|
+
import { auth } from '@/auth'
|
|
215
|
+
|
|
216
|
+
export default createRbacMiddleware<NextRequest>({
|
|
217
|
+
rbac,
|
|
218
|
+
getSubject: async () => {
|
|
219
|
+
const session = await auth()
|
|
220
|
+
return session?.user?.id ? { type: 'user', id: session.user.id } : null
|
|
221
|
+
},
|
|
222
|
+
rules: [{ matcher: '/admin/:path*', role: 'admin' }],
|
|
223
|
+
// guard: 'web', team: (req) => req.cookies.get('team')?.value,
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
export const config = { runtime: 'nodejs', matcher: ['/admin/:path*'] }
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Middleware is a first line of defence for page navigation. Keep the server component / action / route handler
|
|
230
|
+
guards — they are what actually protects your data.
|
|
231
|
+
|
|
232
|
+
## License
|
|
233
|
+
|
|
234
|
+
MIT
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { wildcardImplies } from '@anievo-id/rbac-evolution';
|
|
2
|
+
|
|
3
|
+
// src/matcher.ts
|
|
4
|
+
var cache = /* @__PURE__ */ new Map();
|
|
5
|
+
var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6
|
+
function compilePathPattern(pattern) {
|
|
7
|
+
const hit = cache.get(pattern);
|
|
8
|
+
if (hit) return hit;
|
|
9
|
+
let source = "";
|
|
10
|
+
for (const segment of pattern.split("/")) {
|
|
11
|
+
if (segment === "") continue;
|
|
12
|
+
const param = /^:[A-Za-z_][A-Za-z0-9_]*([*+?])?$/.exec(segment);
|
|
13
|
+
if (!param) {
|
|
14
|
+
source += `/${escape(segment)}`;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
switch (param[1]) {
|
|
18
|
+
case "*":
|
|
19
|
+
source += "(?:/[^/]+)*";
|
|
20
|
+
break;
|
|
21
|
+
case "+":
|
|
22
|
+
source += "(?:/[^/]+)+";
|
|
23
|
+
break;
|
|
24
|
+
case "?":
|
|
25
|
+
source += "(?:/[^/]+)?";
|
|
26
|
+
break;
|
|
27
|
+
default:
|
|
28
|
+
source += "/[^/]+";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const regex = new RegExp(`^${source}/?$`);
|
|
32
|
+
cache.set(pattern, regex);
|
|
33
|
+
return regex;
|
|
34
|
+
}
|
|
35
|
+
function matchPath(matcher, pathname) {
|
|
36
|
+
if (typeof matcher === "string") return compilePathPattern(matcher).test(pathname || "/");
|
|
37
|
+
if (matcher instanceof RegExp) return matcher.test(pathname);
|
|
38
|
+
return matcher.some((m) => matchPath(m, pathname));
|
|
39
|
+
}
|
|
40
|
+
var toList = (value) => typeof value === "string" ? [value] : value;
|
|
41
|
+
function safeImplies(granted, required) {
|
|
42
|
+
try {
|
|
43
|
+
return wildcardImplies(granted, required);
|
|
44
|
+
} catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function snapshotSatisfies(snapshot, requirement, options = {}) {
|
|
49
|
+
const roles = new Set(snapshot.roles);
|
|
50
|
+
const isSuperAdmin = (options.superAdminRoles ?? []).some((r) => roles.has(r));
|
|
51
|
+
const hasRole = (role) => roles.has(role.trim());
|
|
52
|
+
const can = (permission) => {
|
|
53
|
+
if (isSuperAdmin) return true;
|
|
54
|
+
const name = permission.trim();
|
|
55
|
+
if (name === "") return false;
|
|
56
|
+
if (snapshot.permissions.includes(name)) return true;
|
|
57
|
+
return (options.wildcard ?? false) && snapshot.permissions.some((g) => safeImplies(g, name));
|
|
58
|
+
};
|
|
59
|
+
if (requirement.permission !== void 0) return toList(requirement.permission).some(can);
|
|
60
|
+
if (requirement.role !== void 0) return toList(requirement.role).some(hasRole);
|
|
61
|
+
const items = toList(requirement.roleOrPermission);
|
|
62
|
+
return items.some(hasRole) || items.some(can);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// src/middleware.ts
|
|
66
|
+
function ruleRequirements(rule) {
|
|
67
|
+
const out = [];
|
|
68
|
+
if (rule.permission !== void 0) out.push({ permission: rule.permission });
|
|
69
|
+
if (rule.role !== void 0) out.push({ role: rule.role });
|
|
70
|
+
if (rule.roleOrPermission !== void 0) out.push({ roleOrPermission: rule.roleOrPermission });
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
var json = (status, error, message) => new Response(JSON.stringify({ error, message }), { status, headers: { "content-type": "application/json" } });
|
|
74
|
+
function createRbacMiddleware(options) {
|
|
75
|
+
async function loadSnapshot(req) {
|
|
76
|
+
if (options.rbac === void 0) {
|
|
77
|
+
const snapshot = await options.getSnapshot(req) ?? null;
|
|
78
|
+
return snapshot && { snapshot, wildcard: options.wildcard ?? false };
|
|
79
|
+
}
|
|
80
|
+
const subject = await options.getSubject(req) ?? null;
|
|
81
|
+
if (!subject) return null;
|
|
82
|
+
const scope = {};
|
|
83
|
+
if (options.guard !== void 0) scope.guard = options.guard;
|
|
84
|
+
const team = typeof options.team === "function" ? await options.team(req) : options.team;
|
|
85
|
+
if (team !== void 0 && team !== null) scope.team = team;
|
|
86
|
+
return { snapshot: await options.rbac.for(subject, scope).snapshot(), wildcard: options.rbac.wildcard };
|
|
87
|
+
}
|
|
88
|
+
return async (req) => {
|
|
89
|
+
const pathname = req.nextUrl?.pathname ?? new URL(req.url).pathname;
|
|
90
|
+
const matching = options.rules.filter((rule) => matchPath(rule.matcher, pathname));
|
|
91
|
+
if (matching.length === 0) return void 0;
|
|
92
|
+
const loaded = await loadSnapshot(req);
|
|
93
|
+
if (!loaded) {
|
|
94
|
+
const rule = matching[0];
|
|
95
|
+
if (options.onUnauthenticated) return options.onUnauthenticated(req, rule);
|
|
96
|
+
if (options.loginUrl !== void 0) {
|
|
97
|
+
const target = typeof options.loginUrl === "function" ? options.loginUrl(req) : options.loginUrl;
|
|
98
|
+
return Response.redirect(new URL(target, req.url), 307);
|
|
99
|
+
}
|
|
100
|
+
return json(401, "Unauthenticated", "Unauthenticated.");
|
|
101
|
+
}
|
|
102
|
+
const checkOptions = options.rbac === void 0 && options.superAdminRoles ? { wildcard: loaded.wildcard, superAdminRoles: options.superAdminRoles } : { wildcard: loaded.wildcard };
|
|
103
|
+
for (const rule of matching) {
|
|
104
|
+
const passes = ruleRequirements(rule).every((r) => snapshotSatisfies(loaded.snapshot, r, checkOptions));
|
|
105
|
+
if (!passes) {
|
|
106
|
+
if (options.onUnauthorized) return options.onUnauthorized(req, rule);
|
|
107
|
+
return json(403, "Forbidden", "User does not have the right roles or permissions.");
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return void 0;
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export { compilePathPattern, createRbacMiddleware, matchPath, snapshotSatisfies };
|
|
115
|
+
//# sourceMappingURL=chunk-QGRA2JHH.js.map
|
|
116
|
+
//# sourceMappingURL=chunk-QGRA2JHH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/matcher.ts","../src/snapshot.ts","../src/middleware.ts"],"names":[],"mappings":";;;AAAA,IAAM,KAAA,uBAAY,GAAA,EAAoB;AAEtC,IAAM,SAAS,CAAC,CAAA,KAAsB,CAAA,CAAE,OAAA,CAAQ,uBA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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"]}
|