Skip to Content
TelamonJS

Permissions

RBAC materialized in the JWT — pure checkers, role helpers, Nest guard, Prisma tables and catalog sync

@telamonjs/permissions (current version: 1.3.0) is the authorization system of the TelamonJS ecosystem: RBAC materialized in the JWT.

Permissions are resolved from the database once, at login, and carried in the session token as a flat permissions: string[]. Every check after that is a pure function over the token claims — no query per request, no cache to invalidate, client-safe by construction.

  • Core (isomorphic) — createPermissionChecker (can / canAny / canAll / hasBypassRole) and role helpers
  • /nest subpath — @Permissions() decorator + createPermissionsGuard()
  • Prisma RBAC tables — Role, Permission, RolePermission, UserRole to copy into your app, plus diffPermissionCatalog to keep the Permission table in step with the catalog defined in code
pnpm add @telamonjs/permissions

Dual ESM+CJS build; the /nest subpath expects @nestjs/common and @nestjs/core in the host.


Data Model (Prisma)

These are the tables the admin kit generates. Copy the fragment shipped with the package (exported at @telamonjs/permissions/prisma/schema.prisma) into your schema.prisma and migrate — it is a template, not a managed migration:

prisma/schema.prisma
model Role {
  id          String  @id @default(cuid())
  name        String
  code        String  @unique // "superadmin", "admin", "readonly", ...
  description String?
  system      Boolean @default(false) // built-in role: the app must not delete it

  permissions RolePermission[]
  users       UserRole[]
}

model Permission {
  id          String  @id @default(cuid())
  code        String  @unique // "module.action", e.g. "users.read"
  module      String
  action      String  // "read" | "write" | "execute" | "approve"
  category    String?
  description String?

  roles RolePermission[]

  @@index([module, action])
}

model RolePermission {
  roleId       String
  permissionId String

  role       Role       @relation(fields: [roleId], references: [id], onDelete: Cascade)
  permission Permission @relation(fields: [permissionId], references: [id], onDelete: Cascade)

  @@unique([roleId, permissionId])
  @@index([permissionId])
}

model UserRole {
  userId String
  roleId String

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
  role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)

  @@unique([userId, roleId])
  @@index([roleId])
}

Your app owns the User model: add the back-relation roles UserRole[] to it, and keep UserRole.userId the same type as User.id. action is a String holding the suffix of the code, not an enum — a new action needs no migration. Rename the models or map the tables freely; the checker only reads the permissions[] claim.

Effective permissions for a user = the union of all their roles' permissions.

Syncing the catalog

The permission catalog is defined in code; the Permission table follows it. diffPermissionCatalog(catalog, rows) compares the two by code and returns what to change — it never touches the database or its inputs:

FieldHolds
toCreateCodes in the catalog, not in the table — every column resolved, ready for createMany
toUpdateCodes in both whose description or category changed — the row's id plus the catalog's values
toDeleteRows whose code is no longer in the catalog
unchangedRows with nothing to change

module/action default to the two halves of code (split at the last dot, so reports.sales.export → reports.sales + export) and are not compared: a row stored as READ for users.read is left alone. null and a missing value are equal. A duplicate code in the catalog, or a code without a dot and no explicit module/action, throws.

Apply it in one transaction, at deploy, in a seed or when the API boots:

permissions/sync.ts
import { diffPermissionCatalog, type PermissionDefinition } from '@telamonjs/permissions'
import type { PrismaClient } from '@prisma/client'

export const PERMISSIONS: PermissionDefinition[] = [
  { code: 'users.read', category: 'Records', description: 'View users' },
  { code: 'users.write', category: 'Records', description: 'Create, edit and remove users' },
  { code: 'roles.read', category: 'Access', description: 'View roles' },
  { code: 'roles.write', category: 'Access', description: 'Edit roles and the permission matrix' },
]

export async function syncPermissions(prisma: PrismaClient) {
  const rows = await prisma.permission.findMany()
  const { toCreate, toUpdate, toDelete } = diffPermissionCatalog(PERMISSIONS, rows)

  await prisma.$transaction([
    prisma.permission.createMany({ data: toCreate }),
    ...toUpdate.map(({ id, category, description }) =>
      prisma.permission.update({ where: { id }, data: { category, description } }),
    ),
    // RolePermission rows go with them (onDelete: Cascade)
    prisma.permission.deleteMany({ where: { id: { in: toDelete.map((row) => row.id) } } }),
  ])

  return { created: toCreate.length, updated: toUpdate.length, deleted: toDelete.length }
}

