# Roles and permissions

Platform roles for staff, built-in and Custom roles inside an Organization, permission checks in procedures, and Consent before anyone reads a Member's sensitive data.

## Two role layers [#two-role-layers]

A **platform role** (`user.role`) says what a User may do on the platform's own screens under `/admin`: `user`, `admin`, `support` or `analyst`. An Admin sets it. An **Org role** (`member.role`) says what a Member may do inside one Organization: the built-in `owner`, `admin` and `member`, or a **Custom role** the Organization defines (for example `coach` or `reception`). The two never mix: being an Admin grants nothing inside an Organization, and an Organization owner holds no platform role.

Both layers grant actions from one list in code, [`packages/db/src/schema/access.enums.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/db/src/schema/access.enums.ts). Nothing outside that list can be granted, and the roles screen only combines those actions. Why the list lives in `packages/db`, and the rest of the design, is [ADR-0016](/docs/adr/0016-platform-and-organization-roles-and-consent).

| Resource        | Actions                    |
| --------------- | -------------------------- |
| `member`        | `read`, `invite`, `remove` |
| `role`          | `manage`                   |
| `feedback`      | `read`, `triage`, `reply`  |
| `analytics`     | `read`                     |
| `errors`        | `read`                     |
| `billing`       | `read`, `refund`           |
| `sensitiveData` | `read`                     |

## Permission matrix [#permission-matrix]

The matrices below are pinned by [`packages/auth/src/access.test.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/access.test.ts), one case per role and action. Change both in the same commit.

### Platform roles [#platform-roles]

| Action                              | `user` | `admin` | `support` | `analyst` |
| ----------------------------------- | ------ | ------- | --------- | --------- |
| `member: read`, `invite`, `remove`  |        | yes     |           |           |
| `role: manage`                      |        | yes     |           |           |
| `feedback: read`, `triage`, `reply` |        | yes     | yes       |           |
| `analytics: read`                   |        | yes     |           | yes       |
| `errors: read`                      |        | yes     |           | yes       |
| `billing: read`, `refund`           |        | yes     |           |           |
| `sensitiveData: read`               |        |         |           |           |

Only `admin` also holds Better Auth's `user` and `session` actions, so only an Admin may manage Users, sessions and impersonation (`adminProcedure`, `/admin/*`). No platform role reads sensitive data: that happens inside an Organization, by its own staff, with the subject's Consent.

### Built-in Org roles [#built-in-org-roles]

| Action                            | `owner` | `admin` | `member` |
| --------------------------------- | ------- | ------- | -------- |
| `member: read`                    | yes     | yes     | yes      |
| `member: invite`, `remove`        | yes     | yes     |          |
| `role: manage`                    | yes     | yes     |          |
| `feedback`, `analytics`, `errors` | yes     | yes     |          |
| `billing: read`, `refund`         | yes     | yes     |          |
| `sensitiveData: read`             | yes     | yes     |          |

Built-in roles are code. Their grants cannot be edited, they cannot be renamed or deleted, and a Custom role cannot take their name, so `owner` and `admin` never lose `role: manage`. They also keep Better Auth's defaults for its own routes: only `owner` may delete the Organization.

## Custom roles [#custom-roles]

An Organization creates up to 20 Custom roles on the roles screen (`/admin/roles`). Anyone holding `role: manage` may create, edit and delete them: the owner, an admin, or a Member whose Custom role grants it. You can only grant actions you hold yourself, so a role manager cannot create a role more powerful than their own.

Writes go through Better Auth's dynamic access control routes (`/organization/create-role`, `update-role`, `delete-role`), never through a procedure of ours, so every check applies whichever client made the call:

