Skip to content

Auth And Workspace

Last refreshed: 2026-05-18

Auth Stack

Authentication uses Better Auth through payload-auth/better-auth.

Key files:

  • src/lib/auth/options.ts: Better Auth plugins and Payload integration options.
  • src/lib/auth/client.ts: client auth helpers.
  • src/lib/auth/context/get-context-props.ts: cached session/context helpers.
  • src/app/api/auth/[...all]/route.ts: Better Auth Next.js route handler.
  • src/collections/users.ts: user collection and workspace/default brand kit fields.

Enabled Auth Capabilities

Configured plugins include:

  • username
  • email harmony
  • phone harmony and phone number OTP placeholder
  • email OTP
  • passkeys
  • admin
  • multi-session
  • Next.js cookies

Email/password auth requires email verification.

Workspace Resolution

Server actions use requireAuthContext from src/lib/server-actions.ts.

It resolves:

  • Payload Local API client.
  • request headers.
  • authenticated Payload user.
  • workspaceId from user.workspace.
  • Payload-style request object for access-aware operations.

workspaceId can be null; mutations that require a workspace must reject that explicitly.

sequenceDiagram
  participant Action as Server action
  participant Helper as requireAuthContext
  participant Auth as Better Auth and Payload
  participant User as Payload user
  participant Workspace as Workspace ID

  Action->>Helper: Resolve request context
  Helper->>Auth: Read session and headers
  Auth-->>User: Authenticated user
  Helper->>Workspace: Read user.workspace
  Helper-->>Action: Payload client, user, workspaceId

Server Action Pattern

Use:

  • ActionError for typed failures.
  • ActionResult<T> for predictable client return shapes.
  • handleAction for actions that need Mastra storage ready before running agent or workflow work.
  • handleBasicAction for authenticated reads and writes that only need Payload auth/context and should not fail on unrelated Mastra storage startup.

Expected flow:

  1. Resolve auth/workspace context.
  2. Validate input.
  3. Query/update only workspace-owned documents unless intentionally global.
  4. Throw ActionError with stable codes for user-facing failures.
  5. Return predictable data payloads.

Tenant-Boundary Rules

  • Workspace-scoped collections must be filtered by workspace.
  • Relationship inputs from the UI must be checked against the active workspace.
  • Generation jobs, RAG sources, scenes, compilations, credit wallets, transactions, and entitlements must not cross workspace boundaries.
  • Admin bypass behavior should be explicit and tested.

Admin Users

src/lib/coins/metering.ts includes admin bypass handling for AI coin metering. Do not treat admin bypass as a general authorization shortcut outside its specific use cases.