Skip to main content

Overview

The @atproto/oauth-client package provides the core OAuth client implementation for AT Protocol. This is a platform-agnostic base library that serves as the foundation for environment-specific implementations.
This package is designed as a base library. For production use, consider:

Installation

When to Use This Package

Use @atproto/oauth-client directly when:
  • Building a custom OAuth client for a non-standard environment
  • Creating a new platform-specific implementation
  • You need full control over runtime dependencies
For most use cases, prefer the platform-specific packages that provide pre-configured runtime implementations.

Key Concepts

OAuth Client

The main OAuthClient class manages the complete OAuth flow:
  • Authorization: Initiate OAuth flows with AT Protocol servers
  • Token Management: Handle access and refresh tokens automatically
  • DPoP: Built-in Demonstrating Proof-of-Possession support
  • PKCE: Automatic Proof Key for Code Exchange
  • Session Management: Persistent session storage and restoration

Runtime Implementation

The client requires a runtime implementation that provides platform-specific cryptographic operations:

Core Types

OAuthClientOptions

Configuration options for creating an OAuth client.
OAuthClientMetadataInput
required
Client metadata including client_id, redirect_uris, and other OAuth client configuration.
'query' | 'fragment' | 'form_post'
required
How the authorization response is returned:
  • query: Parameters in URL query string (recommended for backend)
  • fragment: Parameters in URL fragment (recommended for browser)
  • form_post: Parameters via HTTP POST (backend only)
RuntimeImplementation
required
Platform-specific implementation of cryptographic operations.
StateStore
required
Storage for OAuth state during authorization flows. Must implement:
SessionStore
required
Storage for authenticated sessions. Must implement:
Keyset | Iterable<Key>
Private keys for client authentication (backend clients only). Required when using private_key_jwt authentication.
string | URL | HandleResolver
Service URL or instance for resolving AT Protocol handles to DIDs.
boolean
default:"false"
Allow HTTP connections for development. Never use in production.
Fetch
Custom fetch implementation for HTTP requests.
(sub: string, session: Session) => void
Callback when a session is updated (e.g., token refresh).
(sub: string, cause: Error) => void
Callback when a session is deleted or revoked.

Main Class: OAuthClient

Constructor

Creates a new OAuth client instance with the provided configuration.

Static Methods

fetchMetadata

Fetches client metadata from a discoverable client ID URL.
string
required
The client ID URL (must start with https://).
Fetch
Custom fetch implementation.
AbortSignal
Signal to abort the request.
OAuthClientMetadata
The parsed and validated client metadata.

Instance Methods

authorize

Initiates an OAuth authorization flow. Returns the URL to redirect the user to.
string
required
User’s handle (e.g., alice.bsky.social), DID (e.g., did:plc:xyz), or PDS URL.
string
Application state to preserve through the OAuth flow.
string
OAuth scopes to request (defaults to client metadata scope).
'none' | 'login' | 'consent'
  • none: Attempt silent sign-in
  • login: Force re-authentication
  • consent: Force re-consent
string
Preferred locales for the authorization UI (e.g., en-US en).
string
Override the default redirect URI from client metadata.
AbortSignal
Signal to abort the authorization.
URL
The URL to redirect the user to for authorization.
Example:

callback

Processes the OAuth callback after the user is redirected back.
URLSearchParams
required
URL parameters from the callback (query or fragment depending on response mode).
string
The redirect URI that was used (must match authorization request).
OAuthSession
The authenticated session object.
string
The application state from the authorization request.
Example:

restore

Restores a previously authenticated session from storage.
string
required
The user’s DID (subject identifier).
boolean | 'auto'
default:"'auto'"
  • true: Force token refresh
  • false: Use cached tokens
  • 'auto': Refresh if tokens are expired
OAuthSession
The restored session object.
Throws:
  • TokenRefreshError if the session cannot be refreshed
  • TokenRevokedError if the session was revoked
Example:

revoke

Revokes an active session and deletes it from storage.
string
required
The user’s DID to revoke.
Example:

Properties

jwks

Returns the public JWKS (JSON Web Key Set) for this client. Use this to expose your client’s public keys at the jwks_uri endpoint.
JsonWebKey[]
Array of public keys in JWK format.
Example:

clientMetadata

The validated client metadata being used by this client.

OAuthSession Class

Represents an authenticated session with automatic token management.

Properties

AtprotoDid
The user’s DID (decentralized identifier).
AtprotoDid
Alias for did - the subject identifier.
OAuthAuthorizationServerMetadata
Metadata of the authorization server that issued this session.

Methods

getTokenInfo

Retrieves information about the current access token.
Date
When the access token expires.
boolean
Whether the token is currently expired.
string
The granted OAuth scopes.
string
The issuer (authorization server URL).
string
The audience (resource server URL).
string
The subject (user’s DID).

fetchHandler

Makes an authenticated HTTP request with automatic token refresh.
string
required
The path to request (relative to the resource server).
RequestInit
Standard fetch options (method, headers, body, etc.).
Response
The HTTP response from the server.
Example:

signOut

Revokes the session tokens on the server and deletes the local session. Example:

Error Classes

OAuthCallbackError

Thrown when the OAuth callback contains an error response.
URLSearchParams
The callback parameters containing the error.
string | null
The state parameter from the request.

TokenRefreshError

Thrown when a token refresh fails.

TokenRevokedError

Thrown when a session is revoked.

TokenInvalidError

Thrown when a token is rejected by the resource server.

OAuth Flow Example

Complete Authorization Flow

Events

The OAuthClient extends EventTarget and emits the following events:

updated

Fired when a session is updated (e.g., after token refresh).

deleted

Fired when a session is deleted from storage.

Integration with @atproto/api

Use OAuthSession as a fetch handler for the Agent class:

Security Best Practices

Follow these security guidelines when implementing OAuth clients:

State Management

  • Always use state parameter to prevent CSRF attacks
  • Store state securely with short TTL (≤1 hour)
  • Validate state matches on callback

Key Storage

  • Backend clients: Store private keys securely (environment variables, key management services)
  • Frontend clients: Use token_endpoint_auth_method: 'none' (no private keys)
  • Never expose private keys in client-side code

Token Handling

  • Store sessions securely (encrypted database, secure cookies)
  • Implement proper session cleanup
  • Use requestLock to prevent concurrent token refreshes
  • Handle token expiration gracefully

Network Security

  • Production: Only use HTTPS connections (allowHttp: false)
  • Development: Use secure tunneling (ngrok) or loopback addresses
  • Validate all OAuth server metadata

Error Handling

@atproto/oauth-client-browser

Browser-specific OAuth client with IndexedDB storage

@atproto/oauth-client-node

Node.js OAuth client with built-in runtime

@atproto/oauth-provider

OAuth authorization server implementation

@atproto/api

High-level AT Protocol API client

Advanced Topics

Custom Handle Resolver

Silent Sign-In

Attempt authentication without user interaction:

Multi-Account Support

TypeScript Types

All types are fully typed with TypeScript: