Skip to main content
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:

Protected account

Client admins can see superadmin accounts but can’t change, ban, delete or impersonate them.

Impersonation

Sign in as another user to see the app through their eyes, within strict role rules.

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:
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.
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:
src/shared/lib/auth/admin-access.ts
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.
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.
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 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: Nobody can impersonate themselves or a non-existent account. Two independent server-side layers enforce this: 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.
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.

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 (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.
src/shared/lib/auth/service-mode.ts
A valid confirmation is exactly { serviceModeConfirmed: true, organizationId } where organizationId equals the active organization from the database session, not a value the browser picked. ServiceModeConfirmationError is a DomainError, so handleCommandError returns its message to the UI as { success: false, error }. 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():
src/shared/components/service-mode/use-service-mode-action.tsx
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 does this.

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