Aviary

RBAC (roles & permissions)

Persisted roles and permissions as official policies — RolePolicy, PermissionPolicy, @Roles / @Permission, the provider seams, and the typeorm / mikro-orm / prisma / drizzle adapters.

The official @nestjs/authorization has policies but no roles or permissions. This package adds them as official policies the official guard runs like any other: RolePolicy and PermissionPolicy. The core reads roles and permissions through two optional seams and has zero database; persistence is an opt-in ORM adapter.

On routes: RolePolicy and PermissionPolicy

import { Can } from '@nestjs/authorization';
import { Permission, PermissionPolicy, RolePolicy, Roles, permission, roles } from '@dudousxd/nestjs-authz';

@Roles('admin', 'editor')                                   // any of = @Can(RolePolicy, 'has', roles(...))
@Can(RolePolicy, 'hasAll', roles('admin', 'editor'))       // all of
@Permission('posts.publish')                               // any of; posts.* grants it
@Can(PermissionPolicy, 'hasAll', permission('posts.publish', 'posts.delete'))

roles() and permission() (alias permissions()) return static resolvers: their arguments are on a non-enumerable Symbol.for('@dudousxd/static-can-args') property, so a requirement can be evaluated without a request. Both policies extend AuthzPolicy and ask only superAdmin in before() (not the external engine: their abilities name roles and permissions, not resources).

In services:

await gate.forUser(user).allows(PermissionPolicy, 'has', 'posts.publish');
await gate.forUser(user).allows('posts.publish');   // a named ability no policy defines
await gate.forUser(user).hasRole('editor');         // a plain fact: superAdmin does not apply

The policy has the final word

A permission only grants named abilities that no policy defines. Holding a permission called update does not let gate.allows('update', post) bypass PostPolicy, and a viewAny permission does not widen PostPolicy.scope(). Only superAdmin short-circuits a policy.

Where roles come from

The union of:

  1. the user object — user.roles (string[]) or user.role (string | string[]), through defaultRoleResolver; override with AuthzModule.forRoot({ resolveRoles: (user) => [...] }). Works with zero tables;
  2. a RoleProvider under ROLE_PROVIDER — supplied by an adapter.

The permission seam

export interface PermissionProvider {
  hasPermission(user: User, permission: string, resource?: object): boolean | Promise<boolean>;
  // optional: every permission the user holds, for wildcard matching and per-request caching
  getPermissions?(user: User): Iterable<string> | undefined | Promise<Iterable<string> | undefined>;
  // optional: true when getPermissions lists everything hasPermission could grant
  readonly exhaustivePermissions?: boolean;
}

Registered under PERMISSION_PROVIDER. Grant-only: false never denies, it falls through.

Wildcards and per-request caching

With getPermissions, the core matches segment by segment, the same for every adapter: posts.* satisfies posts.update, * satisfies anything (permissionSatisfied, CompiledPermissions). Without it, hasPermission is an exact-match check.

Inside one request (a @dudousxd/nestjs-context store), a user's permission set and provider roles are fetched once, however many checks run: the official guard's RolePolicy / PermissionPolicy and the handler's Gate calls share the fetch. Without a store, each check fetches on its own, and an allowsMany batch shares one fetch.

When the cached set misses:

  • exhaustivePermissions: true — the answer is "no grant" with no further query. The four ORM adapters' providers and FakePermissionProvider set it.
  • Unset — hasPermission(user, permission, resource) is still asked (it may grant more than the set lists).

Entries live for the request: a grant or revocation mid-request applies from the next one. Copies of one user share an entry when the user names its row (an id plus a string type or a class of its own). A plain object without type ({ id: 1 }) is keyed by identity, so two users that only share an id never share permissions or roles.

You rarely register the seams by hand; an adapter provides both:

{ provide: ROLE_PROVIDER, useClass: MyRoleProvider }
{ provide: PERMISSION_PROVIDER, useClass: MyPermissionProvider }

Adding persistence

When you want roles and permissions stored in your database, install the adapter for your ORM. It provides the RoleProvider/PermissionProvider implementations and manages the schema.

pnpm add @dudousxd/nestjs-authz-typeorm

The adapter's AuthzRbacModule maps the official guard's user to a store ref with userRefFrom (default { type, id } or { id }). Requires NestJS 12, @nestjs/authorization, @dudousxd/nestjs-authz 0.10+ and Node 24+.

The store is a plain object