- Better Auth refuses a built-in name, an unknown resource, a grant the writer does not hold and deleting a role Members still have.
- The `before` hook in [`packages/auth/src/access-policy.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/access-policy.ts) refuses a name that is not 2–32 lowercase characters starting with a letter, any rename, and any permission that is not exactly `storedPermission(grants)`.
- The `after` hook records `org.role_created`, `org.role_updated` or `org.role_deleted` with the role's name.

`storedPermission` adds the Better Auth grants an action implies, because Better Auth's member and invitation routes check its own resources: `member: invite` stores `invitation: create, cancel`, `member: remove` stores `member: delete`, and `role: manage` stores `ac: *` and `member: update` (giving a Member a role). A client calls the route with `storedPermission(grants)` from the same leaf; the screen never shows Better Auth's resources.

A Member's `member.role` may list several roles (`member,coach`); their grants are the union.

## Screens and navigation [#screens-and-navigation]

- **`/admin` opens by access, not by role name.** The section guard (`routes/_auth/admin/route.tsx`) lets in a platform Admin and any Member whose Org role grants a screen there; each screen checks its own: Users, Flags and Audit need the platform `admin` role, Roles needs `role: manage`, Consent needs `sensitiveData: read` (`requireAdminArea`, `requireAdminScreen` in `features/access/access.queries.ts`). The platform role is read from the database session and the Org grants from `access.myPermissions`, never from the 60-second snapshot. The sidebar shows the same items (`app-shell.nav.hooks.ts`); the server still decides every call.
- **Roles screen (`/admin/roles`).** A table of the built-in and Custom roles with their Member counts, a permission matrix with one column per role, and a dialog that creates or edits a Custom role. Actions the person does not hold are disabled in the dialog, because Better Auth would refuse them. Built-in roles are locked. A platform Admin also sees the platform roles matrix, read-only.
- **Members list (`/settings`, Organization tab).** The role select offers the Custom roles next to the built-in ones, and inviting, changing roles and removing follow the Member's grants (`member: invite`, `role: manage`, `member: remove`) instead of a check for `owner` or `admin`.
- **Consent.** The Privacy tab of `/settings` and the mobile Privacy screen for the Member; `/admin/consent` for staff (below).

## Guard a procedure [#guard-a-procedure]

Inside an Organization, chain `requirePermission` after `orgProcedure`:

```ts
import { requirePermission } from "../../platform/rpc/require-permission";

const feedbackProcedure = effectProcedure(orgProcedure, feedbackRpcError, isFeedbackError);

export const feedbackRouter = {
  triage: feedbackProcedure
    .use(requirePermission({ feedback: ["triage"] }))
    .input(feedbackTriageInput)
    .handler(({ db, organizationId }, input) => triageReport(db, organizationId, input)),
};
```

The middleware reads the Member's Custom roles from `organization_role` through `context.db`, so row-level security scopes the read to the Active Organization, and decides with the same access control the organization plugin uses ([`packages/auth/src/access.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/access.ts)). A Member holding only built-in roles costs no statement. Every requested action must be held; an unknown role, a malformed row or an empty request is `FORBIDDEN`. Nothing is cached, so an edited role counts on the next request.

On a platform screen, use `platformProcedure`, which re-reads the database session like `adminProcedure` and refuses MCP access tokens:

```ts
export const analyticsRouter = {
  summary: platformProcedure({ analytics: ["read"] }).handler(({ context }) =>
    asSystem(context.systemDb, "analytics-admin", (db) => readSummary(db)),
  ),
};
```

`analytics-admin` stands for the feature's own `SystemReason` (a new reason means `node scripts/check-system-call-sites.mjs --write`). Never compare role names in a service or a component. To hide what the server would refuse, clients read `access.myPermissions`, which returns the caller's grants in the Active Organization and on the platform.

## Add a resource or action [#add-a-resource-or-action]

1. Add it to `ACCESS_STATEMENTS` in `access.enums.ts`, and to the built-in roles that should hold it (`PLATFORM_ROLE_GRANTS`, `BUILT_IN_ORG_ROLE_GRANTS`).
2. Update the matrices in `access.test.ts` and on this page.
3. If one of Better Auth's own routes should honour it, add the implied grant to `BETTER_AUTH_IMPLIED_GRANTS`.
4. Add its label to the roles screen in every web catalog (en, de, fr, pt-BR).
5. Guard the procedures with `requirePermission` or `platformProcedure`.

Existing Custom roles do not gain the new action; an owner grants it on the roles screen.

## Consent for sensitive data [#consent-for-sensitive-data]

