@anievo-id/rbac-evolution-next 1.1.0 → 1.3.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/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +69 -11
- package/dist/index.d.ts +69 -11
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/responses.ts","../src/types.ts","../src/server.ts","../src/matcher.ts","../src/snapshot.ts","../src/middleware.ts"],"names":["group","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;;;ACVO,SAAS,gBAAgB,WAAA,EAA2C;AACzE,EAAA,IAAI,WAAA,CAAY,UAAA,KAAe,MAAA,EAAW,OAAO,YAAA;AACjD,EAAA,IAAI,WAAA,CAAY,IAAA,KAAS,MAAA,EAAW,OAAO,MAAA;AAC3C,EAAA,OAAO,oBAAA;AACT;AAGO,SAAS,iBAAiB,WAAA,EAAkC;AACjE,EAAA,QAAQ,eAAA,CAAgB,WAAW,CAAA;AAAG,IACpC,KAAK,YAAA;AACH,MAAA,OAAO,2CAAA;AAAA,IACT,KAAK,MAAA;AACH,MAAA,OAAO,qCAAA;AAAA,IACT;AACE,MAAA,OAAO,w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,GAAA,CAAI,GAAG,GAAG,GAAG,CAAA;AAAA,MACxD;AACA,MAAA,OAAO,uBAAA,EAAwB;AAAA,IACjC;AAEA,IAAA,KAAA,MAAW,QAAQ,QAAA,EAAU;AAC3B,MAAA,IAAI,MAAA;AACJ,MAAA,KAAA,MAAW,WAAA,IAAe,gBAAA,CAAiB,IAAI,CAAA,EAAG;AAChD,QAAA,IAAI,CAAE,MAAM,KAAA,CAAM,WAAW,CAAA,EAAI;AAC/B,UAAA,MAAA,GAAS,WAAA;AACT,UAAA;AAAA,QACF;AAAA,MACF;AACA,MAAA,IAAI,MAAA,EAAQ;AACV,QAAA,IAAI,QAAQ,cAAA,EAAgB,OAAO,OAAA,CAAQ,cAAA,CAAe,KAAK,IAAI,CAAA;AACnE,QAAA,OAAO,kBAAkB,MAAM,CAAA;AAAA,MACjC;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 type { Requirement } from './types'\n\n/** Which kind of requirement failed — same values as the Express package. */\nexport type ForbiddenReason = 'permission' | 'role' | 'role_or_permission'\n\nexport function forbiddenReason(requirement: Requirement): ForbiddenReason {\n if (requirement.permission !== undefined) return 'permission'\n if (requirement.role !== undefined) return 'role'\n return 'role_or_permission'\n}\n\n/** Like spatie, the message names the kind of requirement but not the role/permission names. */\nexport function forbiddenMessage(requirement: Requirement): string {\n switch (forbiddenReason(requirement)) {\n case 'permission':\n return 'User does not have the right permissions.'\n case 'role':\n return 'User does not have the right roles.'\n default:\n return 'User does not have any of the necessary access rights.'\n }\n}\n\n/** `401 { error: 'UNAUTHENTICATED', message }` — same body as `@anievo-id/rbac-evolution-express`. */\nexport function unauthenticatedResponse(): Response {\n return Response.json({ error: 'UNAUTHENTICATED', message: 'User is not logged in.' }, { status: 401 })\n}\n\n/** `403 { error: 'FORBIDDEN', reason, message }` — same body as `@anievo-id/rbac-evolution-express`. */\nexport function forbiddenResponse(requirement: Requirement): Response {\n return Response.json(\n { error: 'FORBIDDEN', reason: forbiddenReason(requirement), message: forbiddenMessage(requirement) },\n { status: 403 },\n )\n}\n","import type { Many } from '@anievo-id/rbac-evolution'\n\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * What a guard requires — mirrors spatie's `permission`, `role` and `role_or_permission` middleware.\n * Arrays and `'a|b'` strings mean \"any of\" (like `permission:a|b` / spatie's `canAny()`).\n * With `all: true`, every listed permission or role is required (spatie v8.5 `canAll()`); a `'a|b'`\n * entry still means \"a or b\" within that entry.\n */\nexport type Requirement =\n | { permission: Many<string>; role?: never; roleOrPermission?: never; all?: boolean }\n | { permission?: never; role: Many<string>; roleOrPermission?: never; all?: boolean }\n | { permission?: never; role?: never; roleOrPermission: Many<string>; all?: never }\n\n/** One requirement as groups: every group must pass, any name inside a group passes it. */\nexport function requirementGroups(names: Many<string>, all: boolean | undefined): string[][] {\n const entries = (typeof names === 'string' ? [names] : [...names]).map((entry) =>\n entry\n .split('|')\n .map((n) => n.trim())\n .filter((n) => n !== ''),\n )\n // shortcut: an entry that is only pipes/spaces yields an empty group, which nobody satisfies.\n return all ? entries : [entries.flat()]\n}\n\n/** Evaluates a requirement with any/all checkers for single names. Empty requirements deny. */\nexport async function checkRequirement(\n requirement: Requirement,\n can: (name: string) => boolean | Promise<boolean>,\n hasRole: (name: string) => boolean | Promise<boolean>,\n): Promise<boolean> {\n const some = async (group: string[], fn: (n: string) => boolean | Promise<boolean>) => {\n for (const n of group) if (await fn(n)) return true\n return false\n }\n const every = async (groups: string[][], fn: (group: string[]) => Promise<boolean>) => {\n if (groups.length === 0) return false\n for (const g of groups) if (!(await fn(g))) return false\n return true\n }\n if (requirement.permission !== undefined) {\n return every(requirementGroups(requirement.permission, requirement.all), (g) => some(g, can))\n }\n if (requirement.role !== undefined) {\n return every(requirementGroups(requirement.role, requirement.all), (g) => some(g, hasRole))\n }\n const [group = []] = requirementGroups(requirement.roleOrPermission, false)\n return (await some(group, hasRole)) || (await some(group, can))\n}\n\nexport type FailureReason = 'unauthenticated' | 'unauthorized'\n","import { notFound, redirect } from 'next/navigation'\nimport type {\n CheckRequirementName,\n DefaultRbacTypes,\n Many,\n PermissionName,\n Rbac,\n RbacSnapshot,\n RbacTypeConfig,\n RoleName,\n ScopeOptions,\n Subject,\n TeamId,\n} from '@anievo-id/rbac-evolution'\nimport { RbacUnauthorizedError } from './errors'\nimport { forbiddenResponse, unauthenticatedResponse } from './responses'\nimport { checkRequirement, type FailureReason, type MaybePromise, type Requirement } from './types'\n\nexport interface NextRbacOptions<T extends RbacTypeConfig = DefaultRbacTypes> {\n /** Your `createRbac(...)` instance. Its typed names (`createRbac<{ permissions: ...; roles: ... }>`) flow into every helper. */\n rbac: Rbac<T>\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 | undefined\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 | undefined\n /** Replaces the default guest handling of `require*()` (must throw, e.g. `() => redirect('/login')`). */\n onUnauthenticated?: (() => never) | undefined\n /** Replaces the default `notFound()` of `require*()` (must throw, e.g. `() => forbidden()`). */\n onUnauthorized?: (() => never) | undefined\n}\n\n/** Per-call options for `require*()`. */\nexport interface RequireOptions extends ScopeOptions {\n /** `requirePermission` / `requireRole`: require EVERY listed name instead of any (spatie v8.5 `canAll()`). */\n all?: boolean | undefined\n loginUrl?: string | undefined\n onUnauthenticated?: (() => never) | undefined\n onUnauthorized?: (() => never) | undefined\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/**\n * Checks a name, a `'a|b'` pipe list or an array of them against the names `N`.\n * Any name passes when `N` is `string` (an untyped engine).\n */\nexport type CheckNames<S, N extends string> = S extends string\n ? CheckRequirementName<S, N>\n : S extends readonly string[]\n ? { [K in keyof S]: S[K] extends string ? CheckRequirementName<S[K], N> : S[K] }\n : S\n\n/** Checks the `permission` / `role` / `roleOrPermission` names of a requirement object `Q` against the names of `T`. */\nexport type CheckRequirement<Q, T extends RbacTypeConfig> = {\n [K in keyof Q]: K extends 'permission'\n ? CheckNames<Q[K], PermissionName<T>>\n : K extends 'role'\n ? CheckNames<Q[K], RoleName<T>>\n : K extends 'roleOrPermission'\n ? CheckNames<Q[K], PermissionName<T> | RoleName<T>>\n : Q[K]\n}\n\n/**\n * The helpers returned by `createNextRbac()`. `T` comes from the `rbac` instance: with typed names,\n * every name (including each part of a `'a|b'` list) must be one of them; untyped, any string is accepted.\n */\nexport interface NextRbac<T extends RbacTypeConfig = DefaultRbacTypes> {\n rbac: Rbac<T>\n getSubject(): Promise<Subject | null>\n /** Non-throwing check: who is the user and do they meet the requirement? */\n authorize<const Q extends Requirement>(\n requirement: Q & CheckRequirement<Q, T>,\n scope?: ScopeOptions,\n ): Promise<AuthorizeResult>\n /** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */\n getSnapshot(scope?: ScopeOptions): Promise<RbacSnapshot>\n can(permission: PermissionName<T>, scope?: ScopeOptions): Promise<boolean>\n canAny(permissions: Many<PermissionName<T>>, scope?: ScopeOptions): Promise<boolean>\n canAll(permissions: Many<PermissionName<T>>, scope?: ScopeOptions): Promise<boolean>\n /** `true` if the user has the role — or ANY of the roles when given an array. */\n hasRole(role: Many<RoleName<T>>, scope?: ScopeOptions): Promise<boolean>\n hasAllRoles(roles: Many<RoleName<T>>, scope?: ScopeOptions): Promise<boolean>\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<const S extends Many<string>>(\n permission: S & CheckNames<S, PermissionName<T>>,\n opts?: RequireOptions,\n ): Promise<Subject>\n /** Ensures the user has the role (or ANY of the roles). Returns the subject. */\n requireRole<const S extends Many<string>>(role: S & CheckNames<S, RoleName<T>>, opts?: RequireOptions): Promise<Subject>\n /** Ensures the user has ANY of the given roles or permissions. Returns the subject. */\n requireRoleOrPermission<const S extends Many<string>>(\n items: S & CheckNames<S, PermissionName<T> | RoleName<T>>,\n opts?: RequireOptions,\n ): Promise<Subject>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */\n withPermission<const S extends Many<string>, Args extends unknown[], R>(\n permission: S & CheckNames<S, PermissionName<T>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions | undefined,\n ): (...args: Args) => Promise<R>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */\n withRole<const S extends Many<string>, Args extends unknown[], R>(\n role: S & CheckNames<S, RoleName<T>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions | undefined,\n ): (...args: Args) => Promise<R>\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[], const O extends WithRbacOptions>(\n handler: (...args: Args) => MaybePromise<Response>,\n options: O & CheckRequirement<O, T>,\n ): (...args: Args) => Promise<Response>\n}\n\nexport { forbiddenMessage } from './responses'\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 *\n * With a typed engine (`createRbac<AppTypes>(...)`), names are checked: `requirePermission('typo')` is a type error.\n */\nexport function createNextRbac<T extends RbacTypeConfig = DefaultRbacTypes>(options: NextRbacOptions<T>): NextRbac<T> {\n // The implementation is untyped (plain `string` names); `NextRbac<T>` adds the typed signatures.\n const helpers = buildNextRbac(options as unknown as NextRbacOptions) satisfies Record<keyof NextRbac, unknown>\n return helpers as unknown as NextRbac<T>\n}\n\nfunction buildNextRbac(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 return checkRequirement(requirement, (n) => s.can(n), (n) => s.hasRole(n))\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 | undefined,\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?.all && { all: true }) }, 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?.all && { all: true }) }, 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 | undefined,\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 | undefined,\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 ? unauthenticatedResponse()\n : forbiddenResponse(requirement as Requirement)\n }\n },\n }\n}\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\nfunction testOne(matcher: string | RegExp, pathname: string): boolean {\n if (typeof matcher === 'string') return compilePathPattern(matcher).test(pathname || '/')\n matcher.lastIndex = 0 // a /g or /y RegExp keeps state between test() calls\n return matcher.test(pathname)\n}\n\nconst decode = (pathname: string): string => {\n try {\n return decodeURI(pathname)\n } catch {\n return pathname\n }\n}\n\n/**\n * `true` if the pathname matches the pattern (or any of the patterns). Both the raw and the\n * percent-decoded pathname are tried, so `/%61dmin` is protected by a rule for `/admin`.\n */\nexport function matchPath(matcher: PathMatcher, pathname: string): boolean {\n const candidates = [pathname, decode(pathname)]\n const list = typeof matcher === 'string' || matcher instanceof RegExp ? [matcher] : matcher\n return list.some((m) => candidates.some((p) => testOne(m, p)))\n}\n","import { wildcardImplies } from '@anievo-id/rbac-evolution'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\nimport { type Requirement, requirementGroups } from './types'\n\nexport interface SnapshotCheckOptions {\n /** Treat granted permissions as wildcard patterns. */\n wildcard?: boolean | undefined\n /** Roles that pass every permission check. */\n superAdminRoles?: readonly string[] | undefined\n}\n\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 // Names the server's `before` hook denies (`snapshot({ checkBefore })`); older snapshots have none.\n const denied = new Set((snapshot.denied ?? []).map((name) => name.trim()))\n const can = (permission: string): boolean => {\n if (denied.has(permission.trim())) return false\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 const all = (groups: string[][], fn: (n: string) => boolean) =>\n groups.length > 0 && groups.every((group) => group.some(fn))\n if (requirement.permission !== undefined) return all(requirementGroups(requirement.permission, requirement.all), can)\n if (requirement.role !== undefined) return all(requirementGroups(requirement.role, requirement.all), hasRole)\n const [items = []] = requirementGroups(requirement.roleOrPermission, false)\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 { forbiddenResponse, unauthenticatedResponse } from './responses'\nimport { snapshotSatisfies, type SnapshotCheckOptions } from './snapshot'\nimport { checkRequirement, type MaybePromise, type 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> | undefined\n /** Requires the role (or ANY of them). */\n role?: Many<string> | undefined\n /** Requires ANY of the given roles or permissions. */\n roleOrPermission?: Many<string> | undefined\n /** Require EVERY listed permission / role instead of any (spatie v8.5 `canAll()`). */\n all?: boolean | undefined\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) | undefined\n /** Custom response for guests. */\n onUnauthenticated?: ((req: Req, rule: RbacMiddlewareRule) => MaybePromise<Response>) | undefined\n /** Custom response for users missing a role/permission. Default: `403` JSON response. */\n onUnauthorized?: ((req: Req, rule: RbacMiddlewareRule) => MaybePromise<Response>) | undefined\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 | undefined\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 | undefined\n /** Roles that pass every permission check. */\n superAdminRoles?: readonly string[] | undefined\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, ...(rule.all && { all: true }) })\n if (rule.role !== undefined) out.push({ role: rule.role, ...(rule.all && { all: true }) })\n if (rule.roleOrPermission !== undefined) out.push({ roleOrPermission: rule.roleOrPermission })\n return out\n}\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 type Checker = (requirement: Requirement) => Promise<boolean>\n\n /**\n * Resolves who is asking and returns a requirement checker, or `null` for guests.\n * In `rbac` mode the checks go through the engine (`canAny` / `hasAnyRole`), so\n * `superAdminRoles` and the `before` hook apply exactly like in the server helpers.\n */\n async function loadChecker(req: Req): Promise<Checker | null> {\n if (options.rbac === undefined) {\n const snapshot = (await options.getSnapshot(req)) ?? null\n if (!snapshot) return null\n const checkOptions: SnapshotCheckOptions = { wildcard: options.wildcard ?? false }\n if (options.superAdminRoles) checkOptions.superAdminRoles = options.superAdminRoles\n return async (requirement) => snapshotSatisfies(snapshot, requirement, checkOptions)\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 const s = options.rbac.for(subject, scope)\n return (requirement) => checkRequirement(requirement, (n) => s.can(n), (n) => s.hasRole(n))\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 check = await loadChecker(req)\n if (!check) {\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 unauthenticatedResponse()\n }\n\n for (const rule of matching) {\n let failed: Requirement | undefined\n for (const requirement of ruleRequirements(rule)) {\n if (!(await check(requirement))) {\n failed = requirement\n break\n }\n }\n if (failed) {\n if (options.onUnauthorized) return options.onUnauthorized(req, rule)\n return forbiddenResponse(failed)\n }\n }\n return undefined\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/responses.ts","../src/types.ts","../src/server.ts","../src/matcher.ts","../src/snapshot.ts","../src/middleware.ts"],"names":["group","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,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ElC,IAAA,MAAM,KAAA,GAAQ,MAAM,WAAA,CAAY,GAAG,CAAA;AACnC,IAAA,IAAI,CAAC,KAAA,EAAO;AACV,MAAA,MAAM,IAAA,GAAO,SAAS,CAAC,CAAA;AACvB,MAAA,IAAI,QAAQ,iBAAA,EAAmB,OAAO,OAAA,CAAQ,iBAAA,CAAkB,KAAK,IAAI,CAAA;AACzE,MAAA,IAAI,OAAA,CAAQ,aAAa,MAAA,EAAW;AAClC,QAAA,MAAM,MAAA,GAAS,OAAO,OAAA,CAAQ,QAAA,KAAa,aAAa,OAAA,CAAQ,QAAA,CAAS,GAAG,CAAA,GAAI,OAAA,CAAQ,QAAA;AACxF,QAAA,OAAO,QAAA,CAAS,SAAS,IAAI,GAAA,CAAI,QAAQ,GAAA,CAAI,GAAG,GAAG,GAAG,CAAA;AAAA,MACxD;AACA,MAAA,OAAO,uBAAA,EAAwB;AAAA,IACjC;AAEA,IAAA,KAAA,MAAW,QAAQ,QAAA,EAAU;AAC3B,MAAA,IAAI,MAAA;AACJ,MAAA,KAAA,MAAW,WAAA,IAAe,gBAAA,CAAiB,IAAI,CAAA,EAAG;AAChD,QAAA,IAAI,CAAE,MAAM,KAAA,CAAM,WAAW,CAAA,EAAI;AAC/B,UAAA,MAAA,GAAS,WAAA;AACT,UAAA;AAAA,QACF;AAAA,MACF;AACA,MAAA,IAAI,MAAA,EAAQ;AACV,QAAA,IAAI,QAAQ,cAAA,EAAgB,OAAO,OAAA,CAAQ,cAAA,CAAe,KAAK,IAAI,CAAA;AACnE,QAAA,OAAO,kBAAkB,MAAM,CAAA;AAAA,MACjC;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 type { Requirement } from './types'\n\n/** Which kind of requirement failed — same values as the Express package. */\nexport type ForbiddenReason = 'permission' | 'role' | 'role_or_permission'\n\nexport function forbiddenReason(requirement: Requirement): ForbiddenReason {\n if (requirement.permission !== undefined) return 'permission'\n if (requirement.role !== undefined) return 'role'\n return 'role_or_permission'\n}\n\n/** Like spatie, the message names the kind of requirement but not the role/permission names. */\nexport function forbiddenMessage(requirement: Requirement): string {\n switch (forbiddenReason(requirement)) {\n case 'permission':\n return 'User does not have the right permissions.'\n case 'role':\n return 'User does not have the right roles.'\n default:\n return 'User does not have any of the necessary access rights.'\n }\n}\n\n/** `401 { error: 'UNAUTHENTICATED', message }` — same body as `@anievo-id/rbac-evolution-express`. */\nexport function unauthenticatedResponse(): Response {\n return Response.json({ error: 'UNAUTHENTICATED', message: 'User is not logged in.' }, { status: 401 })\n}\n\n/** `403 { error: 'FORBIDDEN', reason, message }` — same body as `@anievo-id/rbac-evolution-express`. */\nexport function forbiddenResponse(requirement: Requirement): Response {\n return Response.json(\n { error: 'FORBIDDEN', reason: forbiddenReason(requirement), message: forbiddenMessage(requirement) },\n { status: 403 },\n )\n}\n","import type { Many } from '@anievo-id/rbac-evolution'\n\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * What a guard requires — mirrors spatie's `permission`, `role` and `role_or_permission` middleware.\n * Arrays and `'a|b'` strings mean \"any of\" (like `permission:a|b` / spatie's `canAny()`).\n * With `all: true`, every listed permission or role is required (spatie v8.5 `canAll()`); a `'a|b'`\n * entry still means \"a or b\" within that entry.\n */\nexport type Requirement =\n | { permission: Many<string>; role?: never; roleOrPermission?: never; all?: boolean }\n | { permission?: never; role: Many<string>; roleOrPermission?: never; all?: boolean }\n | { permission?: never; role?: never; roleOrPermission: Many<string>; all?: never }\n\n/** One requirement as groups: every group must pass, any name inside a group passes it. */\nexport function requirementGroups(names: Many<string>, all: boolean | undefined): string[][] {\n const entries = (typeof names === 'string' ? [names] : [...names]).map((entry) =>\n entry\n .split('|')\n .map((n) => n.trim())\n .filter((n) => n !== ''),\n )\n // shortcut: an entry that is only pipes/spaces yields an empty group, which nobody satisfies.\n return all ? entries : [entries.flat()]\n}\n\n/** Evaluates a requirement with any/all checkers for single names. Empty requirements deny. */\nexport async function checkRequirement(\n requirement: Requirement,\n can: (name: string) => boolean | Promise<boolean>,\n hasRole: (name: string) => boolean | Promise<boolean>,\n): Promise<boolean> {\n const some = async (group: string[], fn: (n: string) => boolean | Promise<boolean>) => {\n for (const n of group) if (await fn(n)) return true\n return false\n }\n const every = async (groups: string[][], fn: (group: string[]) => Promise<boolean>) => {\n if (groups.length === 0) return false\n for (const g of groups) if (!(await fn(g))) return false\n return true\n }\n if (requirement.permission !== undefined) {\n return every(requirementGroups(requirement.permission, requirement.all), (g) => some(g, can))\n }\n if (requirement.role !== undefined) {\n return every(requirementGroups(requirement.role, requirement.all), (g) => some(g, hasRole))\n }\n const [group = []] = requirementGroups(requirement.roleOrPermission, false)\n return (await some(group, hasRole)) || (await some(group, can))\n}\n\nexport type FailureReason = 'unauthenticated' | 'unauthorized'\n","import { notFound, redirect } from 'next/navigation'\nimport type {\n CheckGuard,\n CheckRequirementGuard,\n CheckRequirementName,\n DefaultGuardName,\n DefaultRbacTypes,\n GuardOptions,\n Many,\n PermissionName,\n Rbac,\n RbacSnapshot,\n RbacTypeConfig,\n RoleName,\n ScopedGuardName,\n ScopeOptions,\n Subject,\n TeamId,\n} from '@anievo-id/rbac-evolution'\nimport { RbacUnauthorizedError } from './errors'\nimport { forbiddenResponse, unauthenticatedResponse } from './responses'\nimport { checkRequirement, type FailureReason, type MaybePromise, type Requirement } from './types'\n\n/** `G` is the type of `guard`: any string by default; `createNextRbac()` infers it to type the helpers. */\nexport interface NextRbacOptions<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = string> {\n /** Your `createRbac(...)` instance. Its typed names (`createRbac<{ permissions: ...; roles: ... }>`) flow into every helper. */\n rbac: Rbac<T>\n /** Resolves the current user (e.g. from Auth.js `auth()`). Return `null` for guests. */\n getSubject: () => MaybePromise<Subject | null | undefined>\n /**\n * Default guard for every check. Default: the rbac instance's `defaultGuard`. With per-guard names, it must be\n * one of the typed guards (checked by `createNextRbac()`), and the helpers take its names.\n */\n guard?: G | undefined\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 | undefined\n /** Replaces the default guest handling of `require*()` (must throw, e.g. `() => redirect('/login')`). */\n onUnauthenticated?: (() => never) | undefined\n /** Replaces the default `notFound()` of `require*()` (must throw, e.g. `() => forbidden()`). */\n onUnauthorized?: (() => never) | undefined\n}\n\n/** Per-call options for `require*()`. `G` is the type of `guard` (see `ScopeOptions`). */\nexport interface RequireOptions<G extends string = string> extends ScopeOptions<G> {\n /** `requirePermission` / `requireRole`: require EVERY listed name instead of any (spatie v8.5 `canAll()`). */\n all?: boolean | undefined\n loginUrl?: string | undefined\n onUnauthenticated?: (() => never) | undefined\n onUnauthorized?: (() => never) | undefined\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/**\n * Checks a name, a `'a|b'` pipe list or an array of them against the names `N`.\n * Any name passes when `N` is `string` (an untyped engine).\n */\nexport type CheckNames<S, N extends string> = S extends string\n ? CheckRequirementName<S, N>\n : S extends readonly string[]\n ? { [K in keyof S]: S[K] extends string ? CheckRequirementName<S[K], N> : S[K] }\n : S\n\n/**\n * Checks the `permission` / `role` / `roleOrPermission` names of a requirement object `Q` against the names of\n * `T`: with per-guard names, those of guard `G`. A `guard` key in `Q` must be one of the typed guards.\n */\nexport type CheckRequirement<Q, T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> = {\n [K in keyof Q]: K extends 'permission'\n ? CheckNames<Q[K], PermissionName<T, G>>\n : K extends 'role'\n ? CheckNames<Q[K], RoleName<T, G>>\n : K extends 'roleOrPermission'\n ? CheckNames<Q[K], PermissionName<T, G> | RoleName<T, G>>\n : K extends 'guard'\n ? Q[K] extends string\n ? CheckRequirementGuard<T, Q[K]>\n : Q[K]\n : Q[K]\n}\n\n/** The guard a `withRbac()` options object `O` checks in: its `guard`, or `G`. */\nexport type OptionsGuard<O, G extends string> = O extends { readonly guard: infer X extends string } ? X : G\n\n/**\n * The helpers returned by `createNextRbac()`. `T` comes from the `rbac` instance: with typed names,\n * every name (including each part of a `'a|b'` list) must be one of them; untyped, any string is accepted.\n */\nexport interface NextRbac<T extends RbacTypeConfig = DefaultRbacTypes> {\n rbac: Rbac<T>\n getSubject(): Promise<Subject | null>\n /** Non-throwing check: who is the user and do they meet the requirement? */\n authorize<const Q extends Requirement>(\n requirement: Q & CheckRequirement<Q, T>,\n scope?: ScopeOptions,\n ): Promise<AuthorizeResult>\n /** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */\n getSnapshot(scope?: ScopeOptions): Promise<RbacSnapshot>\n can(permission: PermissionName<T>, scope?: ScopeOptions): Promise<boolean>\n canAny(permissions: Many<PermissionName<T>>, scope?: ScopeOptions): Promise<boolean>\n canAll(permissions: Many<PermissionName<T>>, scope?: ScopeOptions): Promise<boolean>\n /** `true` if the user has the role — or ANY of the roles when given an array. */\n hasRole(role: Many<RoleName<T>>, scope?: ScopeOptions): Promise<boolean>\n hasAllRoles(roles: Many<RoleName<T>>, scope?: ScopeOptions): Promise<boolean>\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<const S extends Many<string>>(\n permission: S & CheckNames<S, PermissionName<T>>,\n opts?: RequireOptions,\n ): Promise<Subject>\n /** Ensures the user has the role (or ANY of the roles). Returns the subject. */\n requireRole<const S extends Many<string>>(role: S & CheckNames<S, RoleName<T>>, opts?: RequireOptions): Promise<Subject>\n /** Ensures the user has ANY of the given roles or permissions. Returns the subject. */\n requireRoleOrPermission<const S extends Many<string>>(\n items: S & CheckNames<S, PermissionName<T> | RoleName<T>>,\n opts?: RequireOptions,\n ): Promise<Subject>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */\n withPermission<const S extends Many<string>, Args extends unknown[], R>(\n permission: S & CheckNames<S, PermissionName<T>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions | undefined,\n ): (...args: Args) => Promise<R>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */\n withRole<const S extends Many<string>, Args extends unknown[], R>(\n role: S & CheckNames<S, RoleName<T>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions | undefined,\n ): (...args: Args) => Promise<R>\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[], const O extends WithRbacOptions>(\n handler: (...args: Args) => MaybePromise<Response>,\n options: O & CheckRequirement<O, T>,\n ): (...args: Args) => Promise<Response>\n}\n\n/**\n * The helpers of `createNextRbac()` when the engine has per-guard names (`RbacTypeConfig['guards']`): like\n * {@link NextRbac}, but `G` is the guard of the checks (the `guard` option of `createNextRbac()`, else the default\n * guard), and a call's `{ guard }` takes the names of that guard instead: `can('orders.read', { guard: 'api' })`.\n */\nexport interface ScopedNextRbac<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> {\n rbac: Rbac<T>\n getSubject(): Promise<Subject | null>\n /** Non-throwing check: who is the user and do they meet the requirement? */\n authorize<const Q extends Requirement, G2 extends string = G>(\n requirement: Q & CheckRequirement<Q, T, G2>,\n scope?: ScopeOptions<CheckGuard<T, G2>>,\n ): Promise<AuthorizeResult>\n /** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */\n getSnapshot(scope?: ScopeOptions): Promise<RbacSnapshot>\n can<G2 extends string = G>(permission: PermissionName<T, G2>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>\n canAny<G2 extends string = G>(permissions: Many<PermissionName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>\n canAll<G2 extends string = G>(permissions: Many<PermissionName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>\n /** `true` if the user has the role — or ANY of the roles when given an array. */\n hasRole<G2 extends string = G>(role: Many<RoleName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>\n hasAllRoles<G2 extends string = G>(roles: Many<RoleName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>\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<const S extends Many<string>, G2 extends string = G>(\n permission: S & CheckNames<S, PermissionName<T, G2>>,\n opts?: RequireOptions<CheckGuard<T, G2>>,\n ): Promise<Subject>\n /** Ensures the user has the role (or ANY of the roles). Returns the subject. */\n requireRole<const S extends Many<string>, G2 extends string = G>(\n role: S & CheckNames<S, RoleName<T, G2>>,\n opts?: RequireOptions<CheckGuard<T, G2>>,\n ): Promise<Subject>\n /** Ensures the user has ANY of the given roles or permissions. Returns the subject. */\n requireRoleOrPermission<const S extends Many<string>, G2 extends string = G>(\n items: S & CheckNames<S, PermissionName<T, G2> | RoleName<T, G2>>,\n opts?: RequireOptions<CheckGuard<T, G2>>,\n ): Promise<Subject>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */\n withPermission<const S extends Many<string>, Args extends unknown[], R, G2 extends string = G>(\n permission: S & CheckNames<S, PermissionName<T, G2>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions<CheckGuard<T, G2>> | undefined,\n ): (...args: Args) => Promise<R>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */\n withRole<const S extends Many<string>, Args extends unknown[], R, G2 extends string = G>(\n role: S & CheckNames<S, RoleName<T, G2>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions<CheckGuard<T, G2>> | undefined,\n ): (...args: Args) => Promise<R>\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[], const O extends WithRbacOptions>(\n handler: (...args: Args) => MaybePromise<Response>,\n options: O & CheckRequirement<O, T, OptionsGuard<O, G>>,\n ): (...args: Args) => Promise<Response>\n}\n\n/**\n * What `createNextRbac()` returns: {@link NextRbac} for an engine without per-guard names (as in 1.1), and\n * {@link ScopedNextRbac} for one with `guards`.\n */\nexport type NextRbacFor<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> = T extends {\n guards: object\n}\n ? ScopedNextRbac<T, G>\n : NextRbac<T>\n\nexport { forbiddenMessage } from './responses'\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 *\n * With a typed engine (`createRbac<AppTypes>(...)`), names are checked: `requirePermission('typo')` is a type error.\n * With per-guard names, the helpers take the names of the `guard` option (the default guard's without it).\n */\nexport function createNextRbac<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>>(\n options: NextRbacOptions<T, G> & (T extends { guards: object } ? GuardOptions<CheckGuard<T, G>> : unknown),\n): NextRbacFor<T, ScopedGuardName<T, G>> {\n // The implementation is untyped (plain `string` names); `NextRbac<T>` adds the typed signatures.\n const helpers = buildNextRbac(options as unknown as NextRbacOptions) satisfies Record<keyof NextRbac, unknown>\n return helpers as unknown as NextRbacFor<T, ScopedGuardName<T, G>>\n}\n\nfunction buildNextRbac(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 return checkRequirement(requirement, (n) => s.can(n), (n) => s.hasRole(n))\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 | undefined,\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?.all && { all: true }) }, 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?.all && { all: true }) }, 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 | undefined,\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 | undefined,\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 ? unauthenticatedResponse()\n : forbiddenResponse(requirement as Requirement)\n }\n },\n }\n}\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\nfunction testOne(matcher: string | RegExp, pathname: string): boolean {\n if (typeof matcher === 'string') return compilePathPattern(matcher).test(pathname || '/')\n matcher.lastIndex = 0 // a /g or /y RegExp keeps state between test() calls\n return matcher.test(pathname)\n}\n\nconst decode = (pathname: string): string => {\n try {\n return decodeURI(pathname)\n } catch {\n return pathname\n }\n}\n\n/**\n * `true` if the pathname matches the pattern (or any of the patterns). Both the raw and the\n * percent-decoded pathname are tried, so `/%61dmin` is protected by a rule for `/admin`.\n */\nexport function matchPath(matcher: PathMatcher, pathname: string): boolean {\n const candidates = [pathname, decode(pathname)]\n const list = typeof matcher === 'string' || matcher instanceof RegExp ? [matcher] : matcher\n return list.some((m) => candidates.some((p) => testOne(m, p)))\n}\n","import { wildcardImplies } from '@anievo-id/rbac-evolution'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\nimport { type Requirement, requirementGroups } from './types'\n\nexport interface SnapshotCheckOptions {\n /** Treat granted permissions as wildcard patterns. */\n wildcard?: boolean | undefined\n /** Roles that pass every permission check. */\n superAdminRoles?: readonly string[] | undefined\n}\n\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 // Names the server's `before` hook denies (`snapshot({ checkBefore })`); older snapshots have none.\n const denied = new Set((snapshot.denied ?? []).map((name) => name.trim()))\n const can = (permission: string): boolean => {\n if (denied.has(permission.trim())) return false\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 const all = (groups: string[][], fn: (n: string) => boolean) =>\n groups.length > 0 && groups.every((group) => group.some(fn))\n if (requirement.permission !== undefined) return all(requirementGroups(requirement.permission, requirement.all), can)\n if (requirement.role !== undefined) return all(requirementGroups(requirement.role, requirement.all), hasRole)\n const [items = []] = requirementGroups(requirement.roleOrPermission, false)\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 { forbiddenResponse, unauthenticatedResponse } from './responses'\nimport { snapshotSatisfies, type SnapshotCheckOptions } from './snapshot'\nimport { checkRequirement, type MaybePromise, type 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> | undefined\n /** Requires the role (or ANY of them). */\n role?: Many<string> | undefined\n /** Requires ANY of the given roles or permissions. */\n roleOrPermission?: Many<string> | undefined\n /** Require EVERY listed permission / role instead of any (spatie v8.5 `canAll()`). */\n all?: boolean | undefined\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) | undefined\n /** Custom response for guests. */\n onUnauthenticated?: ((req: Req, rule: RbacMiddlewareRule) => MaybePromise<Response>) | undefined\n /** Custom response for users missing a role/permission. Default: `403` JSON response. */\n onUnauthorized?: ((req: Req, rule: RbacMiddlewareRule) => MaybePromise<Response>) | undefined\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 | undefined\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 | undefined\n /** Roles that pass every permission check. */\n superAdminRoles?: readonly string[] | undefined\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, ...(rule.all && { all: true }) })\n if (rule.role !== undefined) out.push({ role: rule.role, ...(rule.all && { all: true }) })\n if (rule.roleOrPermission !== undefined) out.push({ roleOrPermission: rule.roleOrPermission })\n return out\n}\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 type Checker = (requirement: Requirement) => Promise<boolean>\n\n /**\n * Resolves who is asking and returns a requirement checker, or `null` for guests.\n * In `rbac` mode the checks go through the engine (`canAny` / `hasAnyRole`), so\n * `superAdminRoles` and the `before` hook apply exactly like in the server helpers.\n */\n async function loadChecker(req: Req): Promise<Checker | null> {\n if (options.rbac === undefined) {\n const snapshot = (await options.getSnapshot(req)) ?? null\n if (!snapshot) return null\n const checkOptions: SnapshotCheckOptions = { wildcard: options.wildcard ?? false }\n if (options.superAdminRoles) checkOptions.superAdminRoles = options.superAdminRoles\n return async (requirement) => snapshotSatisfies(snapshot, requirement, checkOptions)\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 const s = options.rbac.for(subject, scope)\n return (requirement) => checkRequirement(requirement, (n) => s.can(n), (n) => s.hasRole(n))\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 check = await loadChecker(req)\n if (!check) {\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 unauthenticatedResponse()\n }\n\n for (const rule of matching) {\n let failed: Requirement | undefined\n for (const requirement of ruleRequirements(rule)) {\n if (!(await check(requirement))) {\n failed = requirement\n break\n }\n }\n if (failed) {\n if (options.onUnauthorized) return options.onUnauthorized(req, rule)\n return forbiddenResponse(failed)\n }\n }\n return undefined\n }\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Subject, RbacTypeConfig, DefaultRbacTypes, Rbac, CheckRequirementName, PermissionName, RoleName, ScopeOptions, RbacSnapshot, Many, TeamId } from '@anievo-id/rbac-evolution';
|
|
1
|
+
import { Subject, RbacTypeConfig, DefaultRbacTypes, Rbac, DefaultGuardName, CheckRequirementName, PermissionName, RoleName, CheckRequirementGuard, ScopeOptions, RbacSnapshot, Many, CheckGuard, TeamId, GuardOptions, ScopedGuardName } from '@anievo-id/rbac-evolution';
|
|
2
2
|
import { R as Requirement, M as MaybePromise, F as FailureReason } from './middleware-entry-BYLAhtrk.cjs';
|
|
3
3
|
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-BYLAhtrk.cjs';
|
|
4
4
|
|
|
@@ -7,13 +7,17 @@ type ForbiddenReason = 'permission' | 'role' | 'role_or_permission';
|
|
|
7
7
|
/** Like spatie, the message names the kind of requirement but not the role/permission names. */
|
|
8
8
|
declare function forbiddenMessage(requirement: Requirement): string;
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
/** `G` is the type of `guard`: any string by default; `createNextRbac()` infers it to type the helpers. */
|
|
11
|
+
interface NextRbacOptions<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = string> {
|
|
11
12
|
/** Your `createRbac(...)` instance. Its typed names (`createRbac<{ permissions: ...; roles: ... }>`) flow into every helper. */
|
|
12
13
|
rbac: Rbac<T>;
|
|
13
14
|
/** Resolves the current user (e.g. from Auth.js `auth()`). Return `null` for guests. */
|
|
14
15
|
getSubject: () => MaybePromise<Subject | null | undefined>;
|
|
15
|
-
/**
|
|
16
|
-
|
|
16
|
+
/**
|
|
17
|
+
* Default guard for every check. Default: the rbac instance's `defaultGuard`. With per-guard names, it must be
|
|
18
|
+
* one of the typed guards (checked by `createNextRbac()`), and the helpers take its names.
|
|
19
|
+
*/
|
|
20
|
+
guard?: G | undefined;
|
|
17
21
|
/** Default team for every check — a value, or a function (e.g. reading the current tenant). */
|
|
18
22
|
team?: TeamId | (() => MaybePromise<TeamId | undefined>);
|
|
19
23
|
/** Where `require*()` redirects guests. Without it, guests get `notFound()`. */
|
|
@@ -23,8 +27,8 @@ interface NextRbacOptions<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
|
23
27
|
/** Replaces the default `notFound()` of `require*()` (must throw, e.g. `() => forbidden()`). */
|
|
24
28
|
onUnauthorized?: (() => never) | undefined;
|
|
25
29
|
}
|
|
26
|
-
/** Per-call options for `require*()`. */
|
|
27
|
-
interface RequireOptions extends ScopeOptions {
|
|
30
|
+
/** Per-call options for `require*()`. `G` is the type of `guard` (see `ScopeOptions`). */
|
|
31
|
+
interface RequireOptions<G extends string = string> extends ScopeOptions<G> {
|
|
28
32
|
/** `requirePermission` / `requireRole`: require EVERY listed name instead of any (spatie v8.5 `canAll()`). */
|
|
29
33
|
all?: boolean | undefined;
|
|
30
34
|
loginUrl?: string | undefined;
|
|
@@ -51,10 +55,17 @@ type WithRbacOptions = Requirement & ScopeOptions;
|
|
|
51
55
|
type CheckNames<S, N extends string> = S extends string ? CheckRequirementName<S, N> : S extends readonly string[] ? {
|
|
52
56
|
[K in keyof S]: S[K] extends string ? CheckRequirementName<S[K], N> : S[K];
|
|
53
57
|
} : S;
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
|
|
58
|
+
/**
|
|
59
|
+
* Checks the `permission` / `role` / `roleOrPermission` names of a requirement object `Q` against the names of
|
|
60
|
+
* `T`: with per-guard names, those of guard `G`. A `guard` key in `Q` must be one of the typed guards.
|
|
61
|
+
*/
|
|
62
|
+
type CheckRequirement<Q, T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> = {
|
|
63
|
+
[K in keyof Q]: K extends 'permission' ? CheckNames<Q[K], PermissionName<T, G>> : K extends 'role' ? CheckNames<Q[K], RoleName<T, G>> : K extends 'roleOrPermission' ? CheckNames<Q[K], PermissionName<T, G> | RoleName<T, G>> : K extends 'guard' ? Q[K] extends string ? CheckRequirementGuard<T, Q[K]> : Q[K] : Q[K];
|
|
57
64
|
};
|
|
65
|
+
/** The guard a `withRbac()` options object `O` checks in: its `guard`, or `G`. */
|
|
66
|
+
type OptionsGuard<O, G extends string> = O extends {
|
|
67
|
+
readonly guard: infer X extends string;
|
|
68
|
+
} ? X : G;
|
|
58
69
|
/**
|
|
59
70
|
* The helpers returned by `createNextRbac()`. `T` comes from the `rbac` instance: with typed names,
|
|
60
71
|
* every name (including each part of a `'a|b'` list) must be one of them; untyped, any string is accepted.
|
|
@@ -91,6 +102,50 @@ interface NextRbac<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
|
91
102
|
*/
|
|
92
103
|
withRbac<Args extends unknown[], const O extends WithRbacOptions>(handler: (...args: Args) => MaybePromise<Response>, options: O & CheckRequirement<O, T>): (...args: Args) => Promise<Response>;
|
|
93
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* The helpers of `createNextRbac()` when the engine has per-guard names (`RbacTypeConfig['guards']`): like
|
|
107
|
+
* {@link NextRbac}, but `G` is the guard of the checks (the `guard` option of `createNextRbac()`, else the default
|
|
108
|
+
* guard), and a call's `{ guard }` takes the names of that guard instead: `can('orders.read', { guard: 'api' })`.
|
|
109
|
+
*/
|
|
110
|
+
interface ScopedNextRbac<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> {
|
|
111
|
+
rbac: Rbac<T>;
|
|
112
|
+
getSubject(): Promise<Subject | null>;
|
|
113
|
+
/** Non-throwing check: who is the user and do they meet the requirement? */
|
|
114
|
+
authorize<const Q extends Requirement, G2 extends string = G>(requirement: Q & CheckRequirement<Q, T, G2>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<AuthorizeResult>;
|
|
115
|
+
/** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */
|
|
116
|
+
getSnapshot(scope?: ScopeOptions): Promise<RbacSnapshot>;
|
|
117
|
+
can<G2 extends string = G>(permission: PermissionName<T, G2>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>;
|
|
118
|
+
canAny<G2 extends string = G>(permissions: Many<PermissionName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>;
|
|
119
|
+
canAll<G2 extends string = G>(permissions: Many<PermissionName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>;
|
|
120
|
+
/** `true` if the user has the role — or ANY of the roles when given an array. */
|
|
121
|
+
hasRole<G2 extends string = G>(role: Many<RoleName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>;
|
|
122
|
+
hasAllRoles<G2 extends string = G>(roles: Many<RoleName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>;
|
|
123
|
+
/**
|
|
124
|
+
* Ensures the user has the permission (or ANY of the permissions). Returns the subject.
|
|
125
|
+
* Guests: `redirect(loginUrl)` or `notFound()`. Missing permission: `notFound()`. Both configurable.
|
|
126
|
+
*/
|
|
127
|
+
requirePermission<const S extends Many<string>, G2 extends string = G>(permission: S & CheckNames<S, PermissionName<T, G2>>, opts?: RequireOptions<CheckGuard<T, G2>>): Promise<Subject>;
|
|
128
|
+
/** Ensures the user has the role (or ANY of the roles). Returns the subject. */
|
|
129
|
+
requireRole<const S extends Many<string>, G2 extends string = G>(role: S & CheckNames<S, RoleName<T, G2>>, opts?: RequireOptions<CheckGuard<T, G2>>): Promise<Subject>;
|
|
130
|
+
/** Ensures the user has ANY of the given roles or permissions. Returns the subject. */
|
|
131
|
+
requireRoleOrPermission<const S extends Many<string>, G2 extends string = G>(items: S & CheckNames<S, PermissionName<T, G2> | RoleName<T, G2>>, opts?: RequireOptions<CheckGuard<T, G2>>): Promise<Subject>;
|
|
132
|
+
/** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */
|
|
133
|
+
withPermission<const S extends Many<string>, Args extends unknown[], R, G2 extends string = G>(permission: S & CheckNames<S, PermissionName<T, G2>>, action: (...args: Args) => MaybePromise<R>, scope?: ScopeOptions<CheckGuard<T, G2>> | undefined): (...args: Args) => Promise<R>;
|
|
134
|
+
/** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */
|
|
135
|
+
withRole<const S extends Many<string>, Args extends unknown[], R, G2 extends string = G>(role: S & CheckNames<S, RoleName<T, G2>>, action: (...args: Args) => MaybePromise<R>, scope?: ScopeOptions<CheckGuard<T, G2>> | undefined): (...args: Args) => Promise<R>;
|
|
136
|
+
/**
|
|
137
|
+
* Wraps a route handler. Responds `401` (guest) or `403` (missing role/permission) with a JSON body.
|
|
138
|
+
* Mirrors spatie's `permission`, `role` and `role_or_permission` middleware.
|
|
139
|
+
*/
|
|
140
|
+
withRbac<Args extends unknown[], const O extends WithRbacOptions>(handler: (...args: Args) => MaybePromise<Response>, options: O & CheckRequirement<O, T, OptionsGuard<O, G>>): (...args: Args) => Promise<Response>;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* What `createNextRbac()` returns: {@link NextRbac} for an engine without per-guard names (as in 1.1), and
|
|
144
|
+
* {@link ScopedNextRbac} for one with `guards`.
|
|
145
|
+
*/
|
|
146
|
+
type NextRbacFor<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> = T extends {
|
|
147
|
+
guards: object;
|
|
148
|
+
} ? ScopedNextRbac<T, G> : NextRbac<T>;
|
|
94
149
|
|
|
95
150
|
/**
|
|
96
151
|
* Server-side helpers for the Next.js App Router (server components, server actions, route handlers).
|
|
@@ -107,8 +162,11 @@ interface NextRbac<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
|
107
162
|
* ```
|
|
108
163
|
*
|
|
109
164
|
* With a typed engine (`createRbac<AppTypes>(...)`), names are checked: `requirePermission('typo')` is a type error.
|
|
165
|
+
* With per-guard names, the helpers take the names of the `guard` option (the default guard's without it).
|
|
110
166
|
*/
|
|
111
|
-
declare function createNextRbac<T extends RbacTypeConfig = DefaultRbacTypes
|
|
167
|
+
declare function createNextRbac<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>>(options: NextRbacOptions<T, G> & (T extends {
|
|
168
|
+
guards: object;
|
|
169
|
+
} ? GuardOptions<CheckGuard<T, G>> : unknown)): NextRbacFor<T, ScopedGuardName<T, G>>;
|
|
112
170
|
|
|
113
171
|
/** Thrown by `withPermission()` / `withRole()` wrapped server actions when access is denied. */
|
|
114
172
|
declare class RbacUnauthorizedError extends Error {
|
|
@@ -119,4 +177,4 @@ declare class RbacUnauthorizedError extends Error {
|
|
|
119
177
|
constructor(reason: FailureReason, message?: string);
|
|
120
178
|
}
|
|
121
179
|
|
|
122
|
-
export { type AuthorizeResult, FailureReason, type ForbiddenReason, MaybePromise, type NextRbac, type NextRbacOptions, RbacUnauthorizedError, type RequireOptions, Requirement, type WithRbacOptions, createNextRbac, forbiddenMessage };
|
|
180
|
+
export { type AuthorizeResult, FailureReason, type ForbiddenReason, MaybePromise, type NextRbac, type NextRbacFor, type NextRbacOptions, RbacUnauthorizedError, type RequireOptions, Requirement, type ScopedNextRbac, type WithRbacOptions, createNextRbac, forbiddenMessage };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Subject, RbacTypeConfig, DefaultRbacTypes, Rbac, CheckRequirementName, PermissionName, RoleName, ScopeOptions, RbacSnapshot, Many, TeamId } from '@anievo-id/rbac-evolution';
|
|
1
|
+
import { Subject, RbacTypeConfig, DefaultRbacTypes, Rbac, DefaultGuardName, CheckRequirementName, PermissionName, RoleName, CheckRequirementGuard, ScopeOptions, RbacSnapshot, Many, CheckGuard, TeamId, GuardOptions, ScopedGuardName } from '@anievo-id/rbac-evolution';
|
|
2
2
|
import { R as Requirement, M as MaybePromise, F as FailureReason } from './middleware-entry-BYLAhtrk.js';
|
|
3
3
|
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-BYLAhtrk.js';
|
|
4
4
|
|
|
@@ -7,13 +7,17 @@ type ForbiddenReason = 'permission' | 'role' | 'role_or_permission';
|
|
|
7
7
|
/** Like spatie, the message names the kind of requirement but not the role/permission names. */
|
|
8
8
|
declare function forbiddenMessage(requirement: Requirement): string;
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
/** `G` is the type of `guard`: any string by default; `createNextRbac()` infers it to type the helpers. */
|
|
11
|
+
interface NextRbacOptions<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = string> {
|
|
11
12
|
/** Your `createRbac(...)` instance. Its typed names (`createRbac<{ permissions: ...; roles: ... }>`) flow into every helper. */
|
|
12
13
|
rbac: Rbac<T>;
|
|
13
14
|
/** Resolves the current user (e.g. from Auth.js `auth()`). Return `null` for guests. */
|
|
14
15
|
getSubject: () => MaybePromise<Subject | null | undefined>;
|
|
15
|
-
/**
|
|
16
|
-
|
|
16
|
+
/**
|
|
17
|
+
* Default guard for every check. Default: the rbac instance's `defaultGuard`. With per-guard names, it must be
|
|
18
|
+
* one of the typed guards (checked by `createNextRbac()`), and the helpers take its names.
|
|
19
|
+
*/
|
|
20
|
+
guard?: G | undefined;
|
|
17
21
|
/** Default team for every check — a value, or a function (e.g. reading the current tenant). */
|
|
18
22
|
team?: TeamId | (() => MaybePromise<TeamId | undefined>);
|
|
19
23
|
/** Where `require*()` redirects guests. Without it, guests get `notFound()`. */
|
|
@@ -23,8 +27,8 @@ interface NextRbacOptions<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
|
23
27
|
/** Replaces the default `notFound()` of `require*()` (must throw, e.g. `() => forbidden()`). */
|
|
24
28
|
onUnauthorized?: (() => never) | undefined;
|
|
25
29
|
}
|
|
26
|
-
/** Per-call options for `require*()`. */
|
|
27
|
-
interface RequireOptions extends ScopeOptions {
|
|
30
|
+
/** Per-call options for `require*()`. `G` is the type of `guard` (see `ScopeOptions`). */
|
|
31
|
+
interface RequireOptions<G extends string = string> extends ScopeOptions<G> {
|
|
28
32
|
/** `requirePermission` / `requireRole`: require EVERY listed name instead of any (spatie v8.5 `canAll()`). */
|
|
29
33
|
all?: boolean | undefined;
|
|
30
34
|
loginUrl?: string | undefined;
|
|
@@ -51,10 +55,17 @@ type WithRbacOptions = Requirement & ScopeOptions;
|
|
|
51
55
|
type CheckNames<S, N extends string> = S extends string ? CheckRequirementName<S, N> : S extends readonly string[] ? {
|
|
52
56
|
[K in keyof S]: S[K] extends string ? CheckRequirementName<S[K], N> : S[K];
|
|
53
57
|
} : S;
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
|
|
58
|
+
/**
|
|
59
|
+
* Checks the `permission` / `role` / `roleOrPermission` names of a requirement object `Q` against the names of
|
|
60
|
+
* `T`: with per-guard names, those of guard `G`. A `guard` key in `Q` must be one of the typed guards.
|
|
61
|
+
*/
|
|
62
|
+
type CheckRequirement<Q, T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> = {
|
|
63
|
+
[K in keyof Q]: K extends 'permission' ? CheckNames<Q[K], PermissionName<T, G>> : K extends 'role' ? CheckNames<Q[K], RoleName<T, G>> : K extends 'roleOrPermission' ? CheckNames<Q[K], PermissionName<T, G> | RoleName<T, G>> : K extends 'guard' ? Q[K] extends string ? CheckRequirementGuard<T, Q[K]> : Q[K] : Q[K];
|
|
57
64
|
};
|
|
65
|
+
/** The guard a `withRbac()` options object `O` checks in: its `guard`, or `G`. */
|
|
66
|
+
type OptionsGuard<O, G extends string> = O extends {
|
|
67
|
+
readonly guard: infer X extends string;
|
|
68
|
+
} ? X : G;
|
|
58
69
|
/**
|
|
59
70
|
* The helpers returned by `createNextRbac()`. `T` comes from the `rbac` instance: with typed names,
|
|
60
71
|
* every name (including each part of a `'a|b'` list) must be one of them; untyped, any string is accepted.
|
|
@@ -91,6 +102,50 @@ interface NextRbac<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
|
91
102
|
*/
|
|
92
103
|
withRbac<Args extends unknown[], const O extends WithRbacOptions>(handler: (...args: Args) => MaybePromise<Response>, options: O & CheckRequirement<O, T>): (...args: Args) => Promise<Response>;
|
|
93
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* The helpers of `createNextRbac()` when the engine has per-guard names (`RbacTypeConfig['guards']`): like
|
|
107
|
+
* {@link NextRbac}, but `G` is the guard of the checks (the `guard` option of `createNextRbac()`, else the default
|
|
108
|
+
* guard), and a call's `{ guard }` takes the names of that guard instead: `can('orders.read', { guard: 'api' })`.
|
|
109
|
+
*/
|
|
110
|
+
interface ScopedNextRbac<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> {
|
|
111
|
+
rbac: Rbac<T>;
|
|
112
|
+
getSubject(): Promise<Subject | null>;
|
|
113
|
+
/** Non-throwing check: who is the user and do they meet the requirement? */
|
|
114
|
+
authorize<const Q extends Requirement, G2 extends string = G>(requirement: Q & CheckRequirement<Q, T, G2>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<AuthorizeResult>;
|
|
115
|
+
/** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */
|
|
116
|
+
getSnapshot(scope?: ScopeOptions): Promise<RbacSnapshot>;
|
|
117
|
+
can<G2 extends string = G>(permission: PermissionName<T, G2>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>;
|
|
118
|
+
canAny<G2 extends string = G>(permissions: Many<PermissionName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>;
|
|
119
|
+
canAll<G2 extends string = G>(permissions: Many<PermissionName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>;
|
|
120
|
+
/** `true` if the user has the role — or ANY of the roles when given an array. */
|
|
121
|
+
hasRole<G2 extends string = G>(role: Many<RoleName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>;
|
|
122
|
+
hasAllRoles<G2 extends string = G>(roles: Many<RoleName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>;
|
|
123
|
+
/**
|
|
124
|
+
* Ensures the user has the permission (or ANY of the permissions). Returns the subject.
|
|
125
|
+
* Guests: `redirect(loginUrl)` or `notFound()`. Missing permission: `notFound()`. Both configurable.
|
|
126
|
+
*/
|
|
127
|
+
requirePermission<const S extends Many<string>, G2 extends string = G>(permission: S & CheckNames<S, PermissionName<T, G2>>, opts?: RequireOptions<CheckGuard<T, G2>>): Promise<Subject>;
|
|
128
|
+
/** Ensures the user has the role (or ANY of the roles). Returns the subject. */
|
|
129
|
+
requireRole<const S extends Many<string>, G2 extends string = G>(role: S & CheckNames<S, RoleName<T, G2>>, opts?: RequireOptions<CheckGuard<T, G2>>): Promise<Subject>;
|
|
130
|
+
/** Ensures the user has ANY of the given roles or permissions. Returns the subject. */
|
|
131
|
+
requireRoleOrPermission<const S extends Many<string>, G2 extends string = G>(items: S & CheckNames<S, PermissionName<T, G2> | RoleName<T, G2>>, opts?: RequireOptions<CheckGuard<T, G2>>): Promise<Subject>;
|
|
132
|
+
/** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */
|
|
133
|
+
withPermission<const S extends Many<string>, Args extends unknown[], R, G2 extends string = G>(permission: S & CheckNames<S, PermissionName<T, G2>>, action: (...args: Args) => MaybePromise<R>, scope?: ScopeOptions<CheckGuard<T, G2>> | undefined): (...args: Args) => Promise<R>;
|
|
134
|
+
/** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */
|
|
135
|
+
withRole<const S extends Many<string>, Args extends unknown[], R, G2 extends string = G>(role: S & CheckNames<S, RoleName<T, G2>>, action: (...args: Args) => MaybePromise<R>, scope?: ScopeOptions<CheckGuard<T, G2>> | undefined): (...args: Args) => Promise<R>;
|
|
136
|
+
/**
|
|
137
|
+
* Wraps a route handler. Responds `401` (guest) or `403` (missing role/permission) with a JSON body.
|
|
138
|
+
* Mirrors spatie's `permission`, `role` and `role_or_permission` middleware.
|
|
139
|
+
*/
|
|
140
|
+
withRbac<Args extends unknown[], const O extends WithRbacOptions>(handler: (...args: Args) => MaybePromise<Response>, options: O & CheckRequirement<O, T, OptionsGuard<O, G>>): (...args: Args) => Promise<Response>;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* What `createNextRbac()` returns: {@link NextRbac} for an engine without per-guard names (as in 1.1), and
|
|
144
|
+
* {@link ScopedNextRbac} for one with `guards`.
|
|
145
|
+
*/
|
|
146
|
+
type NextRbacFor<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> = T extends {
|
|
147
|
+
guards: object;
|
|
148
|
+
} ? ScopedNextRbac<T, G> : NextRbac<T>;
|
|
94
149
|
|
|
95
150
|
/**
|
|
96
151
|
* Server-side helpers for the Next.js App Router (server components, server actions, route handlers).
|
|
@@ -107,8 +162,11 @@ interface NextRbac<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
|
107
162
|
* ```
|
|
108
163
|
*
|
|
109
164
|
* With a typed engine (`createRbac<AppTypes>(...)`), names are checked: `requirePermission('typo')` is a type error.
|
|
165
|
+
* With per-guard names, the helpers take the names of the `guard` option (the default guard's without it).
|
|
110
166
|
*/
|
|
111
|
-
declare function createNextRbac<T extends RbacTypeConfig = DefaultRbacTypes
|
|
167
|
+
declare function createNextRbac<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>>(options: NextRbacOptions<T, G> & (T extends {
|
|
168
|
+
guards: object;
|
|
169
|
+
} ? GuardOptions<CheckGuard<T, G>> : unknown)): NextRbacFor<T, ScopedGuardName<T, G>>;
|
|
112
170
|
|
|
113
171
|
/** Thrown by `withPermission()` / `withRole()` wrapped server actions when access is denied. */
|
|
114
172
|
declare class RbacUnauthorizedError extends Error {
|
|
@@ -119,4 +177,4 @@ declare class RbacUnauthorizedError extends Error {
|
|
|
119
177
|
constructor(reason: FailureReason, message?: string);
|
|
120
178
|
}
|
|
121
179
|
|
|
122
|
-
export { type AuthorizeResult, FailureReason, type ForbiddenReason, MaybePromise, type NextRbac, type NextRbacOptions, RbacUnauthorizedError, type RequireOptions, Requirement, type WithRbacOptions, createNextRbac, forbiddenMessage };
|
|
180
|
+
export { type AuthorizeResult, FailureReason, type ForbiddenReason, MaybePromise, type NextRbac, type NextRbacFor, type NextRbacOptions, RbacUnauthorizedError, type RequireOptions, Requirement, type ScopedNextRbac, type WithRbacOptions, createNextRbac, forbiddenMessage };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/server.ts"],"names":["options"],"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,KA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,KAAA,CAAM,IAAA,GAAO,IAAA;AACrC,MAAA,OAAO,UAAU,IAAA,KAAkC;AACjD,QAAA,MAAM,MAAA,GAAS,MAAM,SAAA,CAAU,WAAA,EAA4B,KAAK,CAAA;AAChE,QAAA,IAAI,MAAA,CAAO,EAAA,EAAI,OAAO,OAAA,CAAQ,GAAG,IAAI,CAAA;AACrC,QAAA,OAAO,OAAO,MAAA,KAAW,iBAAA,GACrB,uBAAA,EAAwB,GACxB,kBAAkB,WAA0B,CAAA;AAAA,MAClD,CAAA;AAAA,IACF;AAAA,GACF;AACF","file":"index.js","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 {\n CheckRequirementName,\n DefaultRbacTypes,\n Many,\n PermissionName,\n Rbac,\n RbacSnapshot,\n RbacTypeConfig,\n RoleName,\n ScopeOptions,\n Subject,\n TeamId,\n} from '@anievo-id/rbac-evolution'\nimport { RbacUnauthorizedError } from './errors'\nimport { forbiddenResponse, unauthenticatedResponse } from './responses'\nimport { checkRequirement, type FailureReason, type MaybePromise, type Requirement } from './types'\n\nexport interface NextRbacOptions<T extends RbacTypeConfig = DefaultRbacTypes> {\n /** Your `createRbac(...)` instance. Its typed names (`createRbac<{ permissions: ...; roles: ... }>`) flow into every helper. */\n rbac: Rbac<T>\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 | undefined\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 | undefined\n /** Replaces the default guest handling of `require*()` (must throw, e.g. `() => redirect('/login')`). */\n onUnauthenticated?: (() => never) | undefined\n /** Replaces the default `notFound()` of `require*()` (must throw, e.g. `() => forbidden()`). */\n onUnauthorized?: (() => never) | undefined\n}\n\n/** Per-call options for `require*()`. */\nexport interface RequireOptions extends ScopeOptions {\n /** `requirePermission` / `requireRole`: require EVERY listed name instead of any (spatie v8.5 `canAll()`). */\n all?: boolean | undefined\n loginUrl?: string | undefined\n onUnauthenticated?: (() => never) | undefined\n onUnauthorized?: (() => never) | undefined\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/**\n * Checks a name, a `'a|b'` pipe list or an array of them against the names `N`.\n * Any name passes when `N` is `string` (an untyped engine).\n */\nexport type CheckNames<S, N extends string> = S extends string\n ? CheckRequirementName<S, N>\n : S extends readonly string[]\n ? { [K in keyof S]: S[K] extends string ? CheckRequirementName<S[K], N> : S[K] }\n : S\n\n/** Checks the `permission` / `role` / `roleOrPermission` names of a requirement object `Q` against the names of `T`. */\nexport type CheckRequirement<Q, T extends RbacTypeConfig> = {\n [K in keyof Q]: K extends 'permission'\n ? CheckNames<Q[K], PermissionName<T>>\n : K extends 'role'\n ? CheckNames<Q[K], RoleName<T>>\n : K extends 'roleOrPermission'\n ? CheckNames<Q[K], PermissionName<T> | RoleName<T>>\n : Q[K]\n}\n\n/**\n * The helpers returned by `createNextRbac()`. `T` comes from the `rbac` instance: with typed names,\n * every name (including each part of a `'a|b'` list) must be one of them; untyped, any string is accepted.\n */\nexport interface NextRbac<T extends RbacTypeConfig = DefaultRbacTypes> {\n rbac: Rbac<T>\n getSubject(): Promise<Subject | null>\n /** Non-throwing check: who is the user and do they meet the requirement? */\n authorize<const Q extends Requirement>(\n requirement: Q & CheckRequirement<Q, T>,\n scope?: ScopeOptions,\n ): Promise<AuthorizeResult>\n /** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */\n getSnapshot(scope?: ScopeOptions): Promise<RbacSnapshot>\n can(permission: PermissionName<T>, scope?: ScopeOptions): Promise<boolean>\n canAny(permissions: Many<PermissionName<T>>, scope?: ScopeOptions): Promise<boolean>\n canAll(permissions: Many<PermissionName<T>>, scope?: ScopeOptions): Promise<boolean>\n /** `true` if the user has the role — or ANY of the roles when given an array. */\n hasRole(role: Many<RoleName<T>>, scope?: ScopeOptions): Promise<boolean>\n hasAllRoles(roles: Many<RoleName<T>>, scope?: ScopeOptions): Promise<boolean>\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<const S extends Many<string>>(\n permission: S & CheckNames<S, PermissionName<T>>,\n opts?: RequireOptions,\n ): Promise<Subject>\n /** Ensures the user has the role (or ANY of the roles). Returns the subject. */\n requireRole<const S extends Many<string>>(role: S & CheckNames<S, RoleName<T>>, opts?: RequireOptions): Promise<Subject>\n /** Ensures the user has ANY of the given roles or permissions. Returns the subject. */\n requireRoleOrPermission<const S extends Many<string>>(\n items: S & CheckNames<S, PermissionName<T> | RoleName<T>>,\n opts?: RequireOptions,\n ): Promise<Subject>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */\n withPermission<const S extends Many<string>, Args extends unknown[], R>(\n permission: S & CheckNames<S, PermissionName<T>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions | undefined,\n ): (...args: Args) => Promise<R>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */\n withRole<const S extends Many<string>, Args extends unknown[], R>(\n role: S & CheckNames<S, RoleName<T>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions | undefined,\n ): (...args: Args) => Promise<R>\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[], const O extends WithRbacOptions>(\n handler: (...args: Args) => MaybePromise<Response>,\n options: O & CheckRequirement<O, T>,\n ): (...args: Args) => Promise<Response>\n}\n\nexport { forbiddenMessage } from './responses'\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 *\n * With a typed engine (`createRbac<AppTypes>(...)`), names are checked: `requirePermission('typo')` is a type error.\n */\nexport function createNextRbac<T extends RbacTypeConfig = DefaultRbacTypes>(options: NextRbacOptions<T>): NextRbac<T> {\n // The implementation is untyped (plain `string` names); `NextRbac<T>` adds the typed signatures.\n const helpers = buildNextRbac(options as unknown as NextRbacOptions) satisfies Record<keyof NextRbac, unknown>\n return helpers as unknown as NextRbac<T>\n}\n\nfunction buildNextRbac(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 return checkRequirement(requirement, (n) => s.can(n), (n) => s.hasRole(n))\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 | undefined,\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?.all && { all: true }) }, 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?.all && { all: true }) }, 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 | undefined,\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 | undefined,\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 ? unauthenticatedResponse()\n : forbiddenResponse(requirement as Requirement)\n }\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/server.ts"],"names":["options"],"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;;;AC8MA,IAAM,iBAA+B,EAAE,KAAA,EAAO,EAAC,EAAG,WAAA,EAAa,EAAC,EAAE;AAqB3D,SAAS,eACd,OAAA,EACuC;AAEvC,EAAA,MAAM,OAAA,GAAU,cAAc,OAAqC,CAAA;AACnE,EAAA,OAAO,OAAA;AACT;AAEA,S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;AAAA,IAChE,CAAA;AAAA;AAAA,IAGA,uBAAA,CAAwB,OAAqB,IAAA,EAAyC;AACpF,MAAA,OAAO,OAAA,CAAQ,EAAE,gBAAA,EAAkB,KAAA,IAAS,IAAI,CAAA;AAAA,IAClD,CAAA;AAAA;AAAA,IAGA,cAAA,CACE,UAAA,EACA,MAAA,EACA,KAAA,EAC+B;AAC/B,MAAA,OAAO,WAAA,CAAY,EAAE,UAAA,EAAW,EAAG,QAAQ,KAAK,CAAA;AAAA,IAClD,CAAA;AAAA;AAAA,IAGA,QAAA,CACE,IAAA,EACA,MAAA,EACA,KAAA,EAC+B;AAC/B,MAAA,OAAO,WAAA,CAAY,EAAE,IAAA,EAAK,EAAG,QAAQ,KAAK,CAAA;AAAA,IAC5C,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMA,QAAA,CACE,SACAA,QAAAA,EACsC;AACtC,MAAA,MAAM,EAAE,KAAA,EAAO,IAAA,EAAM,GAAG,aAAY,GAAIA,QAAAA;AACxC,MAAA,MAAM,QAAsB,EAAC;AAC7B,MAAA,IAAI,KAAA,KAAU,MAAA,EAAW,KAAA,CAAM,KAAA,GAAQ,KAAA;AACvC,MAAA,IAAI,IAAA,KAAS,MAAA,EAAW,KAAA,CAAM,IAAA,GAAO,IAAA;AACrC,MAAA,OAAO,UAAU,IAAA,KAAkC;AACjD,QAAA,MAAM,MAAA,GAAS,MAAM,SAAA,CAAU,WAAA,EAA4B,KAAK,CAAA;AAChE,QAAA,IAAI,MAAA,CAAO,EAAA,EAAI,OAAO,OAAA,CAAQ,GAAG,IAAI,CAAA;AACrC,QAAA,OAAO,OAAO,MAAA,KAAW,iBAAA,GACrB,uBAAA,EAAwB,GACxB,kBAAkB,WAA0B,CAAA;AAAA,MAClD,CAAA;AAAA,IACF;AAAA,GACF;AACF","file":"index.js","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 {\n CheckGuard,\n CheckRequirementGuard,\n CheckRequirementName,\n DefaultGuardName,\n DefaultRbacTypes,\n GuardOptions,\n Many,\n PermissionName,\n Rbac,\n RbacSnapshot,\n RbacTypeConfig,\n RoleName,\n ScopedGuardName,\n ScopeOptions,\n Subject,\n TeamId,\n} from '@anievo-id/rbac-evolution'\nimport { RbacUnauthorizedError } from './errors'\nimport { forbiddenResponse, unauthenticatedResponse } from './responses'\nimport { checkRequirement, type FailureReason, type MaybePromise, type Requirement } from './types'\n\n/** `G` is the type of `guard`: any string by default; `createNextRbac()` infers it to type the helpers. */\nexport interface NextRbacOptions<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = string> {\n /** Your `createRbac(...)` instance. Its typed names (`createRbac<{ permissions: ...; roles: ... }>`) flow into every helper. */\n rbac: Rbac<T>\n /** Resolves the current user (e.g. from Auth.js `auth()`). Return `null` for guests. */\n getSubject: () => MaybePromise<Subject | null | undefined>\n /**\n * Default guard for every check. Default: the rbac instance's `defaultGuard`. With per-guard names, it must be\n * one of the typed guards (checked by `createNextRbac()`), and the helpers take its names.\n */\n guard?: G | undefined\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 | undefined\n /** Replaces the default guest handling of `require*()` (must throw, e.g. `() => redirect('/login')`). */\n onUnauthenticated?: (() => never) | undefined\n /** Replaces the default `notFound()` of `require*()` (must throw, e.g. `() => forbidden()`). */\n onUnauthorized?: (() => never) | undefined\n}\n\n/** Per-call options for `require*()`. `G` is the type of `guard` (see `ScopeOptions`). */\nexport interface RequireOptions<G extends string = string> extends ScopeOptions<G> {\n /** `requirePermission` / `requireRole`: require EVERY listed name instead of any (spatie v8.5 `canAll()`). */\n all?: boolean | undefined\n loginUrl?: string | undefined\n onUnauthenticated?: (() => never) | undefined\n onUnauthorized?: (() => never) | undefined\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/**\n * Checks a name, a `'a|b'` pipe list or an array of them against the names `N`.\n * Any name passes when `N` is `string` (an untyped engine).\n */\nexport type CheckNames<S, N extends string> = S extends string\n ? CheckRequirementName<S, N>\n : S extends readonly string[]\n ? { [K in keyof S]: S[K] extends string ? CheckRequirementName<S[K], N> : S[K] }\n : S\n\n/**\n * Checks the `permission` / `role` / `roleOrPermission` names of a requirement object `Q` against the names of\n * `T`: with per-guard names, those of guard `G`. A `guard` key in `Q` must be one of the typed guards.\n */\nexport type CheckRequirement<Q, T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> = {\n [K in keyof Q]: K extends 'permission'\n ? CheckNames<Q[K], PermissionName<T, G>>\n : K extends 'role'\n ? CheckNames<Q[K], RoleName<T, G>>\n : K extends 'roleOrPermission'\n ? CheckNames<Q[K], PermissionName<T, G> | RoleName<T, G>>\n : K extends 'guard'\n ? Q[K] extends string\n ? CheckRequirementGuard<T, Q[K]>\n : Q[K]\n : Q[K]\n}\n\n/** The guard a `withRbac()` options object `O` checks in: its `guard`, or `G`. */\nexport type OptionsGuard<O, G extends string> = O extends { readonly guard: infer X extends string } ? X : G\n\n/**\n * The helpers returned by `createNextRbac()`. `T` comes from the `rbac` instance: with typed names,\n * every name (including each part of a `'a|b'` list) must be one of them; untyped, any string is accepted.\n */\nexport interface NextRbac<T extends RbacTypeConfig = DefaultRbacTypes> {\n rbac: Rbac<T>\n getSubject(): Promise<Subject | null>\n /** Non-throwing check: who is the user and do they meet the requirement? */\n authorize<const Q extends Requirement>(\n requirement: Q & CheckRequirement<Q, T>,\n scope?: ScopeOptions,\n ): Promise<AuthorizeResult>\n /** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */\n getSnapshot(scope?: ScopeOptions): Promise<RbacSnapshot>\n can(permission: PermissionName<T>, scope?: ScopeOptions): Promise<boolean>\n canAny(permissions: Many<PermissionName<T>>, scope?: ScopeOptions): Promise<boolean>\n canAll(permissions: Many<PermissionName<T>>, scope?: ScopeOptions): Promise<boolean>\n /** `true` if the user has the role — or ANY of the roles when given an array. */\n hasRole(role: Many<RoleName<T>>, scope?: ScopeOptions): Promise<boolean>\n hasAllRoles(roles: Many<RoleName<T>>, scope?: ScopeOptions): Promise<boolean>\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<const S extends Many<string>>(\n permission: S & CheckNames<S, PermissionName<T>>,\n opts?: RequireOptions,\n ): Promise<Subject>\n /** Ensures the user has the role (or ANY of the roles). Returns the subject. */\n requireRole<const S extends Many<string>>(role: S & CheckNames<S, RoleName<T>>, opts?: RequireOptions): Promise<Subject>\n /** Ensures the user has ANY of the given roles or permissions. Returns the subject. */\n requireRoleOrPermission<const S extends Many<string>>(\n items: S & CheckNames<S, PermissionName<T> | RoleName<T>>,\n opts?: RequireOptions,\n ): Promise<Subject>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */\n withPermission<const S extends Many<string>, Args extends unknown[], R>(\n permission: S & CheckNames<S, PermissionName<T>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions | undefined,\n ): (...args: Args) => Promise<R>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */\n withRole<const S extends Many<string>, Args extends unknown[], R>(\n role: S & CheckNames<S, RoleName<T>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions | undefined,\n ): (...args: Args) => Promise<R>\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[], const O extends WithRbacOptions>(\n handler: (...args: Args) => MaybePromise<Response>,\n options: O & CheckRequirement<O, T>,\n ): (...args: Args) => Promise<Response>\n}\n\n/**\n * The helpers of `createNextRbac()` when the engine has per-guard names (`RbacTypeConfig['guards']`): like\n * {@link NextRbac}, but `G` is the guard of the checks (the `guard` option of `createNextRbac()`, else the default\n * guard), and a call's `{ guard }` takes the names of that guard instead: `can('orders.read', { guard: 'api' })`.\n */\nexport interface ScopedNextRbac<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> {\n rbac: Rbac<T>\n getSubject(): Promise<Subject | null>\n /** Non-throwing check: who is the user and do they meet the requirement? */\n authorize<const Q extends Requirement, G2 extends string = G>(\n requirement: Q & CheckRequirement<Q, T, G2>,\n scope?: ScopeOptions<CheckGuard<T, G2>>,\n ): Promise<AuthorizeResult>\n /** Roles & permissions of the current user — pass to `<RbacProvider snapshot={...}>`. Guests get an empty snapshot. */\n getSnapshot(scope?: ScopeOptions): Promise<RbacSnapshot>\n can<G2 extends string = G>(permission: PermissionName<T, G2>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>\n canAny<G2 extends string = G>(permissions: Many<PermissionName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>\n canAll<G2 extends string = G>(permissions: Many<PermissionName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>\n /** `true` if the user has the role — or ANY of the roles when given an array. */\n hasRole<G2 extends string = G>(role: Many<RoleName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>\n hasAllRoles<G2 extends string = G>(roles: Many<RoleName<T, G2>>, scope?: ScopeOptions<CheckGuard<T, G2>>): Promise<boolean>\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<const S extends Many<string>, G2 extends string = G>(\n permission: S & CheckNames<S, PermissionName<T, G2>>,\n opts?: RequireOptions<CheckGuard<T, G2>>,\n ): Promise<Subject>\n /** Ensures the user has the role (or ANY of the roles). Returns the subject. */\n requireRole<const S extends Many<string>, G2 extends string = G>(\n role: S & CheckNames<S, RoleName<T, G2>>,\n opts?: RequireOptions<CheckGuard<T, G2>>,\n ): Promise<Subject>\n /** Ensures the user has ANY of the given roles or permissions. Returns the subject. */\n requireRoleOrPermission<const S extends Many<string>, G2 extends string = G>(\n items: S & CheckNames<S, PermissionName<T, G2> | RoleName<T, G2>>,\n opts?: RequireOptions<CheckGuard<T, G2>>,\n ): Promise<Subject>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the permission (or ANY of them). */\n withPermission<const S extends Many<string>, Args extends unknown[], R, G2 extends string = G>(\n permission: S & CheckNames<S, PermissionName<T, G2>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions<CheckGuard<T, G2>> | undefined,\n ): (...args: Args) => Promise<R>\n /** Wraps a server action; throws `RbacUnauthorizedError` unless the user has the role (or ANY of them). */\n withRole<const S extends Many<string>, Args extends unknown[], R, G2 extends string = G>(\n role: S & CheckNames<S, RoleName<T, G2>>,\n action: (...args: Args) => MaybePromise<R>,\n scope?: ScopeOptions<CheckGuard<T, G2>> | undefined,\n ): (...args: Args) => Promise<R>\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[], const O extends WithRbacOptions>(\n handler: (...args: Args) => MaybePromise<Response>,\n options: O & CheckRequirement<O, T, OptionsGuard<O, G>>,\n ): (...args: Args) => Promise<Response>\n}\n\n/**\n * What `createNextRbac()` returns: {@link NextRbac} for an engine without per-guard names (as in 1.1), and\n * {@link ScopedNextRbac} for one with `guards`.\n */\nexport type NextRbacFor<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> = T extends {\n guards: object\n}\n ? ScopedNextRbac<T, G>\n : NextRbac<T>\n\nexport { forbiddenMessage } from './responses'\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 *\n * With a typed engine (`createRbac<AppTypes>(...)`), names are checked: `requirePermission('typo')` is a type error.\n * With per-guard names, the helpers take the names of the `guard` option (the default guard's without it).\n */\nexport function createNextRbac<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>>(\n options: NextRbacOptions<T, G> & (T extends { guards: object } ? GuardOptions<CheckGuard<T, G>> : unknown),\n): NextRbacFor<T, ScopedGuardName<T, G>> {\n // The implementation is untyped (plain `string` names); `NextRbac<T>` adds the typed signatures.\n const helpers = buildNextRbac(options as unknown as NextRbacOptions) satisfies Record<keyof NextRbac, unknown>\n return helpers as unknown as NextRbacFor<T, ScopedGuardName<T, G>>\n}\n\nfunction buildNextRbac(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 return checkRequirement(requirement, (n) => s.can(n), (n) => s.hasRole(n))\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 | undefined,\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?.all && { all: true }) }, 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?.all && { all: true }) }, 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 | undefined,\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 | undefined,\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 ? unauthenticatedResponse()\n : forbiddenResponse(requirement as Requirement)\n }\n },\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anievo-id/rbac-evolution-next",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.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": "^1.
|
|
60
|
+
"@anievo-id/rbac-evolution": "^1.3.0"
|
|
61
61
|
},
|
|
62
62
|
"peerDependencies": {
|
|
63
63
|
"next": ">=14",
|