Skip to content

@plinthjs/oauth-client ​

An OAuth2 authorization-code client for Plinth. Resolve a provider through the OAuthClient manager (github, google, a generic oauth2 driver, or your own via extend), send the user to redirect(), then exchange the returned code for a OAuthUser.

All HTTP runs through an injectable @plinthjs/http-client HttpClient, and all randomness (state, PKCE verifiers) comes from node:crypto.

Install ​

sh
npm install @plinthjs/oauth-client

Usage ​

ts
import { OAuthClient } from '@plinthjs/oauth-client'

const oauthClient = new OAuthClient({
  config: {
    github: {
      clientId: process.env.GITHUB_CLIENT_ID!,
      clientSecret: process.env.GITHUB_CLIENT_SECRET!,
      redirectUrl: 'https://app.test/auth/github/callback',
    },
  },
})

// Step 1: send the user to the provider. redirect() returns the URL plus the per-flow secrets.
const { url, state } = oauthClient.driver('github').scopes('read:org').redirect()
session.put('oauth_state', state) // persist it, then redirect to `url`

// Step 2: on the callback, verify the state and exchange the code for a user.
// A mismatch or missing state throws InvalidStateError before any request is made.
const user = await oauthClient.driver('github').user({
  code,
  state: callbackState,
  expectedState: session.pull('oauth_state'),
})
user.getId() // '42'
user.getEmail() // 'ada@test.dev'
user.token // the OAuth access token
user.getRaw() // the untouched provider payload

driver() returns a fresh provider on every call and nothing about a flow lives on the instance, so concurrent requests cannot interfere. user() compares state with expectedState in constant time and throws InvalidStateError on a mismatch or when either is missing.

Configuring the authorize URL ​

ts
const provider = oauthClient
  .driver('google')
  .setScopes(['openid', 'email']) // replace the default scopes
  .scopes('profile') // or merge more in (de-duplicated)
  .with({ prompt: 'consent', access_type: 'offline' })
  .enablePkce()

const { url, state, codeVerifier } = provider.redirect()
// Store state and codeVerifier in the session; pass both back to user() on the callback:
// await oauthClient.driver('google').enablePkce().user({ code, state, expectedState, codeVerifier })

// Skip the state parameter entirely.
oauthClient.driver('github').stateless().redirect() // user({ code }) then skips the state check

An existing access token can be turned into a user without the code exchange: await provider.userFromToken(token).

Providers ​

GithubProvider (default scope user:email) and GoogleProvider (default scopes openid, profile, email) preset their endpoints and need only DriverCredentials. The generic oauth2 driver, or a bare AbstractProvider, takes a full ProviderConfig:

ts
import { AbstractProvider, OAuthClient, type ProviderConfig } from '@plinthjs/oauth-client'

const oauthClient = new OAuthClient({
  config: {
    oauth2: {
      clientId: 'client-123',
      clientSecret: 'secret-xyz',
      redirectUrl: 'https://app.test/callback',
      authUrl: 'https://provider.test/oauth/authorize',
      tokenUrl: 'https://provider.test/oauth/token',
      userUrl: 'https://provider.test/api/user',
      scopes: ['read'],
      tokenRequestFormat: 'form', // or 'json'
    },
  },
})

// Register a custom driver (the `OAuthClient::extend` equivalent).
oauthClient.extend('acme', (config) => new AbstractProvider(config as ProviderConfig))
oauthClient.hasDriver('acme') // true

Subclass AbstractProvider and override mapUserToObject(raw) to map a provider's profile shape. The stringField and numberField helpers read fields from a raw payload.

Testing ​

Pass an HttpClient wired to FakeHttp so no request leaves the process:

ts
import { FakeHttp, HttpClient } from '@plinthjs/http-client'

const fake = new FakeHttp()
fake.respond({ body: { access_token: 'tok', expires_in: 3600 } }, { method: 'POST' })
fake.respond({ body: { id: 42, name: 'Ada' } }, { method: 'GET' })

const oauthClient = new OAuthClient({ config, http: new HttpClient({ fetch: fake.fetch }) })

Released under the MIT License.