Some data about a Member is sensitive personal data: measurements, health records and progress photos (LGPD art. 11, GDPR art. 9). A Member decides, per Organization and per category, whether its staff may read it. `CONSENT_CATEGORIES` and `CONSENT_TEXT_VERSION` live in [`packages/db/src/schema/consent.enums.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/db/src/schema/consent.enums.ts).

- **Where a Member decides.** The Privacy section of the web account settings (`/settings`) and the Privacy screen of the mobile app show one switch per category. Each switch calls `consent.grant` or `consent.revoke`; both are audited (`consent.granted`, `consent.revoked`) with the category, and the audit log is the Consent history.
- **Where staff see it.** The consent screen (`/admin/consent`) lists every Member of the Active Organization with their state per category (`consent.organization`, needs `sensitiveData: read`).
- **What counts.** A grant that has not been revoked and was given under the current `CONSENT_TEXT_VERSION`. When the consent text changes in a way that needs consent again, bump the version: older grants show as outdated and stop counting until the Member renews them.
- **How it is stored.** `data_consent` keeps one row per Member, Organization and category. Only the Member writes their own rows, and a revoke sets `revoked_at`; no tenant can delete a row.

### Read sensitive data [#read-sensitive-data]

A procedure that returns a category of another Member's sensitive data chains `sensitiveDataRead` after `orgProcedure`. A project's own table would look like this:

```ts
import { sensitiveDataRead } from "../../platform/rpc/sensitive-data";

export const measurementsRouter = {
  forMember: measurementsProcedure
    .input(z.object({ userId: z.string() }))
    .use(
      sensitiveDataRead<{ userId: string }>({
        category: "measurements",
        subject: (input) => input.userId,
      }),
    )
    .handler(({ db, organizationId }, input) => listMeasurements(db, organizationId, input.userId)),
};
```

Reading your own data passes straight through. Anyone else's needs, in one tenant transaction with the handler: `sensitiveData: read` (else `FORBIDDEN`), the subject's current Consent (else `CONSENT_REQUIRED`, which the screens translate), and a `sensitive_data.viewed` Audit Event naming the viewer, the subject and the category. The handler's `db` is that transaction: the read, the Consent check and the event commit together, so a revoke hides the data on the very next call and a refused read records nothing. A service that reads sensitive data inside a larger program calls `assertConsent` from `consent.service.ts`, which fails with the `ConsentRequired` tagged error.

## Tests [#tests]

- [`packages/auth/src/access.test.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/access.test.ts): both matrices, Custom role grants, fail-closed cases and the Better Auth grants each action implies.
- [`packages/auth/src/access-policy.test.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/access-policy.test.ts) and [`organization-roles.test.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/organization-roles.test.ts): the role write rules, Better Auth's escalation check, the audit trail, and a Custom role honoured by Better Auth's invitation route.
- [`access.procedures.test.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/access/access.procedures.test.ts): the roles list, denials, role names never crossing Organizations, and a role edit taking effect on the next request.
- [`consent.procedures.test.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/consent/consent.procedures.test.ts): grant, revoke, the staff view, outdated grants, and a revoke hiding the data at once.
- [`rls.isolation.test.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/platform/rpc/rls.isolation.test.ts) covers `organization_role` and `data_consent`, including writes inside one Organization; `pnpm --filter @template-cloudflare/db test:rls-matrix` runs it on every connection-role profile with tenant pipelining on and off.

## Key files [#key-files]

- [`packages/db/src/schema/access.enums.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/db/src/schema/access.enums.ts)
- [`packages/auth/src/access.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/access.ts)
- [`packages/auth/src/access-policy.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/access-policy.ts)
- [`packages/api/src/platform/rpc/require-permission.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/platform/rpc/require-permission.ts)
- [`packages/api/src/platform/rpc/sensitive-data.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/platform/rpc/sensitive-data.ts)
- [`packages/api/src/features/access/access.service.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/access/access.service.ts)
- [`packages/api/src/features/consent/consent.service.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/consent/consent.service.ts)
- [`packages/db/src/schema/consent.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/db/src/schema/consent.ts)