Leave out the deleteMany to keep permissions that are no longer in code (an upsert-only sync). Assigning permissions to a role is a separate step: replace the role's RolePermission rows (deleteMany + createMany in a transaction).


The Flow: Resolve at Login, Check from the Token

Resolve permissions in authorize()

At login, the app materializes the user's effective permission codes and puts them in the session claims. The convention is a getPermissionsForJWT helper that takes the union of the user's roles' permissions over the tables above:

auth.ts (authorize)
async authorize(credentials) {
  const user = await verifyLogin(credentials)
  if (!user) return null

  return {
    id: user.id,
    email: user.email,
    role: user.roles[0],                 // { id, name, code }
    roles: user.roles,                   // multi-role via UserRole
    permissions: await getPermissionsForJWT(user.id),
    // → ['users.read', 'users.write', 'roles.read', ...]
  }
}
getPermissionsForJWT
async function getPermissionsForJWT(userId: string): Promise<string[]> {
  const links = await prisma.rolePermission.findMany({
    where: { role: { users: { some: { userId } } } },
    select: { permission: { select: { code: true } } },
  })
  return [...new Set(links.map((l) => l.permission.code))]
}

The Auth package's createAuthCallbacks() copies permissions into the JWT and back into the session — both the Next app and the Nest API see the same array.

Trade-off

Changes to a user's roles/permissions take effect on the next login (or forced token refresh) — the token is the snapshot. In exchange, checks cost zero queries and work identically on client, server and API.

Create the app's checker (once)

lib/permissions.ts
import { createPermissionChecker } from '@telamonjs/permissions'

const checker = createPermissionChecker({
  bypassRoles: ['superadmin'], // app domain — these roles pass every check
})

export const { can, canAny, canAll, hasBypassRole } = checker

Check anywhere

import { can, canAny } from '@/lib/permissions'

// Client Component — session.user satisfies UserWithPermissions by shape
{can(session?.user, 'clientes.create') && <CreateButton />}

// Server Action
export async function deleteCliente(id: string) {
  const session = await auth()
  if (!can(session?.user, 'clientes.delete')) {
    throw new Error('Unauthorized: clientes.delete')
  }
  // ...
}
FunctionSemantics
can(user, p)User has permission p (or a bypass role)
canAny(user, ps)Has at least one (OR)
canAll(user, ps)Has all (AND)
hasBypassRole(user)Has any configured bypass role

All are pure and null-safe (user may be null/undefined → false). An empty list (canAny(user, []), canAll(user, [])) is false too, bypass roles included: an empty requirement is a bug, not "nothing required". The UserWithPermissions type is structural on purpose: the AuthUser from the auth package satisfies it by shape, with no dependency between the packages.

Two optional settings cover apps that keep (part of) the table in code:

createPermissionChecker({
  bypassRoles: [],
  // granted by role code, merged with the user's own permissions[]
  rolePermissions: {
    teacher: ['classes.read', 'grades.write'],
    student: ['portal.access'],
  },
  wildcard: '*', // holding '*' (in the token or through rolePermissions) grants everything
})

rolePermissions reads every role in roles[] (the singular role is the fallback, as for bypassRoles). With wildcard, a user holding that code passes every check; an empty requirement list still denies. Without the options, '*' is an ordinary code. Give createPermissionsGuard the same rolePermissions/wildcard so the server agrees with the client.

A CrudConfig takes the same checker: permissions: { can: p => can(session?.user, p), create: 'clientes.create', … } gates the list's "New" button, row actions and dialogs (see Permissions). To give it once for every list and the AdminShell menu, wrap the shell in <PermissionsProvider can={…}>.


Role Helpers

Two distinct questions, two distinct helpers — do not mix them:

