@amritk/nish-x86_64-linux 0.41.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1107 @@
1
+ /**
2
+ * `nish/net/oidc` — verify a JWT from an OpenID Connect issuer: find the
3
+ * issuer's keys through discovery (OpenID Connect Discovery 1.0), read its
4
+ * JWK Set (RFC 7517, RFC 7518 §6, RFC 8037), follow its key rotation, and
5
+ * check a token's signature and claims with `nish/crypto/jwt`.
6
+ *
7
+ * import { OIDC_OK, OidcKeys, OidcMetadata, OidcOptions, oidcDiscover, oidcVerify } from "nish/net/oidc"
8
+ *
9
+ * const options = new OidcOptions()
10
+ * const meta: OidcMetadata = oidcDiscover("https://issuer.example", options) // once, at start-up
11
+ * const keys = new OidcKeys(meta, options)
12
+ * keys.refresh(now) // fetch the key set; then call refresh(now) from the server's own timer
13
+ * if (oidcVerify(keys, token, "my-api", now) === OIDC_OK) {
14
+ * const claims: string = keys.claimsText()
15
+ * }
16
+ *
17
+ * **Nothing is guessed about the issuer.** The issuer is named by the caller,
18
+ * and the discovery document must name the same issuer, byte for byte; the key
19
+ * set is read only from the `jwks_uri` that document gives, and both must be
20
+ * https (loopback http, with `allowLoopbackHttp`, for an http issuer only). A
21
+ * `jwks_uri` on another origin than the issuer's was chosen by the document,
22
+ * not the program, so it is fetched under an `OutboundPolicy`
23
+ * (`OidcOptions.jwksOutbound`): public addresses only, no proxy. Every key in
24
+ * the set is bound to exactly one algorithm, which comes
25
+ * from the key — its `kty`, its `crv` and its `alg` — and never from a token's
26
+ * header: a key whose `alg` disagrees with its type refuses the whole set, and
27
+ * the verifier refuses a token whose header names any other algorithm.
28
+ *
29
+ * **Fetches are synchronous and happen only where the caller asks.**
30
+ * `oidcDiscover` and `OidcKeys.refresh` each make one blocking GET, bounded by
31
+ * `OidcOptions.timeoutMs`; `OidcKeys.key` and `oidcVerify` never fetch. A
32
+ * token with a `kid` the set does not hold marks the set as wanted, so the
33
+ * next `refresh` fetches it early, at most once per
34
+ * `OIDC_MIN_REFRESH_INTERVAL`. A server calls `refresh(now)` from its own
35
+ * loop or timer, where blocking is harmless, and never from a request.
36
+ *
37
+ * Every function that reads the clock takes it as a `now` parameter, in
38
+ * seconds since 1970, so a test drives the clock; `oidcDiscover` reads none. The security record is `docs/security/oidc.md`.
39
+ *
40
+ * @module
41
+ */
42
+ import {
43
+ JWT_ALG_EDDSA,
44
+ JWT_ALG_ES256,
45
+ JWT_ALG_ES384,
46
+ JWT_ALG_HS256,
47
+ JWT_ALG_HS384,
48
+ JWT_ALG_HS512,
49
+ JWT_ALG_RS256,
50
+ JWT_ALG_RS384,
51
+ JWT_ALG_RS512,
52
+ JWT_ERR_FORMAT,
53
+ JWT_ERR_SIZE,
54
+ JWT_MAX_TOKEN,
55
+ JwtKey,
56
+ JwtVerifier,
57
+ jwtAlgName,
58
+ jwtEcKey,
59
+ jwtEd25519Key,
60
+ jwtRsaKeyParts,
61
+ } from "nish/crypto/jwt"
62
+ import { base64urlDecode } from "nish/crypto/base64url"
63
+ import {
64
+ FetchSyncClient,
65
+ HTTP_E_BODY_TOO_LARGE,
66
+ HttpOptions,
67
+ HttpRequest,
68
+ HttpResponse,
69
+ } from "nish/net/fetch"
70
+ import { OutboundPolicy } from "nish/net/outbound"
71
+ import { Url, urlOrigin, urlParse } from "nish/net/url"
72
+ import {
73
+ JSON_VALUE_ARRAY,
74
+ JSON_VALUE_OBJECT,
75
+ JSON_VALUE_STRING,
76
+ JsonDocument,
77
+ JsonValue,
78
+ } from "nish/json-value"
79
+ import { JsonLimits } from "nish/json-tokenizer"
80
+ import { asciiLower, trim } from "nish/text"
81
+
82
+ /** Success. */
83
+ export const OIDC_OK: i32 = 0
84
+ /** `OidcKeys.refresh` did nothing: the set is fresh and wanted by no token, or the last attempt was too recent. */
85
+ export const OIDC_SKIPPED: i32 = 1
86
+ /** No response, a status other than 200, or a transport error. */
87
+ export const OIDC_ERR_FETCH: i32 = -40
88
+ /** The document is larger than its limit (`OIDC_MAX_DISCOVERY_BYTES`, `OIDC_MAX_JWKS_BYTES`). */
89
+ export const OIDC_ERR_SIZE: i32 = -41
90
+ /** The document is not JSON, not an object, or a member is missing or of the wrong type. */
91
+ export const OIDC_ERR_JSON: i32 = -42
92
+ /** The discovery document's `issuer` is not the configured issuer, byte for byte. */
93
+ export const OIDC_ERR_ISSUER: i32 = -43
94
+ /** 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. */
95
+ export const OIDC_ERR_SCHEME: i32 = -44
96
+ /** A key's `alg` disagrees with its `kty` or `crv`, its material does not make a key, or its `kid` is refused. */
97
+ export const OIDC_ERR_KEY: i32 = -45
98
+ /** A key carries a private or symmetric member (`d`, `p`, `q`, `dp`, `dq`, `qi`, `oth` or `k`). */
99
+ export const OIDC_ERR_PRIVATE: i32 = -46
100
+ /** Two keys taken into the set share a `kid` (two without one count as sharing it). */
101
+ export const OIDC_ERR_DUPLICATE_KID: i32 = -47
102
+ /** The set lists more than `OIDC_MAX_KEYS` keys. */
103
+ export const OIDC_ERR_TOO_MANY_KEYS: i32 = -48
104
+ /** The set holds no key this module takes. */
105
+ export const OIDC_ERR_NO_KEYS: i32 = -49
106
+ /** The token's `kid` is not in the set. */
107
+ export const OIDC_ERR_UNKNOWN_KID: i32 = -50
108
+ /** The token names no `kid` and the set holds more than one key. */
109
+ export const OIDC_ERR_KID_REQUIRED: i32 = -51
110
+ /** No key set has been taken yet, or the last one is past its hard expiry. */
111
+ export const OIDC_ERR_STALE: i32 = -52
112
+
113
+ /** The largest discovery document read, in bytes. */
114
+ export const OIDC_MAX_DISCOVERY_BYTES: i32 = 65536
115
+ /** The largest JWK Set read, in bytes. */
116
+ export const OIDC_MAX_JWKS_BYTES: i32 = 65536
117
+ /** The most entries a JWK Set's `keys` may list, taken or skipped. */
118
+ export const OIDC_MAX_KEYS: i32 = 64
119
+ /** The longest `kid`, in bytes. */
120
+ export const OIDC_MAX_KID: i32 = 256
121
+ /** The shortest a key set is fresh, in seconds, whatever `max-age` says. */
122
+ export const OIDC_MIN_LIFETIME: i64 = 300
123
+ /** The longest a key set is fresh, in seconds, whatever `max-age` says. */
124
+ export const OIDC_MAX_LIFETIME: i64 = 86400
125
+ /** How long a key set is fresh when its response has no usable `max-age`, in seconds. */
126
+ export const OIDC_DEFAULT_LIFETIME: i64 = 3600
127
+ /**
128
+ * The least time between two fetches of the key set, in seconds. A fetch
129
+ * clears the unknown-`kid` mark as it begins, so one that fails is tried
130
+ * again only when another unknown `kid` arrives or the set's lifetime ends,
131
+ * not merely once this interval has passed.
132
+ */
133
+ export const OIDC_MIN_REFRESH_INTERVAL: i64 = 60
134
+ /** How long past its freshness a key set still verifies while refreshes fail, in seconds. */
135
+ export const OIDC_STALE_GRACE: i64 = 86400
136
+ /** The default clock skew allowed on `exp`, `nbf` and `iat`, in seconds. */
137
+ export const OIDC_DEFAULT_LEEWAY: i64 = 60
138
+ /** The default bound on one fetch, connect to last byte, in milliseconds. */
139
+ export const OIDC_DEFAULT_TIMEOUT_MS: i32 = 10000
140
+
141
+ /** The path discovery appends to the issuer (OpenID Connect Discovery 1.0 §4). */
142
+ const OIDC_WELL_KNOWN: string = "/.well-known/openid-configuration"
143
+ /** The bytes a `kid` may hold: printable ASCII, space to tilde. */
144
+ const OIDC_KID_LOW: i32 = 32
145
+ const OIDC_KID_HIGH: i32 = 126
146
+ const OIDC_CH_0: i32 = 48
147
+ const OIDC_CH_9: i32 = 57
148
+ const OIDC_CH_EQUALS: i32 = 61
149
+ const OIDC_CH_COMMA: i32 = 44
150
+ const OIDC_HTTP_OK: i32 = 200
151
+ /** The uncompressed-point marker `jwtEcKey` takes in front of `x‖y`. */
152
+ const OIDC_EC_UNCOMPRESSED: i32 = 4
153
+ const OIDC_P256_COORD: i32 = 32
154
+ const OIDC_P384_COORD: i32 = 48
155
+ const OIDC_ED25519_KEY: i32 = 32
156
+ /** Members that make a JWK private or symmetric (RFC 7518 §6.2.2, §6.3.2, §6.4.1; RFC 8037 §2). */
157
+ const oidcPrivateMembers = (): string[] => ["d", "p", "q", "dp", "dq", "qi", "oth", "k"]
158
+
159
+ /** How discovery and the key set fetch, and how tokens are checked. */
160
+ export class OidcOptions {
161
+ /** Allow `http://` to `127.0.0.1`, `localhost` or `::1` for the issuer and `jwks_uri`; off by default, for tests. */
162
+ allowLoopbackHttp: boolean = false
163
+ /** The bound on one fetch, connect to last byte, in milliseconds; 0 or less means `OIDC_DEFAULT_TIMEOUT_MS`. */
164
+ timeoutMs: i32
165
+ /** The clock skew allowed on `exp`, `nbf` and `iat`, in seconds. */
166
+ leeway: i64
167
+ /** The longest token verified, in bytes. */
168
+ maxToken: i32
169
+ /**
170
+ * The policy a `jwks_uri` on another origin than the issuer's is fetched
171
+ * under, since the discovery document chose it and the program did not: by
172
+ * default `new OutboundPolicy()`, public addresses only and no proxy. Null
173
+ * fetches it like the issuer, through any proxy the environment names.
174
+ */
175
+ jwksOutbound: OutboundPolicy | null
176
+
177
+ /**
178
+ * The defaults: `OIDC_DEFAULT_TIMEOUT_MS`, `OIDC_DEFAULT_LEEWAY`,
179
+ * `JWT_MAX_TOKEN`, no loopback http, and a default `OutboundPolicy` for a
180
+ * `jwks_uri` on another origin.
181
+ */
182
+ constructor() {
183
+ this.timeoutMs = OIDC_DEFAULT_TIMEOUT_MS
184
+ this.leeway = OIDC_DEFAULT_LEEWAY
185
+ this.maxToken = JWT_MAX_TOKEN
186
+ this.jwksOutbound = new OutboundPolicy()
187
+ }
188
+ }
189
+
190
+ /** What discovery found: the issuer as configured and the URL of its key set, or why it failed. */
191
+ export class OidcMetadata {
192
+ /** `OIDC_OK`, or the reason discovery failed; the other fields are empty unless it is `OIDC_OK`. */
193
+ error: i32
194
+ /** The issuer, as configured and as the document named it. */
195
+ issuer: string
196
+ /** The document's `jwks_uri`. */
197
+ jwksUri: string
198
+
199
+ /**
200
+ * Metadata from its parts, checked for nothing; `oidcDiscover` and
201
+ * `oidcParseDiscovery` are the way to make one.
202
+ *
203
+ * @param error `OIDC_OK`, or the reason discovery failed.
204
+ * @param issuer The issuer.
205
+ * @param jwksUri The URL of the issuer's JWK Set.
206
+ */
207
+ constructor(error: i32, issuer: string, jwksUri: string) {
208
+ this.error = error
209
+ this.issuer = issuer
210
+ this.jwksUri = jwksUri
211
+ }
212
+ }
213
+
214
+ /** A JWK Set as taken: each key bound to one algorithm, with its `kid`, or why the set was refused. */
215
+ export class OidcKeySet {
216
+ /** `OIDC_OK`, or the reason the set was refused; a refused set holds no key. */
217
+ error: i32 = 0
218
+ /** The keys taken, in the set's order. */
219
+ keys: JwtKey[]
220
+ /** Each key's `kid`; `""` for a key with none. */
221
+ kids: string[]
222
+
223
+ /** An empty set, `OIDC_OK`; `oidcParseJwks` is the way to fill one. */
224
+ constructor() {
225
+ this.keys = []
226
+ this.kids = []
227
+ }
228
+
229
+ /**
230
+ * The number of keys taken.
231
+ *
232
+ * @returns How many keys the set holds.
233
+ */
234
+ count(): i32 {
235
+ return toI32(this.keys.length)
236
+ }
237
+
238
+ /**
239
+ * The key whose `kid` is `kid`, spelled exactly.
240
+ *
241
+ * @param kid The `kid` to look for.
242
+ * @returns The key, or null when no key has that `kid`.
243
+ */
244
+ find(kid: string): JwtKey | null {
245
+ for (let i: i32 = 0; i < toI32(this.keys.length); i += 1) {
246
+ if (kid !== "" && this.kids[i] === kid) {
247
+ return this.keys[i]
248
+ }
249
+ }
250
+ return null
251
+ }
252
+ }
253
+
254
+ /** A failed set: no key, and the reason. */
255
+ const oidcRefused = (error: i32): OidcKeySet => {
256
+ const set: OidcKeySet = new OidcKeySet()
257
+ set.error = error
258
+ return set
259
+ }
260
+
261
+ /** Whether `host` names this machine, as `allowLoopbackHttp` allows. */
262
+ const oidcLoopback = (host: string): boolean => host === "127.0.0.1" || host === "localhost" || host === "::1"
263
+
264
+ /** Whether `u` may be fetched: https with a host and no userinfo, or loopback http when allowed. */
265
+ const oidcUrlAllowed = (u: Url, options: OidcOptions): boolean => {
266
+ if (u.host === "" || u.username !== "" || u.password !== "") {
267
+ return false
268
+ }
269
+ if (u.scheme === "https") {
270
+ return true
271
+ }
272
+ return u.scheme === "http" && options.allowLoopbackHttp && oidcLoopback(u.host)
273
+ }
274
+
275
+ /**
276
+ * Whether `issuer` is a form this module takes: an https URL with a host and
277
+ * no userinfo, query or fragment (OpenID Connect Discovery 1.0 §2), or loopback
278
+ * http when `options.allowLoopbackHttp` is set.
279
+ *
280
+ * @param issuer The issuer identifier.
281
+ * @param options The options; only `allowLoopbackHttp` is read.
282
+ * @returns True when the issuer may be asked.
283
+ */
284
+ export const oidcIssuerAllowed = (issuer: string, options: OidcOptions): boolean => {
285
+ const u: Url | null = urlParse(issuer)
286
+ if (u === null) {
287
+ return false
288
+ }
289
+ return u.query === null && u.fragment === null && oidcUrlAllowed(u, options)
290
+ }
291
+
292
+ /**
293
+ * Where discovery asks: the issuer, less one trailing `/`, with
294
+ * `/.well-known/openid-configuration` appended (OpenID Connect Discovery 1.0
295
+ * §4.1).
296
+ *
297
+ * @param issuer The issuer identifier.
298
+ * @returns The discovery URL.
299
+ */
300
+ export const oidcDiscoveryUrl = (issuer: string): string => {
301
+ const base: string = issuer.endsWith("/") ? issuer.slice(0, toI32(issuer.length) - 1) : issuer
302
+ return `${base}${OIDC_WELL_KNOWN}`
303
+ }
304
+
305
+ /** A JSON document sized to `limit` bytes. */
306
+ const oidcDocument = (limit: i32): JsonDocument => {
307
+ const limits: JsonLimits = new JsonLimits()
308
+ limits.maxTotalBytes = limit
309
+ limits.maxStringBytes = limit
310
+ return new JsonDocument(limits)
311
+ }
312
+
313
+ /**
314
+ * The discovery document `doc`, already fetched, checked against `issuer`:
315
+ * an object whose `issuer` is `issuer` byte for byte and whose `jwks_uri` is
316
+ * a URL `oidcDiscover` would fetch, and http only when the issuer is (so an
317
+ * https issuer never names an http key set). Fetches nothing.
318
+ *
319
+ * @param issuer The issuer, as configured.
320
+ * @param doc The document's bytes.
321
+ * @param options The options; only `allowLoopbackHttp` is read.
322
+ * @returns The metadata; its `error` is `OIDC_OK` or the reason it was refused.
323
+ */
324
+ export const oidcParseDiscovery = (issuer: string, doc: u8[], options: OidcOptions): OidcMetadata => {
325
+ if (!oidcIssuerAllowed(issuer, options)) {
326
+ return new OidcMetadata(OIDC_ERR_SCHEME, "", "")
327
+ }
328
+ if (toI32(doc.length) > OIDC_MAX_DISCOVERY_BYTES) {
329
+ return new OidcMetadata(OIDC_ERR_SIZE, "", "")
330
+ }
331
+ const json: JsonDocument = oidcDocument(OIDC_MAX_DISCOVERY_BYTES)
332
+ const root: JsonValue = json.parse(doc, toI32(0), toI32(doc.length))
333
+ if (root < 0 || json.kind(root) !== JSON_VALUE_OBJECT) {
334
+ return new OidcMetadata(OIDC_ERR_JSON, "", "")
335
+ }
336
+ const named: JsonValue = json.get(root, "issuer")
337
+ const jwks: JsonValue = json.get(root, "jwks_uri")
338
+ if (json.kind(named) !== JSON_VALUE_STRING || json.kind(jwks) !== JSON_VALUE_STRING) {
339
+ return new OidcMetadata(OIDC_ERR_JSON, "", "")
340
+ }
341
+ if (!json.stringEquals(named, issuer)) {
342
+ return new OidcMetadata(OIDC_ERR_ISSUER, "", "")
343
+ }
344
+ const jwksUri: string = json.string(jwks)
345
+ const u: Url | null = urlParse(jwksUri)
346
+ if (
347
+ u === null ||
348
+ !oidcUrlAllowed(u, options) ||
349
+ (u.scheme === "http" && !asciiLower(issuer).startsWith("http:"))
350
+ ) {
351
+ return new OidcMetadata(OIDC_ERR_SCHEME, "", "")
352
+ }
353
+ return new OidcMetadata(OIDC_OK, issuer, jwksUri)
354
+ }
355
+
356
+ /**
357
+ * The fetch options discovery and a refresh use: no redirect followed, the
358
+ * connect, each read and the whole fetch bounded by `options.timeoutMs` (by
359
+ * `OIDC_DEFAULT_TIMEOUT_MS` when it is 0 or less), the body bounded at
360
+ * `limit`, and `outbound` applied when it is not null.
361
+ *
362
+ * @param options The options.
363
+ * @param limit The largest body taken, in bytes.
364
+ * @param outbound The outbound policy the fetch runs under, or null for none.
365
+ * @returns The fetch options.
366
+ */
367
+ export const oidcHttpOptions = (
368
+ options: OidcOptions,
369
+ limit: i32,
370
+ outbound: OutboundPolicy | null
371
+ ): HttpOptions => {
372
+ const http: HttpOptions = new HttpOptions()
373
+ const timeout: i32 = options.timeoutMs > 0 ? options.timeoutMs : OIDC_DEFAULT_TIMEOUT_MS
374
+ http.followRedirects = false
375
+ http.connectTimeoutMs = timeout
376
+ http.readTimeoutMs = timeout
377
+ http.totalTimeoutMs = timeout
378
+ http.maxBodyBytes = toI64(limit)
379
+ http.outbound = outbound
380
+ return http
381
+ }
382
+
383
+ /** What one GET answered: the body, the `Cache-Control` header, or why there is no body. */
384
+ class OidcFetched {
385
+ error: i32 = 0
386
+ body: u8[]
387
+ cacheControl: string | null = null
388
+
389
+ constructor() {
390
+ this.body = []
391
+ }
392
+ }
393
+
394
+ /** Why `client`'s fetch failed: `OIDC_ERR_SIZE` past the bound, else `OIDC_ERR_FETCH`. */
395
+ const oidcFetchError = (client: FetchSyncClient): i32 =>
396
+ client.error === HTTP_E_BODY_TOO_LARGE ? OIDC_ERR_SIZE : OIDC_ERR_FETCH
397
+
398
+ /** Whether `a` and `b` parse to the same origin (scheme, host and port); false when either does not. */
399
+ const oidcSameOrigin = (a: string, b: string): boolean => {
400
+ const ua: Url | null = urlParse(a)
401
+ const ub: Url | null = urlParse(b)
402
+ if (ua === null || ub === null) {
403
+ return false
404
+ }
405
+ const oa: string | null = urlOrigin(ua)
406
+ const ob: string | null = urlOrigin(ub)
407
+ return oa !== null && ob !== null && oa === ob
408
+ }
409
+
410
+ /** One blocking GET of `url`, its body bounded at `limit` bytes, under `outbound` when not null; only a 200 is taken. */
411
+ const oidcGet = (
412
+ url: string,
413
+ options: OidcOptions,
414
+ limit: i32,
415
+ outbound: OutboundPolicy | null
416
+ ): OidcFetched => {
417
+ const out: OidcFetched = new OidcFetched()
418
+ const client: FetchSyncClient = new FetchSyncClient(oidcHttpOptions(options, limit, outbound))
419
+ const res: HttpResponse | null = client.fetch(new HttpRequest("GET", url))
420
+ if (res === null) {
421
+ out.error = oidcFetchError(client)
422
+ } else if (res.status !== OIDC_HTTP_OK) {
423
+ out.error = OIDC_ERR_FETCH
424
+ } else {
425
+ const body: u8[] | null = res.body.readAll(limit)
426
+ if (body === null) {
427
+ out.error = oidcFetchError(client)
428
+ } else {
429
+ out.body = body
430
+ out.cacheControl = res.header("cache-control")
431
+ }
432
+ }
433
+ client.close()
434
+ return out
435
+ }
436
+
437
+ /**
438
+ * Discovery: one blocking GET of `oidcDiscoveryUrl(issuer)`, no redirect
439
+ * followed, bounded by `options.timeoutMs` and `OIDC_MAX_DISCOVERY_BYTES`,
440
+ * then `oidcParseDiscovery`. Only a 200 is taken.
441
+ *
442
+ * @param issuer The issuer, as configured: https, or loopback http when allowed.
443
+ * @param options The options.
444
+ * @returns The metadata; its `error` is `OIDC_OK` or the reason discovery failed.
445
+ */
446
+ export const oidcDiscover = (issuer: string, options: OidcOptions): OidcMetadata => {
447
+ if (!oidcIssuerAllowed(issuer, options)) {
448
+ return new OidcMetadata(OIDC_ERR_SCHEME, "", "")
449
+ }
450
+ const got: OidcFetched = oidcGet(oidcDiscoveryUrl(issuer), options, OIDC_MAX_DISCOVERY_BYTES, null)
451
+ if (got.error !== OIDC_OK) {
452
+ return new OidcMetadata(got.error, "", "")
453
+ }
454
+ return oidcParseDiscovery(issuer, got.body, options)
455
+ }
456
+
457
+ /** The `JWT_ALG_*` an `alg` member names, 0 for a name `nish/crypto/jwt` does not know. */
458
+ const oidcAlgByName = (name: string): i32 => {
459
+ const algs: i32[] = [
460
+ JWT_ALG_HS256,
461
+ JWT_ALG_HS384,
462
+ JWT_ALG_HS512,
463
+ JWT_ALG_RS256,
464
+ JWT_ALG_RS384,
465
+ JWT_ALG_RS512,
466
+ JWT_ALG_ES256,
467
+ JWT_ALG_ES384,
468
+ JWT_ALG_EDDSA,
469
+ ]
470
+ for (const alg of algs) {
471
+ if (jwtAlgName(alg) === name) {
472
+ return alg
473
+ }
474
+ }
475
+ return 0
476
+ }
477
+
478
+ /** Whether `alg` is one of the RS algorithms. */
479
+ const oidcIsRsa = (alg: i32): boolean =>
480
+ alg === JWT_ALG_RS256 || alg === JWT_ALG_RS384 || alg === JWT_ALG_RS512
481
+
482
+ /** One member of a JWK as `oidcMember` read it: whether it is present, whether it is not a string, and its text. */
483
+ class OidcMember {
484
+ present: boolean = false
485
+ wrong: boolean = false
486
+ text: string = ""
487
+ }
488
+
489
+ /** Read member `name` of object `o`. */
490
+ const oidcMember = (json: JsonDocument, o: JsonValue, name: string): OidcMember => {
491
+ const m: OidcMember = new OidcMember()
492
+ const v: JsonValue = json.get(o, name)
493
+ if (v < 0) {
494
+ return m
495
+ }
496
+ m.present = true
497
+ if (json.kind(v) !== JSON_VALUE_STRING) {
498
+ m.wrong = true
499
+ return m
500
+ }
501
+ m.text = json.string(v)
502
+ return m
503
+ }
504
+
505
+ /** Whether `kid` is 1 to `OIDC_MAX_KID` bytes of printable ASCII. */
506
+ const oidcKidAllowed = (kid: string): boolean => {
507
+ const n: i32 = toI32(kid.length)
508
+ if (n < 1 || n > OIDC_MAX_KID) {
509
+ return false
510
+ }
511
+ for (let i: i32 = 0; i < n; i += 1) {
512
+ const c: i32 = toI32(kid.charCodeAt(i))
513
+ if (c < OIDC_KID_LOW || c > OIDC_KID_HIGH) {
514
+ return false
515
+ }
516
+ }
517
+ return true
518
+ }
519
+
520
+ /** The bytes of a base64url member, or null when it is absent, not a string, or not base64url. */
521
+ const oidcBytes = (json: JsonDocument, o: JsonValue, name: string): u8[] | null => {
522
+ const m: OidcMember = oidcMember(json, o, name)
523
+ if (!m.present || m.wrong) {
524
+ return null
525
+ }
526
+ return base64urlDecode(m.text)
527
+ }
528
+
529
+ /** An EC or OKP key's point: `x‖y` behind the uncompressed marker for EC, `x` alone for OKP; null when a coordinate is not `size` bytes. */
530
+ const oidcPoint = (json: JsonDocument, o: JsonValue, size: i32, withY: boolean): u8[] | null => {
531
+ const x: u8[] | null = oidcBytes(json, o, "x")
532
+ if (x === null || toI32(x.length) !== size) {
533
+ return null
534
+ }
535
+ if (!withY) {
536
+ return x
537
+ }
538
+ const y: u8[] | null = oidcBytes(json, o, "y")
539
+ if (y === null || toI32(y.length) !== size) {
540
+ return null
541
+ }
542
+ const point: u8[] = [toU8(OIDC_EC_UNCOMPRESSED)]
543
+ for (const b of x) {
544
+ point.push(b)
545
+ }
546
+ for (const b of y) {
547
+ point.push(b)
548
+ }
549
+ return point
550
+ }
551
+
552
+ /** The algorithm a key's `kty` and `crv` admit; 0 for a pair this module does not take. */
553
+ const oidcAlgOfType = (kty: string, crv: string): i32 => {
554
+ if (kty === "RSA") {
555
+ return JWT_ALG_RS256
556
+ }
557
+ if (kty === "EC" && crv === "P-256") {
558
+ return JWT_ALG_ES256
559
+ }
560
+ if (kty === "EC" && crv === "P-384") {
561
+ return JWT_ALG_ES384
562
+ }
563
+ if (kty === "OKP" && crv === "Ed25519") {
564
+ return JWT_ALG_EDDSA
565
+ }
566
+ return 0
567
+ }
568
+
569
+ /** The key one JWK makes under `alg`, or null when its material does not make one. */
570
+ const oidcMakeKey = (json: JsonDocument, o: JsonValue, alg: i32): JwtKey | null => {
571
+ if (oidcIsRsa(alg)) {
572
+ const n: u8[] | null = oidcBytes(json, o, "n")
573
+ const e: u8[] | null = oidcBytes(json, o, "e")
574
+ if (n === null || e === null) {
575
+ return null
576
+ }
577
+ return jwtRsaKeyParts(alg, n, e)
578
+ }
579
+ if (alg === JWT_ALG_EDDSA) {
580
+ const pub: u8[] | null = oidcPoint(json, o, OIDC_ED25519_KEY, false)
581
+ return pub === null ? null : jwtEd25519Key(pub)
582
+ }
583
+ const size: i32 = alg === JWT_ALG_ES256 ? OIDC_P256_COORD : OIDC_P384_COORD
584
+ const point: u8[] | null = oidcPoint(json, o, size, true)
585
+ return point === null ? null : jwtEcKey(alg, point)
586
+ }
587
+
588
+ /** What one JWK came to: a key, a skip, or the reason the whole set is refused. */
589
+ class OidcEntry {
590
+ key: JwtKey | null = null
591
+ kid: string = ""
592
+ error: i32 = 0
593
+ }
594
+
595
+ /** One entry of `keys`, read under the rules `oidcParseJwks` states. */
596
+ const oidcEntry = (json: JsonDocument, o: JsonValue): OidcEntry => {
597
+ const out: OidcEntry = new OidcEntry()
598
+ if (json.kind(o) !== JSON_VALUE_OBJECT) {
599
+ out.error = OIDC_ERR_JSON
600
+ return out
601
+ }
602
+ for (const name of oidcPrivateMembers()) {
603
+ if (json.get(o, name) >= 0) {
604
+ out.error = OIDC_ERR_PRIVATE
605
+ return out
606
+ }
607
+ }
608
+ const kty: OidcMember = oidcMember(json, o, "kty")
609
+ const use: OidcMember = oidcMember(json, o, "use")
610
+ const algName: OidcMember = oidcMember(json, o, "alg")
611
+ const kid: OidcMember = oidcMember(json, o, "kid")
612
+ const crv: OidcMember = oidcMember(json, o, "crv")
613
+ if (!kty.present || kty.wrong || use.wrong || algName.wrong || kid.wrong || crv.wrong) {
614
+ out.error = OIDC_ERR_JSON
615
+ return out
616
+ }
617
+ if (kid.present && !oidcKidAllowed(kid.text)) {
618
+ out.error = OIDC_ERR_KEY
619
+ return out
620
+ }
621
+ if (use.present && use.text !== "sig") {
622
+ return out
623
+ }
624
+ const named: i32 = algName.present ? oidcAlgByName(algName.text) : 0
625
+ if (algName.present && named === 0) {
626
+ return out
627
+ }
628
+ const typed: i32 = oidcAlgOfType(kty.text, crv.text)
629
+ if (typed === 0) {
630
+ out.error = algName.present ? OIDC_ERR_KEY : OIDC_OK
631
+ return out
632
+ }
633
+ let alg: i32 = typed
634
+ if (named !== 0) {
635
+ const agrees: boolean = oidcIsRsa(typed) ? oidcIsRsa(named) : named === typed
636
+ if (!agrees) {
637
+ out.error = OIDC_ERR_KEY
638
+ return out
639
+ }
640
+ alg = named
641
+ }
642
+ const key: JwtKey | null = oidcMakeKey(json, o, alg)
643
+ if (key === null) {
644
+ out.error = OIDC_ERR_KEY
645
+ return out
646
+ }
647
+ out.key = key
648
+ out.kid = kid.present ? kid.text : ""
649
+ return out
650
+ }
651
+
652
+ /**
653
+ * A JWK Set, already fetched, read into keys. The rules:
654
+ *
655
+ * - The document is at most `OIDC_MAX_JWKS_BYTES`, a JSON object whose `keys`
656
+ * is an array of at most `OIDC_MAX_KEYS` entries.
657
+ *
658
+ * Each entry is then read by these rules, in this order; the first that
659
+ * applies decides it, and a refusal refuses the whole set:
660
+ *
661
+ * 1. An entry that is not an object refuses the set (`OIDC_ERR_JSON`).
662
+ * 2. An entry holding `d`, `p`, `q`, `dp`, `dq`, `qi`, `oth` or `k` refuses the
663
+ * set (`OIDC_ERR_PRIVATE`), whatever its `use` or type: a publisher that
664
+ * leaks a private or symmetric key has a set no verifier should trust.
665
+ * 3. An entry without `kty`, or whose `kty`, `use`, `alg`, `kid` or `crv` is
666
+ * present and not a string, refuses the set (`OIDC_ERR_JSON`).
667
+ * 4. A `kid` that is not 1 to `OIDC_MAX_KID` bytes of printable ASCII refuses
668
+ * the set (`OIDC_ERR_KEY`), whatever the entry's `use`.
669
+ * 5. An entry whose `use` is present and not `"sig"` is skipped.
670
+ * 6. An entry whose `alg` names an algorithm `nish/crypto/jwt` does not have
671
+ * is skipped.
672
+ * 7. An entry whose `kty`/`crv` is not RSA, EC P-256, EC P-384 or OKP Ed25519
673
+ * is skipped when it has no `alg`, and refuses the set (`OIDC_ERR_KEY`)
674
+ * when it has one, since the `alg` then names a key this module would
675
+ * misread.
676
+ * 8. The key's algorithm is its `alg` when present, which must agree with its
677
+ * type (RS256/384/512 for RSA, ES256 for P-256, ES384 for P-384, EdDSA for
678
+ * Ed25519), or the set is refused (`OIDC_ERR_KEY`); without `alg` it is
679
+ * ES256, ES384 or EdDSA by curve, and RS256 for RSA, OpenID Connect Core's
680
+ * default.
681
+ * 9. The key's material must make a key — `n`/`e` with an RSA modulus of 2048
682
+ * to 8192 bits, `x`/`y` of the curve's size, an Ed25519 `x` of 32 bytes —
683
+ * or the set is refused (`OIDC_ERR_KEY`).
684
+ *
685
+ * Then:
686
+ *
687
+ * - Two keys taken with the same `kid`, or two without one, refuse the set
688
+ * (`OIDC_ERR_DUPLICATE_KID`), and a set where none is taken is
689
+ * `OIDC_ERR_NO_KEYS`.
690
+ *
691
+ * @param doc The JWK Set's bytes.
692
+ * @returns The set; its `error` is `OIDC_OK` or the reason it was refused.
693
+ */
694
+ export const oidcParseJwks = (doc: u8[]): OidcKeySet => {
695
+ if (toI32(doc.length) > OIDC_MAX_JWKS_BYTES) {
696
+ return oidcRefused(OIDC_ERR_SIZE)
697
+ }
698
+ const json: JsonDocument = oidcDocument(OIDC_MAX_JWKS_BYTES)
699
+ const root: JsonValue = json.parse(doc, toI32(0), toI32(doc.length))
700
+ if (root < 0 || json.kind(root) !== JSON_VALUE_OBJECT) {
701
+ return oidcRefused(OIDC_ERR_JSON)
702
+ }
703
+ const list: JsonValue = json.get(root, "keys")
704
+ if (json.kind(list) !== JSON_VALUE_ARRAY) {
705
+ return oidcRefused(OIDC_ERR_JSON)
706
+ }
707
+ const n: i32 = json.length(list)
708
+ if (n > OIDC_MAX_KEYS) {
709
+ return oidcRefused(OIDC_ERR_TOO_MANY_KEYS)
710
+ }
711
+ const set: OidcKeySet = new OidcKeySet()
712
+ for (let i: i32 = 0; i < n; i += 1) {
713
+ const entry: OidcEntry = oidcEntry(json, json.at(list, i))
714
+ if (entry.error !== OIDC_OK) {
715
+ return oidcRefused(entry.error)
716
+ }
717
+ const key: JwtKey | null = entry.key
718
+ if (key !== null) {
719
+ for (let j: i32 = 0; j < set.count(); j += 1) {
720
+ if (set.kids[j] === entry.kid) {
721
+ return oidcRefused(OIDC_ERR_DUPLICATE_KID)
722
+ }
723
+ }
724
+ set.keys.push(key)
725
+ set.kids.push(entry.kid)
726
+ }
727
+ }
728
+ if (set.count() === 0) {
729
+ return oidcRefused(OIDC_ERR_NO_KEYS)
730
+ }
731
+ return set
732
+ }
733
+
734
+ /** The seconds of one `max-age=<digits>` directive, or -1 when `directive` is not one. */
735
+ const oidcMaxAge = (directive: string): i64 => {
736
+ const eq: i32 = toI32(directive.indexOf(String.fromCharCode(OIDC_CH_EQUALS)))
737
+ if (eq < 1 || asciiLower(trim(directive.slice(0, eq))) !== "max-age") {
738
+ return toI64(-1)
739
+ }
740
+ const value: string = trim(directive.slice(eq + 1, toI32(directive.length)))
741
+ const n: i32 = toI32(value.length)
742
+ if (n < 1) {
743
+ return toI64(-1)
744
+ }
745
+ let age: i64 = toI64(0)
746
+ for (let i: i32 = 0; i < n; i += 1) {
747
+ const c: i32 = toI32(value.charCodeAt(i))
748
+ if (c < OIDC_CH_0 || c > OIDC_CH_9) {
749
+ return toI64(-1)
750
+ }
751
+ // Saturate rather than overflow (RFC 9111 §1.2.2): the clamp caps it anyway.
752
+ if (age <= OIDC_MAX_LIFETIME) {
753
+ age = age * toI64(10) + toI64(c - OIDC_CH_0)
754
+ }
755
+ }
756
+ return age
757
+ }
758
+
759
+ /**
760
+ * How long a key set fetched with this `Cache-Control` is fresh: its first
761
+ * `max-age` directive of plain digits, clamped to `[OIDC_MIN_LIFETIME,
762
+ * OIDC_MAX_LIFETIME]`, or `OIDC_DEFAULT_LIFETIME` when there is none. Other
763
+ * directives (`no-cache`, `no-store`, `s-maxage`) are not read: the floor
764
+ * holds whatever the response says.
765
+ *
766
+ * @param cacheControl The header's value, or null when the response had none.
767
+ * @returns The lifetime, in seconds.
768
+ */
769
+ export const oidcLifetime = (cacheControl: string | null): i64 => {
770
+ if (cacheControl === null) {
771
+ return OIDC_DEFAULT_LIFETIME
772
+ }
773
+ const n: i32 = toI32(cacheControl.length)
774
+ let from: i32 = 0
775
+ for (let i: i32 = 0; i <= n; i += 1) {
776
+ if (i === n || toI32(cacheControl.charCodeAt(i)) === OIDC_CH_COMMA) {
777
+ const age: i64 = oidcMaxAge(trim(cacheControl.slice(from, i)))
778
+ if (age >= toI64(0)) {
779
+ if (age < OIDC_MIN_LIFETIME) {
780
+ return OIDC_MIN_LIFETIME
781
+ }
782
+ return age > OIDC_MAX_LIFETIME ? OIDC_MAX_LIFETIME : age
783
+ }
784
+ from = i + 1
785
+ }
786
+ }
787
+ return OIDC_DEFAULT_LIFETIME
788
+ }
789
+
790
+ /**
791
+ * An issuer's rotating key set, and a verifier for its tokens. One thread's,
792
+ * like the `JwtVerifier` it holds.
793
+ *
794
+ * The set is fetched by `refresh`, which fetches only when it is due: there
795
+ * is no set yet, the set is past its lifetime (`oidcLifetime`), or a token
796
+ * named a `kid` the set does not hold — and never twice within
797
+ * `OIDC_MIN_REFRESH_INTERVAL`. A refresh that fails keeps the last set taken,
798
+ * which keeps verifying until `OIDC_STALE_GRACE` past the end of its
799
+ * lifetime; past that hard expiry, nothing verifies until a refresh succeeds.
800
+ * A refresh that succeeds replaces the set whole, so a key the issuer stopped
801
+ * publishing stops verifying then. A token whose `kid` the set holds never
802
+ * makes a refresh due early, so a removed key keeps verifying until the set's
803
+ * lifetime ends — at most `OIDC_MAX_LIFETIME` — and, while refreshes fail,
804
+ * until its hard expiry, at most `OIDC_STALE_GRACE` more.
805
+ */
806
+ export class OidcKeys {
807
+ /** The issuer's metadata, as discovery gave it. */
808
+ readonly meta: OidcMetadata
809
+ /** The options fetches and verification use. */
810
+ readonly options: OidcOptions
811
+ /** The verifier `oidcVerify` uses; after `OIDC_OK`, its `claims`, `exp` and `nbf` are the token's. */
812
+ readonly verifier: JwtVerifier
813
+ /** The last set taken, or null before the first. */
814
+ set: OidcKeySet | null = null
815
+ /** When the last set taken stops being fresh. */
816
+ freshUntil: i64
817
+ /** When the last set taken stops verifying, if no refresh replaces it. */
818
+ hardUntil: i64
819
+ /** When the last fetch was begun. */
820
+ triedAt: i64
821
+ /** Whether any fetch has been begun. */
822
+ tried: boolean = false
823
+ /** Whether a token named a `kid` the set does not hold since the last fetch. */
824
+ wanted: boolean = false
825
+ /** The result of the last refresh that fetched: `OIDC_OK` or why it failed. */
826
+ lastError: i32 = 0
827
+ /** The token's bytes, copied for the verifier. */
828
+ private readonly text: u8[]
829
+ /** The token's `kid`, as `peekKid` writes it. */
830
+ private readonly kidBytes: u8[]
831
+
832
+ /**
833
+ * Keys for the issuer `meta` names; nothing is fetched until `refresh`.
834
+ *
835
+ * @param meta The issuer's metadata, from `oidcDiscover`; a failed one makes
836
+ * every refresh answer its error.
837
+ * @param options The options.
838
+ */
839
+ constructor(meta: OidcMetadata, options: OidcOptions) {
840
+ this.meta = meta
841
+ this.options = options
842
+ this.freshUntil = toI64(0)
843
+ this.hardUntil = toI64(0)
844
+ this.triedAt = toI64(0)
845
+ this.verifier = new JwtVerifier(options.maxToken)
846
+ this.text = new Array<u8>(options.maxToken)
847
+ this.kidBytes = new Array<u8>(OIDC_MAX_KID)
848
+ }
849
+
850
+ /**
851
+ * Whether `refresh(now)` would fetch: there is no set, the set is past its
852
+ * lifetime, or a token wanted a `kid` it lacks — and the last fetch began at
853
+ * least `OIDC_MIN_REFRESH_INTERVAL` ago (or later than `now`, after the
854
+ * clock stepped back).
855
+ *
856
+ * @param now The current time, in seconds since 1970.
857
+ * @returns True when a refresh is due.
858
+ */
859
+ due(now: i64): boolean {
860
+ if (this.tried && now >= this.triedAt && now - this.triedAt < OIDC_MIN_REFRESH_INTERVAL) {
861
+ return false
862
+ }
863
+ return this.set === null || now >= this.freshUntil || this.wanted
864
+ }
865
+
866
+ /**
867
+ * Take `doc` as the key set when a refresh is due, without fetching: for a
868
+ * caller that fetches the set its own way, and for tests. Counts as a
869
+ * fetch for the rate limit.
870
+ *
871
+ * @param doc The JWK Set's bytes, or null when the fetch failed.
872
+ * @param cacheControl The response's `Cache-Control`, or null.
873
+ * @param now The current time, in seconds since 1970.
874
+ * @returns `OIDC_SKIPPED` when no refresh is due, `OIDC_OK` when the set
875
+ * was taken, or why it was refused (the last set is kept); a failed
876
+ * `meta` answers its own error, as `refresh` does.
877
+ */
878
+ refreshWith(doc: u8[] | null, cacheControl: string | null, now: i64): i32 {
879
+ if (!this.due(now)) {
880
+ return OIDC_SKIPPED
881
+ }
882
+ this.begin(now)
883
+ if (this.meta.error !== OIDC_OK) {
884
+ this.lastError = this.meta.error
885
+ return this.meta.error
886
+ }
887
+ if (doc === null) {
888
+ this.lastError = OIDC_ERR_FETCH
889
+ return OIDC_ERR_FETCH
890
+ }
891
+ return this.take(doc, cacheControl, now)
892
+ }
893
+
894
+ /**
895
+ * Fetch the key set from `meta.jwksUri` when a refresh is due: one
896
+ * blocking GET, no redirect followed, bounded by `options.timeoutMs` and
897
+ * `OIDC_MAX_JWKS_BYTES`, and under `options.jwksOutbound` when the
898
+ * `jwks_uri` is on another origin than the issuer. Call it once at
899
+ * start-up and then from the server's own loop or timer.
900
+ *
901
+ * @param now The current time, in seconds since 1970.
902
+ * @returns `OIDC_SKIPPED` when no refresh is due, `OIDC_OK` when a set was
903
+ * taken, or why the refresh failed (the last set is kept).
904
+ */
905
+ refresh(now: i64): i32 {
906
+ if (!this.due(now)) {
907
+ return OIDC_SKIPPED
908
+ }
909
+ this.begin(now)
910
+ if (this.meta.error !== OIDC_OK) {
911
+ this.lastError = this.meta.error
912
+ return this.meta.error
913
+ }
914
+ const outbound: OutboundPolicy | null = oidcSameOrigin(this.meta.issuer, this.meta.jwksUri)
915
+ ? null
916
+ : this.options.jwksOutbound
917
+ const got: OidcFetched = oidcGet(this.meta.jwksUri, this.options, OIDC_MAX_JWKS_BYTES, outbound)
918
+ if (got.error !== OIDC_OK) {
919
+ this.lastError = got.error
920
+ return got.error
921
+ }
922
+ return this.take(got.body, got.cacheControl, now)
923
+ }
924
+
925
+ /**
926
+ * Whether the set verifies at `now`: one has been taken and it is not past
927
+ * its hard expiry.
928
+ *
929
+ * @param now The current time, in seconds since 1970.
930
+ * @returns True when a set is in use.
931
+ */
932
+ usable(now: i64): boolean {
933
+ return this.set !== null && now < this.hardUntil
934
+ }
935
+
936
+ /**
937
+ * The key whose `kid` is `kid`, without fetching. A `kid` the set lacks
938
+ * marks the set as wanted, so the next due `refresh` fetches it.
939
+ *
940
+ * @param kid The `kid` to look for.
941
+ * @param now The current time, in seconds since 1970.
942
+ * @returns The key, or null when there is no usable set or no such key.
943
+ */
944
+ key(kid: string, now: i64): JwtKey | null {
945
+ const set: OidcKeySet | null = this.set
946
+ if (set === null || !this.usable(now)) {
947
+ return null
948
+ }
949
+ const key: JwtKey | null = set.find(kid)
950
+ if (key === null) {
951
+ this.wanted = true
952
+ }
953
+ return key
954
+ }
955
+
956
+ /**
957
+ * The claims of the last token `oidcVerify` accepted, as text.
958
+ *
959
+ * @returns The payload's JSON, or `""` after a refusal.
960
+ */
961
+ claimsText(): string {
962
+ return String.fromBytes(this.verifier.claims, 0, this.verifier.claimsLen)
963
+ }
964
+
965
+ /**
966
+ * The token's bytes in the verifier's buffer, for `oidcVerify`.
967
+ *
968
+ * @param token The compact token.
969
+ * @returns Its length, `JWT_ERR_SIZE` when it is too long, or
970
+ * `JWT_ERR_FORMAT` when a code unit is above 0x7F.
971
+ */
972
+ load(token: string): i32 {
973
+ const n: i32 = toI32(token.length)
974
+ if (n > toI32(this.text.length)) {
975
+ return JWT_ERR_SIZE
976
+ }
977
+ for (let i: i32 = 0; i < n; i += 1) {
978
+ const c: i32 = toI32(token.charCodeAt(i))
979
+ // No token character is above 0x7F. Cut to its low byte, a code unit
980
+ // such as U+0141 would read as `A`, and one signed token would verify
981
+ // under many spellings.
982
+ if (c > 0x7f) {
983
+ return JWT_ERR_FORMAT
984
+ }
985
+ this.text[i] = toU8(c)
986
+ }
987
+ return n
988
+ }
989
+
990
+ /**
991
+ * The `kid` of the token `load` copied, read before any signature is
992
+ * checked, only to choose a key.
993
+ *
994
+ * @param n The token's length.
995
+ * @returns The `kid`, or null when the token has none, its `kid` is not a
996
+ * string, or it is longer than `OIDC_MAX_KID`: such a token is treated as
997
+ * naming no `kid`.
998
+ */
999
+ peekKid(n: i32): string | null {
1000
+ const k: i32 = this.verifier.peekKid(this.text, toI32(0), n, this.kidBytes)
1001
+ return k < 0 ? null : String.fromBytes(this.kidBytes, 0, k)
1002
+ }
1003
+
1004
+ /**
1005
+ * Verify the token `load` copied under `key`, against the issuer and `audience`.
1006
+ *
1007
+ * @param key The key the token's `kid` chose.
1008
+ * @param n The token's length.
1009
+ * @param audience The audience the token must name.
1010
+ * @param now The current time, in seconds since 1970.
1011
+ * @returns `JWT_OK`, or the `JWT_ERR_*` the verifier refused it with.
1012
+ */
1013
+ check(key: JwtKey, n: i32, audience: string, now: i64): i32 {
1014
+ const v: JwtVerifier = this.verifier
1015
+ v.issuer = this.meta.issuer
1016
+ v.audience = audience
1017
+ v.leeway = this.options.leeway
1018
+ return v.verify(key, this.text, toI32(0), n, now)
1019
+ }
1020
+
1021
+ /** Record a fetch begun at `now`. */
1022
+ private begin(now: i64): void {
1023
+ this.tried = true
1024
+ this.triedAt = now
1025
+ this.wanted = false
1026
+ }
1027
+
1028
+ /** Take `doc` as the set when it parses; otherwise keep the last one. */
1029
+ private take(doc: u8[], cacheControl: string | null, now: i64): i32 {
1030
+ const next: OidcKeySet = oidcParseJwks(doc)
1031
+ this.lastError = next.error
1032
+ if (next.error !== OIDC_OK) {
1033
+ return next.error
1034
+ }
1035
+ this.set = next
1036
+ this.freshUntil = now + oidcLifetime(cacheControl)
1037
+ this.hardUntil = this.freshUntil + OIDC_STALE_GRACE
1038
+ return OIDC_OK
1039
+ }
1040
+ }
1041
+
1042
+ /**
1043
+ * Verify `token` with the issuer's keys, without fetching. The key is chosen
1044
+ * by the token's `kid`; a token with no `kid` — or one whose `kid` is not a
1045
+ * string or is longer than `OIDC_MAX_KID`, which counts as none — is taken
1046
+ * only when the set holds exactly one key, and is checked under that key,
1047
+ * since otherwise which key it means is a guess. The key
1048
+ * alone decides the algorithm, so `none`, any HMAC algorithm and any
1049
+ * algorithm but the key's are refused (`JWT_ERR_ALG`); then the signature,
1050
+ * `iss` (the issuer, exactly), `aud` (a string or an array that holds
1051
+ * `audience`), and `exp`, `nbf` and `iat` within `options.leeway` are checked
1052
+ * by `nish/crypto/jwt`'s `JwtVerifier`, and `exp` is required.
1053
+ *
1054
+ * @param keys The issuer's keys.
1055
+ * @param token The compact token.
1056
+ * @param audience The audience the token must name: this service's client id.
1057
+ * @param now The current time, in seconds since 1970.
1058
+ * @returns `OIDC_OK` (`JWT_OK`), an `OIDC_ERR_*` when no key could be chosen,
1059
+ * or the `JWT_ERR_*` the verifier refused the token with.
1060
+ */
1061
+ export const oidcVerify = (keys: OidcKeys, token: string, audience: string, now: i64): i32 => {
1062
+ // Every refusal leaves no claims behind: no payload and no exp, nbf or iat,
1063
+ // neither an earlier token's nor, when the verifier refuses, this one's.
1064
+ oidcClearClaims(keys.verifier)
1065
+ const code: i32 = oidcPick(keys, token, audience, now)
1066
+ if (code !== OIDC_OK) {
1067
+ oidcClearClaims(keys.verifier)
1068
+ }
1069
+ return code
1070
+ }
1071
+
1072
+ /** Forgets the last token's payload and its exp, nbf and iat. */
1073
+ const oidcClearClaims = (v: JwtVerifier): void => {
1074
+ v.claimsLen = 0
1075
+ v.hasExp = false
1076
+ v.hasNbf = false
1077
+ v.hasIat = false
1078
+ v.exp = toI64(0)
1079
+ v.nbf = toI64(0)
1080
+ v.iat = toI64(0)
1081
+ }
1082
+
1083
+ /** Chooses the token's key and verifies the token with it. */
1084
+ const oidcPick = (keys: OidcKeys, token: string, audience: string, now: i64): i32 => {
1085
+ const set: OidcKeySet | null = keys.set
1086
+ if (set === null || !keys.usable(now)) {
1087
+ return OIDC_ERR_STALE
1088
+ }
1089
+ const n: i32 = keys.load(token)
1090
+ if (n < 0) {
1091
+ return n
1092
+ }
1093
+ const kid: string | null = keys.peekKid(n)
1094
+ let key: JwtKey | null = null
1095
+ if (kid === null) {
1096
+ if (set.count() !== 1) {
1097
+ return OIDC_ERR_KID_REQUIRED
1098
+ }
1099
+ key = set.keys[0]
1100
+ } else {
1101
+ key = keys.key(kid, now)
1102
+ }
1103
+ if (key === null) {
1104
+ return OIDC_ERR_UNKNOWN_KID
1105
+ }
1106
+ return keys.check(key, n, audience, now)
1107
+ }