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.
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
Key Concepts
OAuth Client
The mainOAuthClient 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
Static Methods
fetchMetadata
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
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-inlogin: Force re-authenticationconsent: 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.
callback
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.
restore
string
required
The user’s DID (subject identifier).
boolean | 'auto'
default:"'auto'"
true: Force token refreshfalse: Use cached tokens'auto': Refresh if tokens are expired
OAuthSession
The restored session object.
TokenRefreshErrorif the session cannot be refreshedTokenRevokedErrorif the session was revoked
revoke
string
required
The user’s DID to revoke.
Properties
jwks
jwks_uri endpoint.
JsonWebKey[]
Array of public keys in JWK format.
clientMetadata
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
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
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.
signOut
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
TheOAuthClient 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
UseOAuthSession as a fetch handler for the Agent class:
Security Best Practices
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
requestLockto 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
Related Packages
@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