Following the ecosystem convention, the store is a POJO that receives your database connection in its constructor — it is not an @Injectable, and it owns no internal DI token. You construct it with the connection you already have, which keeps the adapter from fighting your ORM setup:

import { TypeOrmAuthzStore } from '@dudousxd/nestjs-authz-typeorm';
import { DataSource } from 'typeorm';

const store = new TypeOrmAuthzStore(dataSource, { /* options */ });

You then hand the store to the RBAC module. When the connection is registered with NestJS's @nestjs/typeorm or @nestjs/drizzle, name it and the module builds the store from the official token (getDataSourceToken(name) / getDrizzleToken(name)):

import { AuthzRbacModule } from '@dudousxd/nestjs-authz-typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({ /* ... */ }),
    AuthzRbacModule.forRoot({
      connectionName: 'default', // or the `name` the connection was registered under
      storeOptions: { schema: 'auth' }, // optional: Postgres schema, tableNames
      autoCreateSchema: true, // default for TypeORM; non-destructive (see below)
    }),
  ],
})
export class AppModule {}

forRootAsync({ connectionName, storeOptions, useFactory }) takes the same connectionName; its factory returns the other options (userRefFrom, autoCreateSchema). @nestjs/typeorm and @nestjs/drizzle are optional peers. Otherwise build the store from any connection yourself and pass it as store, the app owning the token:

import { AuthzRbacModule, TypeOrmAuthzStore } from '@dudousxd/nestjs-authz-typeorm';
import { DataSource } from 'typeorm';

@Module({
  imports: [
    AuthzRbacModule.forRootAsync({
      inject: [DataSource], // your connection's token
      useFactory: (ds: DataSource) => ({
        store: new TypeOrmAuthzStore(ds, { schema: 'auth' }),
      }),
    }),
  ],
})
export class AppModule {}

Schema management

The adapters expose schema helpers so you can let the library create tables or manage them yourself:

  • autoCreateSchema: true (default) runs ensureAuthzSchema at boot. It creates any missing table and adds any missing column — and it is strictly non-destructive: it never drops or alters existing data, and post-v1 columns are added nullable or with defaults. This is ideal for getting started.
  • autoCreateSchema: false leaves the schema entirely to you. Use the exported helpers (createAuthzTables, ensureAuthzSchema) inside your own migrations, or hand-roll the tables. The entity classes (RoleEntity, PermissionEntity, RolePermissionEntity, UserRoleEntity) are exported so you can register them with your ORM's migration tooling.

autoCreateSchema: true is convenient for development and small deployments, but for production with a migration workflow, set it to false and apply schema changes through your migration pipeline so changes are reviewed and versioned.

Adapter specifics:

  • TypeORM — TypeOrmAuthzStore, schema via ensureAuthzSchema.
  • MikroORM — applies updates through getUpdateSchemaSQL({ safe: true }), so generated DDL is non-destructive by construction.
  • Prisma — consumer-managed: Prisma owns the schema, so you add the models to your schema.prisma and run prisma migrate; the adapter reads/writes through your PrismaClient.
  • Drizzle (Postgres) — DrizzleAuthzStore(db). createAuthzTables({ tableNames, schema }) returns the tables as pgTables. Spread them into your drizzle-kit schema and pass the same object to the store ({ tables }), and drizzle-kit owns the migration. Because the schema is usually drizzle-kit's, autoCreateSchema defaults to false here. Turn it on to run the idempotent CREATE ... IF NOT EXISTS instead. The package also compiles gate.scope(Entity) into a Drizzle WHERE: db.select().from(posts).where(await applyScope(gate.forUser(user), Post, posts)).

Database schema

Put the authz tables in their own database schema (a Postgres schema, or a MySQL database) with schema. Every statement the adapter issues names it ("authz"."authz_roles"), so the app's own tables stay in public and nothing depends on search_path.

Don't use search_path for this. Behind PgBouncer in transaction mode a SET search_path leaks to whichever request gets that connection next.

TypeORM (Postgres and MySQL):

AuthzRbacModule.forRoot({ connectionName: 'default', storeOptions: { schema: 'authz' } });

autoCreateSchema creates the schema (on MySQL, the database) when it is missing. If your DataSource synchronizes or generates migrations from entities, register authzEntities({ schema: 'authz', type: 'postgres' }) (type: 'mysql' on MySQL) instead of AUTHZ_ENTITIES. createAuthzTables(queryRunner, { schema: 'authz' }) does the same from a migration.

Drizzle (Postgres):

