nish/net/oidc
Verify a JWT from an OpenID Connect issuer: find the issuer's keys through discovery (OpenID Connect Discovery 1.0), read its JWK Set (RFC 7517, RFC 7518 §6, RFC 8037), follow its key rotation, and check a token's signature and claims with nish/crypto/jwt.
import {
OIDC_DEFAULT_LEEWAY,
OIDC_DEFAULT_LIFETIME,
OIDC_DEFAULT_TIMEOUT_MS,
OIDC_ERR_DUPLICATE_KID,
OIDC_ERR_FETCH,
OIDC_ERR_ISSUER,
OIDC_ERR_JSON,
OIDC_ERR_KEY,
OIDC_ERR_KID_REQUIRED,
OIDC_ERR_NO_KEYS,
OIDC_ERR_PRIVATE,
OIDC_ERR_SCHEME,
OIDC_ERR_SIZE,
OIDC_ERR_STALE,
OIDC_ERR_TOO_MANY_KEYS,
OIDC_ERR_UNKNOWN_KID,
OIDC_MAX_DISCOVERY_BYTES,
OIDC_MAX_JWKS_BYTES,
OIDC_MAX_KEYS,
OIDC_MAX_KID,
OIDC_MAX_LIFETIME,
OIDC_MIN_LIFETIME,
OIDC_MIN_REFRESH_INTERVAL,
OIDC_OK,
OIDC_SKIPPED,
OIDC_STALE_GRACE,
OidcKeySet,
OidcKeys,
OidcMetadata,
OidcOptions,
oidcDiscover,
oidcDiscoveryUrl,
oidcHttpOptions,
oidcIssuerAllowed,
oidcLifetime,
oidcParseDiscovery,
oidcParseJwks,
oidcVerify,
} from "nish/net/oidc";
import { OIDC_OK, OidcKeys, OidcMetadata, OidcOptions, oidcDiscover, oidcVerify } from "nish/net/oidc"
const options = new OidcOptions()
const meta: OidcMetadata = oidcDiscover("https://issuer.example", options) // once, at start-up
const keys = new OidcKeys(meta, options)
keys.refresh(now) // fetch the key set; then call refresh(now) from the server's own timer
if (oidcVerify(keys, token, "my-api", now) === OIDC_OK) {
const claims: string = keys.claimsText()
}
oidcDiscover
Discovery: one blocking GET of oidcDiscoveryUrl(issuer), no redirect followed, bounded by options.timeoutMs and OIDC_MAX_DISCOVERY_BYTES, then oidcParseDiscovery.
oidcDiscoveryUrl
Where discovery asks: the issuer, less one trailing /, with /.well-known/openid-configuration appended (OpenID Connect Discovery 1.0 §4.1).
oidcHttpOptions
The fetch options discovery and a refresh use: no redirect followed, the connect, each read and the whole fetch bounded by options.timeoutMs (by OIDC_DEFAULT_TIMEOUT_MS when it is 0 or less), the body bounded at limit, and outbound applied when it is not null.
oidcIssuerAllowed
Whether issuer is a form this module takes: an https URL with a host and no userinfo, query or fragment (OpenID Connect Discovery 1.0 §2), or loopback http when options.allowLoopbackHttp is set.
oidcLifetime
How long a key set fetched with this Cache-Control is fresh: its first max-age directive of plain digits, clamped to [OIDC_MIN_LIFETIME, OIDC_MAX_LIFETIME], or OIDC_DEFAULT_LIFETIME when there is none.
oidcParseDiscovery
The discovery document doc, already fetched, checked against issuer: an object whose issuer is issuer byte for byte and whose jwks_uri is a URL oidcDiscover would fetch, and http only when the issuer is (so an https issuer never names an http key set).
oidcParseJwks
A JWK Set, already fetched, read into keys.
oidcVerify
Verify token with the issuer's keys, without fetching.
OidcKeySet
A JWK Set as taken: each key bound to one algorithm, with its kid, or why the set was refused.
OidcKeys
An issuer's rotating key set, and a verifier for its tokens.
OidcMetadata
What discovery found: the issuer as configured and the URL of its key set, or why it failed.
OidcOptions
How discovery and the key set fetch, and how tokens are checked.
Nothing is guessed about the issuer
The issuer is named by the caller,
and the discovery document must name the same issuer, byte for byte; the key
set is read only from the jwks_uri that document gives, and both must be
https (loopback http, with allowLoopbackHttp, for an http issuer only). A
jwks_uri on another origin than the issuer's was chosen by the document,
not the program, so it is fetched under an OutboundPolicy
(OidcOptions.jwksOutbound): public addresses only, no proxy. Every key in
the set is bound to exactly one algorithm, which comes
from the key — its kty, its crv and its alg — and never from a token's
header: a key whose alg disagrees with its type refuses the whole set, and
the verifier refuses a token whose header names any other algorithm.
Fetches are synchronous and happen only where the caller asks
oidcDiscover and OidcKeys.refresh each make one blocking GET, bounded by
OidcOptions.timeoutMs; OidcKeys.key and oidcVerify never fetch. A
token with a kid the set does not hold marks the set as wanted, so the
next refresh fetches it early, at most once per
OIDC_MIN_REFRESH_INTERVAL. A server calls refresh(now) from its own
loop or timer, where blocking is harmless, and never from a request.
Every function that reads the clock takes it as a now parameter, in
seconds since 1970, so a test drives the clock; oidcDiscover reads none. The security record is docs/security/oidc.md.
@module
Functions
oidcDiscover
Discovery: one blocking GET of oidcDiscoveryUrl(issuer), no redirect
followed, bounded by options.timeoutMs and OIDC_MAX_DISCOVERY_BYTES,
then oidcParseDiscovery. Only a 200 is taken.
const oidcDiscover: (
issuer: string,
options: OidcOptions,
) => OidcMetadata
issuerstringrequiredThe issuer, as configured: https, or loopback http when allowed.
optionsOidcOptionsrequiredThe options.
returnsOidcMetadataThe metadata; its error is OIDC_OK or the reason discovery failed.
oidcDiscoveryUrl
Where discovery asks: the issuer, less one trailing /, with
/.well-known/openid-configuration appended (OpenID Connect Discovery 1.0
§4.1).
const oidcDiscoveryUrl: (issuer: string) => string
issuerstringrequiredThe issuer identifier.
returnsstringThe discovery URL.
oidcHttpOptions
The fetch options discovery and a refresh use: no redirect followed, the
connect, each read and the whole fetch bounded by options.timeoutMs (by
OIDC_DEFAULT_TIMEOUT_MS when it is 0 or less), the body bounded at
limit, and outbound applied when it is not null.
const oidcHttpOptions: (
options: OidcOptions,
limit: i32,
outbound: OutboundPolicy | null,
) => HttpOptions
optionsOidcOptionsrequiredThe options.
limiti32requiredThe largest body taken, in bytes.
outboundOutboundPolicy | nullrequiredThe outbound policy the fetch runs under, or null for none.
returnsHttpOptionsThe fetch options.
oidcIssuerAllowed
Whether issuer is a form this module takes: an https URL with a host and
no userinfo, query or fragment (OpenID Connect Discovery 1.0 §2), or loopback
http when options.allowLoopbackHttp is set.
const oidcIssuerAllowed: (
issuer: string,
options: OidcOptions,
) => boolean
issuerstringrequiredThe issuer identifier.
optionsOidcOptionsrequiredThe options; only allowLoopbackHttp is read.
returnsbooleanTrue when the issuer may be asked.
oidcLifetime
How long a key set fetched with this Cache-Control is fresh: its first
max-age directive of plain digits, clamped to [OIDC_MIN_LIFETIME, OIDC_MAX_LIFETIME], or OIDC_DEFAULT_LIFETIME when there is none. Other
directives (no-cache, no-store, s-maxage) are not read: the floor
holds whatever the response says.
const oidcLifetime: (cacheControl: string | null) => i64
cacheControlstring | nullrequiredThe header's value, or null when the response had none.
returnsi64The lifetime, in seconds.
oidcParseDiscovery
The discovery document doc, already fetched, checked against issuer:
an object whose issuer is issuer byte for byte and whose jwks_uri is
a URL oidcDiscover would fetch, and http only when the issuer is (so an
https issuer never names an http key set). Fetches nothing.
const oidcParseDiscovery: (
issuer: string,
doc: u8[],
options: OidcOptions,
) => OidcMetadata
issuerstringrequiredThe issuer, as configured.
docu8[]requiredThe document's bytes.
optionsOidcOptionsrequiredThe options; only allowLoopbackHttp is read.
returnsOidcMetadataThe metadata; its error is OIDC_OK or the reason it was refused.
oidcParseJwks
A JWK Set, already fetched, read into keys. The rules:
-
The document is at most
OIDC_MAX_JWKS_BYTES, a JSON object whosekeysis an array of at mostOIDC_MAX_KEYSentries.
Each entry is then read by these rules, in this order; the first that applies decides it, and a refusal refuses the whole set:
- An entry that is not an object refuses the set (
OIDC_ERR_JSON). -
An entry holding
d,p,q,dp,dq,qi,othorkrefuses the set (OIDC_ERR_PRIVATE), whatever itsuseor type: a publisher that leaks a private or symmetric key has a set no verifier should trust. -
An entry without
kty, or whosekty,use,alg,kidorcrvis present and not a string, refuses the set (OIDC_ERR_JSON). -
A
kidthat is not 1 toOIDC_MAX_KIDbytes of printable ASCII refuses the set (OIDC_ERR_KEY), whatever the entry'suse. - An entry whose
useis present and not"sig"is skipped. -
An entry whose
algnames an algorithmnish/crypto/jwtdoes not have is skipped. -
An entry whose
kty/crvis not RSA, EC P-256, EC P-384 or OKP Ed25519 is skipped when it has noalg, and refuses the set (OIDC_ERR_KEY) when it has one, since thealgthen names a key this module would misread. -
The key's algorithm is its
algwhen present, which must agree with its type (RS256/384/512 for RSA, ES256 for P-256, ES384 for P-384, EdDSA for Ed25519), or the set is refused (OIDC_ERR_KEY); withoutalgit is ES256, ES384 or EdDSA by curve, and RS256 for RSA, OpenID Connect Core's default. -
The key's material must make a key —
n/ewith an RSA modulus of 2048 to 8192 bits,x/yof the curve's size, an Ed25519xof 32 bytes — or the set is refused (OIDC_ERR_KEY).
Then:
-
Two keys taken with the same
kid, or two without one, refuse the set (OIDC_ERR_DUPLICATE_KID), and a set where none is taken isOIDC_ERR_NO_KEYS.
const oidcParseJwks: (doc: u8[]) => OidcKeySet
docu8[]requiredThe JWK Set's bytes.
returnsOidcKeySetThe set; its error is OIDC_OK or the reason it was refused.
oidcVerify
Verify token with the issuer's keys, without fetching. The key is chosen
by the token's kid; a token with no kid — or one whose kid is not a
string or is longer than OIDC_MAX_KID, which counts as none — is taken
only when the set holds exactly one key, and is checked under that key,
since otherwise which key it means is a guess. The key
alone decides the algorithm, so none, any HMAC algorithm and any
algorithm but the key's are refused (JWT_ERR_ALG); then the signature,
iss (the issuer, exactly), aud (a string or an array that holds
audience), and exp, nbf and iat within options.leeway are checked
by nish/crypto/jwt's JwtVerifier, and exp is required.
const oidcVerify: (
keys: OidcKeys,
token: string,
audience: string,
now: i64,
) => i32
keysOidcKeysrequiredThe issuer's keys.
tokenstringrequiredThe compact token.
audiencestringrequiredThe audience the token must name: this service's client id.
nowi64requiredThe current time, in seconds since 1970.
returnsi32
OIDC_OK (JWT_OK), an OIDC_ERR_* when no key could be chosen,
or the JWT_ERR_* the verifier refused the token with.
Classes
OidcKeySet
A JWK Set as taken: each key bound to one algorithm, with its kid, or why the set was refused.
class OidcKeySet
| Member | |
|---|---|
new OidcKeySet() |
An empty set, OIDC_OK; oidcParseJwks is the way to fill one. |
error: i32 |
OIDC_OK, or the reason the set was refused; a refused set holds no key. |
keys: JwtKey[] |
The keys taken, in the set's order. |
kids: string[] |
Each key's kid; "" for a key with none. |
count(): i32 |
The number of keys taken. |
find(kid: string): JwtKey | null |
The key whose kid is kid, spelled exactly. |
OidcKeys
An issuer's rotating key set, and a verifier for its tokens. One thread's,
like the JwtVerifier it holds.
The set is fetched by refresh, which fetches only when it is due: there
is no set yet, the set is past its lifetime (oidcLifetime), or a token
named a kid the set does not hold — and never twice within
OIDC_MIN_REFRESH_INTERVAL. A refresh that fails keeps the last set taken,
which keeps verifying until OIDC_STALE_GRACE past the end of its
lifetime; past that hard expiry, nothing verifies until a refresh succeeds.
A refresh that succeeds replaces the set whole, so a key the issuer stopped
publishing stops verifying then. A token whose kid the set holds never
makes a refresh due early, so a removed key keeps verifying until the set's
lifetime ends — at most OIDC_MAX_LIFETIME — and, while refreshes fail,
until its hard expiry, at most OIDC_STALE_GRACE more.
class OidcKeys
| Member | |
|---|---|
new OidcKeys(meta: OidcMetadata, options: OidcOptions) |
Keys for the issuer meta names; nothing is fetched until refresh. |
freshUntil: i64 |
When the last set taken stops being fresh. |
hardUntil: i64 |
When the last set taken stops verifying, if no refresh replaces it. |
lastError: i32 |
The result of the last refresh that fetched: OIDC_OK or why it failed. |
readonly meta: OidcMetadata |
The issuer's metadata, as discovery gave it. |
readonly options: OidcOptions |
The options fetches and verification use. |
set: OidcKeySet | null |
The last set taken, or null before the first. |
tried: boolean |
Whether any fetch has been begun. |
triedAt: i64 |
When the last fetch was begun. |
readonly verifier: JwtVerifier |
The verifier oidcVerify uses; after OIDC_OK, its claims, exp and nbf are the token's. |
wanted: boolean |
Whether a token named a kid the set does not hold since the last fetch. |
check(key: JwtKey, n: i32, audience: string, now: i64): i32 |
Verify the token load copied under key, against the issuer and audience. |
claimsText(): string |
The claims of the last token oidcVerify accepted, as text. |
due(now: i64): boolean |
Whether refresh(now) would fetch: there is no set, the set is past its lifetime, or a token wanted a kid it lacks — and the last fetch began at least OIDC_MIN_REFRESH_INTERVAL ago (or later than now, after the clock stepped back). |
key(kid: string, now: i64): JwtKey | null |
The key whose kid is kid, without fetching. A kid the set lacks marks the set as wanted, so the next due refresh fetches it. |
load(token: string): i32 |
The token's bytes in the verifier's buffer, for oidcVerify. |
peekKid(n: i32): string | null |
The kid of the token load copied, read before any signature is checked, only to choose a key. |
refresh(now: i64): i32 |
Fetch the key set from meta.jwksUri when a refresh is due: one blocking GET, no redirect followed, bounded by options.timeoutMs and OIDC_MAX_JWKS_BYTES, and under options.jwksOutbound when the jwks_uri is on another origin than the issuer. Call it once at start-up and then from the server's own loop or timer. |
refreshWith(doc: u8[] | null, cacheControl: string | null, now: i64): i32 |
Take doc as the key set when a refresh is due, without fetching: for a caller that fetches the set its own way, and for tests. Counts as a fetch for the rate limit. |
usable(now: i64): boolean |
Whether the set verifies at now: one has been taken and it is not past its hard expiry. |
OidcMetadata
What discovery found: the issuer as configured and the URL of its key set, or why it failed.
class OidcMetadata
| Member | |
|---|---|
new OidcMetadata(error: i32, issuer: string, jwksUri: string) |
Metadata from its parts, checked for nothing; oidcDiscover and oidcParseDiscovery are the way to make one. |
error: i32 |
OIDC_OK, or the reason discovery failed; the other fields are empty unless it is OIDC_OK. |
issuer: string |
The issuer, as configured and as the document named it. |
jwksUri: string |
The document's jwks_uri. |
OidcOptions
How discovery and the key set fetch, and how tokens are checked.
class OidcOptions
| Member | |
|---|---|
new OidcOptions() |
The defaults: OIDC_DEFAULT_TIMEOUT_MS, OIDC_DEFAULT_LEEWAY, JWT_MAX_TOKEN, no loopback http, and a default OutboundPolicy for a jwks_uri on another origin. |
allowLoopbackHttp: boolean |
Allow http:// to 127.0.0.1, localhost or ::1 for the issuer and jwks_uri; off by default, for tests. |
jwksOutbound: OutboundPolicy | null |
The policy a jwks_uri on another origin than the issuer's is fetched under, since the discovery document chose it and the program did not: by default new OutboundPolicy(), public addresses only and no proxy. Null fetches it like the issuer, through any proxy the environment names. |
leeway: i64 |
The clock skew allowed on exp, nbf and iat, in seconds. |
maxToken: i32 |
The longest token verified, in bytes. |
timeoutMs: i32 |
The bound on one fetch, connect to last byte, in milliseconds; 0 or less means OIDC_DEFAULT_TIMEOUT_MS. |
Limits
65,536
OIDC_MAX_DISCOVERY_BYTES: i32
The largest discovery document read, in bytes.
65,536
OIDC_MAX_JWKS_BYTES: i32
The largest JWK Set read, in bytes.
64
OIDC_MAX_KEYS: i32
The most entries a JWK Set's keys may list, taken or skipped.
256
OIDC_MAX_KID: i32
The longest kid, in bytes.
86,400
OIDC_MAX_LIFETIME: i64
The longest a key set is fresh, in seconds, whatever max-age says.
300
OIDC_MIN_LIFETIME: i64
The shortest a key set is fresh, in seconds, whatever max-age says.
60
OIDC_MIN_REFRESH_INTERVAL: i64
The least time between two fetches of the key set, in seconds. A fetch
clears the unknown-kid mark as it begins, so one that fails is tried
again only when another unknown kid arrives or the set's lifetime ends,
not merely once this interval has passed.
Constants
60
OIDC_DEFAULT_LEEWAY: i64
The default clock skew allowed on exp, nbf and iat, in seconds.
3,600
OIDC_DEFAULT_LIFETIME: i64
How long a key set is fresh when its response has no usable max-age, in seconds.
10,000
OIDC_DEFAULT_TIMEOUT_MS: i32
The default bound on one fetch, connect to last byte, in milliseconds.
-47
OIDC_ERR_DUPLICATE_KID: i32
Two keys taken into the set share a kid (two without one count as sharing it).
-40
OIDC_ERR_FETCH: i32
No response, a status other than 200, or a transport error.
-43
OIDC_ERR_ISSUER: i32
The discovery document's issuer is not the configured issuer, byte for byte.
-42
OIDC_ERR_JSON: i32
The document is not JSON, not an object, or a member is missing or of the wrong type.
-45
OIDC_ERR_KEY: i32
A key's alg disagrees with its kty or crv, its material does not make a key, or its kid is refused.
-51
OIDC_ERR_KID_REQUIRED: i32
The token names no kid and the set holds more than one key.
-49
OIDC_ERR_NO_KEYS: i32
The set holds no key this module takes.
-46
OIDC_ERR_PRIVATE: i32
A key carries a private or symmetric member (d, p, q, dp, dq, qi, oth or k).
-44
OIDC_ERR_SCHEME: i32
The issuer or jwks_uri is not an https URL (or loopback http, when allowed; an http jwks_uri only for an http issuer), or has a form refused.
-41
OIDC_ERR_SIZE: i32
The document is larger than its limit (OIDC_MAX_DISCOVERY_BYTES, OIDC_MAX_JWKS_BYTES).
-52
OIDC_ERR_STALE: i32
No key set has been taken yet, or the last one is past its hard expiry.
-48
OIDC_ERR_TOO_MANY_KEYS: i32
The set lists more than OIDC_MAX_KEYS keys.
-50
OIDC_ERR_UNKNOWN_KID: i32
The token's kid is not in the set.
0
OIDC_OK: i32
Success.
1
OIDC_SKIPPED: i32
OidcKeys.refresh did nothing: the set is fresh and wanted by no token, or the last attempt was too recent.
86,400
OIDC_STALE_GRACE: i64
How long past its freshness a key set still verifies while refreshes fail, in seconds.

