OidcProvider.ts overview

OIDC provider: registers clients, runs the authorization-code flow with PKCE and consent, and issues opaque access and refresh tokens and id_tokens signed with JwtService’s keys. Secrets, codes and tokens are stored as digests. An id_token is typ: "JWT", which JwtService.verify refuses as a bearer.


Exports Grouped by Category


utils

DEFAULT_OIDC_REGISTRATION_RATE_LIMIT

Rate limit applied to POST {issuer}/register per client IP.

Signature

declare const DEFAULT_OIDC_REGISTRATION_RATE_LIMIT: RateLimitConfig

Source

DEFAULT_OIDC_SCOPES

Scopes clients may request when allowedScopes isn’t configured.

Signature

declare const DEFAULT_OIDC_SCOPES: readonly ["openid", "profile", "email", "offline_access"]

Source

DynamicallyRegisteredOidcClient (interface)

Result of a dynamic registration. The plaintext clientSecret (confidential clients only) and registrationAccessToken are returned exactly once — both are stored as sha256 digests.

Signature

export interface DynamicallyRegisteredOidcClient {
  readonly client: OidcClient
  /** Absent for public clients (`token_endpoint_auth_method: "none"`). */
  readonly clientSecret?: string
  /** RFC 7592 registration access token for the management endpoints. */
  readonly registrationAccessToken: string
}

Source

NormalizedOidcClientMetadata (interface)

OidcClientMetadata after validation, with every RFC default applied.

Signature

export interface NormalizedOidcClientMetadata {
  readonly redirectUris: readonly string[]
  readonly tokenEndpointAuthMethod: OidcTokenEndpointAuthMethod
  readonly grantTypes: readonly string[]
  readonly responseTypes: readonly string[]
  readonly clientName: string
  readonly scope: string
}

Source

OIDC_DYNAMIC_GRANT_TYPES

Grant types a dynamically registered client may ask for.

Signature

declare const OIDC_DYNAMIC_GRANT_TYPES: readonly ["authorization_code", "refresh_token"]

Source

OIDC_DYNAMIC_RESPONSE_TYPES

Response types a dynamically registered client may ask for.

Signature

declare const OIDC_DYNAMIC_RESPONSE_TYPES: readonly ["code"]

Source

OIDC_TOKEN_ENDPOINT_AUTH_METHODS

Client authentication methods the token endpoint implements.

Signature

declare const OIDC_TOKEN_ENDPOINT_AUTH_METHODS: readonly ["client_secret_basic", "client_secret_post", "none"]

Source

OidcAuthorizationCode (interface)

A short-lived authorization artifact: either an issued authorization code (kind: "authorization_code") or a pending consent request (kind: "pending_consent"), keyed by the sha256 hex digest of the user-visible value.

Signature

export interface OidcAuthorizationCode {
  /** sha256 hex digest of the code — never the plaintext. */
  readonly codeHash: string
  readonly kind: "authorization_code" | "pending_consent"
  readonly clientId: string
  readonly userId: string
  readonly scopes: readonly string[]
  readonly redirectUri: string
  readonly state?: string
  readonly codeChallenge?: string
  readonly codeChallengeMethod?: "S256"
  readonly nonce?: string
  /** Epoch milliseconds. */
  readonly expiresAt: number
  readonly createdAt: number
}

Source

OidcAuthorizeRequest (interface)

A parsed GET /oauth2/authorize request (snake_case per RFC 6749).

Signature

export interface OidcAuthorizeRequest {
  readonly responseType: string
  readonly clientId: string
  readonly redirectUri: string
  /** Space-separated scope list. */
  readonly scope?: string
  readonly state?: string
  readonly codeChallenge?: string
  readonly codeChallengeMethod?: string
  readonly nonce?: string
  /** `"consent"` forces the consent screen even when previously granted. */
  readonly prompt?: string
}

Source

OidcAuthorizeResult (type alias)

Outcome of an authorization request. All variants carry a redirectTo URL the HTTP layer answers with a 302:

  • code: success — redirect_uri?code=...&state=...
  • consent: user consent required — the configured consent page, with a consent_code to post back to the consent endpoint
  • error: a spec-level error redirected to the client per RFC 6749 — redirect_uri?error=...&state=...

Signature

type OidcAuthorizeResult =
  | { readonly type: "code"; readonly redirectTo: string }
  | { readonly type: "consent"; readonly redirectTo: string; readonly consentCode: string }
  | { readonly type: "error"; readonly redirectTo: string; readonly error: string }

Source

OidcClient (interface)

A registered OAuth2/OIDC client application.

Signature

export interface OidcClient {
  readonly clientId: string
  /** sha256 hex digest of the client secret — absent for public (native) clients. */
  readonly clientSecretHash?: string
  readonly name: string
  /** Exact-match redirect URIs (no wildcards). */
  readonly redirectUris: readonly string[]
  /** `web` = confidential (has a secret); `native` = public (PKCE required). */
  readonly type: "web" | "native"
  /** Skip the consent screen for this client (first-party apps). */
  readonly skipConsent: boolean
  readonly disabled: boolean
  readonly metadata: Types.JsonObject
  /** User id of the admin who registered the client. */
  readonly userId?: string
  /** Epoch milliseconds. */
  readonly createdAt: number
  readonly updatedAt: number
  /**
   * sha256 hex digest of the RFC 7592 registration access token. Present only
   * for clients created through dynamic registration; it authenticates the
   * `GET`/`PUT`/`DELETE {issuer}/register/:clientId` management calls.
   */
  readonly registrationAccessTokenHash?: string
  /** RFC 7591 `token_endpoint_auth_method`. `none` marks a public client. */
  readonly tokenEndpointAuthMethod?: OidcTokenEndpointAuthMethod
  /**
   * RFC 7591 `grant_types` the client registered for. When present the token
   * endpoint refuses any other grant with `unauthorized_client`; when absent
   * (statically/admin-registered clients) every supported grant is allowed.
   */
  readonly grantTypes?: readonly string[]
  /** RFC 7591 `response_types` the client registered for. */
  readonly responseTypes?: readonly string[]
  /**
   * Space-separated scopes the client registered for. When present the
   * authorization endpoint rejects requests for anything outside this set.
   */
  readonly scope?: string
  /** `true` when the client was created via RFC 7591 dynamic registration. */
  readonly dynamicallyRegistered?: boolean
}

Source

OidcClientMetadata (interface)

RFC 7591 §2 client metadata, camelCase (the HTTP layer decodes the snake_case wire form). Members the provider does not implement (jwks, software_statement, …) are ignored rather than rejected.

Signature

export interface OidcClientMetadata {
  /** Required. Exact-match redirect URIs; https or loopback http by default. */
  readonly redirectUris: readonly string[]
  /** Default `client_secret_basic` per RFC 7591 §2; `none` = public client. */
  readonly tokenEndpointAuthMethod?: string
  /** Default `["authorization_code"]`. */
  readonly grantTypes?: readonly string[]
  /** Default `["code"]`. */
  readonly responseTypes?: readonly string[]
  readonly clientName?: string
  /** Space-separated scope list. */
  readonly scope?: string
}

Source

OidcClientStore (class)

Persistent registry of OIDC clients.

Signature

declare class OidcClientStore

Source

OidcCodeStore (class)

Ephemeral store for authorization codes and pending consent requests.

Signature

declare class OidcCodeStore

Source

OidcConsent (interface)

A user’s recorded consent for a client (the union of granted scopes).

Signature

export interface OidcConsent {
  readonly userId: string
  readonly clientId: string
  readonly scopes: readonly string[]
  /** Epoch milliseconds. */
  readonly createdAt: number
  readonly updatedAt: number
}

Source

OidcConsentStore (class)

Store for recorded user consents.

Signature

declare class OidcConsentStore

Source

OidcDynamicRegistrationConfig (interface)

Enables RFC 7591 dynamic client registration. Registration is off until this is set: POST {issuer}/register answers 404 without it.

Signature

