Roles and Permissions
Configure organization roles, resources, actions and permissions with @kit/rbac, and check who can act on whom.
Organization roles and permissions live in one file you own: packages/rbac/src/rbac.config.ts. You list what to add or change, defineRBACConfig merges it over the kit defaults, validates the result when the module loads and freezes it, and @kit/rbac exposes typed constants, role helpers and Better Auth access-control objects built from it.
Files You Own
| File | Owner | Edit it? |
|---|---|---|
packages/rbac/src/rbac.config.ts | You | Yes: organization roles and permissions |
packages/rbac/src/admin-rbac.config.ts | You | Yes: platform admin roles (Admin RBAC) |
packages/rbac/src/core/*, packages/rbac/src/admin/*, src/index.ts, src/access-controller.ts | Kit | No: kit updates change these, and your edits would conflict |
Keep the short header at the top of rbac.config.ts and the ./core/factory import as they are. The kit treats them as fixed, so kit updates merge cleanly into your file.
Defaults
With an empty config (defineRBACConfig({})) you get three roles:
| Role | Level | Permissions |
|---|---|---|
owner | 100 | Every default statement |
admin | 50 | organization: update; all of member, invitation and billing; ac: read |
member | 10 | ac: read; billing: read (members don't invite) |
The default access controller (every action that exists per resource):
| Resource | Actions |
|---|---|
organization | update, delete |
member | create, update, delete |
invitation | create, cancel |
ac | create, read, update, delete |
billing | create, read, update, delete |
Default actions: create, read, update, delete, cancel.
Customizing
A full example: a project resource with a custom archive action, and a billing_manager role between member and admin.
import { defineRBACConfig } from './core/factory';export default defineRBACConfig({ resources: { PROJECT: 'project' }, actions: { ARCHIVE: 'archive' }, roles: { billing_manager: 30 }, accessController: { project: ['create', 'read', 'update', 'delete', 'archive'], }, permissions: { owner: { project: ['create', 'read', 'update', 'delete', 'archive'] }, admin: { project: ['create', 'read', 'update'] }, member: { project: ['read'], billing: [] }, billing_manager: { billing: ['read', 'update'], invitation: ['create', 'cancel'], project: ['read'], }, },});Merge Rules
resources,actions,rolesare added to the defaults. Reusing a key replaces that entry (roles: { admin: 60 }movesadminto 60).accessController[resource]only adds actions. A list for a default resource must keep every default action:member: ['read']throws, because it looks like it removescreate,updateanddeletebut couldn't. To take an action away from a role, usepermissions.permissions[role][resource]replaces that role's default for that resource.[]revokes it (member: { billing: [] }above). Resources you don't list keep their defaults.removeRolesdrops default roles with their permissions:removeRoles: ['admin']. Onlyowner,adminandmembercan be removed, and a removed key can't appear inrolesorpermissions.- A new role starts with no permissions. List everything it should do.
- The creator role starts with every default statement. It is
owner, or a role you add above every other (adminandmembercan't become it). Whatever its name, the single highest role gets whatownergets by default;permissionsnarrows it like any role. A new resource, or a new action on a default resource, isn't granted to anyone, the creator role included, until you list it inpermissions.
Reshaping Roles
Design your roles before your first deploy. Members and invitations store a role's key, so a key you rename or remove after launch stays in the database as an unknown role: no permissions, and only the creator role can change or remove those members. The kit has no tool to move them.
Rename is remove + add. Copy the permissions you want to keep: the new role starts with none, except the creator role.
export default defineRBACConfig({ // owner becomes founder, member becomes viewer, no admin removeRoles: ['owner', 'admin', 'member'], roles: { founder: 100, viewer: 10 }, permissions: { // founder is the creator role: it starts with every default statement viewer: { ac: ['read'], billing: ['read'] }, },});To change a default role's level, don't remove it: roles: { admin: 60 }.
A role change touches up to three places:
packages/rbac/src/rbac.config.ts: the roles, their levels and permissions. TypeScript then flags every typed use (Role) of a removed role; passremoveRolesas an array literal so the types match.- Role names in every locale:
apps/web/messages/<locale>/roles.json(names: badges, selects) androles.server.json(inSentence: "invited you as an admin", emails). A role missing from either file shows its key instead of a name, so add both when you add a role. - Renaming the creator role: a migration for the owner guard (Renaming the Creator Role).
apps/web/db/__tests__/owner-guard.test.tsfails until it exists and names the command.
Validation
An invalid config throws RBACConfigError when rbac.config.ts loads, which fails pnpm test:unit (a test imports the shipped file) and any server start. Checks stop at the first round with errors, in this order: removeRoles; an accessController list that drops a default action; resources, actions, permissions and levels; the role structure. Each round lists every problem it finds.
| Problem | Message |
|---|---|
| Two resources share a value | Duplicate resource values: "project" is used by PROJECT, PROJECTS |
| Two actions share a value | Duplicate action values: "read" is used by READ, VIEW |
accessController names an unknown resource | Access controller references unknown resource: "projects" |
accessController names an unknown action | Access controller for "project" references unknown action: "archive" |
| A default resource's list drops a default action | accessController.member drops default action(s) create, update, delete… |
permissions names an unknown role | Role permissions defined for unknown role: "manager" |
permissions names an unknown resource | Role "member" has permissions for unknown resource: "projects" |
| An action isn't in the access controller | Role "admin" has action "archive" for "project" but it's not in accessController |
| An action is listed twice | Role "admin" lists action "read" twice for "project" |
| A level isn't a finite number | Role "guest" has invalid hierarchy level: NaN |
| A level is negative | Role "guest" has negative hierarchy level: -1. Use positive numbers. |
removeRoles names a role that isn't a default | removeRoles lists "ghost", which is not a default role (owner, admin, member) |
A removed role is listed in roles | "admin" is both removed and listed in roles. To change its level, set roles: { admin: <level> } without removing it |
A removed role is listed in permissions | permissions lists "admin", which removeRoles removes… |
admin or member would end up highest (owner removed, lowered, or another default raised) | "admin" would become the creator role (highest level, every permission). The creator role is owner or a role you add… |
A new role ranks above a kept owner that has no permissions.owner | "founder" is above owner, but owner keeps every default permission. Remove it (removeRoles: ['owner']) or list what it may do in permissions.owner |
| Two roles share the highest level | Roles owner, founder share the highest level (100). Exactly one role may be highest… |
| Fewer than two roles | Organizations need at least two roles: the creator role (highest level) and one for new members |
Roles below the top may share a level. The compiled config is deep-frozen: no module can change permissions at runtime.
Typed Constants
import { ACTIONS, RESOURCES, ROLE_HIERARCHY, type Action, type Resource, type Role,} from '@kit/rbac';RESOURCES.BILLING; // 'billing'const role: Role = 'owner'; // 'owner' | 'admin' | 'member' plus your rolesAnyRole is Role plus any string, for role names that come from the database.
Who Can Act on Whom
canTargetRole(actingRole, targetRole, { allowEqual }) answers "may this member change, remove or invite that role?":
import { canTargetRole } from '@kit/rbac';canTargetRole('admin', 'member'); // true: higher level targets lowercanTargetRole('admin', 'admin'); // falsecanTargetRole('admin', 'admin', { allowEqual: true }); // truecanTargetRole('admin', 'owner', { allowEqual: true }); // false: only owner targets ownercanTargetRole('owner', 'owner', { allowEqual: true }); // truecanTargetRole('admin', 'Owner'); // false: unknown role- A higher level can target a lower one. An equal level only with
allowEqual. - The creator role (the highest level,
ownerby default) can be targeted only by itself, withallowEqual, even if another role has the same level. - Unknown roles are denied both ways. Typos, wrong case,
toStringand comma-joined strings like'member,admin'returnfalse. Better Auth stores several roles comma-joined, so split them before calling.
Related helpers, all bound to your config:
| Helper | Returns |
|---|---|
getRoleLevel(role) | The level, or undefined for an unknown role |
getCreatorRole() / isCreatorRole(role) | The single highest role (owner by default) |
getDefaultRole() | The lowest role other than the creator (member), for new members |
getRolesSorted() / getAllRoles() | Role names, highest first / in config order |
roleHasPermission(roles, resource, action) | Whether a configured role, or any of a member's roles (splitRoles(member.role)), has the action |
splitRoles(joinedRoles) | A member's roles from Better Auth's comma-joined member.role (split on ,, no trim) |
Custom Roles From the Database
Every helper except getCreatorRole, isCreatorRole, getDefaultRole and roleHasPermission takes the roles an organization created at runtime: canTargetRole(a, b, { custom }), getRoleLevel(role, custom). Before saving them, call validateCustomRoles(custom, { actingRole, existing }). It throws unless every role has a new name and a level from 0 up to, but not including, both the owner's level and the acting member's level, so nobody creates a role above themselves. When reading, an invalid stored role is skipped (treated as unknown, so denied) and logged as Ignoring invalid custom roles.
The Owner Guard
Every organization keeps at least one member with the creator role (owner by default, getCreatorRole()). Postgres enforces it with a trigger, so no code path gets around it: Better Auth's leave, remove and role change, your own queries, admin scripts.
- What it refuses: deleting the last owner's membership, changing it to another role, or moving it to another organization. Also when two owners leave or demote each other at the same moment: the second one fails.
- What it allows: deleting the whole organization (members, invitations and the organization go together, in one transaction), and any change that leaves another owner.
- What you see: the service answers 409
LAST_OWNER("The organization needs at least one owner."). Deleting a user who is an organization's only owner fails in the database too (SQLSTATEKT001); only organization actions map it toLAST_OWNER. Leaving shows "Delete the organization or make someone else owner first." - Where it lives:
apps/web/db/migrations/*_owner_guard.sql, a hand-written migration (its header explains how it works). Never edit it into a generated migration or regenerate migrations from scratch:apps/web/db/__tests__/owner-guard.test.tsfails without it.
Renaming the Creator Role
The trigger reads the creator role from a Postgres function, kit_creator_role(), which returns 'owner'. A new creator role replaces owner (removeRoles: ['owner'], roles: { founder: 100 }) or ranks above it (roles: { founder: 110 }, owner stays as a lower role, and you list what it may do in permissions.owner). Ship a custom migration that replaces the function, or the guard keeps protecting owner while the app treats founder as the creator. Before your first deploy there are no owners to move, so the UPDATE below is only needed after launch:
pnpm --filter web exec void gen migration creator_roleCREATE OR REPLACE FUNCTION kit_creator_role() RETURNS text LANGUAGE sql STABLE AS $$ SELECT 'founder' $$;--> statement-breakpoint-- existing owners, legacy comma-joined rows includedUPDATE "member"SET role = array_to_string( array_replace(string_to_array(role, ','), 'owner', 'founder'), ',')WHERE 'owner' = ANY (string_to_array(role, ','));Replace the function first, then rename the rows, in the same migration: the guard then never sees an organization without its creator role. apps/web/db/__tests__/owner-guard.test.ts checks that kit_creator_role() matches getCreatorRole(), and its failure message names this fix.
Role Names
Role names are your copy, in apps/web/messages/<locale>/, seeded with the defaults:
roles.json, shown in the app:
{ "names": { "owner": "Owner", "admin": "Admin", "member": "Member" } }roles.server.json, emails only, never sent to the browser:
{ "inSentence": { "owner": "an owner", "admin": "an admin", "member": "a member" } }RoleLabel (@kit/organizations/ui) shows names in the members table, the invite and role selects, pending invitations, the account switcher and the invitation link page; the invitation email uses inSentence. A role without a name shows its key.
Better Auth Access Control
@kit/rbac/access-controller builds Better Auth's access controller and one role per configured role:
import { ac, roles } from '@kit/rbac/access-controller';roles.member.authorize({ billing: ['read'] }).success; // trueroles.member.authorize({ member: ['delete'] }).success; // falseroles is keyed by your role names, so a typo fails type-checking. This entry point loads better-auth; @kit/rbac itself doesn't, and is safe to import in the browser.
Better Auth gets your roles, and your creator role as creatorRole (packages/better-auth/src/organization.ts). It also accepts its own default names (owner, admin, member) even when you removed them, so the kit refuses any role your config doesn't define when a member is added, re-roled, invited or accepts an invitation (ORGANIZATION_ROLE_NOT_CONFIGURED): an invitation sent before you removed its role can't be accepted. The kit's services check roles before that; this catches your own auth.api calls too.
Testing With Another Config
Every unit test sees the default roles (owner, admin, member), whatever your rbac.config.ts says (packages/rbac/src/default-roles.setup.ts, a test setup file), so reshaping roles never breaks the kit's tests. After a reshape, pnpm test:unit fails only where you have work to do: a renamed creator role's migration (owner-guard.test.ts). Also check that roles.json and roles.server.json name every role. A test about your own config reads it with vi.unmock('@kit/rbac/config'). Test databases (createAppTestDatabase, testDatabase) set the owner guard to the creator role tests see, so your creator-role migration doesn't change kit tests either.
Kit code reads roles only through @kit/rbac, never by name. To check your rules against a reshaped config, mock @kit/rbac with @kit/rbac/testing (tests only; it loads better-auth):
vi.mock('@kit/rbac', async () => { const { rbacMockFor, SAMPLE_CUSTOM_CONFIG } = await import('@kit/rbac/testing'); return rbacMockFor(SAMPLE_CUSTOM_CONFIG);});SAMPLE_CUSTOM_CONFIG replaces owner with founder, removes admin and adds billing; pass any defineRBACConfig(...) instead. Mock @kit/rbac/access-controller with accessControllerModuleFor(config) when Better Auth is involved.
Common Mistakes
- Editing
core/defaults.ts. It's kit-owned and gets overwritten. Customize inrbac.config.ts. - Narrowing a default resource in
accessController. It throws. Revoke per role inpermissions. - Adding a resource without granting it. Nobody, not even
owner, gets it until you list it inpermissions. - Renaming or removing a role after launch. Stored members keep the old key and lose their permissions. Design roles before your first deploy.
- Passing Better Auth's raw role string to
canTargetRole.'member,admin'is denied. Split on,first.
Related
- Managing Members: who may change or remove whom, on the members page.
- Admin RBAC: platform admin roles, a separate namespace.
- Authorization Policies: business rules (limits, subscriptions) on top of permissions.