Developer docs
OpenID Connect
Add World ID-backed sign-in through Human Gateway using Authorization Code with PKCE. Start with the secure protocol flow, then plan production controls and your application's own sessions.
1. Minimal secure integration
Human Gateway is private/pre-beta and available to selected Partners. It complements World ID adoption and is independently operated; it does not replace World ID and is not affiliated with, endorsed by, or operated by World. Request access before a live integration.
OIDC uses browser redirects, authorization codes and server-side token validation. It is a separate integration path from SDK-launched Hosted Auth and Verify. SDK signed backend callbacks are not an inherent OIDC requirement. For those flows, see the Auth and SDK documentation.
Prepare the Project and Client
- Use an active Project and an eligible Auth Action with sessions enabled in the same environment. Verify Actions do not qualify.
- Create a confidential strict-v1 OAuth Client bound to that Action in the Partner Console's OAuth Clients workspace.
- Register the exact application return URI, including its path. Wildcards, credentials and fragments are prohibited; redirects for one Client must share a hostname.
- Explicitly issue a Client credential. Store the one-time secret on your backend; Client creation alone does not issue it.
- Obtain the enabled environment's trusted issuer from Human Gateway. OAuth client credentials, Project server credentials and SDK callback signing secrets are separate.
OAuth redirect URIs are separate from Project Allowed Origins and backend Callback URLs. Preserve the exact registered redirect in authorization and exchange. Do not derive it from untrusted request headers or a user-supplied return URL.
Discover and start authorization
Load /.well-known/openid-configuration from your trusted issuer and require the returned issuer to match exactly. Use its advertised authorization, token and JWKS endpoints. The reference additionally pins HG's current endpoint paths and origin; this is a bounded HG example, not a universal OIDC client.
Generate independent cryptographically random state, nonce and PKCE verifier for each attempt. Derive the S256 challenge from the verifier. Keep the expected nonce and verifier in an expiring server-side transaction bound to the initiating browser. Send response_type=code, response_mode=query and scope=openid.
authorizationUrl(
transaction: {
state: string;
nonce: string;
verifier: string;
}
): string {
const { issuer, clientId, redirectUri } = this.configuration;
const url = new URL(`${issuer}/authorize`);
url.search = new URLSearchParams({
client_id: clientId,
redirect_uri: redirectUri,
response_type: "code",
response_mode: "query",
scope: "openid",
state: transaction.state,
nonce: transaction.nonce,
code_challenge: digest(transaction.verifier),
code_challenge_method: "S256",
}).toString();
return url.href;
}
This is a method of the reference's Protocol class. The complete files below include its imports, configuration and helpers. Essential security checks are part of the executable minimal path, not optional additions from Layer 2.
The standalone Node adapter is illustrative, not mandatory. In an existing application, use its own routing, HTTPS deployment and transaction/session storage, or a conforming OIDC client library. Require PKCE S256, state and nonce validation, exact redirects, confidential authentication, trusted issuer/JWKS validation and safe transaction/session handling. Disable unsupported default scopes and features. No specific framework or library integration is claimed compatible until it has been executed and tested.
Validate the callback and exchange once
Require one matching state and exactly one success code or OAuth error. Reject duplicate, mixed, missing, empty or malformed values. Check browser binding and expiry, then atomically consume the transaction before exchange. A valid bound error also consumes it; a wrong browser must not consume another browser's transaction.
Exchange server-side with the same redirect URI, matching verifier and confidential Client authentication. HG supports client_secret_basic and client_secret_post; Basic is the example's default. Never send credentials in authorization URLs or token-request queries, or mix authentication methods. This callback excerpt includes the optional local-session step explained in Layer 3.
const params = callbackParameters(url);
const binding = cookie(
request,
BROWSER_COOKIE
);
const previous = cookie(
request,
SESSION_COOKIE
);
if (
!binding
) {
throw new OidcFailure();
}
const transaction = transactions.consume(
params.state,
binding
);
if (
!transaction ||
!params.code
) {
// A valid, bound OAuth error consumes the transaction too.
throw new OidcFailure();
}
// Discovery is checked again; no exchange occurs after failure.
await protocol.discover();
const identity = await protocol.exchange(
params.code,
transaction.verifier,
transaction.nonce
);
const credential = sessions.create(
identity,
previous
);
const result = response(
null,
303,
"/"
);
setCookie(
result,
SESSION_COOKIE,
credential,
SESSION_TTL_MS / 1000
);
Accept authentication only after verifying the ID Token's RS256 signature using trusted JWKS, issuer, Client audience, subject, nonce and time claims. Treat (issuer, sub) as an opaque identity pair. Do not infer email or civil identity, or assume the same subject across unrelated integrations. A minimal application may stop at the verified result without creating an account.
2. Security and Production readiness
Token times and OP reuse
The reference requires iss, sub, aud, exp, iat, auth_time and nonce. It shares one captured clock between jose and application checks, enforcing finite time claims, auth_time <= iat < expand bounded future times. Its configurable 0-60 second clock tolerance is an RP choice; a token expired by less than that tolerance can pass.
HG may reuse an eligible OP authentication event, preserving its immutable auth_time while issuing a new token. Do not demand recent authentication unless your application deliberately requests and validates freshness. An id_token_hintconstrains identity; it does not authenticate a browser. The minimal example does not use hints or freshness options.
// Capture one time for jose and the additional application checks.
const now = this.clock();
if (
!Number.isFinite(now)
) {
throw new OidcFailure();
}
const { payload, protectedHeader } = await jwtVerify(
token.id_token,
this.jwks,
{
algorithms: [
"RS256",
],
issuer: config.issuer,
audience: config.clientId,
requiredClaims: [
"iss",
"sub",
"aud",
"exp",
"iat",
"auth_time",
"nonce",
],
currentDate: new Date(now),
clockTolerance: config.clockToleranceSeconds,
}
);
const { iat, exp, auth_time: authTime } = payload;
if (
typeof protectedHeader.kid !== "string" ||
!protectedHeader.kid ||
typeof payload.sub !== "string" ||
!payload.sub ||
payload.aud !== config.clientId ||
typeof payload.nonce !== "string" ||
!equalSecret(
payload.nonce,
nonce
) ||
typeof iat !== "number" ||
!Number.isFinite(iat) ||
typeof exp !== "number" ||
!Number.isFinite(exp) ||
typeof authTime !== "number" ||
!Number.isFinite(authTime) ||
authTime > iat ||
iat >= exp ||
iat > Math.floor(now / 1000) + config.clockToleranceSeconds ||
authTime > Math.floor(now / 1000) + config.clockToleranceSeconds
) {
throw new OidcFailure();
}
Optional authorization parameters
| Parameter | HG provider behavior |
|---|---|
| prompt=none | Non-interactive authorization requires independently valid, eligible OP authentication. Otherwise HG returns login_required. Do not combine none with other prompt values. |
| prompt=login | Requires fresh authentication rather than OP-session reuse. |
| prompt=consent | With eligible OP-session reuse, requires explicit consent interaction before authorization completes. Otherwise authentication is still required. Consent does not authenticate the browser. |
| prompt=select_account | Parsed, but returns account_selection_required. An account chooser is not available. |
| max_age | A non-negative safe integer in seconds constrains authentication freshness using the original auth_time. Zero forces fresh authentication, even in the same second; it does not set the RP session lifetime. |
| login_hint | A bounded singleton is validated and ignored. It does not select an identity or supply authentication evidence. |
| id_token_hint | A verified hint constrains identity. It never authenticates the browser or bypasses OP-session admission, freshness or current Client policy. |
These are provider capabilities, not options implemented by the standalone reference. Its authorization request omits prompt, max_age and identity hints. If adding freshness requests to your own RP, validate the returned auth_time against the request; do not infer that the reference already does so.
Concurrent attempts, keys and network trust
Independent ten-minute transactions are stored in a bounded Map. Lookup, binding/expiry checks and deletion run synchronously without an intervening await; only one callback wins. This is atomic within one process. Replicas require shared atomic consumption; TTL cleanup never replaces an expiry check.
consume(
state: string,
binding: string
): Transaction | null {
const key = digest(state);
const record = this.records.get(key);
const now = this.clock();
// No await between lookup, validation and deletion. Single process only.
// An invalid browser must not consume another browser's transaction.
if (
!record ||
!Number.isFinite(now) ||
!equalSecret(
record.state,
state
) ||
!equalSecret(
record.bindingDigest,
digest(binding)
)
) {
return null;
}
this.records.delete(key);
if (
record.expiresAt <= now ||
record.createdAt > now
) {
return null;
}
return {
...record,
};
}
Outbound requests reject redirects, limit JSON bodies to 64 KiB and have five-second deadlines. Only trusted HG destinations are allowed. The reused JWKS resolver has a five-minute cache and thirty-second unknown-key refresh cooldown. Rotation may require refresh, and removed keys can remain cached; key removal is not instant revocation.
Keep secrets server-side. Do not log callback URLs, codes, verifier/nonce values, cookies or tokens. The reference discards tokens after verification and returns generic failures. Failed or timed-out exchange may already have consumed a code: never blindly retry it or restore the transaction. Restart with fresh values. Cancellation or abandonment does not guarantee a callback.
Troubleshooting without sensitive logs
HG protocol errors and the reference application's failures are different surfaces. The reference intentionally returns a generic HTTP 400 for sign-in failures; that response does not identify an HG error or its cause. The possibilities below are not certain diagnoses. Check configuration and control flow without logging secrets, codes, tokens, state/nonce/verifier values, cookies or raw callback URLs.
| Observation | Possible causes | Safe next check |
|---|---|---|
| Discovery, issuer or configuration failure | Wrong or unavailable issuer, disabled Preview runtime, missing RP configuration, or metadata rejected by the example's endpoint restrictions. | Confirm the enabled HG environment's trusted issuer and exact configuration format. Check availability and the reference's allowed destinations; do not invent endpoints or disable validation. |
| HG token endpoint: invalid_client | Missing, malformed, invalid or revoked Client credentials, or an incorrect/mixed authentication method. | Check Client ID and active credential provenance without displaying the secret. Use one supported method and its required encoding. Restart authorization after correcting configuration. |
| HG token endpoint: invalid_grant | Expired or consumed code, binding/policy mismatch, different redirect URI, or incorrect PKCE verifier. | Check that the same Client, exact redirect and original transaction verifier are used. The error does not reveal which check failed. Start a fresh authorization; never blindly retry the code, including after an uncertain exchange. |
| RP browser-binding, state or expired-transaction failure | Missing or replaced browser binding, wrong state, expired/consumed transaction, or missing Secure cookies in the browser path. | For the reference, open the configured HTTPS RP root first, then sign in in the same browser. Check TLS proxy Origin/Cookie forwarding and transaction TTL/consumption. Start again without weakening binding checks. |
| HG authorization: login_required | For prompt=none, no eligible independently authenticated OP session satisfies the request; freshness or identity constraints can make reuse ineligible. | After validating the error response's state, start a new interactive authorization when appropriate. A hint is not proof of authentication; do not retry the same code or force silent success. |
| HG /authorize: HTTP 503 | OIDC authorization is unavailable. The response does not determine the underlying cause; the cause of the initial checkpoint occurrence was not established. | Check provider availability and respect any recovery guidance or retry signals if supplied. When appropriate, start a fresh authorization with new transaction values; do not reuse earlier parameters or codes, disable rate limits or log sensitive values. |
Sandbox and Production
HG Sandbox permits HTTP redirects only for localhost or 127.0.0.1 with an explicit port. Production requires HTTPS and an allowed public-network host. The reference deliberately requires HTTPS and Secure cookies even locally; its Node adapter needs a trusted TLS reverse proxy. This example choice does not remove HG's Sandbox allowance. Preview deployments do not enable HG's OIDC runtime.
Project promotion and OAuth Client promotion are separate. After Project and Auth Action dependencies are Production, review Client promotion and Production redirects. Client promotion replaces active Sandbox credentials with a new one-time Production credential. Client records, Health Checks and SDK Callback Test do not prove a completed OIDC login. Validate the complete flow against an enabled runtime with an approved integration.
3. Application-owned sessions
Your application decides whether to map a verified identity to an account and establish its own session. The reference illustrates this only after successful ID Token validation. It issues a fresh opaque application credential, stores its digest with the identity, and sends a Secure, HttpOnly, host-only, SameSite=Lax cookie.
Sessions have a thirty-minute absolute lifetime, are replaced on successful reauthentication and can be invalidated by same-origin POST logout. These are illustrative RP choices, not HG session guarantees. Never use an authorization code, ID Token, access token or PKCE verifier as your application-session credential.
RP application sessions, HG OP authentication sessions and SDK Auth sessions are separate. Local logout ends only the RP session; later sign-in can reuse eligible HG OP authentication. HG OIDC v1 does not provide RP-Initiated Logout. Account linking, authorization, retention and recovery remain your application's responsibility.
Capabilities and limitations
- OIDC v1 supports only openid. UserInfo returns only the pairwise sub; profile/email claims are unavailable.
- No refresh tokens, offline access, public/native Clients, dynamic registration or Request Objects are provided by this profile.
- The example has no distributed persistence, complete account system or production operations setup. Restart loses in-memory transactions and sessions.
- Establish browser binding before parallel attempts. Competing initial page loads can cause a safe failure and restart.
- The single-string audience policy and endpoint pinning target HG's current contract, not every OIDC provider.
Relevant OIDC v1 behavior has been tested with the OpenID Foundation Conformance Suite. Human Gateway is not officially OpenID Certified. Synthetic tests do not prove deployed browser or Production interoperability. A positive real Sandbox authentication flow was completed on 21 November 2026, with sanitized evidence recorded in docs/testing/oidc-public-guide-checkpoint.md. This does not establish universal interoperability or certify Production; negative browser scenarios were not fully exercised.
Complete executable reference
These excerpts come from the same files exercised by the example tests. Copy all five complete files below into examples/oidc/ in your own working directory. Relative imports require all four runtime modules. Each section has an independent Copy control. The extraction markers are inert comments.
Validated versions: Node.js 22.20.0, TypeScript 5.9.3, jose 6.2.12 and Node type definitions 22.20.4. In a fresh working directory, install jose@6.2.12 and development dependencies typescript@5.9.3 @types/node@22.20.4. Compile with npx tsc -p examples/oidc/tsconfig.json, then run node build/oidc-example/server.mjs.
| Server-side variable | Source and responsibility |
|---|---|
| OIDC_ISSUER | Obtain the trusted issuer from the enabled HG environment. The reference requires an exact HTTPS origin without a trailing slash, not an endpoint or a guessed documentation host. |
| OIDC_CLIENT_ID | Use the confidential OAuth Client registered in your Project's OAuth Clients workspace; this is not a Project ID. |
| OIDC_CLIENT_SECRET | Explicitly issue the Client credential in OAuth Clients and store its one-time secret only on the backend. It is not a Project server credential or callback signing secret. |
| OIDC_REDIRECT_URI | Choose and register your exact RP callback URI with the HG Client. The reference requires HTTPS at /oidc/callback on RP_ORIGIN; use the same URI for authorization and exchange. |
| RP_ORIGIN | Choose your application's exact HTTPS origin without a trailing slash. You own HTTPS/TLS termination and the trusted proxy setup for the reference's loopback adapter. |
These variable names are example conventions, not HG requirements. No environment files are loaded. The supplied server adapter uses client_secret_basic by default and has no token-authentication-method environment selector. To use HG's client_secret_post support in your own application, select tokenAuthMethod explicitly when constructing Protocol; changing an invented environment variable does nothing.
The adapter listens only on 127.0.0.1:3210 behind your trusted HTTPS reverse proxy. Preserve Origin, Cookie and the original request target. Do not expose that HTTP listener publicly. Open the configured RP origin first, then start sign-in. TLS certificates/proxy setup are operator-owned. The --smoke flag only starts and closes the listener; it is not an authentication test. Use synthetic configuration for offline smoke validation.
protocol.mts - complete source
import {
createHash,
randomBytes,
timingSafeEqual,
} from "node:crypto";
import {
createRemoteJWKSet,
customFetch,
jwtVerify,
} from "jose";
export type Transport = (
url: string,
init: RequestInit
) => Promise<Response>;
export type Configuration = {
issuer: string;
clientId: string;
clientSecret: string;
redirectUri: string;
rpOrigin: string;
tokenAuthMethod?: "client_secret_basic" | "client_secret_post";
clockToleranceSeconds?: number;
timeoutMs?: number;
};
export type Identity = {
issuer: string;
subject: string;
authenticatedAt: number;
};
export class OidcFailure extends Error {
constructor() {
// Deliberately excludes remote errors, URLs and credentials.
super("Sign-in failed. Start a new sign-in.");
}
}
export function randomValue(): string {
return randomBytes(32).toString(
"base64url"
);
}
export function digest(
value: string
): string {
return createHash("sha256").update(value).digest("base64url");
}
export function equalSecret(
left: string,
right: string
): boolean {
const a = Buffer.from(left);
const b = Buffer.from(right);
return a.length === b.length && timingSafeEqual(
a,
b
);
}
function httpsUrl(
value: string
): URL {
const url = new URL(value);
if (
url.protocol !== "https:" ||
url.username ||
url.password ||
url.search ||
url.hash ||
url.href !== value
) {
throw new OidcFailure();
}
return url;
}
export function validateConfiguration(
input: Configuration
): Readonly<Required<Configuration>> {
try {
const issuer = httpsUrl(`${input.issuer}/`);
const origin = httpsUrl(`${input.rpOrigin}/`);
const redirect = httpsUrl(input.redirectUri);
const tolerance = input.clockToleranceSeconds ?? 60;
const timeout = input.timeoutMs ?? 5000;
const method = input.tokenAuthMethod ?? "client_secret_basic";
if (
issuer.origin !== input.issuer ||
origin.origin !== input.rpOrigin ||
redirect.origin !== input.rpOrigin ||
redirect.pathname !== "/oidc/callback" ||
!input.clientId ||
!input.clientSecret ||
!Number.isInteger(tolerance) ||
tolerance < 0 ||
tolerance > 60 ||
!Number.isInteger(timeout) ||
timeout < 1 ||
timeout > 10000 ||
![
"client_secret_basic",
"client_secret_post",
].includes(method)
) {
throw new OidcFailure();
}
return Object.freeze({
...input,
tokenAuthMethod: method,
clockToleranceSeconds: tolerance,
timeoutMs: timeout,
});
} catch {
throw new OidcFailure();
}
}
// Limits include body reading, even when an injected transport ignores abort.
async function boundedJson(
transport: Transport,
url: string,
init: RequestInit,
timeoutMs: number
): Promise<Record<string, unknown>> {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
try {
return await Promise.race([
(async () => {
const response = await transport(
url,
{
...init,
redirect: "error",
cache: "no-store",
signal: controller.signal,
}
);
if (
controller.signal.aborted ||
response.status !== 200 ||
response.redirected ||
response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() !== "application/json" ||
!response.body
) {
void response.body?.cancel().catch(
() => { }
);
throw new OidcFailure();
}
reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let length = 0;
while (true) {
const chunk = await reader.read();
if (
chunk.done
) {
break;
}
length += chunk.value.byteLength;
if (
length > 65536
) {
throw new OidcFailure();
}
chunks.push(chunk.value);
}
const parsed: unknown = JSON.parse(
new TextDecoder(
"utf-8",
{
fatal: true,
}
).decode(Buffer.concat(chunks))
);
if (
!parsed ||
typeof parsed !== "object" ||
Array.isArray(parsed)
) {
throw new OidcFailure();
}
return parsed as Record<string, unknown>;
})(),
new Promise<never>(
(_, reject) => {
timer = setTimeout(
() => {
controller.abort();
reject(new OidcFailure());
},
timeoutMs
);
}
),
]);
} catch {
throw new OidcFailure();
} finally {
clearTimeout(timer);
controller.abort();
if (
reader
) {
void reader.cancel().catch(
() => { }
);
}
}
}
export class Protocol {
readonly configuration: Readonly<Required<Configuration>>;
private readonly jwks;
constructor(
configuration: Configuration,
private readonly transport: Transport,
private readonly clock: () => number = Date.now
) {
this.configuration = validateConfiguration(configuration);
// HG publishes this exact URI. Metadata must agree before it is used.
const jwksUrl = `${configuration.issuer}/.well-known/jwks.json`;
this.jwks = createRemoteJWKSet(
new URL(jwksUrl),
{
timeoutDuration: this.configuration.timeoutMs,
cooldownDuration: 30000,
cacheMaxAge: 300000,
[customFetch]: async (url, init) => {
if (
url !== jwksUrl
) {
throw new OidcFailure();
}
const keys = await boundedJson(
this.transport,
url,
init,
this.configuration.timeoutMs
);
return Response.json(keys);
},
}
);
}
async discover(): Promise<void> {
const { issuer, tokenAuthMethod, timeoutMs } = this.configuration;
const metadata = await boundedJson(
this.transport,
`${issuer}/.well-known/openid-configuration`,
{
headers: {
accept: "application/json",
},
},
timeoutMs
);
const expected = {
issuer,
authorization_endpoint: `${issuer}/authorize`,
token_endpoint: `${issuer}/token`,
jwks_uri: `${issuer}/.well-known/jwks.json`,
};
for (const [name, value] of Object.entries(expected)) {
if (
metadata[name] !== value
) {
throw new OidcFailure();
}
}
const capabilities = {
response_types_supported: "code",
response_modes_supported: "query",
grant_types_supported: "authorization_code",
scopes_supported: "openid",
code_challenge_methods_supported: "S256",
id_token_signing_alg_values_supported: "RS256",
token_endpoint_auth_methods_supported: tokenAuthMethod,
};
for (const [name, value] of Object.entries(capabilities)) {
const values = metadata[name];
if (
!Array.isArray(values) ||
!values.every(
(item) => typeof item === "string"
) ||
!values.includes(value)
) {
throw new OidcFailure();
}
}
}
// docs:start authorization
authorizationUrl(
transaction: {
state: string;
nonce: string;
verifier: string;
}
): string {
const { issuer, clientId, redirectUri } = this.configuration;
const url = new URL(`${issuer}/authorize`);
url.search = new URLSearchParams({
client_id: clientId,
redirect_uri: redirectUri,
response_type: "code",
response_mode: "query",
scope: "openid",
state: transaction.state,
nonce: transaction.nonce,
code_challenge: digest(transaction.verifier),
code_challenge_method: "S256",
}).toString();
return url.href;
}
// docs:end authorization
async exchange(
code: string,
verifier: string,
nonce: string
): Promise<Identity> {
try {
const config = this.configuration;
const body = new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: config.redirectUri,
code_verifier: verifier,
});
const headers = new Headers({
"content-type": "application/x-www-form-urlencoded",
accept: "application/json",
});
if (
config.tokenAuthMethod === "client_secret_basic"
) {
const encode = (value: string) => new URLSearchParams({
value,
}).toString().slice("value=".length);
headers.set(
"authorization",
`Basic ${Buffer.from(`${encode(config.clientId)}:${encode(config.clientSecret)}`).toString(
"base64"
)}`
);
} else {
body.set(
"client_id",
config.clientId
);
body.set(
"client_secret",
config.clientSecret
);
}
const token = await boundedJson(
this.transport,
`${config.issuer}/token`,
{
method: "POST",
headers,
body: body.toString(),
},
config.timeoutMs
);
if (
typeof token.id_token !== "string" ||
typeof token.access_token !== "string" ||
!token.access_token ||
token.token_type !== "Bearer" ||
token.scope !== "openid" ||
typeof token.expires_in !== "number" ||
!Number.isFinite(token.expires_in) ||
token.expires_in <= 0
) {
throw new OidcFailure();
}
// docs:start verification
// Capture one time for jose and the additional application checks.
const now = this.clock();
if (
!Number.isFinite(now)
) {
throw new OidcFailure();
}
const { payload, protectedHeader } = await jwtVerify(
token.id_token,
this.jwks,
{
algorithms: [
"RS256",
],
issuer: config.issuer,
audience: config.clientId,
requiredClaims: [
"iss",
"sub",
"aud",
"exp",
"iat",
"auth_time",
"nonce",
],
currentDate: new Date(now),
clockTolerance: config.clockToleranceSeconds,
}
);
const { iat, exp, auth_time: authTime } = payload;
if (
typeof protectedHeader.kid !== "string" ||
!protectedHeader.kid ||
typeof payload.sub !== "string" ||
!payload.sub ||
payload.aud !== config.clientId ||
typeof payload.nonce !== "string" ||
!equalSecret(
payload.nonce,
nonce
) ||
typeof iat !== "number" ||
!Number.isFinite(iat) ||
typeof exp !== "number" ||
!Number.isFinite(exp) ||
typeof authTime !== "number" ||
!Number.isFinite(authTime) ||
authTime > iat ||
iat >= exp ||
iat > Math.floor(now / 1000) + config.clockToleranceSeconds ||
authTime > Math.floor(now / 1000) + config.clockToleranceSeconds
) {
throw new OidcFailure();
}
// docs:end verification
// Tokens are discarded, not used as application-session credentials.
return {
issuer: config.issuer,
subject: payload.sub,
authenticatedAt: authTime,
};
} catch {
throw new OidcFailure();
}
}
}
transactions.mts - complete source
import {
digest,
equalSecret,
OidcFailure,
randomValue,
} from "./protocol.mjs";
export const TRANSACTION_TTL_MS = 10 * 60 * 1000;
export type Transaction = {
state: string;
nonce: string;
verifier: string;
bindingDigest: string;
createdAt: number;
expiresAt: number;
};
export interface TransactionStore {
create(
binding: string
): Transaction;
consume(
state: string,
binding: string
): Transaction | null;
}
export class MemoryTransactions implements TransactionStore {
private readonly records = new Map<string, Transaction>();
constructor(
private readonly clock: () => number = Date.now,
private readonly capacity = 1000
) {
if (
!Number.isInteger(capacity) ||
capacity < 1 ||
capacity > 10000
) {
throw new OidcFailure();
}
}
create(
binding: string
): Transaction {
const now = this.clock();
if (
!Number.isFinite(now) ||
!/^[A-Za-z0-9_-]{43}$/.test(binding)
) {
throw new OidcFailure();
}
for (const [key, record] of this.records) {
if (
record.expiresAt <= now ||
record.createdAt > now
) {
this.records.delete(key);
}
}
if (
this.records.size >= this.capacity
) {
throw new OidcFailure();
}
const transaction = {
state: randomValue(),
nonce: randomValue(),
verifier: randomValue(),
bindingDigest: digest(binding),
createdAt: now,
expiresAt: now + TRANSACTION_TTL_MS,
};
const key = digest(transaction.state);
if (
this.records.has(key)
) {
throw new OidcFailure();
}
this.records.set(
key,
transaction
);
return {
...transaction,
};
}
// docs:start consumption
consume(
state: string,
binding: string
): Transaction | null {
const key = digest(state);
const record = this.records.get(key);
const now = this.clock();
// No await between lookup, validation and deletion. Single process only.
// An invalid browser must not consume another browser's transaction.
if (
!record ||
!Number.isFinite(now) ||
!equalSecret(
record.state,
state
) ||
!equalSecret(
record.bindingDigest,
digest(binding)
)
) {
return null;
}
this.records.delete(key);
if (
record.expiresAt <= now ||
record.createdAt > now
) {
return null;
}
return {
...record,
};
}
// docs:end consumption
}
application.mts - complete source
import {
digest,
OidcFailure,
Protocol,
randomValue,
type Identity,
} from "./protocol.mjs";
import type {
TransactionStore,
} from "./transactions.mjs";
export const BROWSER_COOKIE = "__Host-oidc-example-browser";
export const SESSION_COOKIE = "__Host-oidc-example-session";
export const SESSION_TTL_MS = 30 * 60 * 1000;
function cookie(
request: Request,
name: string
): string | null {
const values = (request.headers.get("cookie") ?? "").split(";")
.map(
(item) => item.trim().split("=")
).filter(
([key]) => key === name
);
if (
values.length === 0
) {
return null;
}
if (
values.length !== 1 ||
values[0].length !== 2 ||
!/^[A-Za-z0-9_-]{43}$/.test(values[0][1])
) {
throw new OidcFailure();
}
return values[0][1];
}
function setCookie(
response: Response,
name: string,
value: string,
seconds?: number
): void {
// Browser binding is browser-session scoped; each server transaction has TTL.
const age = seconds === undefined
? ""
: `; Max-Age=${seconds}`;
response.headers.append(
"set-cookie",
`${name}=${value}; Path=/; Secure; HttpOnly; SameSite=Lax${age}`
);
}
function response(
body: string | null,
status = 200,
location?: string
): Response {
const headers = new Headers({
"cache-control": "no-store",
pragma: "no-cache",
"referrer-policy": "same-origin",
"content-type": "text/html; charset=utf-8",
"x-content-type-options": "nosniff",
"content-security-policy": "default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
});
if (
location
) {
headers.set(
"location",
location
);
}
return new Response(
body,
{
status,
headers,
}
);
}
type Session = {
identity: Identity;
createdAt: number;
expiresAt: number;
};
// Deliberately no account database, refresh, sliding expiry or distributed adapter.
export class MemorySessions {
private readonly records = new Map<string, Session>();
constructor(
private readonly clock: () => number = Date.now
) { }
create(
identity: Identity,
previous: string | null
): string {
const now = this.clock();
if (
!Number.isFinite(now)
) {
throw new OidcFailure();
}
for (const [key, record] of this.records) {
if (
record.expiresAt <= now ||
record.createdAt > now
) {
this.records.delete(key);
}
}
if (
this.records.size >= 1000
) {
throw new OidcFailure();
}
const credential = randomValue();
const key = digest(credential);
if (
this.records.has(key)
) {
throw new OidcFailure();
}
this.invalidate(previous);
this.records.set(
key,
{
identity: {
...identity,
},
createdAt: now,
expiresAt: now + SESSION_TTL_MS,
}
);
return credential;
}
read(
credential: string | null
): Identity | null {
if (
!credential
) {
return null;
}
const key = digest(credential);
const record = this.records.get(key);
const now = this.clock();
if (
!record ||
!Number.isFinite(now) ||
record.expiresAt <= now ||
record.createdAt > now
) {
this.records.delete(key);
return null;
}
return {
...record.identity,
};
}
invalidate(
credential: string | null
): void {
if (
credential
) {
this.records.delete(digest(credential));
}
}
}
function callbackParameters(
url: URL
): {
state: string;
code: string | null;
} {
if (
url.search.length > 4096 ||
/%(?![\da-f]{2})/i.test(url.search)
) {
throw new OidcFailure();
}
// Reject malformed percent-encoded UTF-8, which URLSearchParams repairs.
decodeURIComponent(url.search.replaceAll(
"+",
" "
));
const params = url.searchParams;
for (const name of params.keys()) {
if (
![
"state",
"code",
"error",
"error_description",
].includes(name) ||
params.getAll(name).length !== 1
) {
throw new OidcFailure();
}
}
const state = params.get("state");
const code = params.get("code");
const error = params.get("error");
if (
!state ||
!/^[A-Za-z0-9_-]{43}$/.test(state) ||
params.has("code") === params.has("error") ||
(params.has("code") &&
(!code ||
!/^[\x21-\x7e]{1,512}$/.test(code))) ||
(params.has("error") &&
(!error ||
!/^[A-Za-z0-9_]{1,128}$/.test(error))) ||
(params.get("error_description")?.length ?? 0) > 1024
) {
throw new OidcFailure();
}
return {
state,
code,
};
}
export function createApplication(
protocol: Protocol,
transactions: TransactionStore,
sessions: MemorySessions
): (request: Request) => Promise<Response> {
const { rpOrigin, redirectUri } = protocol.configuration;
return async (request) => {
try {
const url = new URL(request.url);
if (
url.origin !== rpOrigin
) {
throw new OidcFailure();
}
if (
request.method === "GET" &&
url.pathname === "/"
) {
const signedIn = sessions.read(cookie(
request,
SESSION_COOKIE
));
const heading = signedIn
? "Signed in"
: "OIDC example";
const page = response(
`<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>OIDC example</title></head>
<body>
<h1>${heading}</h1>
<form method="post" action="/start"><button>Start sign-in</button></form>
<form method="post" action="/logout"><button>Local logout</button></form>
<p>Local logout does not end Human Gateway OP authentication.</p>
</body>
</html>`
);
if (
!cookie(
request,
BROWSER_COOKIE
)
) {
setCookie(
page,
BROWSER_COOKIE,
randomValue()
);
}
return page;
}
if (
request.method === "POST" &&
[
"/start",
"/logout",
].includes(url.pathname)
) {
if (
request.headers.get("origin") !== rpOrigin ||
url.search
) {
throw new OidcFailure();
}
if (
url.pathname === "/logout"
) {
sessions.invalidate(cookie(
request,
SESSION_COOKIE
));
const result = response(
null,
303,
"/"
);
setCookie(
result,
SESSION_COOKIE,
"",
0
);
return result;
}
const binding = cookie(
request,
BROWSER_COOKIE
);
if (
!binding
) {
throw new OidcFailure();
}
await protocol.discover();
const transaction = transactions.create(binding);
return response(
null,
303,
protocol.authorizationUrl(transaction)
);
}
if (
request.method === "GET" &&
url.origin + url.pathname === redirectUri
) {
// docs:start callback
const params = callbackParameters(url);
const binding = cookie(
request,
BROWSER_COOKIE
);
const previous = cookie(
request,
SESSION_COOKIE
);
if (
!binding
) {
throw new OidcFailure();
}
const transaction = transactions.consume(
params.state,
binding
);
if (
!transaction ||
!params.code
) {
// A valid, bound OAuth error consumes the transaction too.
throw new OidcFailure();
}
// Discovery is checked again; no exchange occurs after failure.
await protocol.discover();
const identity = await protocol.exchange(
params.code,
transaction.verifier,
transaction.nonce
);
const credential = sessions.create(
identity,
previous
);
const result = response(
null,
303,
"/"
);
setCookie(
result,
SESSION_COOKIE,
credential,
SESSION_TTL_MS / 1000
);
// docs:end callback
return result;
}
return response(
"Not found.",
404
);
} catch {
// Never serialize exceptions, query parameters or provider payloads.
return response(
"Sign-in failed. Return to / and start a new sign-in.",
400
);
}
};
}
server.mts - complete source
import {
createServer,
} from "node:http";
import {
fileURLToPath,
} from "node:url";
import {
createApplication,
MemorySessions,
} from "./application.mjs";
import {
Protocol,
} from "./protocol.mjs";
import {
MemoryTransactions,
} from "./transactions.mjs";
// Run behind a local TLS reverse proxy. Never trust Host/forwarded origin values.
export function exampleServer(
application: (request: Request) => Promise<Response>,
rpOrigin: string
) {
return createServer(
async (incoming, outgoing) => {
try {
let bytes = 0;
for await (const chunk of incoming) {
bytes += Buffer.byteLength(chunk);
if (
bytes > 2048
) {
outgoing.writeHead(413);
outgoing.end();
return;
}
}
const target = incoming.url ?? "/";
if (
!target.startsWith("/") ||
target.startsWith("//") ||
target.length > 8192
) {
throw new Error();
}
const headers = new Headers();
// Reject duplicate security-relevant headers before Web API merging.
for (const name of [
"cookie",
"origin",
"host",
]) {
const values = incoming.headersDistinct[name];
if (
values &&
values.length > 1
) {
throw new Error();
}
}
for (const name of [
"cookie",
"origin",
]) {
const value = incoming.headers[name];
if (
typeof value === "string"
) {
headers.set(
name,
value
);
}
}
const result = await application(
new Request(
`${rpOrigin}${target}`,
{
method: incoming.method,
headers,
}
)
);
result.headers.forEach(
(value, name) => {
if (
name !== "set-cookie"
) {
outgoing.setHeader(
name,
value
);
}
}
);
outgoing.setHeader(
"set-cookie",
result.headers.getSetCookie()
);
outgoing.writeHead(result.status);
outgoing.end(await result.text());
} catch {
outgoing.writeHead(
400,
{
"cache-control": "no-store",
}
);
outgoing.end("Request failed.");
}
}
);
}
if (
process.argv[1] === fileURLToPath(import.meta.url)
) {
try {
const protocol = new Protocol(
{
issuer: process.env.OIDC_ISSUER ?? "",
clientId: process.env.OIDC_CLIENT_ID ?? "",
clientSecret: process.env.OIDC_CLIENT_SECRET ?? "",
redirectUri: process.env.OIDC_REDIRECT_URI ?? "",
rpOrigin: process.env.RP_ORIGIN ?? "",
},
(url, init) => fetch(
url,
init
)
);
const application = createApplication(
protocol,
new MemoryTransactions(),
new MemorySessions()
);
const server = exampleServer(
application,
protocol.configuration.rpOrigin
);
server.requestTimeout = 10000;
server.headersTimeout = 10000;
server.on(
"error",
() => {
console.error("OIDC example could not listen.");
process.exitCode = 1;
}
);
server.listen(
3210,
"127.0.0.1",
() => {
console.log("OIDC example listening on loopback port 3210; TLS proxy required.");
if (
process.argv.includes("--smoke")
) {
server.close();
}
}
);
} catch {
console.error("Invalid OIDC example configuration.");
process.exitCode = 1;
}
}
tsconfig.json - complete source
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"strict": true,
"skipLibCheck": true,
"rootDir": ".",
"outDir": "../../build/oidc-example"
},
"include": ["*.mts"],
"exclude": ["*.test.mts", "test-support.mts"]
}
Request Partner access or return to the Docs overview.