export interface OidcDynamicRegistrationConfig {
  /**
   * Deny/allow hook run against the normalized metadata. Without it every
   * well-formed registration is accepted (open registration) — pair it with
   * {@link initialAccessToken} for anything internet-facing.
   */
  readonly policy?: OidcRegistrationPolicy
  /**
   * Require `Authorization: Bearer <initial access token>` on `POST /register`.
   * Either a shared secret (compared in constant time) or a verifier hook.
   */
  readonly initialAccessToken?: Redacted.Redacted | OidcInitialAccessTokenVerifier
  /**
   * Scope granted when the request omits `scope`. Defaults to the provider's
   * `allowedScopes`.
   */
  readonly defaultScope?: string
  /** Skip the consent screen for dynamically registered clients (default `false`). */
  readonly skipConsent?: boolean
  /**
   * Additional redirect-URI schemes accepted on top of https and loopback http
   * — e.g. `["myapp"]` to allow the RFC 8252 §7.1 private-use scheme
   * `myapp://callback`. Compared case-insensitively without the trailing `:`.
   */
  readonly allowedRedirectUriSchemes?: readonly string[]
  /**
   * Serve the RFC 7592 management endpoints
   * (`GET`/`PUT`/`DELETE {issuer}/register/:clientId`). Default `true`.
   */
  readonly management?: boolean
  /**
   * Per-IP rate limit for `POST /register`, applied by the HTTP layer. Defaults
   * to {@link DEFAULT_OIDC_REGISTRATION_RATE_LIMIT}. The limit needs a
   * `RateLimiter` in the handler's `services`: without one, `Http.make` throws
   * `RateLimiterConfigError`, and `Http.makeAsync` rejects with it. The group
   * layers composed outside `Http.make` and `Http.makeAsync` refuse every
   * registration with `429`.
   *
   * The limit keys on the client address in the `ClientIP` service, which
   * `Http.make` and `Http.makeAsync` resolve from their own `trustedProxy`.
   * They fail at startup with `ClientAddressConfigError` when registration is
   * enabled with no `trustedProxy`.
   * A registration with no address is refused with `429`, and is never counted
   * under a shared bucket.
   */
  readonly rateLimit?: RateLimitConfig
}

Source

OidcDynamicRegistrationInfo (interface)

What the HTTP layer needs to know about the registration configuration.

Signature

export interface OidcDynamicRegistrationInfo {
  /** `POST /register` is served (404 otherwise). */
  readonly enabled: boolean
  /** The RFC 7592 management endpoints are served. */
  readonly management: boolean
  /** Per-IP rate limit for `POST /register`. */
  readonly rateLimit: RateLimitConfig
}

Source

OidcInitialAccessTokenVerifier (type alias)

Verifier for the optional initial access token (RFC 7591 §3.1) presented as Authorization: Bearer on POST {issuer}/register.

Signature

type OidcInitialAccessTokenVerifier = (token: string) => Effect.Effect<boolean, AuthError>

Source

OidcProviderConfig (interface)

Configuration for make.

Signature

export interface OidcProviderConfig {
  /**
   * Issuer identifier: the external base URL where the auth handler is
   * mounted (e.g. `https://app.example.com/api/auth`). Used as the `iss`
   * claim and to derive the discovery document endpoints.
   */
  readonly issuer: string
  /** Where to redirect unauthenticated authorization requests. */
  readonly loginPage: string
  /**
   * Consent page URL. Authorization requests that need consent redirect here
   * with `consent_code`, `client_id`, and `scope` query parameters; the page
   * posts the user's decision to the consent endpoint. When unset, requests
   * requiring consent are answered with an `error=consent_required` redirect.
   */
  readonly consentPage?: string
  /** Authorization code lifetime in ms (default: 10 minutes). */
  readonly codeExpiresIn?: number
  /** Access token lifetime in ms (default: 1 hour). */
  readonly accessTokenExpiresIn?: number
  /** Refresh token lifetime in ms (default: 30 days). */
  readonly refreshTokenExpiresIn?: number
  /** Scopes clients may request (default: `openid profile email offline_access`). */
  readonly allowedScopes?: readonly string[]
  /** Require PKCE from confidential clients too (default: `false`). */
  readonly requirePKCE?: boolean
  /** Statically configured first-party clients (consent skipped by default). */
  readonly trustedClients?: readonly TrustedOidcClient[]
  /**
   * Enable RFC 7591 dynamic client registration (and, unless disabled, the
   * RFC 7592 management endpoints). Omit to keep `POST /register` unmounted.
   */
  readonly dynamicRegistration?: OidcDynamicRegistrationConfig
}

Source

OidcProviderError (class)

Failure to register a client or process an authorization request.

Signature

declare class OidcProviderError

Source

OidcProviderService (class)

Acts as an OpenID Connect identity provider: client registration (including RFC 7591 dynamic registration), the authorization-code flow with PKCE and consent, the token and userinfo endpoints, and discovery metadata.