export const authz = createAuthzTables({ schema: 'authz' }); // pgSchema('authz') tables
AuthzRbacModule.forRoot({ store: new DrizzleAuthzStore(db, { tables: authz }) });

drizzle-kit then puts them in authz. With autoCreateSchema: true, ensureSchema creates the schema and the tables.

MikroORM (Postgres and MySQL): build the entities with the schema and register them as usual:

const authz = createAuthzEntitySchemas({}, { schema: 'authz' });
MikroOrmModule.forRoot({ entities: [...authz.all, ...appEntities] });

The store reads the schema from the entity metadata. autoCreateSchema creates the schema (on MySQL, the database) and the tables, and authzSchemaSql() gives the same statements for a migration.

Prisma (Postgres): Prisma owns the schema, so turn on multiSchema and put the four models in the schema with @@schema. Then tell the store:

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["multiSchema"] // not needed on Prisma 6.13+
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
  schemas  = ["public", "authz"]
}

model AuthzRole {
  // …fields as above…
  @@map("authz_roles")
  @@schema("authz")
}
// …@@schema("authz") on AuthzPermission, AuthzRolePermission and AuthzUserRole too
AuthzRbacModule.forRoot({ client: prisma, schema: 'authz' });

The permission read then runs as one $queryRawUnsafe with the schema in the SQL and every value bound.

Rules for every adapter:

  • The name must be a plain identifier (letters, digits, _) of at most 63 characters.
  • SQLite has no schemas, so schema there fails at boot with a clear error. Prisma only supports @@schema on Postgres, so on MySQL or SQLite the Prisma store refuses schema.
  • Creating the schema needs the CREATE privilege (GRANT CREATE ON DATABASE … TO …; on MySQL, CREATE on the server). The adapters check first and only create it when it is missing. When your role can't create it, create it yourself once.
  • Without schema, nothing changes.

Role sources (manual vs SSO/SCIM)

Every role assignment records a source. It defaults to 'manual', so existing calls and rows keep their meaning. setUserRoles replaces only that source's assignments, so an SSO sync never removes a role an admin granted by hand:

// On each SSO login: exactly these roles come from SSO. Manual grants are untouched.
await store.setUserRoles(user, rolesFromIdpGroups, { source: 'sso', tenantId });

await store.assignRole(user, 'editor', { source: 'scim' });
await store.removeRole(user, 'editor', { source: 'scim' }); // without `source`: removed from every source
await store.getRoleAssignments(user); // [{ role, source, tenantId }]

Adapter notes:

  • Existing databases: schema sync adds the source column, and existing rows become manual assignments. It never rewrites a primary key. Widening the key so that one role can come from two sources is a one-time migration; each adapter's changelog and README have the SQL.
  • Prisma: this is opt-in with roleSources: true after you add source String @default("manual") to UserRole and its @@id.

Admin management

Every store has the same operations for an admin UI: syncRolePermissions(role, names) replaces a role's permission set, getRolePermissions(roles) returns { [role]: permissionNames } (missing roles absent), deleteRole(role) removes a role with its links and assignments, listRoleAssignments({ tenantId?, role?, user?, source? }) lists raw { userType, userId, role, source, tenantId } rows (tenantId: null = global only, a string = that tenant's scoped rows only), and removeUser(user) drops all of a user's assignments.

Tenant-scoped permissions

A role can be assigned globally (it applies in every tenant) or inside one tenant:

await store.assignRole(user, 'editor', { tenantId: 'acme' }); // only inside acme
await store.assignRole(user, 'viewer');                        // everywhere
await store.getRolesForUser(user, { tenantId: 'acme' });      // ['editor', 'viewer']
await store.getRolesForUser(user);                            // ['viewer']

The TypeORM and Drizzle adapters store tenant-scoped assignments out of the box. MikroORM and Prisma need a tenantId column first (see Tenant column for MikroORM and Prisma).

The RBAC module picks the tenant of each check for you, so permission and role checks need no tenant argument. In order:

  1. Your tenant resolver, when you configure one (below).
  2. With tenancy on, the request's tenant from @dudousxd/nestjs-context.
  3. With tenancy off, TypeORM and Drizzle read the plain Context.tenantId(), and MikroORM and Prisma check global assignments only.

Tenancy

Tenancy follows the switch in ContextModule.forRoot({ tenancy: { enabled: true } }). Your app sets the tenant of each request with Context.setTenant(...) (see the context Tenancy page), and every check is then scoped to it:

