@atproto/oauth-client: atproto flavoured OAuth client
Core library for implementing atproto OAuth clients.
For a browser specific implementation, see @atproto/oauth-client-browser.
For a node specific implementation, see
@atproto/oauth-client-node.
Usage
Configuration
import { OAuthClient, Key, Session } from '@atproto/oauth-client'
import { JoseKey } from '@atproto/jwk-jose'
const client = new OAuthClient({
handleResolver: 'https://my-backend.example',
responseMode: 'query',
clientMetadata: {
client_id: 'https://my-app.example/atproto-oauth-client.json',
jwks_uri: 'https://my-app.example/jwks.json',
},
runtimeImplementation: {
createKey(algs: string[]): Promise<Key> {
return JoseKey.generate(algs)
},
getRandomValues(length: number): Uint8Array | PromiseLike<Uint8Array> {
return crypto.getRandomValues(new Uint8Array(length))
},
digest(
bytes: Uint8Array,
algorithm: { name: string },
): Uint8Array | PromiseLike<Uint8Array> {
if (algorithm.name.startsWith('sha')) {
const subtleAlgo = `SHA-${algorithm.name.slice(3)}`
const buffer = await crypto.subtle.digest(subtleAlgo, bytes)
return new Uint8Array(buffer)
}
throw new TypeError(`Unsupported algorithm: ${algorithm.name}`)
},
requestLock: <T>(
name: string,
fn: () => T | PromiseLike<T>,
): Promise<T> => {
declare const locks: Map<string, Promise<void>>
const current = locks.get(name) || Promise.resolve()
const next = current
.then(fn)
.catch(() => {})
.finally(() => {
if (locks.get(name) === next) locks.delete(name)
})
locks.set(name, next)
return next
},
},
stateStore: {
set(key: string, internalState: InternalStateData): Promise<void> {
throw new Error('Not implemented')
},
get(key: string): Promise<InternalStateData | undefined> {
throw new Error('Not implemented')
},
del(key: string): Promise<void> {
throw new Error('Not implemented')
},
},
sessionStore: {
set(sub: string, session: Session): Promise<void> {
throw new Error('Not implemented')
},
get(sub: string): Promise<Session | undefined> {
throw new Error('Not implemented')
},
del(sub: string): Promise<void> {
throw new Error('Not implemented')
},
},
keyset: [
await JoseKey.fromImportable(process.env.PRIVATE_KEY_1),
await JoseKey.fromImportable(process.env.PRIVATE_KEY_2),
await JoseKey.fromImportable(process.env.PRIVATE_KEY_3),
],
})
Authentication
const url = await client.authorize('foo.bsky.team', {
state: '434321',
prompt: 'consent',
scope: 'email',
ui_locales: 'fr',
})
Make user visit url
. Then, once it was redirected to the callback URI, perform the following:
const params = new URLSearchParams('code=...&state=...')
const result = await client.callback(params)
result.state === '434321'
const oauthSession = result.session
The sign-in process results in an OAuthSession
instance that can be used to make
authenticated requests to the resource server. This instance will automatically
refresh the credentials when needed.
Making authenticated requests
The OAuthSession
instance obtained after signing in can be used to make
authenticated requests to the user's PDS. There are two main use-cases:
-
Making authenticated request to Bluesky's AppView in order to fetch and
manipulate data from the app.bsky
lexicon.
-
Making authenticated request to your own AppView, in order to fetch and
manipulate data from your own lexicon.
Making authenticated requests to Bluesky's AppView
The @atproto/oauth-client
package provides a OAuthSession
class that can be
used to make authenticated requests to Bluesky's AppView. This can be achieved
by constructing an Agent
(from @atproto/api
) instance using the
OAuthSession
instance.
import { Agent } from '@atproto/api'
const agent = new Agent(oauthSession)
await agent.post({
text: 'Hello, world!',
})
await agent.signOut()
Making authenticated requests to your own AppView
The OAuthSession
instance obtained after signing in can be used to instantiate
the XrpcClient
class from the @atproto/xrpc
package.
import { Lexicons } from '@atproto/lexicon'
import { OAuthClient } from '@atproto/oauth-client'
import { XrpcClient } from '@atproto/xrpc'
const myLexicon = new Lexicons([
{
lexicon: 1,
id: 'com.example.query',
defs: {
main: {
},
},
},
])
const oauthClient = new OAuthClient({
})
const oauthSession = await oauthClient.restore('did:plc:123')
const client = new XrpcClient(oauthSession, myLexicon)
const response = await client.call('com.example.query')
Note that the user's PDS might not know about your lexicon, or what to do with
those calls (PDS' are only mandated to implement the com.atproto
lexicon). In
order to process your calls, you need to have a backend that will process those
calls. You can then instruct your PDS to forward those calls to your backend.
const response = await client.call(
'com.example.query',
{
},
{
headers: {
'atproto-proxy': 'did:plc:xyz#serviceId',
},
},
)
You can also instantiate the XrpcClient
class with a custom fetch
function
that will provide the atproto-proxy
header on all calls:
const boundClient = new XrpcClient((url, init) => {
const headers = new Headers(init?.headers)
if (!headers.has('atproto-proxy')) {
headers.set('atproto-proxy', 'did:plc:xyz#serviceId')
}
return oauthSession.fetchHandler(url, { ...init, headers })
}, myLexicon)
const response = await boundClient.call('com.example.query')
[!NOTE]
Proxying every call through the PDS is not recommended for performance
reasons, as it will increase the latency of readonly calls to your lexicon.
Doing so will also prevent your backend from being able to anticipate writes
on the network. Indeed, write calls will be sent to the PDS, which will then
propagate them on the network through a relay (a.k.a. "firehose"). This will
introduce a delay between the time the write is made and the time it is
processed by your backend.
In order to avoid those issues, it is recommended that you implement your
backend using a backend-for-frontend pattern. This backend will be responsible
for processing the calls made by the client, and will be able to anticipate
writes on the network.
Read more about the backend-for-frontend pattern in the atproto
documentation website.
Advances use-cases
Listening for session updates and deletion
The OAuthClient
will emit events whenever a session is updated or deleted.
import {
Session,
TokenRefreshError,
TokenRevokedError,
} from '@atproto/oauth-client'
client.addEventListener('updated', (event: CustomEvent<Session>) => {
console.log('Refreshed tokens were saved in the store:', event.detail)
})
client.addEventListener(
'deleted',
(
event: CustomEvent<{
sub: string
cause: TokenRefreshError | TokenRevokedError | unknown
}>,
) => {
console.log('Session was deleted from the session store:', event.detail)
const { cause } = event.detail
if (cause instanceof TokenRefreshError) {
} else if (cause instanceof TokenRevokedError) {
} else {
}
},
)
Force user to re-authenticate
const url = await client.authorize(handle, {
prompt: 'login',
state,
})
or
const url = await client.authorize(handle, {
state,
})
Silent Sign-In
Using silent sign-in requires to handle retries on the callback endpoint.
async function createLoginUrl(handle: string, state?: string): string {
return client.authorize(handle, {
state,
prompt: 'none',
})
}
async function handleCallback(params: URLSearchParams) {
try {
return await client.callback(params)
} catch (err) {
if (
err instanceof OAuthCallbackError &&
['login_required', 'consent_required'].includes(err.params.get('error'))
) {
const url = await client.authorize(handle, { state: err.state })
return new MyLoginRequiredError(url)
}
throw err
}
}