Requires OidcClientStore, OidcCodeStore, OidcConsentStore, OidcTokenStore, JwtService, UserStore and IdentifierStore.

Signature

declare class OidcProviderService

Source

OidcRegistrationDisposition (interface)

A registration policy’s verdict. allow: false is answered with invalid_client_metadata (400) per RFC 7591 §3.2.2 unless error names a different code — use access_denied for a 403-shaped refusal that is not about the metadata itself.

Signature

export interface OidcRegistrationDisposition {
  readonly allow: boolean
  /** RFC 7591 §3.2.2 error code when denying. Default `invalid_client_metadata`. */
  readonly error?: string
  readonly errorDescription?: string
  /** Accepting: skip the consent screen for this client (default from config). */
  readonly skipConsent?: boolean
}

Source

OidcRegistrationError (class)

Dynamic client registration failure carrying an RFC 7591 §3.2.2 error code (invalid_redirect_uri, invalid_client_metadata), plus the two codes the guarded endpoints need: invalid_token (bad initial-access or registration access token → 401) and access_denied (refused outright → 403).

Signature

declare class OidcRegistrationError

Source

OidcRegistrationPolicy (type alias)

Gate for POST {issuer}/register, evaluated after the metadata is validated and normalized. Return true/false, or an OidcRegistrationDisposition to choose the error code or opt the client out of the consent screen.

Signature

type OidcRegistrationPolicy = (
  metadata: NormalizedOidcClientMetadata
) => Effect.Effect<boolean | OidcRegistrationDisposition, AuthError>

Source

OidcToken (interface)

An issued opaque token, keyed by the sha256 hex digest of its value.

kind: "rotated" is the record a refresh token leaves behind when it is rotated, under a key derived from the token’s digest: it grants nothing, and presenting its token again is a replay that revokes the whole family (RFC 6819 §5.2.2.3). It expires with the family. A family revoked because two refreshes raced also leaves one, with no familyId of its own, so the winner of the race finds it after issuing and gives its tokens up.

Signature

export interface OidcToken {
  /** sha256 hex digest of the token — never the plaintext. */
  readonly tokenHash: string
  readonly kind: "access" | "refresh" | "rotated"
  readonly clientId: string
  readonly userId: string
  readonly scopes: readonly string[]
  /** Epoch milliseconds. */
  readonly expiresAt: number
  readonly createdAt: number
  /**
   * The grant family: every access and refresh token issued from one
   * authorization code and its refreshes. Revoking the family revokes all of
   * them. Optional only for records written before families covered access
   * tokens.
   */
  readonly familyId?: string
  /** Absolute (non-sliding) expiry for the whole refresh family. Epoch milliseconds. */
  readonly absoluteExpiresAt?: number
}

Source

OidcTokenEndpointAuthMethod (type alias)

How a client authenticates at the token endpoint: one of OIDC_TOKEN_ENDPOINT_AUTH_METHODS.

Signature

type OidcTokenEndpointAuthMethod = (typeof OIDC_TOKEN_ENDPOINT_AUTH_METHODS)[number]

Source

OidcTokenError (class)

Token endpoint failure carrying an RFC 6749 error code (invalid_request, invalid_client, invalid_grant, unsupported_grant_type, invalid_scope, server_error).

Signature

declare class OidcTokenError

Source

OidcTokenRequest (interface)

A parsed POST /oauth2/token request (snake_case per RFC 6749).

Signature

export interface OidcTokenRequest {
  readonly grantType: string
  readonly code?: string
  readonly redirectUri?: string
  readonly codeVerifier?: string
  readonly refreshToken?: string
  /** Client credentials from the request body or the Basic Authorization header. */
  readonly clientId?: string
  readonly clientSecret?: string
  /** Optional down-scoped scope list for the refresh_token grant (RFC 6749 §6). */
  readonly scope?: string
}

Source

OidcTokenResult (interface)

A successful token response (camelCase; the HTTP layer encodes snake_case).

Signature

export interface OidcTokenResult {
  readonly accessToken: string
  readonly tokenType: "Bearer"
  /** Seconds until the access token expires. */
  readonly expiresIn: number
  readonly refreshToken?: string
  readonly idToken?: string
  readonly scope: string
}

Source

OidcTokenStore (class)

Store for issued access and refresh tokens.

