Skip to content

OAuth Client ​

Introduction ​

"Sign in with GitHub" and "Sign in with Google" let users authenticate with an account they already have. @plinthjs/oauth-client implements the OAuth 2.0 authorization-code flow from the client side. You send the user to the provider, the provider sends them back with a code, and you exchange that code for the user's profile. It ships providers for GitHub and Google, a generic OAuth 2.0 provider you configure with your own endpoints, and a base class for writing more.

bash
pnpm add @plinthjs/oauth-client

All network calls go through the HttpClient from HTTP Client, so you can fake them in tests. Randomness comes from node:crypto.

Configuring providers ​

Providers are resolved by name from a OAuthClient manager. Give it one configuration entry per provider you use. For GitHub and Google you only supply your credentials, because the endpoints are built in:

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',
    },
    google: {
      clientId: process.env['GOOGLE_CLIENT_ID'] ?? '',
      clientSecret: process.env['GOOGLE_CLIENT_SECRET'] ?? '',
      redirectUrl: 'https://app.test/auth/google/callback',
    },
  },
})

const github = oauthClient.driver('github')

The redirectUrl must match the callback URL you registered with the provider. driver(name) builds a fresh provider on every call, so settings such as scopes(), with(), stateless(), and enablePkce() apply to that one flow and never leak between concurrent requests. Asking for a name with no registered driver throws OAuthClient driver [name] is not supported., and a driver with no configuration entry throws OAuthClient driver [name] has no configuration. hasDriver(name) reports whether a driver is registered.

Each credentials entry also accepts optional scopes, scopeSeparator, and http (a custom HttpClient).

The sign-in flow ​

The flow has two routes: one that redirects to the provider and one that handles the callback.

Redirecting to the provider ​

redirect() returns an object with the authorization url and the per-flow secrets: the random state that protects against forged callbacks and, when PKCE is on, the codeVerifier. Nothing is kept on the provider, so save these values in the session and redirect:

ts
import { Response } from '@plinthjs/http'
import { session } from '@plinthjs/session'

router.get('/auth/github', (request) => {
  const { url, state } = oauthClient.driver('github').redirect()

  session(request).put('oauth.state', state)
  return Response.redirectTo(url)
})

Handling the callback ​

On the callback, pass the returned state and the saved one to user(). It compares them in constant time and throws InvalidStateError on a mismatch or when either is missing, before any request reaches the provider:

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

router.get('/auth/github/callback', async (request) => {
  let user
  try {
    user = await oauthClient.driver('github').user({
      code: request.string('code'),
      state: request.query('state'),
      expectedState: session(request).pull<string>('oauth.state'),
    })
  } catch (error) {
    if (error instanceof InvalidStateError) return Response.make('Invalid state.', 400)
    throw error
  }

  user.id // => '42'
  user.nickname // => 'ada'
  user.name // => 'Ada'
  user.email // => 'ada@example.com'
  user.avatar // => 'https://.../avatar.png'
  user.token // the access token
  user.refreshToken // present when the provider issued one
  user.expiresIn // seconds, when reported

  // Find or create your own user from user.id and user.email, then log them in.
  return Response.redirectTo('/dashboard')
})

Skipping the state comparison is not possible: user() requires expectedState unless the provider is stateless (see below). Pass pull()'s result straight through so the saved value is single use.

The OAuthUser has id, nickname, name, email, avatar, token, refreshToken, expiresIn, and raw, the untouched profile payload from the provider. Optional fields are simply absent when the provider did not supply them. Getter methods (getId(), getName(), getEmail(), and so on) are also available.

After you have the profile, find or create a user in your own database and log them in with a guard from Authentication, remembering to regenerate the session.

If you already hold an access token, skip the code exchange with userFromToken(token):

ts
const user = await oauthClient.driver('github').userFromToken(existingAccessToken)

Scopes and extra parameters ​

GitHub requests user:email by default and Google requests openid, profile, and email. Add more with scopes() or replace the list with setScopes(). with() adds arbitrary query parameters to the authorization URL:

ts
const provider = oauthClient
  .driver('google')
  .scopes('https://www.googleapis.com/auth/calendar.readonly')
  .with({ prompt: 'consent', access_type: 'offline' })

provider.getScopes() // => ['openid', 'profile', 'email', 'https://www.googleapis.com/auth/calendar.readonly']
const { url } = provider.redirect()

Each driver() call starts from the configured defaults, so these settings are per flow.

Stateless flows ​

Use stateless() to omit the state parameter. This suits APIs that cannot keep a session, but it gives up the forgery protection that state provides, so reserve it for cases where you have another defence. A stateless provider skips the state check, and user({ code }) (or the bare user(code)) works without expectedState:

ts
const { url } = oauthClient.driver('github').stateless().redirect() // no state in the URL
const user = await oauthClient.driver('github').stateless().user({ code })

