> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Superadmin, impersonation and service mode

> How GatoJS protects the support team's superadmin accounts, controls impersonation, and requires confirmation for every data change made in service mode.

A GatoJS app is usually built and maintained by one team and used by another. The client's administrators manage their users, but the team that builds and supports the app (for Web Amigos apps, Web Amigos) still needs access for support. The `superadmin` global role is that support account.

The kit gives it three things a regular admin doesn't have, and adds guardrails to each:

> [card] Protected account
>
> Client admins can see superadmin accounts but can't change, ban, delete or impersonate them.

> [card] Impersonation
>
> Sign in as another user to see the app through their eyes, within strict role rules.

> [card] Service mode
>
> Enter any organization without membership. Every data change asks for confirmation.

## Superadmin vs. global admin

Create a superadmin deliberately with the admin script:

```bash theme={null}
npm run admin:create -- --email support@yourteam.com --role superadmin
```

| Capability | Global `admin` | `superadmin` |
| - | - | - |
| Access to every module (menu and `requireModuleAccess`) | yes | yes |
| Users page: all accounts and **Invite user** | yes | yes |
| `admin` plugin endpoints on `user` and `admin` accounts (role, ban, delete, password, profile, sessions) | yes | yes |
| The same endpoints on a `superadmin` account | no, 403 | yes |
| Granting the `superadmin` role | no, 403 | yes |
| Impersonation | Only `user` accounts, only with `ADMIN_IMPERSONATION=true` | `user` and `admin` accounts, regardless of the flag |
| Working in an organization without membership | no, `NoOrganizationError` | yes, in service mode |

The Users page has two actions in the UI: **Invite user** and **Sign in as**. The other `admin` plugin actions (role changes, bans, deletion, passwords, sessions) are available only as `/api/auth/admin/*` endpoints, for example via `authClient.admin.setRole` or `auth.api.setRole`. Superadmin accounts appear in the account list with a **Service** badge and without a **Sign in as** button.

> [!NOTE]
>
> The badge and the service-mode dialog ship with the text "Web Amigos". Change `role-superadmin` in `src/features/users/i18n/*.json` and `serviceMode.dialog-description` in `src/app/messages/*.json` to name your own team.

## Protecting service accounts

Hiding a button doesn't protect anything, because `admin` plugin endpoints can be called directly. The rules therefore live in better-auth's `before` hook, which runs before every endpoint, including server-side `auth.api.*` calls. It covers `/admin/create-user` and every endpoint that acts on a specific account or its sessions:

```ts src/shared/lib/auth/admin-access.ts theme={null}
export const IMPERSONATE_PATH = "/admin/impersonate-user";

export const ADMIN_TARGET_PATHS: readonly string[] = [
  "/admin/set-role",
  "/admin/ban-user",
  "/admin/unban-user",
  "/admin/remove-user",
  "/admin/set-user-password",
  "/admin/update-user",
  IMPERSONATE_PATH,
  "/admin/revoke-user-session",
  "/admin/revoke-user-sessions",
  "/admin/list-user-sessions",
];
```

Reads (`/admin/list-users`, `/admin/get-user`) aren't covered, so admins can see superadmin accounts.

For each request the hook resolves three values and passes them to `assertAdminActionAllowed`:

* **Caller role**, read from the session **in the database**, not the cookie cache. A demoted superadmin loses power immediately, in the same session.
* **Target role**, read from the database for `userId` and for the owner of `sessionToken` (the higher one wins). If no account is found, the target is unknown.
* **Requested role**, from `role` or `data.role` (string or array). If any value is `superadmin`, the request asks for `superadmin`.

```mermaid theme={null}
flowchart TD
    start["Request to /admin/create-user<br/>or an ADMIN_TARGET_PATHS endpoint"] --> server{"No session, no request,<br/>no headers?"}
    server -->|"yes"| skip["Server-side call: hook skips checks"]
    server -->|"no"| requested{"Non-superadmin asks<br/>for the superadmin role?"}
    requested -->|"yes"| deny1["403"]
    requested -->|"no"| imp{"Impersonation?"}
    imp -->|"yes"| can{"Target known and<br/>canImpersonate?"}
    can -->|"no"| deny2["403"]
    can -->|"yes"| plugin["better-auth permission check"]
    imp -->|"no"| target{"Non-superadmin acting<br/>on a superadmin?"}
    target -->|"yes"| deny3["403"]
    target -->|"no"| unknown{"Non-superadmin,<br/>unknown target?"}
    unknown -->|"yes"| deny4["403"]
    unknown -->|"no"| plugin
```

After the hook, better-auth checks the caller's role permissions as usual. In practice:

* An admin acting on a superadmin gets 403 on every listed path and nothing is written, including bypass attempts such as an array `userId` or a regular `userId` combined with a superadmin's session token.
* An unknown target (non-existent `userId`, unknown token) gives an admin 403 instead of passing through.
* A superadmin can act on another superadmin, except impersonation.
* An admin can grant and revoke `admin` and create `user` or `admin` accounts.

