ObjectStackObjectStack

IAuthService — the authentication contract

Reference for the Auth Service contract — authentication, session verification, user resolution, and logout

The Auth Service handles authentication — verifying user identity through credentials, tokens, or external providers. It does not handle authorization (permissions); that is governed separately by the security layer (PermissionSets, sharing rules) in plugin-security.

Source: packages/spec/src/contracts/auth-service.ts
Service token: 'auth' (the CoreServiceName value; resolve with ctx.getService('auth'))


Interface Definition

export interface IAuthService {
  /** Handle an incoming HTTP authentication request (login, callback, etc.). */
  handleRequest(request: Request): Promise<Response>;

  /** Verify a bearer token or session identifier and return the result. */
  verify(token: string): Promise<AuthResult>;

  /** Invalidate a session (logout). Optional. */
  logout?(sessionId: string): Promise<void>;

  /** Resolve the current user from a request. Optional. */
  getCurrentUser?(request: Request): Promise<AuthUser | undefined>;

  /** The session API, when the provider mounts it directly (legacy shape). Optional. */
  api?: AuthSessionApi;

  /** Resolve the session API, creating the auth instance on first use. Optional. */
  getApi?(): Promise<AuthSessionApi | undefined>;

  /** Whether this deployment's auth gate is live. Optional. */
  isAuthGateActive?(): boolean;

  /** Is the user an administrator in the organization, under any of ADR-0090 D12's three kinds? Optional. */
  isOrganizationAdministrator?(userId: string, organizationId: string | undefined): Promise<boolean>;

  /** Verify an OAuth 2.1 access token from the embedded AS (MCP surface); the optional `organizationId` is the organization the user's OAuth consent bound, absent for a token minted before consents bound an organization. Optional. */
  verifyMcpAccessToken?(token: string): Promise<{ userId: string; scopes: string[]; clientId?: string; organizationId?: string } | undefined>;

  /** Record that the caller admitted a call made with a verified MCP access token: called once, after the caller's last refusal, with the object `verifyMcpAccessToken` returned; a principal the provider did not return records nothing. `transport` is the admitted request's headers and peer address, from which the provider establishes where the use came from. Never throws. Optional. */
  recordMcpAccessTokenUse?(principal: { userId: string; scopes: string[]; clientId?: string; organizationId?: string }, transport?: AuthRequestTransport): void;

  /** The client address the deployment establishes for a request (`headers`, `remoteAddress`) under its client-address trust rule, or `undefined` when it establishes none. Optional. */
  resolveClientAddress?(transport: AuthRequestTransport): string | undefined;

  /** The MCP resource identifier (RFC 8707 `resource` / token `aud`). Optional. */
  getMcpResourceUrl?(): string;

  /** RFC 9728 protected-resource metadata URL, or `null` when OAuth is off. Optional. */
  getMcpResourceMetadataUrl?(): string | null;
}

The two required members are the core: it follows the Dependency Inversion Principle so that plugins depend on the contract rather than a concrete provider. Concrete implementations (better-auth, custom, LDAP, etc.) supply the actual logic, and handleRequest works directly with the standard Request/Response types.

Everything after verify is optional, and each optional member describes a capability a provider may or may not have — a caller must probe before use. Three pairs are worth reading together:

  • api and getApi() are the same session handle by two routes. api is the legacy direct mount; getApi() is the lazy accessor, and it is the one to prefer — the shipped plugin-auth registers an AuthManager, which has no api member at all, so a caller that reads only api gets undefined on every current deployment. Read api ?? await getApi?.().
  • getMcpResourceUrl() and getMcpResourceMetadataUrl() both describe the MCP OAuth surface; the second returns null (rather than being absent) when the OAuth track is off for the deployment.
  • verifyMcpAccessToken() and recordMcpAccessTokenUse() split verifying a token from admitting the call. The MCP door verifies first, then applies its own refusals (a banned subject, an authorization store it could not read), and only for a call it admits hands the verified principal back to recordMcpAccessTokenUse(). So a refused call is never recorded as a use of the grant (the coarse "last used" time the authorized-clients reads show). Admitting is the decision about who calls, not every later verdict: a refusal of what the admitted principal then asks for (a 403 insufficient_scope for a token that grants none of the MCP tool families, a tool or an action its scopes do not reach) is still a use, and is recorded.
  • resolveClientAddress() is the one reading of a request's client address. A forwarded header (X-Forwarded-For, X-Real-IP) counts only when the deployment declares server.trustProxy, and under its trusted-network form ({ networks, header }) only when the transport's peer address is also inside the declared networks: both the peer and the declaration are needed. Otherwise the address is the transport's own peer address. A door hands the auth service the two facts it holds (AuthRequestTransport) and never reads a forwarded header as an address itself. The credential_use audit row records the address this member establishes, and recordMcpAccessTokenUse() establishes it the same way from its transport argument.