Signature

declare class OidcTokenStore

Source

RegisterOidcClientInput (interface)

Input to OidcProviderService.registerClient.

Signature

export interface RegisterOidcClientInput {
  readonly name: string
  readonly redirectUris: readonly string[]
  /** Default `"web"` (confidential — a secret is generated). */
  readonly type?: "web" | "native"
  /** Default `false`. */
  readonly skipConsent?: boolean
  readonly metadata?: Types.JsonObject
}

Source

RegisteredOidcClient (interface)

Result of registering a client: the plaintext secret is shown exactly once.

Signature

export interface RegisteredOidcClient {
  readonly client: OidcClient
  /** Only present for `web` (confidential) clients. */
  readonly clientSecret?: string
}

Source

TrustedOidcClient (interface)

A statically configured, implicitly trusted client (consent skipped).

Signature

export interface TrustedOidcClient {
  readonly clientId: string
  /** Plaintext secret (hashed at service creation); omit for public clients. */
  readonly clientSecret?: Redacted.Redacted
  readonly name: string
  readonly redirectUris: readonly string[]
  readonly type?: "web" | "native"
  readonly skipConsent?: boolean
}

Source

UpdateOidcClientInput (interface)

Fields updatable via OidcProviderService.updateClient.

Signature

export interface UpdateOidcClientInput {
  readonly name?: string
  readonly redirectUris?: readonly string[]
  readonly skipConsent?: boolean
  readonly disabled?: boolean
  readonly metadata?: Types.JsonObject
}

Source

hashOidcSecret

SHA-256 hex digest used for every OIDC secret at rest (tokens, codes, secrets).

Signature

declare const hashOidcSecret: (token: string) => Effect.Effect<string, never, Digest.Digest>

Source

make

Signature

declare const make: (
  config: OidcProviderConfig
) => Effect.Effect<
  typeof OidcProviderService.Service,
  never,
  | OidcClientStore
  | OidcCodeStore
  | OidcConsentStore
  | OidcTokenStore
  | UserStore
  | IdentifierStore
  | JwtService
  | SecureRandom.SecureRandom
  | Digest.Digest
>

Source

mcpProviderPreset

The OIDC provider configuration an MCP server needs: PKCE enforced for every client, dynamic client registration on, and the RFC 7592 management endpoints available so a client can maintain its own registration.

import assert from "node:assert/strict"
import { Effect, Layer, Redacted } from "effect"
import { JwtService } from "@thomasfosterau/effect-auth/Jwt"
import { mcpProviderPreset, OidcProviderService } from "@thomasfosterau/effect-auth/OidcProvider"
import * as Testing from "@thomasfosterau/effect-auth/testing"

const config = mcpProviderPreset({
  issuer: "https://mcp.example.com/api/auth",
  loginPage: "https://mcp.example.com/login",
  consentPage: "https://mcp.example.com/consent",
  dynamicRegistration: {
    initialAccessToken: Redacted.make("example-initial-access-token")
  }
})

// The preset turns on PKCE and dynamic client management.
assert.equal(config.requirePKCE, true)
assert.equal(config.dynamicRegistration?.management, true)

// The provider layer. It needs the app's OIDC client, code, token and consent
// stores and its user and identifier stores (here the in-memory reference
// stores), plus a JWT service for ID tokens.
export const oidcLayer = OidcProviderService.layer(config).pipe(
  Layer.provideMerge(JwtService.layer({ issuer: config.issuer })),
  Layer.provideMerge(Testing.memoryStores)
)

// A client registers, and the provider stores it.
const program = Effect.gen(function* () {
  const provider = yield* OidcProviderService
  const { client, clientSecret } = yield* provider.registerClient({
    name: "Claude",
    redirectUris: ["https://claude.ai/api/mcp/auth_callback"]
  })
  assert.equal(client.name, "Claude")
  assert.ok(clientSecret !== undefined)
})

await Effect.runPromise(program.pipe(Effect.provide(oidcLayer)))

Everything is overridable: the spread order keeps whatever the caller passes, and dynamicRegistration is merged field-by-field so adding a policy or an initialAccessToken does not drop the preset’s defaults.

Signature

declare const mcpProviderPreset: (config: OidcProviderConfig) => OidcProviderConfig

Source


This site uses Just the Docs, a documentation theme for Jekyll.