> [!WARNING]
>
> **Server-side calls skip the hook.** A call with no session, no `request` and no headers (like `auth.api.createUser({ body })` in `admin:create`) isn't checked, and `/admin/create-user` doesn't check permissions in that case either. If your code calls the `admin` plugin API on behalf of a signed-in user, always pass the request `headers`. Without them it could create an account with any role, including `superadmin`. An empty `new Headers()` is not exempt.

### Removing the service account after support ends

Only a superadmin can cut off the support team's access:

* better-auth doesn't let you remove yourself, and client admins get 403, so nobody can delete the last superadmin through the API while it has that role.
* A superadmin can change their own role to `user` via `/admin/set-role`. After that, the account is no longer protected and a client admin can remove it.
* Changing the role alone doesn't remove data access: an account created by `admin:create` keeps its `owner` membership in the oldest organization until it's removed.

See [Handover](https://docs.gatojs.com/deployment/handover.md) for the full checklist.

## Impersonation

Impersonation means working on another user's account without their password. It helps you reproduce what a specific person sees, but it grants full access to their account, so it's gated by role. The rule is `canImpersonate` in `src/shared/lib/auth/impersonation-policy.ts`:

| Who \ as whom | `user` | `admin` | `superadmin` |
| - | - | - | - |
| `superadmin` | yes | yes | no |
| `admin`, `ADMIN_IMPERSONATION=false` (default) | no | no | no |
| `admin`, `ADMIN_IMPERSONATION=true` | yes | no | no |
| `user` | no | no | no |

Nobody can impersonate themselves or a non-existent account. Two independent server-side layers enforce this:

| Layer | Checks |
| - | - |
| `before` hook on `/admin/impersonate-user` | `canImpersonate` with the target role read from the database |
| `admin` plugin permissions | `user:impersonate` (granted to `admin` only when the flag is on), plus `user:impersonate-admins` for `admin`/`superadmin` targets (only `superadmin` has it) |

The **Sign in as** button only appears when `canImpersonate` allows it. That's convenience, not protection.

How it works:

**1. Start**

`UsersManager` calls `authClient.admin.impersonateUser({ userId })`. better-auth creates a session for the target with `impersonatedBy` set to the caller, valid for one hour, and stores the caller's own session token in an `admin_session` cookie.

**2. Log**

The browser calls `logImpersonationStartCommand()`, which logs `[USERS] Impersonation started` with both user ids, then navigates to `/dashboard`.

**3. Work as the target**

The whole app behaves as the target account: `getOrgContext()` returns its roles and active organization. A banner at the top says you're signed in as another user and offers **Back to my account**.

**4. Stop**

The button logs `[USERS] Impersonation stopped`, then `authClient.admin.stopImpersonating()` restores the original session and the browser returns to `/users`.

> [!NOTE]
>
> The start and stop log entries are written by the UI. Calling `/api/auth/admin/impersonate-user` directly leaves no `Impersonation started` entry. In production, logs go anywhere only if you configure OTLP export. See [Logging and observability](https://docs.gatojs.com/configuration/logging-and-observability.md).

## Service mode

A superadmin needs to see and fix data in any client organization, including ones they don't belong to. GatoJS lets them enter any organization, but always **one at a time and through the same `organizationId` filter** as everyone else. There are no "all organizations at once" views. Working in an organization without membership is **service mode**. Because the superadmin acts with owner rights in someone else's company, every data change in service mode requires explicit confirmation.

### When service mode is active

`getOrgContext()` returns `serviceMode: true` and `orgRole: "owner"` only when the account's global role is exactly `superadmin`, the active organization exists, and the account has no membership in it. With a membership, the superadmin gets the membership's role and `serviceMode: false`.

A superadmin created by `admin:create` is an `owner` member of the oldest organization, so there they work like a regular owner, with no banner and no dialog. Service mode appears in every other organization: with `MULTI_ORG=true` in organizations other than the oldest, and in any mode after the membership is removed.

### Entering an organization

* For a superadmin, the **organization switcher** lists every organization, sorted by name.
* The `/no-organization` page shows the same list as **Enter an organization**.
* Both call `enterOrganizationCommand(organizationId)`, which checks `canEnterOrganization` (superadmin: organization exists; others: membership) and updates only the current session.
* Entering doesn't change domain data, so there's no dialog. When a superadmin enters without membership, the command records an `organization.entered` audit event with `serviceMode: true`. The same happens at sign-in when a superadmin without memberships is placed in the oldest organization. Events are stored only if the [audit-logs module](https://docs.gatojs.com/modules/audit-logs.md) (or your own audit sink) is installed.

While service mode is active, the `(app)` layout shows a banner: **Service mode: `<organization name>`**.

### The confirmation contract in commands

A UI dialog alone isn't enough: a component that forgot to use it would skip the reminder silently. So every command on organization data checks the confirmation on the server:

* signature `(input: unknown, confirmation?: unknown)`;
* right after `getOrgContext()` or `requireModuleAccess()`, call `assertServiceModeConfirmed(context, confirmation)`, before the first Prisma call.

```ts src/shared/lib/auth/service-mode.ts theme={null}
export function assertServiceModeConfirmed(
  context: OrgContext,
  confirmation: unknown,
): void {
  if (confirmation === undefined && !context.serviceMode) {
    return;
  }
  if (!confirmsOrganization(confirmation, context.organizationId)) {
    throw new ServiceModeConfirmationError();
  }
}
```

A valid confirmation is exactly `{ serviceModeConfirmed: true, organizationId }` where `organizationId` equals the active organization from the **database session**, not a value the browser picked.

| Context | `confirmation` | Result |
| - | - | - |
| Not in service mode | `undefined` | Passes |
| Not in service mode | Valid confirmation for the active organization | Passes |
| Not in service mode | Confirmation for another organization, `null`, anything else | Error |
| Service mode | Valid confirmation for the active organization | Passes |
| Service mode | Anything else (missing, `null`, `true`, `{}`, wrong or differently-cased `organizationId`) | Error |

`ServiceModeConfirmationError` is a `DomainError`, so `handleCommandError` returns its message to the UI as `{ success: false, error }`. The [architecture test](https://docs.gatojs.com/guides/code-patterns.md#the-architecture-test) fails if a `"use server"` function that uses the organization context touches Prisma before calling `assertServiceModeConfirmed`.

### In the UI: `useServiceModeAction().run`

Components never call organization-data commands directly. They go through `run` from `useServiceModeAction()`:

```tsx src/shared/components/service-mode/use-service-mode-action.tsx theme={null}
const requestConfirmation = useCallback(async () => {
  if (!active) {
    return undefined;
  }
  const confirmed = await askForConfirmation();
  if (!confirmed) {
    return null;
  }
  return { serviceModeConfirmed: true as const, organizationId };
}, [active, organizationId, askForConfirmation]);

const run = useCallback(
  async <TInput, TResult>(
    action: ServiceModeAction<TInput, TResult>,
    input: TInput,
  ): Promise<TResult | null> => {
    const confirmation = await requestConfirmation();
    if (confirmation === null) {
      return null;
    }
    return confirmation ? action(input, confirmation) : action(input);
  },
  [requestConfirmation],
);
```

Outside service mode, `run` calls the command right away. In service mode it first shows a **Service mode** dialog and calls the command only after **Change**. Rules for components:

* Render the `dialog` returned by the hook, or the dialog never appears and `run` waits forever.
* Handle `null`: it means the user cancelled. Don't treat it as an error.
* Don't build your own confirmation dialog.
* For calls that aren't server actions (for example `fetch` to a module's API route), use `requestConfirmation()` from the same hook and send the result along. The route must verify it the same way a command does. The [Uploads module](https://docs.gatojs.com/modules/uploads.md) does this.

```mermaid theme={null}
sequenceDiagram
    autonumber
    actor U as Superadmin
    participant F as Form component
    participant R as run
    participant W as Confirmation dialog
    participant C as Command
    U->>F: submits form
    F->>R: run(command, values)
    R->>W: service mode active, open dialog
    alt Cancel
        W-->>R: false
        R-->>F: null (command not called)
    else Change
        W-->>R: true
        R->>C: command(values, { serviceModeConfirmed, organizationId })
        C->>C: getOrgContext() + assertServiceModeConfirmed
        C-->>F: OperationResult
    end
```

### Stale tabs

The active organization lives in the session, which all browser tabs share. If you switch organizations in one tab, another tab keeps showing the old one until refreshed. When that stale tab submits through `run`:

| Stale tab shows | Other tab switched to | Result |
| - | - | - |
| Org X in service mode | Org Y | Confirmation mismatch, nothing saved |
| Org A (member) | Org X in service mode | Missing confirmation, nothing saved |
| Org A (member) | Org B (also member) | Saved in B, even though the tab shows A |

The protection against stale tabs therefore works only when one side is in service mode.

### `authClient.organization.*` calls

better-auth's `organization` endpoints don't know about service mode: `run` doesn't wrap them and the server doesn't check confirmation. They also require the caller to be a member, so a superadmin in service mode can't change organization data through them; the `owner` role exists only in the `getOrgContext()` result. If a module should let a superadmin change data in service mode, implement it as a kit command (`getOrgContext()`, `assertServiceModeConfirmed`, Prisma with `organizationId`, called through `run`). See [Code patterns](https://docs.gatojs.com/guides/code-patterns.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.