isOrganizationAdministrator() is the one reading of "is this user an administrator in this organization": it answers true for ADR-0090 D12's three kinds (tenant-level, organization-level and delegated, a delegated grant that cannot be read counting as an administrator), and the multi-factor requirement's administrators level asks this same member, so a caller outside the auth provider gets the gate's own answer.


Core Authentication

handleRequest

The HTTP entry point for authentication. It receives a standard Request (login, OAuth callback, etc.) and returns a standard Response. The concrete implementation owns route handling, credential parsing, and cookie/token issuance. An implementation answers its whole auth route surface here, the routes it mounts itself as well as its library's, so a host that forwards its auth path to this method serves what the implementation's own mount does.

With the shipped plugin-auth, a host that forwards to handleRequest gets:

  • The whole auth surface. Every route the self-hosted mount serves under /api/v1/auth/*: the routes the platform mounts itself (/config, /bootstrap-status, the /admin/* doors and the rest) and better-auth behind them, not better-auth alone.
  • The mount-layer checks. The same checks as the self-hosted mount run on this path: the IP allow-list (allowed_ip_ranges), the one-account-per-request rule, the organization IP list and the platform-admin wrappers.
  • An optional transport argument. The checks judge the client address from the transport the host passes. Pass the transport's peer as the second argument, handleRequest(request, { remoteAddress }), or declare server.trustProxy when the host sits behind a proxy that sets X-Forwarded-For. With neither, a deployment that sets allowed_ip_ranges answers 403 IP_NOT_ALLOWED. The second argument belongs to the plugin's AuthManager; the IAuthService shape above is unchanged.
// Wire the auth service into an HTTP handler
const response = await authService.handleRequest(request);
return response;

// With plugin-auth's AuthManager, also pass the transport's peer address
const managed = await authManager.handleRequest(request, { remoteAddress });

verify

Validates a bearer token or session identifier and returns an AuthResult. On success the result carries user and session; on failure success is false and error holds a message.

const result = await authService.verify(accessToken);
if (!result.success) {
  throw new Error(result.error ?? 'Invalid or expired token');
}
console.log(result.user?.email); // "jane@example.com"

logout

Invalidates a session by its identifier. This method is optional on the contract.

await authService.logout?.(session.id);

AuthUser Interface

The AuthUser object represents an authenticated user throughout the system.

export interface AuthUser {
  /** User identifier */
  id: string;
  /** Email address */
  email: string;
  /** Display name */
  name: string;
  /** Assigned position identifiers */
  positions?: string[];
  /** Current tenant identifier (multi-tenant) */
  tenantId?: string;
}
PropertyTypeDescription
idstringUnique user identifier
emailstringUser's email address
namestringDisplay name
positionsstring[]?Assigned position identifiers
tenantIdstring?Current tenant identifier (multi-tenant)

User Resolution

getCurrentUser

Resolves the authenticated user from a request. Returns undefined when the request is unauthenticated. This method is optional on the contract.

const user = await authService.getCurrentUser?.(request);
if (user) {
  console.log(`Request from ${user.name} (${user.positions?.join(', ')})`);
}

AuthSession Interface

export interface AuthSession {
  /** Session identifier */
  id: string;
  /** Associated user identifier */
  userId: string;
  /** Session expiry (ISO 8601) */
  expiresAt: string;
  /** Bearer token (if not using cookies) */
  token?: string;
}

AuthResult

verify resolves to an AuthResult. On success it carries the user and session; on failure error holds a message string.

export interface AuthResult {
  /** Whether authentication succeeded */
  success: boolean;
  /** Authenticated user (if success) */
  user?: AuthUser;
  /** Active session (if success) */
  session?: AuthSession;
  /** Error message (if failure) */
  error?: string;
}

On this page