@anievo-id/rbac-evolution-next 0.8.0 → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +17 -224
  2. package/package.json +2 -2
package/README.md CHANGED
@@ -1,252 +1,45 @@
1
1
  # @anievo-id/rbac-evolution-next
2
2
 
3
- 📖 **[Documentation](https://creation.anievo.id/rbac-evolution/frameworks/nextjs)**
3
+ Next.js App Router helpers for [RBAC Evolution](https://github.com/AniEvo-ID/rbac-evolution): guards for server
4
+ components, server actions and route handlers, plus route rules for `middleware.ts`.
4
5
 
5
- Next.js (App Router) helpers for [rbac-evolution](https://github.com/AniEvo-ID/rbac-evolution): guards for server components, server actions and route
6
- handlers, plus route protection in `middleware.ts` — the Next.js counterpart of spatie/laravel-permission's
7
- `permission`, `role` and `role_or_permission` middleware.
6
+ ## Install
8
7
 
9
8
  ```bash
10
- npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-next
11
- # for client-side <Can> / useCan():
12
- npm i @anievo-id/rbac-evolution-react
9
+ npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-next next react
10
+ npm i @anievo-id/rbac-evolution-react # optional, for <Can> / useCan() in client components
13
11
  ```
14
12
 
15
- `next` (14+) and `react` are peer dependencies. This package is server-only; it does not re-export the React bindings.
16
-
17
- ## Setup
18
-
19
- You resolve the session yourself (Auth.js, Clerk, Lucia, iron-session, ...) and tell rbac-evolution who the
20
- current subject is:
13
+ ## Usage
21
14
 
22
15
  ```ts
23
16
  // lib/rbac.ts
24
17
  import { createRbac } from '@anievo-id/rbac-evolution'
25
18
  import { createNextRbac } from '@anievo-id/rbac-evolution-next'
26
- import { PrismaAdapter } from '@anievo-id/rbac-evolution-prisma'
27
- import { auth } from '@/auth'
28
- import { prisma } from '@/lib/prisma'
19
+ import { auth } from '@/auth' // your session library (Auth.js, Clerk, Lucia, ...)
29
20
 
30
- export const rbac = createRbac({ adapter: new PrismaAdapter(prisma), wildcard: true })
21
+ export const rbac = createRbac({ adapter })
31
22
 
32
- export const {
33
- getSnapshot,
34
- can,
35
- hasRole,
36
- requirePermission,
37
- requireRole,
38
- withPermission,
39
- withRbac,
40
- } = createNextRbac({
23
+ export const { getSnapshot, requirePermission, withPermission, withRbac } = createNextRbac({
41
24
  rbac,
42
25
  getSubject: async () => {
43
26
  const session = await auth()
44
27
  return session?.user?.id ? { type: 'user', id: session.user.id } : null
45
28
  },
46
- loginUrl: '/login', // optional: where require*() sends guests
47
- // guard: 'web', // optional default guard
48
- // team: async () => (await cookies()).get('team')?.value, // optional default team
49
- })
50
- ```
51
-
52
- ## Server components → `RbacProvider` → `<Can>`
53
-
54
- ```tsx
55
- // app/layout.tsx (server component)
56
- import { RbacProvider } from '@anievo-id/rbac-evolution-react'
57
- import { getSnapshot, rbac } from '@/lib/rbac'
58
-
59
- export default async function RootLayout({ children }: { children: React.ReactNode }) {
60
- return (
61
- <html lang="en">
62
- <body>
63
- {/* guests get { roles: [], permissions: [] } */}
64
- <RbacProvider snapshot={await getSnapshot()} wildcard={rbac.wildcard}>
65
- {children}
66
- </RbacProvider>
67
- </body>
68
- </html>
69
- )
70
- }
71
- ```
72
-
73
- ```tsx
74
- // app/articles/[id]/toolbar.tsx (client component)
75
- 'use client'
76
-
77
- import { Can } from '@anievo-id/rbac-evolution-react'
78
-
79
- export function Toolbar() {
80
- return (
81
- <Can permission="articles.edit" fallback={<span>Read only</span>}>
82
- <button>Edit</button>
83
- </Can>
84
- )
85
- }
86
- ```
87
-
88
- `<Can>` only hides UI. The page, actions and APIs below must still be protected on the server:
89
-
90
- ## Protecting pages
91
-
92
- ```tsx
93
- // app/admin/page.tsx
94
- import { requireRole } from '@/lib/rbac'
95
-
96
- export default async function AdminPage() {
97
- const user = await requireRole('admin') // returns the subject when allowed
98
- return <h1>Admin</h1>
99
- }
100
- ```
101
-
102
- `requirePermission(permission | permissions[], opts?)`, `requireRole(role | roles[], opts?)` and
103
- `requireRoleOrPermission(items, opts?)` — arrays and `'a|b'` strings mean "any of" (like spatie's
104
- `permission:a|b` and `canAny()`). Pass `{ all: true }` to `requirePermission` / `requireRole` (or `all: true` in a
105
- `withRbac` option or middleware rule) to require every entry, like spatie v8.5's `canAll()`.
106
-
107
- On failure (both configurable per factory or per call):
108
-
109
- | Case | Default | Option |
110
- | ------------------------------ | ----------------------------------------------------------- | ------------------- |
111
- | Guest (`getSubject()` → null) | `redirect(loginUrl)` if `loginUrl` is set, else `notFound()` | `onUnauthenticated` |
112
- | Missing role/permission | `notFound()` (does not reveal the page exists) | `onUnauthorized` |
113
-
114
- ```ts
115
- import { redirect } from 'next/navigation'
116
-
117
- await requirePermission('billing.view', {
118
- onUnauthorized: () => redirect('/403'),
119
- // or, with `experimental.authInterrupts` (Next 15.1+): onUnauthorized: () => forbidden(),
120
- })
121
- ```
122
-
123
- Use `can()`, `canAny()`, `canAll()`, `hasRole()`, `hasAllRoles()` for plain boolean checks, and
124
- `authorize(requirement)` for a non-throwing `{ ok, reason, subject }` result.
125
-
126
- ## Server actions
127
-
128
- ```ts
129
- // app/articles/actions.ts
130
- 'use server'
131
-
132
- import { withPermission } from '@/lib/rbac'
133
-
134
- export const deleteArticle = withPermission('articles.delete', async (id: string) => {
135
- await db.article.delete({ where: { id } })
136
- })
137
- ```
138
-
139
- When access is denied the wrapped action throws `RbacUnauthorizedError` (`reason: 'unauthenticated' | 'unauthorized'`,
140
- `status: 401 | 403`) before running. `withRole(role, action)` works the same. Note that Next.js hides error details
141
- from the client in production; if the UI needs to react, catch it in the action and return a value instead.
142
-
143
- ## Route handlers
144
-
145
- ```ts
146
- // app/api/articles/[id]/route.ts
147
- import { withRbac } from '@/lib/rbac'
148
-
149
- export const DELETE = withRbac(
150
- async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
151
- const { id } = await params
152
- // ...
153
- return Response.json({ deleted: id })
154
- },
155
- { permission: 'articles.delete' }, // or { role: 'admin' } or { roleOrPermission: ['admin', 'articles.delete'] }
156
- )
157
- ```
158
-
159
- Guests get `401 { "error": "UNAUTHENTICATED", "message": … }`, users without access get
160
- `403 { "error": "FORBIDDEN", "reason": "permission" | "role" | "role_or_permission", "message": … }` — the same
161
- bodies as `@anievo-id/rbac-evolution-express`.
162
- `withRbac` also accepts `guard` and `team`.
163
-
164
- ## Typed names
165
-
166
- With a typed engine (`createRbac<AppRbac>()`), `createNextRbac` checks every name. A typo is a compile error:
167
-
168
- ```ts
169
- const { requirePermission } = createNextRbac({ rbac, getSubject }) // rbac: Rbac<AppRbac>
170
-
171
- await requirePermission('articles.edit|articles.delete') // ok
172
- await requirePermission('articles.edti') // type error
173
- ```
174
-
175
- With an untyped engine, any string is accepted.
176
-
177
- ## Guards & teams
178
-
179
- Every helper accepts `{ guard, team }` (passed to `rbac.for(subject, { guard, team })`). Defaults come from the
180
- `guard` / `team` options of `createNextRbac`; `team` may be a function so it can read the current tenant per request.
181
-
182
- ```ts
183
- await can('invoices.view', { team: params.teamId })
184
- ```
185
-
186
- ## Middleware
187
-
188
- ```ts
189
- // middleware.ts
190
- import type { NextRequest } from 'next/server'
191
- import { createRbacMiddleware } from '@anievo-id/rbac-evolution-next/middleware'
192
-
193
- export default createRbacMiddleware<NextRequest>({
194
- rules: [
195
- { matcher: '/admin/:path*', role: 'admin' },
196
- { matcher: '/articles/:id/edit', permission: 'articles.edit' },
197
- { matcher: '/reports/:path*', roleOrPermission: ['manager', 'reports.view'] },
198
- { matcher: '/dashboard/:path*' }, // logged in only
199
- ],
200
- // Snapshot stored in the session/JWT (see below) — works in the Edge runtime:
201
- getSnapshot: async (req) => readSessionSnapshot(req), // RbacSnapshot | null
202
- wildcard: true,
203
- loginUrl: (req) => `/login?callbackUrl=${encodeURIComponent(req.nextUrl.pathname)}`,
204
29
  })
205
-
206
- export const config = { matcher: ['/admin/:path*', '/articles/:path*', '/reports/:path*', '/dashboard/:path*'] }
207
30
  ```
208
31
 
209
- - Matchers support `/exact`, `:param` (one segment), `:path*` (zero or more), `:path+` (one or more), `:param?`,
210
- a `RegExp`, or an array of these. Trailing slashes are ignored.
211
- - Every matching rule must pass; a rule may combine `permission`, `role` and `roleOrPermission` (all must hold).
212
- - Requests matching no rule pass through (the middleware returns `undefined`), so you can compose it:
213
- `const res = await rbacMiddleware(req); if (res) return res`.
214
- - Defaults: guests → redirect to `loginUrl`, or `401` JSON without it; missing access → `403` JSON.
215
- Override with `onUnauthenticated(req, rule)` / `onUnauthorized(req, rule)` returning a `Response`
216
- (e.g. `NextResponse.rewrite(new URL('/403', req.url))`).
217
- - Import from `@anievo-id/rbac-evolution-next/middleware`: this entry does not import `next/navigation`.
218
-
219
- ### Where the roles come from in middleware
220
-
221
- Middleware runs on every matched request, so database lookups there are costly — and **database adapters (Prisma,
222
- Drizzle, ...) do not work in the Edge runtime**, which was the only middleware runtime before Next.js 15.5. Two options:
223
-
224
- 1. **Snapshot in the session/JWT (recommended).** Store `await rbac.for(user).snapshot()` in the token when the
225
- user signs in (e.g. Auth.js `jwt` callback) and return it from `getSnapshot(req)`. Remember to refresh the token
226
- when roles change; the server-side guards above still read live data.
227
- 2. **Use the `rbac` instance with the Node.js middleware runtime** (Next.js 15.5+):
228
-
229
- ```ts
230
- import type { NextRequest } from 'next/server'
231
- import { createRbacMiddleware } from '@anievo-id/rbac-evolution-next/middleware'
232
- import { rbac } from '@/lib/rbac'
233
- import { auth } from '@/auth'
32
+ Then `await requirePermission('articles.edit')` in a page, `withPermission('articles.delete', action)` around a
33
+ server action, and `withRbac(handler, { permission: 'articles.delete' })` around a route handler.
234
34
 
235
- export default createRbacMiddleware<NextRequest>({
236
- rbac,
237
- getSubject: async () => {
238
- const session = await auth()
239
- return session?.user?.id ? { type: 'user', id: session.user.id } : null
240
- },
241
- rules: [{ matcher: '/admin/:path*', role: 'admin' }],
242
- // guard: 'web', team: (req) => req.cookies.get('team')?.value,
243
- })
35
+ - Pages answer `notFound()` by default, so a page the user can't open looks like one that doesn't exist.
36
+ - `createRbacMiddleware` (from `@anievo-id/rbac-evolution-next/middleware`) is a first filter for page navigation.
37
+ Keep the guards in pages, actions and route handlers: they are what protect your data.
38
+ - With a typed engine (`createRbac<AppRbac>()`), every helper type-checks the names.
244
39
 
245
- export const config = { runtime: 'nodejs', matcher: ['/admin/:path*'] }
246
- ```
40
+ ## Documentation
247
41
 
248
- Middleware is a first line of defence for page navigation. Keep the server component / action / route handler
249
- guards — they are what actually protects your data.
42
+ https://creation.anievo.id/rbac-evolution/frameworks/nextjs
250
43
 
251
44
  ## License
252
45
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anievo-id/rbac-evolution-next",
3
- "version": "0.8.0",
3
+ "version": "1.0.0-rc.0",
4
4
  "description": "Next.js helpers for rbac-evolution: middleware, server components & server action guards.",
5
5
  "license": "MIT",
6
6
  "author": "AniEvo-ID (https://github.com/AniEvo-ID)",
@@ -57,7 +57,7 @@
57
57
  "access": "public"
58
58
  },
59
59
  "dependencies": {
60
- "@anievo-id/rbac-evolution": "^0.8.0"
60
+ "@anievo-id/rbac-evolution": "^1.0.0-rc.0"
61
61
  },
62
62
  "peerDependencies": {
63
63
  "next": ">=14",