@web-ts-toolkit/express-oidc-vault
v0.74.0
Published
Express OIDC sessions with body or cookie transport, optional DPoP-bound local JWTs, and pluggable vault stores
Maintainers
Readme
@web-ts-toolkit/express-oidc-vault
OIDC session middleware for Express with body or cookie session transport and server-side storage of upstream refresh tokens and logout-capable id_tokens.
Status
This package now implements the core OIDC flow with body or cookie session transport.
Current implementation includes:
- the core middleware factory
- OIDC login redirect with PKCE,
state, andnonce - opt-in JSON POST login with an HttpOnly transaction cookie and verified/reserved proof when DPoP is enabled
- callback token exchange, server-side session creation, and one-time local exchange codes
- opt-in frontend error navigation for explicitly HTML-preferred failed GET callbacks
- session refresh with session ID rotation
- server-driven upstream logout redirect using stored
id_token - OIDC backchannel logout handling via
logout_token - public TypeScript interfaces for hooks, sessions, config helpers, and store providers
- request-aware local JWT API authentication with opt-in DPoP proof, nonce, and shared replay enforcement
- separate opt-in generic fingerprint recognition at POST login and before exchange/refresh (change detection, not PoP)
Installation
pnpm add @web-ts-toolkit/express-oidc-vault expressFor the quick start, also install @web-ts-toolkit/express-oidc-vault-memory-store. TypeScript applications need @types/express and @types/node as development dependencies. Express >=5.0.0 is the runtime peer dependency.
Use named imports from the package root for backend APIs; there is no default export. The pure /wire type entry is available for browser DTO consumers.
Requirements
- Node.js
>=22.12.0. The published CJS entry (index.js) synchronously requires the ESM-onlyjosedependency, which needs Node'srequire(esm)support. That support is enabled by default starting with Node22.12.0; earlier Node 22 releases fail to load the CJS root withERR_REQUIRE_ESMunless an experimental flag is passed. Both the CJS (require) and ESM (import) roots load without experimental flags on every verified runtime (22.12.0,22.18.0,22.20.0,24.x,26.x). - TypeScript consumers typecheck with
skipLibCheck: falseunder strictNodeNext/Bundlersettings. ESM consumers resolve theimportdeclaration condition (index.d.mts); CommonJS (.cts) consumers resolve therequirecondition (index.d.ts). Both include the public Expressreq.authaugmentation. Workspace builds place these files underdist/; release packaging moves them to the package root and rewrites metadata accordingly. Consumer imports always use the package name.
Browser wire types
@web-ts-toolkit/express-oidc-vault/wire exports types only:
OidcVaultLoginInitiationInput, OidcVaultLoginInitiationResult,
OidcVaultExchangeResult, OidcVaultLogoutResult, OidcVaultSessionTransport,
OidcVaultTokenIssueResult, and OidcVaultUserProfile. These are the same
single-sourced DTOs available at the backend root. Use import type from
/wire in browser code; it has no Express augmentation or Node type dependency.
Its ESM/CJS declarations are wire.d.mts / wire.d.ts, with empty
wire.mjs / wire.js runtime entries and no runtime imports. Both layouts
follow the workspace/release path rules above.
The companion browser client bundles the DTO declarations it needs, so installing
@web-ts-toolkit/oidc-vault-dpop-client needs neither this backend package nor
Express/Node ambient types. See Browser DPoP client.
Frontend Storage Policy
Default browser-side transport:
- mirror
sessionIdintosessionStorage - keep
accessTokenin memory only - do not store either value in
localStorage
Why:
sessionIdneeds to survive page refresh so the frontend can callPOST /auth/oidc/refreshduring app bootstrapaccessTokenis the credential used on normal API requests and should remain non-persistent in the browsersessionStorageis still readable by JavaScript, so it reduces persistence but does not remove XSS risk
Optional alternative:
- set
sessionTransport: 'cookie' - store
sessionIdin anHttpOnlybrowser cookie instead ofsessionStorage - keep
accessTokenin memory only
That mode simplifies the frontend and keeps the session pointer out of JavaScript-visible storage, but it reintroduces cookie deployment concerns such as SameSite, Secure, and cross-origin credential handling.
Session Transport Modes
The package supports two ways to move the opaque sessionId between browser and backend.
sessionTransport: 'body'
This is the default mode.
exchangeandrefreshresponses includesessionId- the frontend stores
sessionId, typically insessionStorage - the frontend sends
sessionIdback in the JSON body forrefreshandlogout refreshandlogoutdo not read session cookies in this mode
sessionTransport: 'cookie'
This mode stores sessionId in a backend-managed cookie.
exchangesets the session cookie and omitssessionIdfrom the JSON bodyrefreshreads the cookie, rotates the session, and updates the cookielogoutreads the cookie and clears itrefreshandlogoutrequire the cookie and reject body-onlysessionIdvalues- the frontend does not need to keep
sessionIdinsessionStorage
Backchannel logout is separate from both transport modes because it is a server-to-server request from the IdP and does not rely on browser storage at all.
Available cookie options:
cookie.namecookie.deploymentMode:'same-origin' | 'same-site' | 'cross-site'cookie.sameSite:'lax' | 'strict' | 'none'cookie.securecookie.domaincookie.pathtrustedOrigins: browser sources for POST login/guarded exchange in both transports and cookie-authenticatedrefresh/logout; required when cross-site session cookie transport is enabled
cookie.httpOnly is always enforced as true. Middleware creation rejects httpOnly: false and unsafe cookie names, domains, or paths so untrusted values cannot be serialized into Set-Cookie headers. __Secure- names require an effectively Secure cookie; __Host- names additionally require no cookie.domain and cookie.path: '/'.
Default cookie behavior:
name:oidc_vault_sessionpath:/httpOnly:truedeploymentMode:same-originsameSite:laxunlessdeploymentModeiscross-sitesecure:truefor HTTPSbackendOrigin,sameSite: 'none', ordeploymentMode: 'cross-site'; otherwisefalseas an intentional HTTP local-development policy (setsecure: trueexplicitly when terminating TLS upstream of anhttporigin, orsecure: falseexplicitly to opt out on HTTPS)SameSite=Noneis always serialized withSecurebecause browsers rejectSameSite=Nonewithout it, even with explicitsecure: false
Cookie-authenticated refresh and logout requests use a fail-closed CSRF policy for every SameSite mode. The request must include an Origin header, or a valid Referer header, whose origin matches backendOrigin or one of the configured trustedOrigins. Requests with no source-origin header are rejected. Backchannel logout is not affected because it is authenticated with the signed OIDC logout token rather than the browser session cookie.
Session transport and device-binding mode are independent options. Opt-in POST login and guarded exchange always need the temporary transaction cookie, including with sessionTransport: 'body'. The session cookie is separate and starts at successful exchange. Same-site subdomains can use Lax cookies with credentialed cross-origin requests; cross-origin does not itself mean cross-site. Cross-site SPAs need an explicit HTTPS transactionCookie: { sameSite: 'none' } as well as suitable session-cookie settings, credentialed CORS, and a browser policy that permits those cookies.
Recommended frontend boot flow (default unbound transport):
- Read
sessionIdfromsessionStorage. - If present, call
POST /auth/oidc/refreshimmediately. - If refresh succeeds, replace the stored
sessionIdwith the rotated value and keep the returnedaccessTokenin memory only. - On a terminal session error, clear the handle and route to sign-in. A transient/proof/nonce failure is not evidence that the session was revoked; retain recovery state and apply the operation's retry contract.
If you use sessionTransport: 'cookie', the frontend boot flow becomes simpler:
- Keep
accessTokenin memory only. - Call
POST /auth/oidc/refreshon app startup. - Let the backend read and rotate the session cookie.
- On a terminal session error, clear local auth and route to sign-in. The DPoP client classifies these using
OidcVaultDpopClientError.requiresLogin, not HTTP status alone.
Endpoints
The core middleware exposes these endpoints under a configurable base path:
GET /auth/oidc/loginPOST /auth/oidc/loginwhendeviceBindingorfingerprintRecognitionis configured (JSON initiation; see below)GET /auth/oidc/callbackPOST /auth/oidc/exchangePOST /auth/oidc/refreshPOST /auth/oidc/logoutPOST /auth/oidc/logout/navigationandGET /auth/oidc/logout/navigationwhenlogoutNavigationis configured (JSON initiation, then one-time navigation)POST /auth/oidc/backchannel-logout
The mounted OIDC router parses JSON and application/x-www-form-urlencoded request bodies with an explicit default limit of 16kb. This covers the small route payloads used by exchange, refresh, logout, and form-encoded backchannel logout. POST login accepts only application/json; other media types return 415 OIDC_VAULT_UNSUPPORTED_REQUEST_BODY_TYPE before the general parsers run. If an IdP requires a larger logout_token, set requestBodyLimit to a string or byte count accepted by Express body parsers.
Parser failures return a JSON client error before route handlers or store/provider hooks run. The stable error codes are:
OIDC_VAULT_REQUEST_BODY_TOO_LARGEOIDC_VAULT_REQUEST_BODY_PARAMETER_LIMIT_EXCEEDEDOIDC_VAULT_UNSUPPORTED_REQUEST_BODY_ENCODINGOIDC_VAULT_MALFORMED_REQUEST_BODYOIDC_VAULT_INVALID_REQUEST_BODY
Quick Start (default unbound lifecycle)
import express from 'express';
import { createOidcVaultMiddleware } from '@web-ts-toolkit/express-oidc-vault';
import { createMemoryOidcVaultStore } from '@web-ts-toolkit/express-oidc-vault-memory-store';
const app = express();
const storeProvider = createMemoryOidcVaultStore();
app.use(
createOidcVaultMiddleware({
basePath: '/auth/oidc',
backendOrigin: 'https://api.example.com',
config: {
issuer: process.env.OIDC_ISSUER,
clientId: process.env.OIDC_CLIENT_ID,
clientSecret: process.env.OIDC_CLIENT_SECRET,
},
frontendRedirectUri: 'https://frontend.example.com/callback',
storeProvider,
sessionTtlMs: 8 * 60 * 60 * 1000, // Opt in to an eight-hour absolute session lifetime.
}),
);Use the memory store for local development and tests. For production deployments, prefer a Redis or MongoDB store provider.
backendOrigin must be the public backend origin registered with your OIDC provider, such as https://api.example.com. Callback redirect_uri values are built from this pinned origin and the configured basePath, so reverse proxies and untrusted Host headers cannot change the provider callback URL. Configure Express trust proxy only for other request metadata needs; it is not used to derive the OIDC callback origin.
Public Options And Defaults
| Option | Default | Contract |
| ------------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| basePath | /auth/oidc | Mount path for the OIDC router. Route paths listed in this README are relative to this value. |
| backendOrigin | required | Public backend origin registered with the OIDC provider. Callback redirect URIs are derived from this pinned origin, not request host headers. |
| storeProvider | required | Durable vault store provider. Use Redis or MongoDB for production and multi-instance deployments. |
| config | required provider values | Supply issuer and clientId, or use resolveOidcVaultConfigFromEnv(process.env). Endpoint settings select manual mode; see Config Helpers. |
| frontendRedirectUri | unset | Default browser return target after backend callback completion. Required if login accepts a custom returnTo. Validated before durable callback state; missing destination fails the callback with 500 OIDC_VAULT_MISSING_FRONTEND_REDIRECT_URI. |
| frontendErrorRedirectUri | unset | Fixed opt-in destination for explicitly HTML-preferred terminal GET callback errors; otherwise existing JSON/status. Independent of success/default/trusted origins. See Frontend Callback Error Recovery for validation and byte limits. |
| postLogoutRedirectUri | unset | Provider-registered return URL for redirected logout and opt-in navigation. Navigation applies stricter syntax/2048-byte checks; upstream failures retain local logout. |
| fetchUserInfo | enabled when usable | Fetches UserInfo if an endpoint exists and the token response supplies an access token; false disables it. Claims merge only after matching the verified subject. |
| authorizationTransactionTtlMs | 600000 | TTL for one-time authorization transactions created during login. |
| exchangeCodeTtlMs | 30000 | TTL for one-time local exchange codes returned to the frontend callback route. |
| sessionTtlMs | unset | Opt-in positive safe-integer lifetime in milliseconds from callback session creation. Hooks may shorten it; refresh never extends it. |
| sessionTransport | body | body returns and accepts JSON sessionId; cookie stores the session pointer in an HttpOnly cookie and rejects body-only refresh/logout IDs. |
| cookie | see cookie defaults above | Cookie transport options. httpOnly is always enforced as true; unsafe names, paths, domains, and __Secure-/__Host- prefix violations are rejected. |
| deviceBinding | disabled | Vault DPoP policy; object defaults to optional. Selects the initiating key at POST login and enforces it through callback/exchange/refresh/logout. Configure API enforcement separately. |
| logoutNavigation | disabled | Proof-authorized JSON logout and headerless continuation. Required fallback, default ticketTtlMs: 60000 (1000..120000), default namespace label default. Requires DPoP and ticket-store capabilities. |
| fingerprintRecognition | disabled | Separate opt-in recognition; headerName defaults to X-Device-Fingerprint. POST-only enrollment, precommit exchange/refresh comparison, fresh login on change; never PoP or an API sender constraint. |
| transactionCookie | HTTPS __Host-oidc_vault_transaction, Lax | Temporary POST-login browser cookie, independent of session transport; only name and sameSite: 'lax' \| 'none' are configurable. |
| trustedOrigins | [] plus backendOrigin internally | POST-login/guarded-exchange source origins in both transports, plus cookie-authenticated refresh and logout. Required for cross-site session cookie transport. |
| requestBodyLimit | 16kb | Express JSON and URL-encoded parser limit for OIDC route bodies. Increase only for known provider backchannel logout token size needs. |
| providerRequestTimeoutMs | 5000 | Deadline per provider HTTP exchange (headers plus complete body). Cancellation is attempted without awaiting cleanup. Positive finite integer; validated before cache lookup. |
| hooks | unset | Pre-commit hooks can veto operations by throwing; post-commit notification hook failures are reported to onError without undoing committed state. |
| tokenIssuer | unset | Issues app-local access tokens for exchange and refresh. This lifetime is separate from upstream token and vault-session lifetimes. |
| now | Date.now | Epoch-millisecond clock; sampled at construction and creation for TTL checks and used by vault proof/nonce/replay policy. Shared instances and store clocks must agree. |
Construction takes an internal resolved snapshot of the options object without mutating it: normalized values are stored on the snapshot, cookie/trustedOrigins/config containers are shallow-copied, transactionCookie and fingerprintRecognition are resolved into detached frozen configurations, and storeProvider/hooks/tokenIssuer/now service references are retained live (never deep-cloned). Frozen inputs work, reused inputs are not mutated, and mutating or replacing the caller object after creation has no effect on the created router.
fetchUserInfo defaults to enabled when a UserInfo endpoint exists and the token response supplies an access token; false disables it. config itself is optional in the declaration, but valid provider values (issuer/clientId or the complete manual set) are required by construction. Vault deviceBinding configures the lifecycle router; API deviceBinding must be configured separately on each accepting API middleware.
Frontend Callback Error Recovery
frontendErrorRedirectUri?: string is an additive, opt-in presentation option, not a successful login. Distinguish these URLs:
| URL | Purpose |
| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| https://api.example.com/auth/oidc/callback | Backend provider callback (backendOrigin + normalized basePath + /callback); register this with the IdP. |
| frontendRedirectUri, e.g. https://app.example.com/callback | Successful frontend default; the transaction's validated returnTo takes precedence. Receives a fresh local exchange code, not the provider's authorization code. |
| frontendErrorRedirectUri, e.g. https://help.example.net/sign-in-error | Fixed frontend failure destination; receives public diagnostics only, never an exchange credential. |
The provider normally calls the backend with ?code=...&state=... or ?error=...&state=.... State, transaction cookie (when applicable), provider identity/tokens, and session/code creation still undergo their existing validation. A password/MFA error shown entirely at the IdP does not reach this callback. Recovery changes no validation, transaction consumption, rollback, cookie cleanup, or established-session revocation rules; body/cookie transports and existing binding modes remain supported without adding a callback proof requirement.
Same-page success and error destination
This unbound development example sends both outcomes to the application's /callback page. The frontend must branch on error before attempting successful code exchange:
import express from 'express';
import { createOidcVaultMiddleware } from '@web-ts-toolkit/express-oidc-vault';
import { createMemoryOidcVaultStore } from '@web-ts-toolkit/express-oidc-vault-memory-store';
const app = express();
app.use(
createOidcVaultMiddleware({
backendOrigin: 'https://api.example.com',
basePath: '/auth/oidc', // Register https://api.example.com/auth/oidc/callback at the IdP.
config: { issuer: process.env.OIDC_ISSUER, clientId: process.env.OIDC_CLIENT_ID },
storeProvider: createMemoryOidcVaultStore(), // Use shared durable storage in production.
frontendRedirectUri: 'https://app.example.com/callback',
frontendErrorRedirectUri: 'https://app.example.com/callback',
}),
);Dedicated error destination
The error page may be on a different origin and keeps its configured pathname and unrelated query entries:
import { createOidcVaultMiddleware } from '@web-ts-toolkit/express-oidc-vault';
import { createMemoryOidcVaultStore } from '@web-ts-toolkit/express-oidc-vault-memory-store';
const vault = createOidcVaultMiddleware({
backendOrigin: 'https://api.example.com',
config: { issuer: process.env.OIDC_ISSUER, clientId: process.env.OIDC_CLIENT_ID },
storeProvider: createMemoryOidcVaultStore(),
frontendRedirectUri: 'https://app.example.com/callback',
frontendErrorRedirectUri: 'https://help.example.net/sign-in-error?locale=en',
});The error destination is snapshotted deployment configuration, never derived from incoming returnTo, state, Host/forwarded headers, or transaction data. Its origin need not match frontendRedirectUri or trustedOrigins; configuring it does not expand trustedOrigins or grant API/POST access. It may be configured without a successful frontend default, but it cannot satisfy the success prerequisite: transaction.returnTo ?? frontendRedirectUri still controls success, with 500 OIDC_VAULT_MISSING_FRONTEND_REDIRECT_URI before provider/session/code work when neither exists.
Eligibility, diagnostics and limits
Only terminal errors from the registered GET callback handler qualify. Parser/router errors before that handler, HEAD/non-GET requests, all other lifecycle/API routes, and nonfatal post-commit notification errors keep their existing behavior. In particular, an onSessionCreated notification failure must not turn a successful callback into an error navigation. Do not redirect inside hooks.onError, which also observes nonfatal notifications.
The request must explicitly accept bare text/html or application/xhtml+xml at a positive quality strictly greater than effective application/json quality. JSON wins ties regardless of header order. Media wildcards never opt in; JSON quality uses the most specific matching range (application/json > application/* > */*), preserving q=0 exclusions. Examples with the option configured:
| Accept | Failed GET callback |
| --------------------------------------------------------------- | ----------------------------- |
| text/html or application/xhtml+xml | 302 to the error page |
| text/html, */*;q=0.8 | 302 |
| text/html, application/json (either order) | Original JSON/status |
| text/html;q=0.8, application/json;q=0.9 | Original JSON/status |
| Missing/empty, */*, text/*, application/*, or image/png | Original JSON/status |
| text/html;q=0, */*;q=1 or text/html;q=0.5, */*;q=1 | Original JSON/status |
| text/html, application/json;q=0, */*;q=1 | 302 (specific JSON exclusion) |
| text/html;q=bogus or text/html, garbage | Original JSON/status |
Matching is case-insensitive. A malformed nonempty member (including invalid/duplicate q or unmatched quotes) makes the whole signal ineligible. Quality is an unquoted 0–1 with at most three decimal places; equally specific duplicates use the highest quality. Media parameters before q do not match the bare supported candidates; valid accept extensions after q do not change matching. Accept is a presentation signal, not authentication or browser identity; fallback never introduces HTTP 406.
Omitting frontendErrorRedirectUri preserves sanitized JSON and the original error status even for HTML requests. There is no implicit fallback to frontendRedirectUri, the login endpoint, or returnTo.
An eligible response is an empty HTTP 302, with Cache-Control: no-store, Referrer-Policy: no-referrer, applicable cookie cleanup preserved, and no WWW-Authenticate/DPoP-Nonce challenge. The URL API replaces all decoded case-insensitive configured error/error_description variants with exactly one lowercase parameter each:
https://help.example.net/sign-in-error?locale=en&error=OIDC_VAULT_INVALID_STATE&error_description=OIDC+state+is+invalid+or+expired.error is the stable public library code; error_description is its sanitized public client message. Unknown failures use OIDC_VAULT_INTERNAL_ERROR / Unexpected OIDC vault error. The incoming provider message, authorization code, state, tokens, session identifiers, and other callback query values are never forwarded. Only deliberately public messages belong in application-defined public errors. The sanitized response and prepared destination are captured before mutable error observers; hooks.onError still observes the original failure. Already-sent responses retain existing error forwarding, not a second response.
Construction rejects non-absolute/non-HTTP(S) error URLs, raw whitespace/controls/backslashes, userinfo (including empty @), fragments (including bare #), and same-backend callback loops. Loop comparison uses the canonical origin (host/default-port normalization) and normalized callback pathname, case-insensitively with one trailing slash removed; URL dot segments normalize, but proxy aliases/recursively decoded paths are not inferred. For example, backend https://api.example.com rejects https://API.EXAMPLE.COM:443/auth/oidc/x/../CALLBACK/?view=error.
Decoded, case-insensitive configured query names code, state, sessionId, session_id, access_token, accessToken, refresh_token, refreshToken, id_token, idToken, and id_token_hint are rejected even with empty values (?%63ode= is invalid). Unrelated query entries, including duplicates, are preserved semantically. This finite list is not a general secret detector: never put secrets in other configured parameters.
All limits below are inclusive UTF-8 byte counts, not JavaScript string lengths:
| Value | Limit / failure policy |
| ---------------------------------------- | ---------------------------------------------------------------------------------- |
| Raw configured URI and canonical URI | Each at most 2,048 bytes; exceeding either throws during construction. |
| Public error code | Nonempty string, at most 128 bytes. |
| Public error_description message | String, at most 512 bytes (e.g. 128 😀 characters). |
| Final serialized, URL-encoded Location | At most 4,096 bytes, including encoding expansion and preserved query entries. |
Invalid/oversized public fields, preparation exceptions, or an oversized final Location fall back to the original captured sanitized JSON/status/protocol headers. There is no truncation, code/message replacement, recursive error observation, callback replay, or additional provider/store work for presentation fallback.
Frontend error display and explicit retry
Query diagnostics are display-only: anyone can construct them. They neither authenticate a user nor establish session revocation; do not exchange an error as a code, clear a valid session solely because of this URL, or infer authentication from its absence. URLs can appear in browser history and access logs despite no-store/no-referrer. Remove diagnostics from the current URL when practical (this does not erase existing logs/history), and treat even public messages as untrusted display text.
Create a text element with ID sign-in-error and a button with ID retry-sign-in. Call this branch before your normal success-code handling. Inject your existing fresh login action (for DPoP/recognition, the normal proof-aware POST login; for legacy unbound mode, navigation to the login endpoint). It runs only on an explicit click, never by replaying the backend callback or automatically retrying:
export function renderCallbackFailure(startFreshLogin: () => Promise<void>): boolean {
const url = new URL(location.href);
if (!url.searchParams.has('error')) return false; // Continue ordinary success handling.
const code = url.searchParams.get('error') ?? '';
const description = url.searchParams.get('error_description') ?? 'Sign-in could not be completed.';
url.searchParams.delete('error');
url.searchParams.delete('error_description');
history.replaceState(null, '', url.href);
const message = document.getElementById('sign-in-error');
if (message) message.textContent = `${code}: ${description}`; // Escaped text, never innerHTML.
const retry = document.querySelector<HTMLButtonElement>('#retry-sign-in');
if (retry) {
retry.onclick = async () => {
retry.disabled = true;
try {
await startFreshLogin(); // New login transaction, not callback replay.
} catch {
retry.disabled = false;
if (message) message.textContent = 'Unable to start sign-in. Please try again.';
}
};
}
return true; // Stop success-code exchange for this error branch; no auth/session mutation.
}DPoP Quick Start (local JWT + protected API)
DPoP binds a login to a browser-held private key. The complete server below issues a short-lived local JWT with cnf.jkt and protects the API with the same replay provider. It uses the development memory store; select a shared Redis/MongoDB provider for multiple processes. CORS is an application dependency:
pnpm add @web-ts-toolkit/express-oidc-vault @web-ts-toolkit/express-oidc-vault-memory-store express cors
pnpm add -D @types/express @types/node @types/cors typescriptComplete DPoP server
Set OIDC_ISSUER, OIDC_CLIENT_ID, optional OIDC_CLIENT_SECRET, and a stable strong random APP_JWT_SECRET encoding at least 32 bytes. Register https://api.example.com/auth/oidc/callback with the IdP. Terminate HTTPS at the configured public backend origin and preserve the public vault mount path.
import express from 'express';
import cors from 'cors';
import {
createOidcVaultMiddleware,
createOidcVaultAccessTokenMiddleware,
createOidcVaultJwtAccessTokenIssuer,
createOidcVaultJwtAccessTokenValidator,
} from '@web-ts-toolkit/express-oidc-vault';
import { createMemoryOidcVaultStore } from '@web-ts-toolkit/express-oidc-vault-memory-store';
const backendOrigin = 'https://api.example.com';
const frontendOrigin = 'https://frontend.example.com';
const audience = 'app-api-v1';
const rawSecret = process.env.APP_JWT_SECRET;
if (!rawSecret || Buffer.byteLength(rawSecret, 'utf8') < 32) {
throw new Error('APP_JWT_SECRET must encode at least 32 strong random bytes.');
}
const signingKey = new TextEncoder().encode(rawSecret);
const store = createMemoryOidcVaultStore({ dpopReplayMaxEntries: 100_000 });
const app = express();
app.use(
cors({
origin: frontendOrigin,
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization', 'DPoP', 'X-Device-Fingerprint'],
exposedHeaders: ['DPoP-Nonce', 'WWW-Authenticate'],
}),
);
app.use(
createOidcVaultMiddleware({
backendOrigin,
basePath: '/auth/oidc',
config: {
issuer: process.env.OIDC_ISSUER,
clientId: process.env.OIDC_CLIENT_ID,
clientSecret: process.env.OIDC_CLIENT_SECRET,
},
frontendRedirectUri: `${frontendOrigin}/callback`,
trustedOrigins: [frontendOrigin],
storeProvider: store,
sessionTransport: 'body',
sessionTtlMs: 8 * 60 * 60 * 1000,
deviceBinding: { mode: 'required' }, // ES256, age 60s, skew 5s, nonces off.
tokenIssuer: createOidcVaultJwtAccessTokenIssuer({
key: signingKey,
algorithm: 'HS256',
issuer: backendOrigin,
audience,
lifetimeSeconds: 300,
mapClaims({ session }) {
// Application-owned allowlist; account/permission decisions belong here.
return { email: typeof session.user?.email === 'string' ? session.user.email : undefined };
},
}),
}),
);
app.use(
'/api',
createOidcVaultAccessTokenMiddleware({
validator: createOidcVaultJwtAccessTokenValidator({
key: signingKey,
issuer: backendOrigin,
audience,
algorithms: ['HS256'],
}),
deviceBinding: { mode: 'required', publicOrigin: backendOrigin, replayNamespace: 'app-api-v1', replayStore: store },
}),
);
app.get('/api/profile', (req, res) => {
res.json({ subject: req.auth?.subject, scope: req.auth?.scope, binding: req.auth?.deviceBinding?.jkt });
});
app.listen(3000);Local HS256 signing and ES256 proof signing are independent. The issuer helper captures verified IssueTokenInput.deviceBinding for cnf.jkt and automatically selects DPoP/Bearer; mutable profile/session fields are not proof authority. This JWT contains no vault sessionId/sid, so switching to cookie transport keeps that handle out of browser-readable tokens. APIs still independently verify JWT signature/issuer/audience/expiry and request proof. Authorization remains application-owned.
For cookie transport, change sessionTransport to 'cookie' and configure the frontend for that same mount/transport. For multiple mounts, give each a distinct transactionCookie.name and session cookie.name. Nonces are optional: to enable them, supply nonce: { secret: sharedRandomBytes, lifetimeSeconds: 60 } in each vault/API proof policy; use at least 32 random bytes shared by instances of that protection space. A random secret created anew on each instance is unsuitable for shared challenge verification.
Device-binding policy and issuance contracts
The package root exposes policy, record, local-issuer, guarded-store, POST-login DTO/cookie, and request-aware API contracts. The backend lifecycle is implemented: POST initiation, cookie-authenticated callback, original-key exchange/refresh/logout (including unexpired aliases), and API proof/nonce/shared replay enforcement. The persistent-key SPA example includes both transports, an Express/local IdP fixture, and real-browser redirect/reload/IndexedDB/CORS/nonce/cross-tab checks. Request-aware DPoP APIs describes API configuration.
OidcVaultOptions.deviceBinding?: OidcVaultDeviceBindingOptions is opt-in. Omitting it preserves bearer behavior. An object defaults to mode: 'optional'; required rejects unbound context. Legacy records are never enrolled by a later proof, and stored bound credentials never become bearer credentials by omission. Construction requires all six OidcVaultDeviceBindingStoreProvider capabilities and a static HTTPS backendOrigin, except loopback HTTP development.
| Vault policy | New login | Existing records |
| ----------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| Omitted | Legacy unbound GET; POST exists only if recognition is configured | Unbound compatible; bound credentials fail closed |
| {} / optional | GET unbound; JSON POST binds only when a valid proof is supplied, otherwise cookie-only | Legacy unbound allowed; supplied later proof validates but never enrolls |
| required | JSON POST with proof; GET rejected before discovery/allocation | Unbound transaction/code/session use rejected; bound credentials require their original key |
There is no legacyPolicy or downgrade switch. Migrate clients to proof-aware POST login and configure every API before selecting required; old unbound sessions then need fresh login. Disabling the feature does not make existing bound sessions/JWTs usable as Bearer.
The proof profile is separate from local JWT signing: algorithms defaults to ['ES256'] and permits explicit PS256/RS256; proofMaxAgeSeconds defaults to 60 (integer 1–300), clockSkewSeconds to 5 (integer 0–30). nonce is off/false by default; an enabled { secret: Uint8Array, lifetimeSeconds?: number } requires at least 32 shared random bytes and defaults to 60 seconds (integer 1–300). Policy and algorithm containers are detached/frozen, and nonce bytes are copied at construction.
The shared nonce policy signs versioned, random HMAC-SHA-256 challenges bound to the key and protection space, with no per-client nonce storage. It accepts any authentic live issued nonce for parallel fresh proofs; proof age and single-use JTI reservation still apply. Challenges are at most 512 bytes and issued only after other verification prerequisites, before replay allocation. Configured APIs write fixed OIDC_VAULT_USE_DPOP_NONCE JSON, one DPoP-Nonce header, and no-store with HTTP 401 and the DPoP nonce challenge. DPoP-bearing vault POSTs use the same fixed JSON/header with HTTP 400 before transaction/code/session mutation, upstream calls or hooks. Clients retry once with a fresh proof/JTI/iat/signature. Headerless callback and no-proof unbound requests do not require a nonce.
Sessions, authorization transactions, and exchange codes carry optional deviceBinding: { type: 'dpop', jkt: string }; transactions/codes also carry optional browserBindingHash. Only the canonical RFC 7638 SHA-256 thumbprint is persisted, without a JWK, private key, proof algorithm, or historical mode. Core retains security-owned binding independently of mutable precreate hooks and issuer inputs. All three built-ins implement live preflight reads, atomic exact/null match-and-consume, lineage revocation context, immutable rotation, and shared bounded replay admission; see the provider contracts below. These store primitives do not themselves verify HTTP proofs.
Per-check DPoP failure overrides
Steps 6–8 have independent log-and-continue settings. Each check still runs; an enabled setting writes every failure to the server's console.warn and continues to the next check. Both vault POSTs and API middleware read these defaults from process.env when constructed:
| Step | Check | Environment variable | deviceBinding option |
| ---- | ----------------------------------------------------------------------------------- | ------------------------------------------ | ------------------------ |
| 6 | HTTP method and normalized pinned URL (htm/htu), including target normalization | OIDC_VAULT_DPOP_IGNORE_TARGET_FAILURE | ignoreTargetFailure |
| 7 | Signed proof freshness (iat age and clock skew) | OIDC_VAULT_DPOP_IGNORE_FRESHNESS_FAILURE | ignoreFreshnessFailure |
| 8 | Atomic JTI replay admission, including duplicates, capacity, and provider failures | OIDC_VAULT_DPOP_IGNORE_REPLAY_FAILURE | ignoreReplayFailure |
Only the exact environment value true enables an override; unset, false, or any other value retains enforcement. Set whichever flags you need before constructing middleware, for example:
OIDC_VAULT_DPOP_IGNORE_TARGET_FAILURE=true
OIDC_VAULT_DPOP_IGNORE_FRESHNESS_FAILURE=false
OIDC_VAULT_DPOP_IGNORE_REPLAY_FAILURE=trueExplicit booleans on OidcVaultDeviceBindingOptions / OidcVaultApiDeviceBindingOptions take precedence over the environment for that policy:
import type { OidcVaultDeviceBindingOptions } from '@web-ts-toolkit/express-oidc-vault';
const deviceBinding: OidcVaultDeviceBindingOptions = {
mode: 'required',
ignoreTargetFailure: true,
ignoreFreshnessFailure: false,
ignoreReplayFailure: false,
};An ignored freshness failure still reaches nonce verification and replay admission. To give replay admission a live bounded expiry independently of the rejected iat, core uses now + (proofMaxAgeSeconds + clockSkewSeconds) * 1000 (65 seconds with defaults). A failed configured proof clock is logged and falls back to Date.now. Successful replay reservations retain their expiry; duplicates never renew them, even when their failure is ignored. Signature, header/JWK, claim-shape, original-key, API ath, and nonce checks retain their normal enforcement.
Console output identifies the step, option/environment variable, and original error (including replay provider causes), for example:
[express-oidc-vault] DPoP step 8 (replay) failed; continuing (ignoreReplayFailure=true; OIDC_VAULT_DPOP_IGNORE_REPLAY_FAILURE).Environment changes take effect on newly constructed middleware. Ignored failures go directly to the console; onError handles failures that stop the request.
POST login and browser-authenticated callback
Configure the vault with the existing stronger store and an opt-in policy:
import express from 'express';
import { createOidcVaultMiddleware, type OidcVaultTransactionCookieOptions } from '@web-ts-toolkit/express-oidc-vault';
import { createMemoryOidcVaultStore } from '@web-ts-toolkit/express-oidc-vault-memory-store';
const transactionCookie: OidcVaultTransactionCookieOptions = { sameSite: 'lax' };
const app = express();
app.use(
createOidcVaultMiddleware({
backendOrigin: 'https://api.example.com',
frontendRedirectUri: 'https://frontend.example.com/callback',
trustedOrigins: ['https://frontend.example.com'],
config: { issuer: process.env.OIDC_ISSUER, clientId: process.env.OIDC_CLIENT_ID },
storeProvider: createMemoryOidcVaultStore(), // Local development; shared durable provider in production.
deviceBinding: { mode: 'required' },
transactionCookie,
}),
);The initiation wire contract is POST <basePath>/login, Content-Type: application/json, body { returnTo?: string }, response 200 { authorizationUrl: string } (OidcVaultLoginInitiationInput / OidcVaultLoginInitiationResult). The key is selected only by a verified DPoP header. returnTo is read only from JSON and uses the existing same-frontend-origin policy; query-string/body JWK/thumbprint shortcuts do not select binding. In optional mode, no proof creates an unbound cookie-guarded POST transaction; any supplied invalid proof fails. Required mode needs a proof and rejects legacy GET login before discovery or state allocation. GET in disabled/optional mode remains the unbound redirect and ignores proof/key shortcuts.
A browser using a persistent key can initiate as follows; the published browser client generates/persists the key and bounds retries:
import type {
OidcVaultLoginInitiationInput,
OidcVaultLoginInitiationResult,
} from '@web-ts-toolkit/express-oidc-vault/wire';
async function initiateLogin(freshDpopProof: string): Promise<OidcVaultLoginInitiationResult> {
// Proof: typ=dpop+jwt, allowed public JWK, POST, pinned absolute login htu,
// fresh iat/JTI/signature, nonce if challenged. No access-token ath is needed.
const body: OidcVaultLoginInitiationInput = { returnTo: '/signed-in' };
const response = await fetch('https://api.example.com/auth/oidc/login', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json', DPoP: freshDpopProof },
body: JSON.stringify(body),
});
if (!response.ok) throw new Error('Login initiation failed.');
const value: unknown = await response.json();
if (
typeof value !== 'object' ||
value === null ||
!('authorizationUrl' in value) ||
typeof value.authorizationUrl !== 'string'
) {
throw new Error('Invalid login initiation response.');
}
const result: OidcVaultLoginInitiationResult = { authorizationUrl: value.authorizationUrl };
return result; // Navigate to result.authorizationUrl using the same browser/profile.
}- Admission order: source Origin (valid Referer fallback only when Origin is absent), JSON/returnTo, shared proof/nonce/replay admission, then discovery/hooks/transaction persistence. POST source checks apply to both body and cookie session transports, and missing/null/duplicate/untrusted sources fail closed. Proof target uses pinned
backendOrigin+ externally visiblereq.originalUrlpath; Host/forwarded headers cannot change it. Browser proofs are never sent upstream. Replay reservations survive later discovery/store/hook failures; retry needs a fresh proof. - Temporary cookie: every successful POST creates a fresh 32-byte random base64url secret and stores only its SHA-256 hash. Defaults are HTTPS
__Host-oidc_vault_transactionor HTTPoidc_vault_transaction, host-only,Path=/, HttpOnly, Secure on HTTPS,SameSite=Lax. OnlynameandsameSiteare public overrides;nonerequires HTTPS and an explicit cross-site SPA choice. Strict/Domain/path/HttpOnly/Secure opt-outs fail construction. Session/transaction names must differ; multiple vault mounts need distinct transaction names. - Navigation authentication:
GET /callbackreads state and the selected cookie, preflights live identity/policy/hash, then atomically consumes the exact stored key/hash match before any upstream token request, session, or code. It does not treat a navigation as a DPoP-bearing request. Missing/wrong/noncanonical/duplicate selected cookies do not spend or clear the transaction; unrelated malformed cookies are ignored. Required-mode legacy records and disabled-mode bound records fail closed. POST transaction metadata reservesoidcVaultTransactionProviderfor the exact resolved issuer/client ID; returned atomic authority is rechecked before upstream use. - Propagation/cleanup: successful callback copies the original jkt into the session and key/hash into the code independently of mutable hooks; the transaction cookie is retained and its deadline shortened to the code's expiry. Max-Age and Expires round down to the record deadline, including hook/store delays. An authenticated provider-error callback consumes state and clears the temporary cookie with fixed
OIDC_VAULT_CALLBACK_ERROR/OIDC callback failed.(HTTP 400 JSON unless eligible frontend error recovery selects 302). Other authenticated terminal callback failures also clear it; mismatches leave cookies untouched. Abandoned records/cookies expire. A fresh initiation replaces the single cookie, so one browser/vault mount supports one pending flow; earlier flows can require restart. - Exchange: the retained cookie and a fresh proof from the original initiating key authenticate bound codes before atomic consumption; success or authenticated terminal issuance failure clears the temporary cookie. Origin/Referer checks apply to guarded JSON and URL-encoded exchange in both session transports. Missing/wrong cookie, wrong/missing/stale/replayed proof, identity/binding mismatch and nonce challenge do not spend an honest code or clear its cookie. Browser CORS must allow explicit trusted origins, credentials, Content-Type/DPoP and expose DPoP-Nonce/WWW-Authenticate; third-party cookie blocking can require same-site deployment.
Sender-constrained exchange, refresh and logout
Use the same persistent private key selected at POST login for every request. Exchange cannot claim a new key from the first presenter, JSON/JWK/thumbprint fields, hooks or a later optional proof.
| POST route | Authority and proof | Successful result |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- |
| <basePath>/exchange | { code }, temporary transaction cookie in both transports, trusted Origin/Referer for guarded codes, fresh original-key DPoP header when bound | OidcVaultExchangeResult; clears transaction cookie, sets session cookie only in cookie transport |
| <basePath>/refresh | Body { sessionId } or session cookie, fresh original-key DPoP header when bound; cookie transport also checks Origin/Referer | Same result with a rotated session handle and unchanged binding/lineage/absolute expiry |
| <basePath>/logout | Same handle/cookie and original-key proof; optional { redirect: true } on live handles | 200 { loggedOut: true } or best-effort upstream redirect after local revocation |
Vault POST proofs use the exact method and pinned backendOrigin plus externally visible path, fresh iat/jti, and nonce if challenged. They do not require an Authorization access token or ath, so refresh/logout work after local JWT expiry. Browser proofs are never forwarded to the upstream IdP. API requests separately require Authorization: DPoP <accessToken>, a fresh proof with ath, and request-aware validation.
For example, with a configured local issuer, the exchange response can be checked without backend deep imports (the caller supplies a fresh proof from its persistent original key):
import type { OidcVaultExchangeResult } from '@web-ts-toolkit/express-oidc-vault/wire';
async function exchangeBoundCode(code: string, freshDpopProof: string): Promise<OidcVaultExchangeResult> {
const response = await fetch('https://api.example.com/auth/oidc/exchange', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json', DPoP: freshDpopProof },
body: JSON.stringify({ code }),
});
if (!response.ok) throw new Error('Code exchange failed.');
const value: unknown = await response.json();
if (
typeof value !== 'object' ||
value === null ||
!('accessToken' in value) ||
typeof value.accessToken !== 'string' ||
!('tokenType' in value) ||
value.tokenType !== 'DPoP' ||
!('expiresIn' in value) ||
typeof value.expiresIn !== 'number' ||
!Number.isSafeInteger(value.expiresIn) ||
value.expiresIn < 0 ||
('sessionId' in value && typeof value.sessionId !== 'string')
) {
throw new Error('Invalid bound credential response.');
}
// Project validated credentials. Keep the access token in memory; in body
// transport persist sessionId in sessionStorage. Cookie JSON omits the ID.
return {
accessToken: value.accessToken,
tokenType: value.tokenType,
expiresIn: value.expiresIn,
...('sessionId' in value ? { sessionId: value.sessionId as string } : {}),
};
}Refresh sends a fresh proof to /refresh with { sessionId } in body transport or {} plus credentials: 'include' in cookie transport. Logout does likewise at /logout. Login/exchange always need credentials: 'include' for the temporary cookie. When tokenIssuer is omitted, the backend still enforces binding but returns no local accessToken/expiresIn/tokenType; the example above deliberately expects a configured issuer.
- Precommit order: capture request/record/provider authority; authenticate mode, code/session agreement, Origin/cookie and any enrolled recognition; verify signature/key/target/time/nonce and reserve shared replay; then consume/issue or use the upstream refresh token/rotate, or invoke logout hooks/revoke. Exchange atomically matches
expectedSessionIdand both exact/null binding fields and rechecks the returned code/session authority before issuance. Invalid proofs cannot burn upstream refresh tokens. Reservations survive downstream failure; a retry needs a fresh proof. - Legacy migration:
requiredrejects unbound records before state/upstream work.optionalpermits legacy unbound sessions/codes, explicitly matching omitted fields. Any supplied proof still validates/nonces/reserves but never enrolls or rebinds the legacy record. Cookie-only POSTs still need their temporary cookie and guarded-exchange Origin. Disabled binding rejects bound sessions/codes and built-in live/alias logout contexts. - Immutable refresh/issuance: rotation uses the original key, provider, subject, logical ID and absolute expiry; fresh ID/UserInfo profile precedence is preserved. Issuers and refresh/logout hooks receive owned plain session containers. Hook/issuer mutations cannot redirect lineage revocation or replace response/profile/binding authority. Invalid issuer output retains original-lineage rollback and sanitized/no-store errors.
- Logout aliases: built-ins resolve
getSessionRevocationContext(handle)for live handles and unexpired aliases, checking the surviving lineage's provider/key rather than an alias's missing historical binding. A mismatch leaves the lineage/cookie intact. No live target is idempotent success without deletion/replay/hooks (the selected transport's handle/cookie is still required). Aliases grant revocation only, not refresh or upstream redirect credentials; alias-only logout retains no live-session hook notification. Signed backchannel logout is unchanged. Stateless local JWTs remain valid until expiry unless the API validator checks application revocation state.
Optional Fingerprint Recognition (Not PoP)
fingerprintRecognition?: OidcVaultFingerprintRecognitionOptions is a separate opt-in browser recognition/change-detection policy. Fingerprint matching is recognition/change detection, not theft prevention against deliberate copying. A FingerprintJS visitorId or another browser-computed identifier is copyable/spoofable; matching it does not prove possession of a private key, identify a physical device, or constrain API access. Recognition never satisfies deviceBinding.mode: 'required'.
Enable it independently or alongside DPoP, using named package-root imports:
import {
createOidcVaultMiddleware,
type OidcVaultFingerprintRecognitionOptions,
} from '@web-ts-toolkit/express-oidc-vault';
import { createMemoryOidcVaultStore } from '@web-ts-toolkit/express-oidc-vault-memory-store';
const fingerprintRecognition: OidcVaultFingerprintRecognitionOptions = {};
const vault = createOidcVaultMiddleware({
backendOrigin: 'https://api.example.com',
frontendRedirectUri: 'https://frontend.example.com/callback',
trustedOrigins: ['https://frontend.example.com'],
config: { issuer: process.env.OIDC_ISSUER, clientId: process.env.OIDC_CLIENT_ID },
storeProvider: createMemoryOidcVaultStore(), // Development; shared Redis/Mongo provider in production.
fingerprintRecognition, // Or { headerName: 'X-App-Browser' }.
sessionTtlMs: 8 * 60 * 60 * 1000,
// Add deviceBinding: { mode: 'required' } for cryptographic sender constraint.
});- Wire signal: default
X-Device-Fingerprint; a customheaderNamemust be a valid HTTP field name without authentication, cookie, origin, content, or transport-header collisions (case-insensitive). Supply exactly one raw field, with a nonempty printable ASCII value, at most 256 bytes. Core does not trim, case-fold, split commas, or normalize the opaque server-observed value. Duplicate fields (even identical/case-varied), invalid characters, empty or oversized opted-in signals return 400OIDC_VAULT_INVALID_FINGERPRINT/Fingerprint signal is invalid.before credential work. Omitting the option means no capture/check. - Enrollment: only a supplied signal on JSON POST login enrolls recognition. An absent signal intentionally creates an unenrolled session; legacy/GET login stays unenrolled even if a header, profile claim, or later exchange/refresh signal is supplied. Fingerprint-only POST login is unbound and rejects a supplied DPoP header while DPoP is disabled. It still uses the single temporary HttpOnly transaction cookie and trusted Origin/Referer in both session transports. Construction requires all six guarded-store capabilities, just like the other opt-in flow; all built-ins implement them. The headerless callback authenticates the cookie and copies the original transaction evidence into the original new session.
- Precommit comparison: enrolled exchange/refresh require the original signal before proof/nonce/replay admission, guarded code consumption, upstream refresh-token use, or rotation. Missing/mismatch returns 403
OIDC_VAULT_FINGERPRINT_REAUTH_REQUIRED/Browser recognition changed; sign in again.without consuming codes, burning upstream refresh tokens, rotating/revoking sessions, or setting/clearing cookies. Handle it by clearing frontend auth state and starting a fresh POST login. There is no automatic tolerance, re-enrollment, or value rotation at exchange/refresh. A fresh login establishes a new value/new session; an earlier session remains until explicit revocation or expiry. - Private metadata: SHA-256 is stored as canonical base64url in
transaction.metadata.oidcVaultFingerprintRecognition, thensession.metadata.oidcVaultFingerprintRecognition = { version: 1, hash }. This key is reserved. Core preserves its original value/unenrolled absence through mutable precreate hooks, refresh, and portable metadata copies; profile claims cannot enroll/rebind it. Core stores no raw signal, emits no recognition evidence in user/credential responses, omits it from token-issuer session input, and logs neither raw signals nor hashes. Issuers should use allowlisted claims; hooks and request/proxy logging must also avoid fingerprint headers and reserved metadata. - Logout and APIs: recognition checks apply only to exchange/refresh. Live/alias logout and signed backchannel logout retain their existing rules, so a changed fingerprint does not prevent revocation; bound logout still needs its original DPoP key. Rotation aliases contain no recognition metadata and do not authenticate refresh. Fingerprint-only local tokens remain
Bearer; API recognition/risk policy is application-owned. DPoP JWTs still need request-aware proof enforcement at every API.
Frontend signal adapter
Keep collection in the frontend; the backend has no FingerprintJS dependency. Inject a current signal source and obtain headers for each POST login/exchange/refresh. For an intentionally unenrolled choice return undefined; collection failures should stop the operation rather than silently disabling an enrolled check. A minimal generic adapter (no backend runtime imports) is:
async function recognitionHeaders(getSignal: () => Promise<string | undefined>): Promise<Record<string, string>> {
let signal: string | undefined;
try {
signal = await getSignal();
} catch {
throw new Error('Browser recognition is unavailable.');
}
if (signal === undefined) return {};
if (
signal.length === 0 ||
signal.length > 256 ||
Array.from(signal).some((character) => character.charCodeAt(0) < 0x20 || character.charCodeAt(0) > 0x7e)
) {
throw new Error('Fingerprint signal is invalid.');
}
return { 'X-Device-Fingerprint': signal };
}
async function initiateRecognizedLogin(getSignal: () => Promise<string | undefined>): Promise<string> {
const response = await fetch('https://api.example.com/auth/oidc/login', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json', ...(await recognitionHeaders(getSignal)) },
body: JSON.stringify({}), // Add a fresh DPoP header separately when binding is enabled.
});
if (!response.ok) throw new Error('Login initiation failed.');
const value: unknown = await response.json();
if (
typeof value !== 'object' ||
value === null ||
!('authorizationUrl' in value) ||
typeof value.authorizationUrl !== 'string'
) {
throw new Error('Invalid login initiation response.');
}
return value.authorizationUrl; // Navigate after initiation.
}Obtain the same current signal through the source at /exchange (body { code }) and /refresh (body { sessionId } or cookie {}). Login/exchange always use credentials: 'include' for the temporary cookie; cookie refresh does too. On a recognition 403, start fresh login rather than a refresh retry loop. CORS must allow the configured fingerprint header and Content-Type, explicit trusted origins and credentials; also allow Authorization/DPoP and expose DPoP-Nonce/WWW-Authenticate when using DPoP. Cross-site SPAs may need explicit HTTPS transactionCookie: { sameSite: 'none' }; browser third-party-cookie policy still applies.
Published recognition adapter
The published browser client @web-ts-toolkit/oidc-vault-dpop-client ships this generic adapter as createDeviceFingerprint(source, { headerName? }) plus a structural optional-vendor adapter:
// In your frontend, after choosing to collect recognition:
import {
createDeviceFingerprint,
fingerprintJsSignalSource,
type FingerprintJsAgent,
} from '@web-ts-toolkit/oidc-vault-dpop-client';
function recognitionWithOptionalFingerprintJs(load: () => Promise<FingerprintJsAgent>) {
return createDeviceFingerprint(fingerprintJsSignalSource(load));
}
// If YOUR frontend installs @fingerprintjs/fingerprintjs, inject:
// recognitionWithOptionalFingerp