import {
  isAdminRole,
  isSuperAdminRole,
  hasGlobalDataVisibility,
  getPrimaryRole,
} from '@telamonjs/permissions'
HelperQuestion it answersUse for
isSuperAdminRole(role, roles)"Is this a superadmin?"Privilege gates: system roles management, impersonating admins, dangerous maintenance
hasGlobalDataVisibility(role, roles)"Can they see all records?" (admin or superadmin)Data scoping: skip the per-user visibility filter
isAdminRole(role, roles)admin or superadminBuilding block of the above
getPrimaryRole(role, roles)First role of the list (or the singular role)Display

All helpers check roles[] first (multi-role) and fall back to the singular role.


NestJS: Decorator + Guard

@Permissions — clause semantics

import { Permissions, RequirePermission } from '@telamonjs/permissions/nest'

// string clauses = OR: needs ONE of the two
@Permissions('relatorios.read', 'relatorios.export')

// array clause = AND: needs BOTH
@Permissions(['clientes.update', 'clientes.approve'])

// mixed: (a AND b) OR c
@Permissions(['clientes.update', 'clientes.approve'], 'admin.override')

RequirePermission is an alias of Permissions for projects that use that naming convention. Routes without the decorator are not restricted by the guard, unless it is created with failClosed: true (see below).

@Permissions() with no clause, or with an empty [] clause, throws when the decorator is applied. The guard denies (403) any route whose permission metadata is an empty list — whoever the user is — instead of treating it as "no decorator".

createPermissionsGuard

src/common/guards/permissions.guard.ts
import { createPermissionsGuard } from '@telamonjs/permissions/nest'

export const PermissionsGuard = createPermissionsGuard()
// options: createPermissionsGuard({ bypassRoles: ['superadmin', 'admin'], failClosed: true })
// defaults: bypassRoles ['superadmin'], failClosed false
// rolePermissions / wildcard: as in createPermissionChecker
@Get('admin')
@UseGuards(JwtAuthGuard, PermissionsGuard) // order matters
@Permissions('admin.read')
getAdminData() {}

The guard runs after the auth guard from @telamonjs/auth: it reads request.user.permissions (the array materialized in the JWT), applies the clause semantics, and throws ForbiddenException (403) with the generic message Insufficient permissions — the required codes are never sent to the client. A request without request.user gets UnauthorizedException (401). Bypass roles short-circuit to allow. It can also be registered globally via APP_GUARD after the auth guard.

failClosed — deny by default

With failClosed: true, a route that carries no @Permissions is denied (403) unless it is marked @Public(). That turns a forgotten decorator into a denial instead of an open endpoint — useful with a global APP_GUARD.

import { createPermissionsGuard, Public } from '@telamonjs/permissions/nest'

export const PermissionsGuard = createPermissionsGuard({ failClosed: true })

@Public()
@Get('health')
health() {}

Public() uses the metadata key 'isPublic', the same as Public() from @telamonjs/auth/nest, so either decorator marks a route public for both guards. Default: false — routes without the decorator stay open.

onDenied — observe denials

onDenied is called right before every 403 with { user, required, request }: the route's clauses ([] on a failClosed denial, where user may be undefined) and the raw HTTP request. The client still gets the generic Insufficient permissions.

export const PermissionsGuard = createPermissionsGuard({
  onDenied: ({ user, required }) =>
    logger.warn('permission denied', { userId: user?.id, required }),
})

It runs synchronously: a returned promise is not awaited, and an error thrown inside it replaces the 403. It is not called on a 401.

createException — throw the host's exceptions

createException?: (status: 401 | 403, message: string) => Error builds the 401 and 403 the guard throws. Leave it out and the guard throws UnauthorizedException/ForbiddenException from the package's @nestjs/common; set it when the package is linked and that copy is not the host's — see NestJS guard exceptions across package instances. The JWT guard of @telamonjs/auth takes the same option, so one function serves both.


Troubleshooting

can() returns false for a permission the user clearly has

The token predates the grant — permissions are materialized at login. Have the user log out/in, or implement token refresh. Verify by logging session.user.permissions.

Guard throws "User not authenticated" (401)

PermissionsGuard ran without JwtAuthGuard before it — nothing attached request.user. Check guard order.

Every check passes for some users

They hold a bypass role. bypassRoles is configured per app in createPermissionChecker / createPermissionsGuard — make sure the list is what you intend (default for the guard: ['superadmin']).

permissions is empty in the token

The login path never called the resolution helper, or the auth callbacks dropped the claim — see the auth troubleshooting.


On this page