@plinthjs/oauth-server
A dependency-free OAuth2 authorization server for Plinth. It ships client registration, the four core grants (authorization code with PKCE S256, client credentials, refresh token, password), a scope registry, an AuthorizationServer that drives the authorize, token and revoke endpoints, and a ResourceServer that protects APIs. Persistence sits behind store interfaces with in-memory Array* defaults, and the clock and id/secret generators are injectable.
Install
npm install @plinthjs/oauth-serverUsage
import {
ArrayAuthCodeStore,
ArrayClientStore,
ArrayRefreshTokenStore,
ArrayTokenStore,
AuthorizationServer,
Client,
hashClientSecret,
ResourceServer,
ScopeRegistry,
} from '@plinthjs/oauth-server'
const clients = new ArrayClientStore([
Client.from({
id: 'client-1',
name: 'First Party',
secretHash: hashClientSecret('client-secret'),
redirectUris: ['https://app.test/callback'],
grantTypes: ['authorization_code', 'client_credentials', 'refresh_token'],
scopes: ['users:read', 'users:write'],
confidential: true,
}),
])
const tokens = new ArrayTokenStore()
const server = new AuthorizationServer({
clients,
tokens,
refreshTokens: new ArrayRefreshTokenStore(),
authCodes: new ArrayAuthCodeStore(),
scopes: new ScopeRegistry()
.define('users:read', 'Read users')
.define('users:write', 'Write users'),
ttl: { accessTokenTtlSeconds: 3600 },
})
// Machine-to-machine: no user, no refresh token.
const issued = await server.issueToken('client_credentials', {
client_id: 'client-1',
client_secret: 'client-secret',
scope: 'users:read',
})
issued.accessToken // 'id.secret', returned exactly once
issued.expiresIn // 3600
// Protect an API.
const resource = new ResourceServer({ tokens })
await resource.validate(issued.accessToken) // AccessToken | null
await resource.validateForScope(issued.accessToken, 'users:read') // trueAuthorization code flow
// GET /oauth/authorize: validate, then show the consent screen.
const request = await server.validateAuthorizationRequest(query) // client_id, redirect_uri, scope, state, code_challenge...
// After the user decides:
const { redirectTo } = await server.completeAuthorizationRequest({
request,
userId: '42',
approved: true,
})
// POST /oauth/token: exchange the code (code_verifier required when a PKCE challenge was sent).
const pair = await server.issueToken('authorization_code', body)
const rotated = await server.issueToken('refresh_token', {
refresh_token: pair.refreshToken!,
client_id: 'client-1',
client_secret: 'client-secret',
})Public (secret-less) clients must use PKCE; deriveCodeChallenge(verifier) computes the S256 challenge. Refresh tokens rotate: the presented pair is revoked and a new pair is issued. The password grant is enabled only when verifyCredentials: (username, password) => userId | null is configured.
Revocation
await server.revokeToken(issued.accessToken) // true
await server.revokeToken(pair.accessToken) // also revokes its paired refresh token
await server.revokeToken(rotated.refreshToken!, 'refresh_token') // optional token_type_hintUnknown tokens return false rather than throwing (RFC 7009).
Tokens and errors
Tokens and codes are opaque, not JWTs: the plaintext id.secret is returned once and only sha256(secret) is stored, verified in constant time. Tokens are therefore only verifiable by this server. A resolved AccessToken exposes clientId, userId, scopes, can(scope) and cant(scope).
Every failure throws an OAuthError with an RFC 6749 code and an HTTP status (400 by default, 401 for invalid_client, 403 for access_denied). handleTokenRequest(server, { headers, body }) runs the whole token endpoint, including HTTP Basic client authentication, and returns { status, headers, body } with the RFC 6749 JSON and Cache-Control: no-store:
import { handleTokenRequest } from '@plinthjs/oauth-server'
const { status, headers, body } = await handleTokenRequest(server, {
headers: { authorization: request.header('authorization') },
body: formFields,
})All store interfaces (ClientStore, TokenStore, RefreshTokenStore, AuthCodeStore) may return a value or a promise (MaybePromise<T>), so a database-backed store works directly; the server awaits every call.