{"_id":"@bluesky-social/oauth-client-node","_rev":"2-6324a261c86bfab88ffb418e0a82a62b","name":"@bluesky-social/oauth-client-node","dist-tags":{"latest":"0.3.9"},"versions":{"0.3.3":{"name":"@bluesky-social/oauth-client-node","version":"0.3.3","keywords":["atproto","oauth","client","node"],"license":"MIT","_id":"@bluesky-social/oauth-client-node@0.3.3","maintainers":[{"name":"openweb3.io","email":"mtsocialdao@gmail.com"},{"name":"web3km","email":"web3km@proton.me"}],"homepage":"https://atproto.com","bugs":{"url":"https://github.com/bluesky-social/atproto/issues"},"dist":{"shasum":"7896a1bcda45b7f76c9dc5e4c7f2e30ee8841249","tarball":"https://registry.npmjs.org/@bluesky-social/oauth-client-node/-/oauth-client-node-0.3.3.tgz","fileCount":19,"integrity":"sha512-kkGRZ/hq6FF1w9ngJUmmhwLVhaq1p+DeAiCUhVCklxaq79JAHGpKLKYYv9iJ/E671IIWX+TbEcdYHdYxH8noCA==","signatures":[{"sig":"MEUCIGEfe/eyPTjkU6k6h0L3OlLhVGOcxJxJmdbHTNTvvstIAiEAgkOs/NQIsL8bf8uSHP7H2D6ZTSsaZ40GoCdGvJiaH0w=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":27881},"main":"dist/index.js","type":"commonjs","_from":"file:bluesky-social-oauth-client-node-0.3.3.tgz","types":"dist/index.d.ts","engines":{"node":">=18.7.0"},"exports":{".":{"types":"./dist/index.d.ts","default":"./dist/index.js"}},"scripts":{"build":"tsc --build tsconfig.build.json"},"_npmUser":{"name":"web3km","email":"web3km@proton.me"},"_resolved":"/private/var/folders/cb/7sst87dj7jd40nc7b7q7h76r0000gn/T/9c1af3d7012ba55ff968a9d45ce3948a/bluesky-social-oauth-client-node-0.3.3.tgz","_integrity":"sha512-kkGRZ/hq6FF1w9ngJUmmhwLVhaq1p+DeAiCUhVCklxaq79JAHGpKLKYYv9iJ/E671IIWX+TbEcdYHdYxH8noCA==","repository":{"url":"git+https://github.com/bluesky-social/atproto.git","type":"git","directory":"packages/oauth/oauth-client-node"},"_npmVersion":"10.8.2","description":"ATPROTO OAuth client for the NodeJS","directories":{},"_nodeVersion":"18.20.8","dependencies":{"@bluesky-social/did":"0.1.5","@bluesky-social/jwk":"0.4.0","@bluesky-social/jwk-jose":"0.1.9","@atproto-labs/did-resolver":"0.2.0","@atproto-labs/simple-store":"0.2.0","@bluesky-social/oauth-types":"0.4.0","@bluesky-social/oauth-client":"0.5.1","@bluesky-social/jwk-webcrypto":"0.1.9","@atproto-labs/handle-resolver-node":"0.1.18"},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^5.6.3"},"_npmOperationalInternal":{"tmp":"tmp/oauth-client-node_0.3.3_1753545369460_0.7291328655204952","host":"s3://npm-registry-packages-npm-production"}},"0.3.9":{"name":"@bluesky-social/oauth-client-node","version":"0.3.9","license":"MIT","description":"ATPROTO OAuth client for the NodeJS","keywords":["atproto","oauth","client","node"],"homepage":"https://atproto.com","repository":{"type":"git","url":"git+https://github.com/bluesky-social/atproto.git","directory":"packages/oauth/oauth-client-node"},"type":"commonjs","main":"dist/index.js","types":"dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","default":"./dist/index.js"}},"engines":{"node":">=18.7.0"},"dependencies":{"@atproto-labs/did-resolver":"0.2.2","@bluesky-social/did":"0.2.1","@bluesky-social/jwk-jose":"0.1.11","@bluesky-social/jwk":"0.6.0","@atproto-labs/simple-store":"0.3.0","@bluesky-social/jwk-webcrypto":"0.2.0","@bluesky-social/oauth-types":"0.4.2","@bluesky-social/oauth-client":"0.5.7","@atproto-labs/handle-resolver-node":"0.1.20"},"devDependencies":{"typescript":"^5.9.3"},"scripts":{"build":"tsc --build tsconfig.build.json"},"_id":"@bluesky-social/oauth-client-node@0.3.9","bugs":{"url":"https://github.com/bluesky-social/atproto/issues"},"_integrity":"sha512-DAg8YosJLeUn8Z32+i/i/nEzyhwoa9M3JlCOyghHOmJHImht8ZgrQP1vkDyx0GNDfaLMAmAmd0NLcPFR+JX1dw==","_resolved":"/private/var/folders/cb/7sst87dj7jd40nc7b7q7h76r0000gn/T/dcd1ebe9fd36a477fb3b5c6b0685674a/bluesky-social-oauth-client-node-0.3.9.tgz","_from":"file:bluesky-social-oauth-client-node-0.3.9.tgz","_nodeVersion":"20.15.0","_npmVersion":"10.7.0","dist":{"integrity":"sha512-DAg8YosJLeUn8Z32+i/i/nEzyhwoa9M3JlCOyghHOmJHImht8ZgrQP1vkDyx0GNDfaLMAmAmd0NLcPFR+JX1dw==","shasum":"02243b7c35a053a92afb2673786165af52fd56d3","tarball":"https://registry.npmjs.org/@bluesky-social/oauth-client-node/-/oauth-client-node-0.3.9.tgz","fileCount":19,"unpackedSize":32583,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQCBPCIl/yYcegJBkfYdMfN2eG6mS2GyJLjteRf/63AokQIhAMobDwBdjc7s5xFZQZJ5w/JIl9DRoDNF8lnqO8oBzUOZ"}]},"_npmUser":{"name":"web3km","email":"web3km@proton.me"},"directories":{},"maintainers":[{"name":"openweb3.io","email":"mtsocialdao@gmail.com"},{"name":"web3km","email":"web3km@proton.me"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/oauth-client-node_0.3.9_1761039229358_0.8416418055941821"},"_hasShrinkwrap":false}},"time":{"created":"2025-07-26T15:56:09.333Z","modified":"2025-10-21T09:33:49.795Z","0.3.3":"2025-07-26T15:56:09.654Z","0.3.9":"2025-10-21T09:33:49.572Z"},"bugs":{"url":"https://github.com/bluesky-social/atproto/issues"},"license":"MIT","homepage":"https://atproto.com","keywords":["atproto","oauth","client","node"],"repository":{"type":"git","url":"git+https://github.com/bluesky-social/atproto.git","directory":"packages/oauth/oauth-client-node"},"description":"ATPROTO OAuth client for the NodeJS","maintainers":[{"name":"openweb3.io","email":"mtsocialdao@gmail.com"},{"name":"web3km","email":"web3km@proton.me"}],"readme":"# atproto OAuth Client for NodeJS\n\nThis package implements all the OAuth features required by [ATPROTO] (PKCE,\netc.) to run in a NodeJS based environment such as desktop apps built with\nElectron or traditional web app backends built with frameworks like Express.\n\n## Setup\n\n### Client configuration\n\nThe `client_id` is what identifies your application to the OAuth server. It is\nused to fetch the client metadata, and to initiate the OAuth flow. The\n`client_id` must be a URL that points to the client metadata.\n\nYour OAuth client metadata should be hosted at a URL that corresponds to the\n`client_id` of your application. This URL should return a JSON object with the\nclient metadata. The client metadata should be configured according to the\nneeds of your application, and must respect the [ATPROTO].\n\n#### From a backend service\n\nThe `client_metadata` object will typically be built by the backend at startup.\n\n```ts\nimport { NodeOAuthClient, Session } from '@bluesky-social/oauth-client-node'\nimport { JoseKey } from '@bluesky-social/jwk-jose'\n\nconst client = new NodeOAuthClient({\n  // This object will be used to build the payload of the /client-metadata.json\n  // endpoint metadata, exposing the client metadata to the OAuth server.\n  clientMetadata: {\n    // Must be a URL that will be exposing this metadata\n    client_id: 'https://my-app.com/client-metadata.json',\n    client_name: 'My App',\n    client_uri: 'https://my-app.com',\n    logo_uri: 'https://my-app.com/logo.png',\n    tos_uri: 'https://my-app.com/tos',\n    policy_uri: 'https://my-app.com/policy',\n    redirect_uris: ['https://my-app.com/callback'],\n    grant_types: ['authorization_code', 'refresh_token'],\n    scope: 'atproto transition:generic',\n    response_types: ['code'],\n    application_type: 'web',\n    token_endpoint_auth_method: 'private_key_jwt',\n    token_endpoint_auth_signing_alg: 'RS256',\n    dpop_bound_access_tokens: true,\n    jwks_uri: 'https://my-app.com/jwks.json',\n  },\n\n  // Used to authenticate the client to the token endpoint. Will be used to\n  // build the jwks object to be exposed on the \"jwks_uri\" endpoint.\n  keyset: await Promise.all([\n    JoseKey.fromImportable(process.env.PRIVATE_KEY_1, 'key1'),\n    JoseKey.fromImportable(process.env.PRIVATE_KEY_2, 'key2'),\n    JoseKey.fromImportable(process.env.PRIVATE_KEY_3, 'key3'),\n  ]),\n\n  // Interface to store authorization state data (during authorization flows)\n  stateStore: {\n    async set(key: string, internalState: NodeSavedState): Promise<void> {},\n    async get(key: string): Promise<NodeSavedState | undefined> {},\n    async del(key: string): Promise<void> {},\n  },\n\n  // Interface to store authenticated session data\n  sessionStore: {\n    async set(sub: string, session: Session): Promise<void> {},\n    async get(sub: string): Promise<Session | undefined> {},\n    async del(sub: string): Promise<void> {},\n  },\n\n  // A lock to prevent concurrent access to the session store. Optional if only one instance is running.\n  requestLock,\n})\n\nconst app = express()\n\n// Expose the metadata and jwks\napp.get('client-metadata.json', (req, res) => res.json(client.clientMetadata))\napp.get('jwks.json', (req, res) => res.json(client.jwks))\n\n// Create an endpoint to initiate the OAuth flow\napp.get('/login', async (req, res, next) => {\n  try {\n    const handle = 'some-handle.bsky.social' // eg. from query string\n    const state = '434321'\n\n    // Revoke any pending authentication requests if the connection is closed (optional)\n    const ac = new AbortController()\n    req.on('close', () => ac.abort())\n\n    const url = await client.authorize(handle, {\n      signal: ac.signal,\n      state,\n      // Only supported if OAuth server is openid-compliant\n      ui_locales: 'fr-CA fr en',\n    })\n\n    res.redirect(url)\n  } catch (err) {\n    next(err)\n  }\n})\n\n// Create an endpoint to handle the OAuth callback\napp.get('/atproto-oauth-callback', async (req, res, next) => {\n  try {\n    const params = new URLSearchParams(req.url.split('?')[1])\n\n    const { session, state } = await client.callback(params)\n\n    // Process successful authentication here\n    console.log('authorize() was called with state:', state)\n\n    console.log('User authenticated as:', session.did)\n\n    const agent = new Agent(session)\n\n    // Make Authenticated API calls\n    const profile = await agent.getProfile({ actor: agent.did })\n    console.log('Bsky profile:', profile.data)\n\n    res.json({ ok: true })\n  } catch (err) {\n    next(err)\n  }\n})\n\n// Whenever needed, restore a user's session\nasync function worker() {\n  const userDid = 'did:plc:123'\n\n  const oauthSession = await client.restore(userDid)\n\n  // Note: If the current access_token is expired, the session will automatically\n  // (and transparently) refresh it. The new token set will be saved though\n  // the client's session store.\n\n  const agent = new Agent(oauthSession)\n\n  // Make Authenticated API calls\n  const profile = await agent.getProfile({ actor: agent.did })\n  console.log('Bsky profile:', profile.data)\n}\n```\n\n#### From a native application\n\nThis applies to mobile apps, desktop apps, etc. based on NodeJS (e.g. Electron).\n\nThe client metadata must be hosted on an internet-accessible URL owned by you.\nThe client metadata will typically contain:\n\n```json\n{\n  \"client_id\": \"https://my-app.com/client-metadata.json\",\n  \"client_name\": \"My App\",\n  \"client_uri\": \"https://my-app.com\",\n  \"logo_uri\": \"https://my-app.com/logo.png\",\n  \"tos_uri\": \"https://my-app.com/tos\",\n  \"policy_uri\": \"https://my-app.com/policy\",\n  \"redirect_uris\": [\"https://my-app.com/atproto-oauth-callback\"],\n  \"scope\": \"atproto\",\n  \"grant_types\": [\"authorization_code\", \"refresh_token\"],\n  \"response_types\": [\"code\"],\n  \"application_type\": \"native\",\n  \"token_endpoint_auth_method\": \"none\",\n  \"dpop_bound_access_tokens\": true\n}\n```\n\nInstead of hard-coding the client metadata in your app, you can fetch it when\nthe app starts:\n\n```ts\nimport { NodeOAuthClient } from '@bluesky-social/oauth-client-node'\n\nconst client = await NodeOAuthClient.fromClientId({\n  clientId: 'https://my-app.com/client-metadata.json',\n\n  stateStore: {\n    async set(key: string, internalState: NodeSavedState): Promise<void> {},\n    async get(key: string): Promise<NodeSavedState | undefined> {},\n    async del(key: string): Promise<void> {},\n  },\n\n  sessionStore: {\n    async set(sub: string, session: Session): Promise<void> {},\n    async get(sub: string): Promise<Session | undefined> {},\n    async del(sub: string): Promise<void> {},\n  },\n\n  // A lock to prevent concurrent access to the session store. Optional if only one instance is running.\n  requestLock,\n})\n```\n\n> [!NOTE]\n>\n> There is no `keyset` in this instance. This is due to the fact that app\n> clients cannot safely store a private key. The `token_endpoint_auth_method` is\n> set to `none` in the client metadata, which means that the client will not be\n> authenticating itself to the token endpoint. This will cause sessions to have\n> a shorter lifetime. You can circumvent this by providing a \"BFF\" (Backend for\n> Frontend) that will perform an authenticated OAuth flow and use a session id\n> based mechanism to authenticate the client.\n\n### Common configuration options\n\nThe `OAuthClient` and `OAuthAgent` classes will manage and refresh OAuth tokens\ntransparently. They are also responsible to properly format the HTTP requests\npayload, using DPoP, and transparently retrying requests when the access token\nexpires.\n\nFor this to work, the client must be configured with the following options:\n\n#### `sessionStore`\n\nA simple key-value store to save the OAuth session data. This is used to save\nthe access token, refresh token, and other session data.\n\n```ts\nconst sessionStore: NodeSavedSessionStore = {\n  async set(sub: string, sessionData: NodeSavedSession) {\n    // Insert or update the session data in your database\n    await saveSessionDataToDb(sub, sessionData)\n  },\n\n  async get(sub: string) {\n    // Retrieve the session data from your database\n    const sessionData = await getSessionDataFromDb(sub)\n    if (!sessionData) return undefined\n\n    return sessionData\n  },\n\n  async del(sub: string) {\n    // Delete the session data from your database\n    await deleteSessionDataFromDb(sub)\n  },\n}\n```\n\n#### `stateStore`\n\nA simple key-value store to save the state of the OAuth\nauthorization flow. This is used to prevent CSRF attacks.\n\nThe implementation of the `StateStore` is similar to the\n[`sessionStore`](#sessionstore).\n\n```ts\ninterface NodeSavedStateStore {\n  set: (key: string, internalState: NodeSavedState) => Promise<void>\n  get: (key: string) => Promise<NodeSavedState | undefined>\n  del: (key: string) => Promise<void>\n}\n```\n\nOne notable exception is that state store items can (and should) be deleted\nafter a short period of time (one hour should be more than enough).\n\n#### `requestLock`\n\nWhen multiple instances of the client are running, this lock will prevent\nconcurrent refreshes of the same session.\n\nHere is an example implementation based on [`redlock`](https://www.npmjs.com/package/redlock):\n\n```ts\nimport { RuntimeLock } from '@bluesky-social/oauth-client-node'\nimport Redis from 'ioredis'\nimport Redlock from 'redlock'\n\nconst redisClients = new Redis()\nconst redlock = new Redlock(redisClients)\n\nconst requestLock: RuntimeLock = async (key, fn) => {\n  // 30 seconds should be enough. Since we will be using one lock per user id\n  // we can be quite liberal with the lock duration here.\n  const lock = await redlock.lock(key, 45e3)\n  try {\n    return await fn()\n  } finally {\n    await redlock.unlock(lock)\n  }\n}\n```\n\n## Usage with `@bluesky-social/api`\n\n`@bluesky-social/oauth-client-*` packages all return an `ApiClient` instance upon\nsuccessful authentication. This instance can be used to make authenticated\nrequests using all the `ApiClient` methods defined in [[API]] (non exhaustive\nlist of examples below). Any refresh of the credentials will happen under the\nhood, and the new tokens will be saved in the session store.\n\n```ts\nconst session = await client.restore('did:plc:123')\nconst agent = new Agent(session)\n\n// Feeds and content\nawait agent.getTimeline(params, opts)\nawait agent.getAuthorFeed(params, opts)\nawait agent.getPostThread(params, opts)\nawait agent.getPost(params)\nawait agent.getPosts(params, opts)\nawait agent.getLikes(params, opts)\nawait agent.getRepostedBy(params, opts)\nawait agent.post(record)\nawait agent.deletePost(postUri)\nawait agent.like(uri, cid)\nawait agent.deleteLike(likeUri)\nawait agent.repost(uri, cid)\nawait agent.deleteRepost(repostUri)\nawait agent.uploadBlob(data, opts)\n\n// Social graph\nawait agent.getFollows(params, opts)\nawait agent.getFollowers(params, opts)\nawait agent.follow(did)\nawait agent.deleteFollow(followUri)\n\n// Actors\nawait agent.getProfile(params, opts)\nawait agent.upsertProfile(updateFn)\nawait agent.getProfiles(params, opts)\nawait agent.getSuggestions(params, opts)\nawait agent.searchActors(params, opts)\nawait agent.searchActorsTypeahead(params, opts)\nawait agent.mute(did)\nawait agent.unmute(did)\nawait agent.muteModList(listUri)\nawait agent.unmuteModList(listUri)\nawait agent.blockModList(listUri)\nawait agent.unblockModList(listUri)\n\n// Notifications\nawait agent.listNotifications(params, opts)\nawait agent.countUnreadNotifications(params, opts)\nawait agent.updateSeenNotifications()\n\n// Identity\nawait agent.resolveHandle(params, opts)\nawait agent.updateHandle(params, opts)\n\n// etc.\n\n// Always remember to revoke the credentials when you are done\nawait session.signOut()\n```\n\n## Advances use-cases\n\n### Listening for session updates and deletion\n\nThe `OAuthClient` will emit events whenever a session is updated or deleted.\n\n```ts\nimport {\n  Session,\n  TokenRefreshError,\n  TokenRevokedError,\n} from '@bluesky-social/oauth-client-node'\n\nclient.addEventListener('updated', (event: CustomEvent<Session>) => {\n  console.log('Refreshed tokens were saved in the store:', event.detail)\n})\n\nclient.addEventListener(\n  'deleted',\n  (\n    event: CustomEvent<{\n      sub: string\n      cause: TokenRefreshError | TokenRevokedError | unknown\n    }>,\n  ) => {\n    console.log('Session was deleted from the session store:', event.detail)\n\n    const { cause } = event.detail\n\n    if (cause instanceof TokenRefreshError) {\n      // - refresh_token unavailable or expired\n      // - oauth response error (`cause.cause instanceof OAuthResponseError`)\n      // - session data does not match expected values returned by the OAuth server\n    } else if (cause instanceof TokenRevokedError) {\n      // Session was revoked through:\n      // - session.signOut()\n      // - client.revoke(sub)\n    } else {\n      // An unexpected error occurred, causing the session to be deleted\n    }\n  },\n)\n```\n\n### Silent Sign-In\n\nUsing silent sign-in requires to handle retries on the callback endpoint.\n\n```ts\napp.get('/login', async (req, res) => {\n  const handle = 'some-handle.bsky.social' // eg. from query string\n  const user = req.user.id\n\n  const url = await client.authorize(handle, {\n    // Use \"prompt=none\" to attempt silent sign-in\n    prompt: 'none',\n\n    // Build an internal state to map the login request to the user, and allow retries\n    state: JSON.stringify({\n      user,\n      handle,\n    }),\n  })\n\n  res.redirect(url)\n})\n\napp.get('/atproto-oauth-callback', async (req, res) => {\n  const params = new URLSearchParams(req.url.split('?')[1])\n  try {\n    try {\n      const { session, state } = await client.callback(params)\n\n      // Process successful authentication here. For example:\n\n      const agent = new Agent(session)\n\n      const profile = await agent.getProfile({ actor: agent.did })\n\n      console.log('Bsky profile:', profile.data)\n    } catch (err) {\n      // Silent sign-in failed, retry without prompt=none\n      if (\n        err instanceof OAuthCallbackError &&\n        ['login_required', 'consent_required'].includes(err.params.get('error'))\n      ) {\n        // Parse previous state\n        const { user, handle } = JSON.parse(err.state)\n\n        const url = await client.authorize(handle, {\n          // Note that we omit the prompt parameter here. Setting \"prompt=none\"\n          // here would result in an infinite redirect loop.\n\n          // Build a new state (or re-use the previous one)\n          state: JSON.stringify({\n            user,\n            handle,\n          }),\n        })\n\n        // redirect to new URL\n        res.redirect(url)\n\n        return\n      }\n\n      throw err\n    }\n  } catch (err) {\n    next(err)\n  }\n})\n```\n\n[ATPROTO]: https://atproto.com/ 'AT Protocol'\n[API]: ../../api/README.md\n","readmeFilename":"README.md"}