# Roles and Permissions

> Configure organization roles, resources, actions and permissions with @kit/rbac, and check who can act on whom.

*Canonical: https://makerkit.dev/docs/void-cloudflare/members-management/roles-permissions*

---

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](../admin/rbac-permissions)) |
| `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`.

```ts
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`, `roles`** are added to the defaults. Reusing a key replaces that entry (`roles: { admin: 60 }` moves `admin` to 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 removes `create`, `update` and `delete` but couldn't. To take an action away from a role, use `permissions`.
- **`permissions[role][resource]`** replaces that role's default for that resource. `[]` revokes it (`member: { billing: [] }` above). Resources you don't list keep their defaults.
- **`removeRoles`** drops default roles with their permissions: `removeRoles: ['admin']`. Only `owner`, `admin` and `member` can be removed, and a removed key can't appear in `roles` or `permissions`.
- **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 (`admin` and `member` can't become it). Whatever its name, the single highest role gets what `owner` gets by default; `permissions` narrows 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 in `permissions`.

### 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.

```ts
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:

1. `packages/rbac/src/rbac.config.ts`: the roles, their levels and permissions. TypeScript then flags every typed use (`Role`) of a removed role; pass `removeRoles` as an array literal so the types match.
2. Role names in every locale: `apps/web/messages/<locale>/roles.json` (`names`: badges, selects) and `roles.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.
3. Renaming the creator role: a migration for the owner guard ([Renaming the Creator Role](#renaming-the-creator-role)). `apps/web/db/__tests__/owner-guard.test.ts` fails 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

```ts
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 roles
```

`AnyRole` 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?":

```ts
import { canTargetRole } from '@kit/rbac';

canTargetRole('admin', 'member'); // true: higher level targets lower
canTargetRole('admin', 'admin'); // false
canTargetRole('admin', 'admin', { allowEqual: true }); // true
canTargetRole('admin', 'owner', { allowEqual: true }); // false: only owner targets owner
canTargetRole('owner', 'owner', { allowEqual: true }); // true
canTargetRole('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, `owner` by default) can be targeted only by itself, with `allowEqual`, even if another role has the same level.
- **Unknown roles are denied both ways.** Typos, wrong case, `toString` and comma-joined strings like `'member,admin'` return `false`. 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 (SQLSTATE `KT001`); only organization actions map it to `LAST_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.ts` fails 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:

```bash
pnpm --filter web exec void gen migration creator_role
```

```sql
CREATE OR REPLACE FUNCTION kit_creator_role() RETURNS text
  LANGUAGE sql STABLE AS $$ SELECT 'founder' $$;
--> statement-breakpoint
-- existing owners, legacy comma-joined rows included
UPDATE "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:

```json
{ "names": { "owner": "Owner", "admin": "Admin", "member": "Member" } }
```

`roles.server.json`, emails only, never sent to the browser:

```json
{ "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:

```ts
import { ac, roles } from '@kit/rbac/access-controller';

roles.member.authorize({ billing: ['read'] }).success; // true
roles.member.authorize({ member: ['delete'] }).success; // false
```

`roles` 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`):

```ts
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 in `rbac.config.ts`.
- **Narrowing a default resource in `accessController`.** It throws. Revoke per role in `permissions`.
- **Adding a resource without granting it.** Nobody, not even `owner`, gets it until you list it in `permissions`.
- **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](./members): who may change or remove whom, on the members page.
- [Admin RBAC](../admin/rbac-permissions): platform admin roles, a separate namespace.
- [Authorization Policies](../development-guide/authorization-policies): business rules (limits, subscriptions) on top of permissions.