A stateful provider rejects the bare user(code) form with InvalidStateError.

PKCE ​

PKCE (Proof Key for Code Exchange) protects the code exchange by tying it to a secret that only your client knows. Turn it on with enablePkce(). The authorization URL then carries an S256 code_challenge, and redirect() returns the matching codeVerifier. Store it with the state, and pass it back to user() on the callback, which may run on a different provider instance (or a different server):

ts
// On the redirect request:
const { url, state, codeVerifier } = oauthClient.driver('github').enablePkce().redirect()
session(request).put('oauth.flow', { state, codeVerifier })

// On the callback request:
const flow = session(request).pull<{ state: string; codeVerifier: string }>('oauth.flow')
const user = await oauthClient
  .driver('github')
  .enablePkce()
  .user({
    code: request.string('code'),
    state: request.query('state'),
    expectedState: flow?.state,
    codeVerifier: flow?.codeVerifier,
  })

With PKCE enabled, user() throws if codeVerifier is missing. No subclass or shared instance is needed.

Generic OAuth 2.0 providers ​

For a service without a built-in provider, use the oauth2 driver and supply every endpoint:

ts
const oauthClient = new OAuthClient({
  config: {
    oauth2: {
      clientId: 'id',
      clientSecret: 'secret',
      redirectUrl: 'https://app.test/auth/callback',
      authUrl: 'https://login.example.com/authorize',
      tokenUrl: 'https://login.example.com/token',
      userUrl: 'https://api.example.com/me',
      scopes: ['profile', 'email'],
      scopeSeparator: ',', // default is a space
      tokenRequestFormat: 'form', // or 'json'
    },
  },
})

oauthClient.driver('oauth2').redirect().url

The generic provider maps the common profile fields (id or sub, name, email, and picture, avatar_url, or avatar) into the OAuthUser. The token request is form encoded by default, as OAuth 2.0 requires. Set tokenRequestFormat: 'json' for providers that want a JSON body.

Writing a custom provider ​

When the profile shape needs custom mapping, subclass AbstractProvider. Preset the endpoints in the constructor and override mapUserToObject() to convert the raw profile into the common attributes:

ts
import { AbstractProvider, stringField } from '@plinthjs/oauth-client'
import type { HttpClient } from '@plinthjs/http-client'
import type { OAuthUserAttributes } from '@plinthjs/oauth-client'

class DiscordProvider extends AbstractProvider {
  constructor(config: {
    clientId: string
    clientSecret: string
    redirectUrl: string
    http?: HttpClient
  }) {
    super({
      ...config,
      authUrl: 'https://discord.com/oauth2/authorize',
      tokenUrl: 'https://discord.com/api/oauth2/token',
      userUrl: 'https://discord.com/api/users/@me',
      scopes: ['identify', 'email'],
    })
  }

  override mapUserToObject(raw: Record<string, unknown>): OAuthUserAttributes {
    const attributes: OAuthUserAttributes = { id: stringField(raw, 'id') ?? '' }
    const username = stringField(raw, 'username')
    const email = stringField(raw, 'email')
    if (username !== undefined) attributes.nickname = username
    if (email !== undefined) attributes.email = email
    return attributes
  }
}

Register it with extend(). The factory receives the configuration entry for that name and the shared HttpClient:

ts
oauthClient.extend('discord', (config, http) => {
  const credentials = config as { clientId: string; clientSecret: string; redirectUrl: string }
  return new DiscordProvider({ ...credentials, ...(http === undefined ? {} : { http }) })
})

oauthClient.driver('discord').redirect().url

For finer control, AbstractProvider exposes protected hooks you can override: tokenFields() to change the token request body, getUserByToken() to change how the profile is fetched, parseTokenResponse(), validateState(state, expected), generateState(), and generatePkce().

Testing ​

Pass an HttpClient wired to a FakeHttp as the manager's http option, queue the token and profile responses, and run the whole flow without a network:

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

const fake = new FakeHttp()
const oauthClient = new OAuthClient({
  config: {
    github: { clientId: 'id', clientSecret: 'secret', redirectUrl: 'https://app.test/cb' },
  },
  http: new HttpClient({ fetch: fake.fetch }),
})

fake.respond(
  { body: { access_token: 'at', refresh_token: 'rt', expires_in: 3600 } },
  { method: 'POST' },
)
fake.respond(
  { body: { id: 42, login: 'ada', name: 'Ada', email: 'ada@example.com' } },
  { method: 'GET' },
)

const user = await oauthClient.driver('github').user({
  code: 'the-code',
  state: 'abc',
  expectedState: 'abc',
})
user.id // => '42'
user.nickname // => 'ada'
user.token // => 'at'
  • Authentication for logging the resolved user into a session.
  • HTTP Client for the client used under the hood and for faking it.
  • OAuth Server when you are the provider rather than the client.

Released under the MIT License.