RequestAssignments that count
Has a tenantglobal ones, plus that tenant's
Has a nested tenant (a unit inside a clinic)global ones, plus those of every level of the chain the module honours
No tenant, or a tenant of a kind outside kindsglobal ones (an error with required)
Inside Context.allTenants(), or outside any requestglobal ones

Each RBAC module takes the same tenancy option:

AuthzRbacModule.forRoot({
  connectionName: 'default',
  tenancy: {
    enabled: 'inherit',         // default: follow ContextModule; true/false to override
    kinds: ['organization'],    // optional: tenant kinds this module honours
    family: 'account',          // optional: only the tenant of this family counts
    required: true,             // optional: a check with no tenant is a 403 (default: the context's)
    roles: {                    // optional: the caller's role inside the tenant → authz roles
      owner: 'org_admin',
      member: ['org_member', 'reader'],
    },
  },
});
  • tenancy: 'inherit' is the default. tenancy: false keeps the module out of tenancy even when the context turns it on.
  • roles maps tenant.role (the role you pass to Context.setTenant) to authz roles that apply in that tenant only. Their permissions come from your store, like any role: store.syncRolePermissions('org_admin', ['billing.manage']). Unmapped roles grant nothing. The mapped roles belong to the current user of the context (Context.userRef()), so gate.forUser(someoneElse) does not get them.
  • With nested tenants (Context.setTenant({ id: 'u1', kind: 'unit', chain: [clinic] })), a role assigned in the clinic also counts inside its units, and the caller's role at each level is mapped by roles. kinds picks the levels: with kinds: ['clinic', 'unit'] both count, with kinds: ['unit'] only the unit does. The level the request's tenant matched always counts, since the context only matches a level whose kind is listed.
  • required turns a check with no tenant into a TenantRequiredError (403, code: 'E_TENANT_REQUIRED') instead of a check in the global scope. Each package (context and every adapter) throws its own class, so match on error.code === 'E_TENANT_REQUIRED', not instanceof. It defaults to the context's tenancy.required. Checks that are not about tenant data never require a tenant: the Aviary console authorize helpers, the MCP dev tools, and any code you wrap in runWithoutRequiredTenant(() => …) from @dudousxd/nestjs-authz. A tenant resolver that answers, or runInTenantScope(tenantId, () => …), also never needs one.
  • nullRows is accepted for the shared shape but changes nothing here: a global assignment always applies.

To decide the tenant yourself, pass a tenant resolver. It wins over the context:

AuthzRbacModule.forRoot({
  store,
  // a tenant id, null for the global scope, or undefined to fall back to the context
  tenant: (user) => (user as { orgId?: string }).orgId,
});

Tenant column for MikroORM and Prisma

MikroORM: build the entities with tenantScoped: true. ensureSchema (or authzSchemaSql) adds a tenant_id column, default '' (global), to the user-role table, and its role_id is 64 characters so the key fits on MySQL:

import { createAuthzEntitySchemas } from '@dudousxd/nestjs-authz-mikro-orm';

const authz = createAuthzEntitySchemas({}, { tenantScoped: true });
MikroOrmModule.forRoot({ entities: [...authz.all /* , your entities */] });

Prisma: add the column to UserRole, include it in the @@id, run your migration, and turn it on in the module (or in new PrismaAuthzStore(prisma, { tenantScoped: true })):

model UserRole {
  userType String
  userId   String
  roleId   String
  tenantId String @default("")

  @@id([userType, userId, roleId, tenantId])
  @@index([userType, userId])
  @@map("authz_user_role")
}
AuthzRbacModule.forRoot({ client: prisma, tenantScoped: true });

Existing rows become global assignments. On an existing MikroORM table, widen the primary key so the same role can be assigned in two tenants; the MikroORM README has the SQL. Without the column, every assignment stays global: assignRole and setUserRoles with a tenantId throw, and removeRole with one does nothing.

How it fits together

@Roles / @Permission / @Can(RolePolicy | PermissionPolicy)   gate.allows('posts.publish') / hasRole
                         │  (official guard)                         │  (Gate)
                         └──────────────── AuthzRbac ────────────────┘
                                              │  one fetch per user per request
                      resolveRoles / user.roles ∪ ROLE_PROVIDER / PERMISSION_PROVIDER
                                              │
                         TypeORM / MikroORM / Prisma / Drizzle store (your connection)

RBAC is optional. Plenty of apps ship with official policies alone. Add an adapter when "who can do what" becomes data your admins edit at runtime.

On this page