@deltarocks/pykrete-oidc 0.2.0 → 0.2.2

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.
package/client.d.ts CHANGED
@@ -64,6 +64,13 @@ export interface AuthorizeRequest {
64
64
  state: string;
65
65
  nonce: string;
66
66
  verifier: string;
67
+ keysJwk?: string;
68
+ }
69
+ export interface TokenSet {
70
+ idToken: string;
71
+ accessToken: string | null;
72
+ keysJwe: string | null;
73
+ claims: IdClaims;
67
74
  }
68
75
  export declare function randomToken(bytes?: number): string;
69
76
  export declare function codeChallenge(verifier: string): Promise<string>;
@@ -73,11 +80,7 @@ export declare class OidcClient {
73
80
  constructor(opts: OidcClientOpts);
74
81
  discovery(): Promise<Discovery>;
75
82
  authorizeUrl(req: AuthorizeRequest): Promise<string>;
76
- exchange(code: string, req: AuthorizeRequest): Promise<{
77
- idToken: string;
78
- accessToken: string | null;
79
- claims: IdClaims;
80
- }>;
83
+ exchange(code: string, req: AuthorizeRequest): Promise<TokenSet>;
81
84
  introspect(token: string): Promise<Introspection>;
82
85
  endSessionUrl(idTokenHint: string, postLogoutRedirectUri: string): Promise<string | null>;
83
86
  verifyIdToken(token: string, nonce: string | null): Promise<IdClaims>;
package/client.js CHANGED
@@ -13,8 +13,14 @@ const discoveryDoc = zm.object({
13
13
  introspection_endpoint: zm.optional(zm.string()),
14
14
  revocation_endpoint: zm.optional(zm.string())
15
15
  });
16
+ //= https://www.rfc-editor.org/rfc/rfc7517#section-4
17
+ //# Additional members can be present in the JWK; if not understood by
18
+ //# implementations encountering them, they MUST be ignored.
16
19
  const jwk = zm.object({
17
20
  kid: zm.optional(zm.string()),
21
+ //= https://www.rfc-editor.org/rfc/rfc7517#section-4.1
22
+ //# This
23
+ //# member MUST be present in a JWK.
18
24
  kty: zm.string(),
19
25
  alg: zm.optional(zm.string()),
20
26
  use: zm.optional(zm.string()),
@@ -24,6 +30,10 @@ const jwk = zm.object({
24
30
  x: zm.optional(zm.string()),
25
31
  y: zm.optional(zm.string())
26
32
  });
33
+ //= https://www.rfc-editor.org/rfc/rfc7517#section-5
34
+ //# A JWK Set is a JSON object that represents a set of JWKs. The JSON
35
+ //# object MUST have a "keys" member, with its value being an array of
36
+ //# JWKs.
27
37
  const jwks = zm.object({
28
38
  keys: zm.array(jwk)
29
39
  });
@@ -37,6 +47,13 @@ export const orgClaim = zm.object({
37
47
  name: zm.string(),
38
48
  roles: zm._default(zm.array(zm.string()), [])
39
49
  });
50
+ //= https://www.rfc-editor.org/rfc/rfc7519#section-4
51
+ //# However, in
52
+ //# the absence of such requirements, all claims that are not understood
53
+ //# by implementations MUST be ignored.
54
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-2
55
+ //# Any Claims used that are not
56
+ //# understood MUST be ignored.
40
57
  const idClaims = zm.object({
41
58
  iss: zm.string(),
42
59
  sub: zm.string(),
@@ -51,9 +68,12 @@ const idClaims = zm.object({
51
68
  picture: zm.optional(zm.nullable(zm.string())),
52
69
  orgs: zm.optional(zm.array(orgClaim))
53
70
  });
71
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-5.1
72
+ //# The client MUST ignore unrecognized value names in the response.
54
73
  const tokenResponse = zm.object({
55
74
  id_token: zm.string(),
56
- access_token: zm.optional(zm.string())
75
+ access_token: zm.optional(zm.string()),
76
+ keys_jwe: zm.optional(zm.string())
57
77
  });
58
78
  const introspection = zm.object({
59
79
  active: zm.boolean(),
@@ -81,10 +101,20 @@ function sameIssuer(a, b) {
81
101
  export function randomToken(bytes = 32) {
82
102
  return encodeBase64Url(crypto.getRandomValues(new Uint8Array(bytes)));
83
103
  }
104
+
105
+ //= https://www.rfc-editor.org/rfc/rfc7636#section-4.2
106
+ //# S256
107
+ //# code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))
84
108
  export async function codeChallenge(verifier) {
85
109
  return encodeBase64Url(new Uint8Array(await crypto.subtle.digest('SHA-256', ENCODER.encode(verifier))));
86
110
  }
87
111
  function verifyParams(alg, key) {
112
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-3.3
113
+ //# The RSASSA-PKCS1-v1_5 SHA-256 digital signature for a JWS is
114
+ //# validated as follows: submit the JWS Signing Input, the JWS
115
+ //# Signature, and the public key corresponding to the private key used
116
+ //# by the signer to the RSASSA-PKCS1-v1_5-VERIFY algorithm using SHA-256
117
+ //# as the hash function.
88
118
  if (alg === 'RS256' && key.kty === 'RSA') {
89
119
  return {
90
120
  importAlg: {
@@ -94,6 +124,9 @@ function verifyParams(alg, key) {
94
124
  verify: 'RSASSA-PKCS1-v1_5'
95
125
  };
96
126
  }
127
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-3.4
128
+ //# Submit the JWS Signing Input, R, S, and the public key (x, y) to
129
+ //# the ECDSA P-256 SHA-256 validator.
97
130
  if (alg === 'ES256' && key.kty === 'EC' && key.crv === 'P-256') {
98
131
  return {
99
132
  importAlg: {
@@ -106,6 +139,18 @@ function verifyParams(alg, key) {
106
139
  }
107
140
  };
108
141
  }
142
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-3.6
143
+ //# Implementations MUST NOT accept Unsecured JWSs by default.
144
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-2
145
+ //# ID Tokens MUST NOT use "none" as
146
+ //# the "alg" value unless the Response Type used returns no ID Token
147
+ //# from the Authorization Endpoint (such as when using the Authorization
148
+ //# Code Flow) and the Client explicitly requested the use of "none" at
149
+ //# Registration time.
150
+ //= https://www.rfc-editor.org/rfc/rfc7519#section-7.2
151
+ //# Even if a JWT can be successfully
152
+ //# validated, unless the algorithms used in the JWT are acceptable to
153
+ //# the application, it SHOULD reject the JWT.
109
154
  return null;
110
155
  }
111
156
  export class OidcClient {
@@ -147,16 +192,39 @@ export class OidcClient {
147
192
  }
148
193
  async authorizeUrl(req) {
149
194
  const url = new URL((await this.discovery()).authorization_endpoint);
150
- url.search = new URLSearchParams({
195
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1
196
+ //# The client constructs the request URI by adding the following
197
+ //# parameters to the query component of the authorization endpoint URI
198
+ //# using the "application/x-www-form-urlencoded" format, per Appendix B:
199
+ const params = new URLSearchParams({
200
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1
201
+ //# response_type
202
+ //# REQUIRED. Value MUST be set to "code".
203
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.2.1
204
+ //# When using the Authorization Code Flow, this value is "code".
151
205
  response_type: 'code',
152
206
  client_id: this.opts.clientId,
153
207
  redirect_uri: this.opts.redirectUri,
208
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-3.3
209
+ //# The value of the scope parameter is expressed as a list of space-
210
+ //# delimited, case-sensitive strings.
154
211
  scope: this.opts.scopes.join(' '),
212
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1
213
+ //# The parameter SHOULD be used for preventing
214
+ //# cross-site request forgery as described in Section 10.12.
155
215
  state: req.state,
156
216
  nonce: req.nonce,
217
+ //= https://www.rfc-editor.org/rfc/rfc7636#section-4.3
218
+ //# code_challenge
219
+ //# REQUIRED. Code challenge.
157
220
  code_challenge: await codeChallenge(req.verifier),
221
+ //= https://www.rfc-editor.org/rfc/rfc7636#section-4.2
222
+ //# If the client is capable of using "S256", it MUST use "S256", as
223
+ //# "S256" is Mandatory To Implement (MTI) on the server.
158
224
  code_challenge_method: 'S256'
159
- }).toString();
225
+ });
226
+ if (req.keysJwk !== undefined) params.set('keys_jwk', req.keysJwk);
227
+ url.search = params.toString();
160
228
  return url.href;
161
229
  }
162
230
  #clientAuth(body) {
@@ -165,20 +233,49 @@ export class OidcClient {
165
233
  clientSecret,
166
234
  tokenAuthMethod
167
235
  } = this.opts;
236
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-3.2.1
237
+ //# In the
238
+ //# "authorization_code" "grant_type" request to the token endpoint, an
239
+ //# unauthenticated client MUST send its "client_id" to prevent itself
240
+ //# from inadvertently accepting a code intended for a client with a
241
+ //# different "client_id".
242
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3
243
+ //# client_id
244
+ //# REQUIRED, if the client is not authenticating with the
245
+ //# authorization server as described in Section 3.2.1.
168
246
  if (tokenAuthMethod === 'none') {
169
247
  body.set('client_id', clientId);
170
248
  return {};
171
249
  }
250
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-9
251
+ //# Clients that have received a "client_secret" value from the
252
+ //# Authorization Server, authenticate with the Authorization Server
253
+ //# in accordance with Section 2.3.1 of OAuth 2.0 [RFC6749] by
254
+ //# including the Client Credentials in the request body.
255
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-2.3.1
256
+ //# The parameters can only
257
+ //# be transmitted in the request-body and MUST NOT be included in the
258
+ //# request URI.
172
259
  if (tokenAuthMethod === 'client_secret_post') {
173
260
  body.set('client_id', clientId);
174
261
  body.set('client_secret', clientSecret);
175
262
  return {};
176
263
  }
264
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-9
265
+ //# Clients that have received a "client_secret" value from the
266
+ //# Authorization Server authenticate with the Authorization Server in
267
+ //# accordance with Section 2.3.1 of OAuth 2.0 [RFC6749] using the
268
+ //# HTTP Basic authentication scheme.
177
269
  const pair = `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`;
178
270
  return {
179
271
  authorization: `Basic ${btoa(pair)}`
180
272
  };
181
273
  }
274
+
275
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.1
276
+ //# The Client sends the parameters to the Token Endpoint using the HTTP
277
+ //# "POST" method and the Form Serialization, per Section 13.2, as
278
+ //# described in Section 4.1.3 of OAuth 2.0 [RFC6749].
182
279
  async #post(endpoint, body) {
183
280
  const auth = this.#clientAuth(body);
184
281
  return await this.#json(await fetch(endpoint, {
@@ -196,14 +293,33 @@ export class OidcClient {
196
293
  token_endpoint
197
294
  } = await this.discovery();
198
295
  const res = parse(await this.#post(token_endpoint, new URLSearchParams({
296
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3
297
+ //# grant_type
298
+ //# REQUIRED. Value MUST be set to "authorization_code".
299
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.1
300
+ //# A Client makes a Token Request by presenting its Authorization Grant
301
+ //# (in the form of an Authorization Code) to the Token Endpoint using
302
+ //# the "grant_type" value "authorization_code", as described in Section
303
+ //# 4.1.3 of OAuth 2.0 [RFC6749].
199
304
  grant_type: 'authorization_code',
200
305
  code,
306
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3
307
+ //# redirect_uri
308
+ //# REQUIRED, if the "redirect_uri" parameter was included in the
309
+ //# authorization request as described in Section 4.1.1, and their
310
+ //# values MUST be identical.
201
311
  redirect_uri: this.opts.redirectUri,
312
+ //= https://www.rfc-editor.org/rfc/rfc7636#section-4.5
313
+ //# code_verifier
314
+ //# REQUIRED. Code verifier
202
315
  code_verifier: req.verifier
203
316
  })), tokenResponse);
204
317
  return {
205
318
  idToken: res.id_token,
206
319
  accessToken: res.access_token ?? null,
320
+ keysJwe: res.keys_jwe ?? null,
321
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.5
322
+ //# Follow the ID Token validation rules in Section 3.1.3.7.
207
323
  claims: await this.verifyIdToken(res.id_token, req.nonce)
208
324
  };
209
325
  }
@@ -234,9 +350,15 @@ export class OidcClient {
234
350
  #jwks(refresh) {
235
351
  if (refresh) this.#keys = null;
236
352
  this.#keys ??= (async () => {
353
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7
354
+ //# The Client MUST use the keys provided by the Issuer.
237
355
  const {
238
356
  jwks_uri
239
357
  } = await this.discovery();
358
+ //= https://www.rfc-editor.org/rfc/rfc7517#section-4.2
359
+ //# The "use" parameter is employed to indicate whether
360
+ //# a public key is used for encrypting data or verifying the signature
361
+ //# on data.
240
362
  return parse(await this.#json(await fetch(jwks_uri)), jwks).keys.filter(k => k.use === undefined || k.use === 'sig');
241
363
  })().catch(e => {
242
364
  this.#keys = null;
@@ -245,7 +367,20 @@ export class OidcClient {
245
367
  return this.#keys;
246
368
  }
247
369
  async #key(alg, kid) {
370
+ //= https://www.rfc-editor.org/rfc/rfc7517#section-4.5
371
+ //# When used with JWS or JWE, the "kid" value is used to match a JWS or
372
+ //# JWE "kid" Header Parameter value.
373
+ //= https://www.rfc-editor.org/rfc/rfc7517#section-4.4
374
+ //# The "alg" (algorithm) parameter identifies the algorithm intended for
375
+ //# use with the key.
376
+ //= https://www.rfc-editor.org/rfc/rfc7517#section-5
377
+ //# Implementations SHOULD ignore JWKs within a JWK Set that use "kty"
378
+ //# (key type) values that are not understood by them,
248
379
  const find = keys => keys.find(k => (kid === undefined || k.kid === kid) && (k.alg === undefined || k.alg === alg) && verifyParams(alg, k) !== null);
380
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-10.1.1
381
+ //# The
382
+ //# verifier knows to go back to the "jwks_uri" location to re-retrieve
383
+ //# the keys when it sees an unfamiliar "kid" value.
249
384
  const key = find(await this.#jwks(false)) ?? find(await this.#jwks(true));
250
385
  if (key === undefined) {
251
386
  throw new OidcError('invalid_token', `no signing key ${kid ?? alg}`);
@@ -254,6 +389,9 @@ export class OidcClient {
254
389
  }
255
390
  async verifyIdToken(token, nonce) {
256
391
  const parts = token.split('.');
392
+ //= https://www.rfc-editor.org/rfc/rfc7519#section-7.2
393
+ //# Verify that the JWT contains at least one period ('.')
394
+ //# character.
257
395
  if (parts.length !== 3) throw new OidcError('invalid_token', 'not a JWS');
258
396
  const [h, p, s] = parts;
259
397
  let head, claims;
@@ -263,6 +401,10 @@ export class OidcClient {
263
401
  } catch (e) {
264
402
  throw new OidcError('invalid_token', `malformed id token: ${e}`);
265
403
  }
404
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7
405
+ //# The Client MUST validate
406
+ //# the signature of all other ID Tokens according to JWS [JWS]
407
+ //# using the algorithm specified in the JWT "alg" Header Parameter.
266
408
  const key = await this.#key(head.alg, head.kid);
267
409
  const params = verifyParams(head.alg, key);
268
410
  const cryptoKey = await crypto.subtle.importKey('jwk', key, params.importAlg, false, ['verify']);
@@ -273,15 +415,41 @@ export class OidcClient {
273
415
  } = await this.discovery();
274
416
  const aud = typeof claims.aud === 'string' ? [claims.aud] : claims.aud;
275
417
  const now = Date.now() / 1000;
418
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7
419
+ //# The Issuer Identifier for the OpenID Provider (which is
420
+ //# typically obtained during Discovery) MUST exactly match the
421
+ //# value of the "iss" (issuer) Claim.
422
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-16.15
423
+ //# The issuer returned by discovery MUST exactly match the
424
+ //# value of "iss" in the ID Token.
276
425
  if (claims.iss !== issuer) {
277
426
  throw new OidcError('invalid_token', `unexpected issuer ${claims.iss}`);
278
427
  }
428
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7
429
+ //# The Client MUST validate that the "aud" (audience) Claim
430
+ //# contains its "client_id" value registered at the Issuer
431
+ //# identified by the "iss" (issuer) Claim as an audience.
432
+ //= https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3
433
+ //# If the principal processing the claim does not identify itself with a
434
+ //# value in the "aud" claim when this claim is present, then the JWT MUST
435
+ //# be rejected.
279
436
  if (!aud.includes(this.opts.clientId) || aud.length > 1 && claims.azp !== this.opts.clientId) {
280
437
  throw new OidcError('invalid_token', 'id token is for another client');
281
438
  }
439
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7
440
+ //# The current time MUST be before the time represented by the
441
+ //# "exp" Claim.
442
+ //= https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4
443
+ //# Implementers MAY provide for some small leeway, usually no more than
444
+ //# a few minutes, to account for clock skew.
282
445
  if (claims.exp + SKEW_S < now || claims.iat - SKEW_S > now) {
283
446
  throw new OidcError('invalid_token', 'id token expired');
284
447
  }
448
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7
449
+ //# If a nonce value was sent in the Authentication Request, a
450
+ //# "nonce" Claim MUST be present and its value checked to verify
451
+ //# that it is the same value as the one that was sent in the
452
+ //# Authentication Request.
285
453
  if (nonce !== null && claims.nonce !== nonce) {
286
454
  throw new OidcError('invalid_token', 'id token nonce mismatch');
287
455
  }
package/client.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":[],"sources":["client.ts"],"sourcesContent":["import { decodeBase64Url, encodeBase64Url } from '@std/encoding/base64url';\nimport * as zm from 'zod/mini';\nimport { parse } from './parse.ts';\n\nconst SKEW_S = 60;\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nconst discoveryDoc = zm.object({\n\tissuer: zm.string(),\n\tauthorization_endpoint: zm.string(),\n\ttoken_endpoint: zm.string(),\n\tjwks_uri: zm.string(),\n\tend_session_endpoint: zm.optional(zm.string()),\n\tintrospection_endpoint: zm.optional(zm.string()),\n\trevocation_endpoint: zm.optional(zm.string()),\n});\nexport type Discovery = zm.infer<typeof discoveryDoc>;\n\nconst jwk = zm.object({\n\tkid: zm.optional(zm.string()),\n\tkty: zm.string(),\n\talg: zm.optional(zm.string()),\n\tuse: zm.optional(zm.string()),\n\tn: zm.optional(zm.string()),\n\te: zm.optional(zm.string()),\n\tcrv: zm.optional(zm.string()),\n\tx: zm.optional(zm.string()),\n\ty: zm.optional(zm.string()),\n});\ntype Jwk = zm.infer<typeof jwk>;\n\nconst jwks = zm.object({ keys: zm.array(jwk) });\n\nconst header = zm.object({ alg: zm.string(), kid: zm.optional(zm.string()) });\n\nexport const orgClaim = zm.object({\n\tid: zm.string(),\n\tslug: zm.string(),\n\tname: zm.string(),\n\troles: zm._default(zm.array(zm.string()), []),\n});\nexport type OrgClaim = zm.infer<typeof orgClaim>;\n\nconst idClaims = zm.object({\n\tiss: zm.string(),\n\tsub: zm.string(),\n\taud: zm.union([zm.string(), zm.array(zm.string())]),\n\tazp: zm.optional(zm.string()),\n\texp: zm.number(),\n\tiat: zm.number(),\n\tnonce: zm.optional(zm.string()),\n\tname: zm.optional(zm.nullable(zm.string())),\n\tpreferred_username: zm.optional(zm.nullable(zm.string())),\n\temail: zm.optional(zm.nullable(zm.string())),\n\tpicture: zm.optional(zm.nullable(zm.string())),\n\torgs: zm.optional(zm.array(orgClaim)),\n});\nexport type IdClaims = zm.infer<typeof idClaims>;\n\nconst tokenResponse = zm.object({\n\tid_token: zm.string(),\n\taccess_token: zm.optional(zm.string()),\n});\n\nconst introspection = zm.object({\n\tactive: zm.boolean(),\n\tkind: zm.optional(zm.string()),\n\tclient_id: zm.optional(zm.string()),\n\tsub: zm.optional(zm.string()),\n\torg_id: zm.optional(zm.string()),\n\texp: zm.optional(zm.nullable(zm.number())),\n\tscope: zm.optional(zm.string()),\n\tapi_key_id: zm.optional(zm.string()),\n});\nexport type Introspection = zm.infer<typeof introspection>;\n\nconst errorBody = zm.object({\n\terror: zm.string(),\n\terror_description: zm.optional(zm.string()),\n});\n\nexport class OidcError extends Error {\n\tconstructor(readonly code: string, message: string) {\n\t\tsuper(message);\n\t}\n}\n\nexport type TokenAuthMethod =\n\t| 'client_secret_post'\n\t| 'client_secret_basic'\n\t| 'none';\n\nexport interface OidcClientOpts {\n\tissuer: string;\n\tclientId: string;\n\tclientSecret?: string;\n\ttokenAuthMethod: TokenAuthMethod;\n\tredirectUri: string;\n\tscopes: string[];\n}\n\nexport interface AuthorizeRequest {\n\tstate: string;\n\tnonce: string;\n\tverifier: string;\n}\n\nfunction sameIssuer(a: string, b: string): boolean {\n\treturn a.replace(/\\/+$/, '') === b.replace(/\\/+$/, '');\n}\n\nexport function randomToken(bytes = 32): string {\n\treturn encodeBase64Url(crypto.getRandomValues(new Uint8Array(bytes)));\n}\n\nexport async function codeChallenge(verifier: string): Promise<string> {\n\treturn encodeBase64Url(\n\t\tnew Uint8Array(\n\t\t\tawait crypto.subtle.digest('SHA-256', ENCODER.encode(verifier)),\n\t\t),\n\t);\n}\n\nfunction verifyParams(\n\talg: string,\n\tkey: Jwk,\n): {\n\timportAlg: RsaHashedImportParams | EcKeyImportParams;\n\tverify: AlgorithmIdentifier | EcdsaParams;\n} | null {\n\tif (alg === 'RS256' && key.kty === 'RSA') {\n\t\treturn {\n\t\t\timportAlg: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },\n\t\t\tverify: 'RSASSA-PKCS1-v1_5',\n\t\t};\n\t}\n\tif (alg === 'ES256' && key.kty === 'EC' && key.crv === 'P-256') {\n\t\treturn {\n\t\t\timportAlg: { name: 'ECDSA', namedCurve: 'P-256' },\n\t\t\tverify: { name: 'ECDSA', hash: 'SHA-256' },\n\t\t};\n\t}\n\treturn null;\n}\n\nexport class OidcClient {\n\t#discovery: Promise<Discovery> | null = null;\n\t#keys: Promise<Jwk[]> | null = null;\n\n\tconstructor(readonly opts: OidcClientOpts) {\n\t\tif (opts.tokenAuthMethod !== 'none' && !opts.clientSecret) {\n\t\t\tthrow new OidcError(\n\t\t\t\t'invalid_client',\n\t\t\t\t`${opts.tokenAuthMethod} needs a client secret`,\n\t\t\t);\n\t\t}\n\t}\n\n\tdiscovery(): Promise<Discovery> {\n\t\tthis.#discovery ??= (async () => {\n\t\t\tconst base = this.opts.issuer.endsWith('/')\n\t\t\t\t? this.opts.issuer\n\t\t\t\t: `${this.opts.issuer}/`;\n\t\t\tconst doc = parse(\n\t\t\t\tawait this.#json(\n\t\t\t\t\tawait fetch(new URL('.well-known/openid-configuration', base)),\n\t\t\t\t),\n\t\t\t\tdiscoveryDoc,\n\t\t\t);\n\t\t\tif (!sameIssuer(doc.issuer, this.opts.issuer)) {\n\t\t\t\tthrow new OidcError(\n\t\t\t\t\t'invalid_issuer',\n\t\t\t\t\t`discovery issuer ${doc.issuer} does not match ${this.opts.issuer}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn doc;\n\t\t})().catch((e) => {\n\t\t\tthis.#discovery = null;\n\t\t\tthrow e;\n\t\t});\n\t\treturn this.#discovery;\n\t}\n\n\tasync #json(res: Response): Promise<unknown> {\n\t\tconst text = await res.text();\n\t\tlet body: unknown;\n\t\ttry {\n\t\t\tbody = JSON.parse(text);\n\t\t} catch {\n\t\t\tthrow new OidcError(\n\t\t\t\t'invalid_response',\n\t\t\t\t`${res.url} answered ${res.status}: ${text.slice(0, 200)}`,\n\t\t\t);\n\t\t}\n\t\tif (!res.ok) {\n\t\t\tconst err = errorBody.safeParse(body);\n\t\t\tthrow new OidcError(\n\t\t\t\terr.success ? err.data.error : 'http_error',\n\t\t\t\terr.success\n\t\t\t\t\t? err.data.error_description ?? err.data.error\n\t\t\t\t\t: `${res.url} answered ${res.status}`,\n\t\t\t);\n\t\t}\n\t\treturn body;\n\t}\n\n\tasync authorizeUrl(req: AuthorizeRequest): Promise<string> {\n\t\tconst url = new URL((await this.discovery()).authorization_endpoint);\n\t\turl.search = new URLSearchParams({\n\t\t\tresponse_type: 'code',\n\t\t\tclient_id: this.opts.clientId,\n\t\t\tredirect_uri: this.opts.redirectUri,\n\t\t\tscope: this.opts.scopes.join(' '),\n\t\t\tstate: req.state,\n\t\t\tnonce: req.nonce,\n\t\t\tcode_challenge: await codeChallenge(req.verifier),\n\t\t\tcode_challenge_method: 'S256',\n\t\t}).toString();\n\t\treturn url.href;\n\t}\n\n\t#clientAuth(body: URLSearchParams): HeadersInit {\n\t\tconst { clientId, clientSecret, tokenAuthMethod } = this.opts;\n\t\tif (tokenAuthMethod === 'none') {\n\t\t\tbody.set('client_id', clientId);\n\t\t\treturn {};\n\t\t}\n\t\tif (tokenAuthMethod === 'client_secret_post') {\n\t\t\tbody.set('client_id', clientId);\n\t\t\tbody.set('client_secret', clientSecret!);\n\t\t\treturn {};\n\t\t}\n\t\tconst pair = `${encodeURIComponent(clientId)}:${\n\t\t\tencodeURIComponent(clientSecret!)\n\t\t}`;\n\t\treturn { authorization: `Basic ${btoa(pair)}` };\n\t}\n\n\tasync #post(endpoint: string, body: URLSearchParams): Promise<unknown> {\n\t\tconst auth = this.#clientAuth(body);\n\t\treturn await this.#json(\n\t\t\tawait fetch(endpoint, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t...auth,\n\t\t\t\t\t'content-type': 'application/x-www-form-urlencoded',\n\t\t\t\t\taccept: 'application/json',\n\t\t\t\t},\n\t\t\t\tbody,\n\t\t\t}),\n\t\t);\n\t}\n\n\tasync exchange(\n\t\tcode: string,\n\t\treq: AuthorizeRequest,\n\t): Promise<\n\t\t{ idToken: string; accessToken: string | null; claims: IdClaims }\n\t> {\n\t\tconst { token_endpoint } = await this.discovery();\n\t\tconst res = parse(\n\t\t\tawait this.#post(\n\t\t\t\ttoken_endpoint,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\tgrant_type: 'authorization_code',\n\t\t\t\t\tcode,\n\t\t\t\t\tredirect_uri: this.opts.redirectUri,\n\t\t\t\t\tcode_verifier: req.verifier,\n\t\t\t\t}),\n\t\t\t),\n\t\t\ttokenResponse,\n\t\t);\n\t\treturn {\n\t\t\tidToken: res.id_token,\n\t\t\taccessToken: res.access_token ?? null,\n\t\t\tclaims: await this.verifyIdToken(res.id_token, req.nonce),\n\t\t};\n\t}\n\n\tasync introspect(token: string): Promise<Introspection> {\n\t\tconst { introspection_endpoint } = await this.discovery();\n\t\tif (introspection_endpoint === undefined) {\n\t\t\tthrow new OidcError(\n\t\t\t\t'unsupported',\n\t\t\t\t'the identity provider has no introspection endpoint',\n\t\t\t);\n\t\t}\n\t\treturn parse(\n\t\t\tawait this.#post(introspection_endpoint, new URLSearchParams({ token })),\n\t\t\tintrospection,\n\t\t);\n\t}\n\n\tasync endSessionUrl(\n\t\tidTokenHint: string,\n\t\tpostLogoutRedirectUri: string,\n\t): Promise<string | null> {\n\t\tconst { end_session_endpoint } = await this.discovery();\n\t\tif (end_session_endpoint === undefined) return null;\n\t\tconst url = new URL(end_session_endpoint);\n\t\turl.search = new URLSearchParams({\n\t\t\tid_token_hint: idTokenHint,\n\t\t\tpost_logout_redirect_uri: postLogoutRedirectUri,\n\t\t\tclient_id: this.opts.clientId,\n\t\t}).toString();\n\t\treturn url.href;\n\t}\n\n\t#jwks(refresh: boolean): Promise<Jwk[]> {\n\t\tif (refresh) this.#keys = null;\n\t\tthis.#keys ??= (async () => {\n\t\t\tconst { jwks_uri } = await this.discovery();\n\t\t\treturn parse(await this.#json(await fetch(jwks_uri)), jwks).keys\n\t\t\t\t.filter((k) => k.use === undefined || k.use === 'sig');\n\t\t})().catch((e) => {\n\t\t\tthis.#keys = null;\n\t\t\tthrow e;\n\t\t});\n\t\treturn this.#keys;\n\t}\n\n\tasync #key(alg: string, kid: string | undefined): Promise<Jwk> {\n\t\tconst find = (keys: Jwk[]) =>\n\t\t\tkeys.find((k) =>\n\t\t\t\t(kid === undefined || k.kid === kid) &&\n\t\t\t\t(k.alg === undefined || k.alg === alg) && verifyParams(alg, k) !== null\n\t\t\t);\n\t\tconst key = find(await this.#jwks(false)) ?? find(await this.#jwks(true));\n\t\tif (key === undefined) {\n\t\t\tthrow new OidcError('invalid_token', `no signing key ${kid ?? alg}`);\n\t\t}\n\t\treturn key;\n\t}\n\n\tasync verifyIdToken(token: string, nonce: string | null): Promise<IdClaims> {\n\t\tconst parts = token.split('.');\n\t\tif (parts.length !== 3) throw new OidcError('invalid_token', 'not a JWS');\n\t\tconst [h, p, s] = parts;\n\t\tlet head, claims;\n\t\ttry {\n\t\t\thead = parse(\n\t\t\t\tJSON.parse(DECODER.decode(decodeBase64Url(h))),\n\t\t\t\theader,\n\t\t\t);\n\t\t\tclaims = parse(\n\t\t\t\tJSON.parse(DECODER.decode(decodeBase64Url(p))),\n\t\t\t\tidClaims,\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tthrow new OidcError('invalid_token', `malformed id token: ${e}`);\n\t\t}\n\t\tconst key = await this.#key(head.alg, head.kid);\n\t\tconst params = verifyParams(head.alg, key)!;\n\t\tconst cryptoKey = await crypto.subtle.importKey(\n\t\t\t'jwk',\n\t\t\tkey as JsonWebKey,\n\t\t\tparams.importAlg,\n\t\t\tfalse,\n\t\t\t['verify'],\n\t\t);\n\t\tconst ok = await crypto.subtle.verify(\n\t\t\tparams.verify,\n\t\t\tcryptoKey,\n\t\t\tdecodeBase64Url(s),\n\t\t\tENCODER.encode(`${h}.${p}`),\n\t\t);\n\t\tif (!ok) throw new OidcError('invalid_token', 'bad id token signature');\n\t\tconst { issuer } = await this.discovery();\n\t\tconst aud = typeof claims.aud === 'string' ? [claims.aud] : claims.aud;\n\t\tconst now = Date.now() / 1000;\n\t\tif (claims.iss !== issuer) {\n\t\t\tthrow new OidcError('invalid_token', `unexpected issuer ${claims.iss}`);\n\t\t}\n\t\tif (\n\t\t\t!aud.includes(this.opts.clientId) ||\n\t\t\t(aud.length > 1 && claims.azp !== this.opts.clientId)\n\t\t) {\n\t\t\tthrow new OidcError('invalid_token', 'id token is for another client');\n\t\t}\n\t\tif (claims.exp + SKEW_S < now || claims.iat - SKEW_S > now) {\n\t\t\tthrow new OidcError('invalid_token', 'id token expired');\n\t\t}\n\t\tif (nonce !== null && claims.nonce !== nonce) {\n\t\t\tthrow new OidcError('invalid_token', 'id token nonce mismatch');\n\t\t}\n\t\treturn claims;\n\t}\n}\n"],"mappings":"AAAA,SAAS,eAAe,EAAE,eAAe,QAAQ,yBAAyB;AAC1E,OAAO,KAAK,EAAE,MAAM,UAAU;AAC9B,SAAS,KAAK,QAAQ,YAAY;AAElC,MAAM,MAAM,GAAG,EAAE;AACjB,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,CAAC;AACjC,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,CAAC;AAEjC,MAAM,YAAY,GAAG,EAAE,CAAC,MAAM,CAAC;EAC9B,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;EACnB,sBAAsB,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;EACnC,cAAc,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;EAC3B,QAAQ,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;EACrB,oBAAoB,EAAE,EAAE,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AG,CAAC,IAAI,CAAC,EAAE,CAC3B,CAAC;IACD,IAAI,CAAC,EAAE,EAAE,MAAM,IAAI,SAAS,CAAC,eAAe,EAAE,wBAAwB,CAAC;IACvE,MAAM;MAAE;IAAO,CAAC,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,CAAC;IACzC,MAAM,GAAG,GAAG,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG;IACtE,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI;IAC7B,IAAI,MAAM,CAAC,GAAG,KAAK,MAAM,EAAE;MAC1B,MAAM,IAAI,SAAS,CAAC,eAAe,EAAE,qBAAqB,MAAM,CAAC,GAAG,EAAE,CAAC;IACxE;IACA,IACC,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAChC,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,KAAK,IAAI,CAAC,IAAI,CAAC,QAAS,EACpD;MACD,MAAM,IAAI,SAAS,CAAC,eAAe,EAAE,gCAAgC,CAAC;IACvE;IACA,IAAI,MAAM,CAAC,GAAG,GAAG,MAAM,GAAG,GAAG,IAAI,MAAM,CAAC,GAAG,GAAG,MAAM,GAAG,GAAG,EAAE;MAC3D,MAAM,IAAI,SAAS,CAAC,eAAe,EAAE,kBAAkB,CAAC;IACzD;IACA,IAAI,KAAK,KAAK,IAAI,IAAI,MAAM,CAAC,KAAK,KAAK,KAAK,EAAE;MAC7C,MAAM,IAAI,SAAS,CAAC,eAAe,EAAE,yBAAyB,CAAC;IAChE;IACA,OAAO,MAAM;EACd;AACD","ignoreList":[]}
1
+ {"version":3,"names":[],"sources":["client.ts"],"sourcesContent":["import { decodeBase64Url, encodeBase64Url } from '@std/encoding/base64url';\nimport * as zm from 'zod/mini';\nimport { parse } from './parse.ts';\n\nconst SKEW_S = 60;\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nconst discoveryDoc = zm.object({\n\tissuer: zm.string(),\n\tauthorization_endpoint: zm.string(),\n\ttoken_endpoint: zm.string(),\n\tjwks_uri: zm.string(),\n\tend_session_endpoint: zm.optional(zm.string()),\n\tintrospection_endpoint: zm.optional(zm.string()),\n\trevocation_endpoint: zm.optional(zm.string()),\n});\nexport type Discovery = zm.infer<typeof discoveryDoc>;\n\n//= https://www.rfc-editor.org/rfc/rfc7517#section-4\n//# Additional members can be present in the JWK; if not understood by\n//# implementations encountering them, they MUST be ignored.\nconst jwk = zm.object({\n\tkid: zm.optional(zm.string()),\n\t//= https://www.rfc-editor.org/rfc/rfc7517#section-4.1\n\t//# This\n\t//# member MUST be present in a JWK.\n\tkty: zm.string(),\n\talg: zm.optional(zm.string()),\n\tuse: zm.optional(zm.string()),\n\tn: zm.optional(zm.string()),\n\te: zm.optional(zm.string()),\n\tcrv: zm.optional(zm.string()),\n\tx: zm.optional(zm.string()),\n\ty: zm.optional(zm.string()),\n});\ntype Jwk = zm.infer<typeof jwk>;\n\n//= https://www.rfc-editor.org/rfc/rfc7517#section-5\n//# A JWK Set is a JSON object that represents a set of JWKs. The JSON\n//# object MUST have a \"keys\" member, with its value being an array of\n//# JWKs.\nconst jwks = zm.object({ keys: zm.array(jwk) });\n\nconst header = zm.object({ alg: zm.string(), kid: zm.optional(zm.string()) });\n\nexport const orgClaim = zm.object({\n\tid: zm.string(),\n\tslug: zm.string(),\n\tname: zm.string(),\n\troles: zm._default(zm.array(zm.string()), []),\n});\nexport type OrgClaim = zm.infer<typeof orgClaim>;\n\n//= https://www.rfc-editor.org/rfc/rfc7519#section-4\n//# However, in\n//# the absence of such requirements, all claims that are not understood\n//# by implementations MUST be ignored.\n//= https://openid.net/specs/openid-connect-core-1_0.txt#section-2\n//# Any Claims used that are not\n//# understood MUST be ignored.\nconst idClaims = zm.object({\n\tiss: zm.string(),\n\tsub: zm.string(),\n\taud: zm.union([zm.string(), zm.array(zm.string())]),\n\tazp: zm.optional(zm.string()),\n\texp: zm.number(),\n\tiat: zm.number(),\n\tnonce: zm.optional(zm.string()),\n\tname: zm.optional(zm.nullable(zm.string())),\n\tpreferred_username: zm.optional(zm.nullable(zm.string())),\n\temail: zm.optional(zm.nullable(zm.string())),\n\tpicture: zm.optional(zm.nullable(zm.string())),\n\torgs: zm.optional(zm.array(orgClaim)),\n});\nexport type IdClaims = zm.infer<typeof idClaims>;\n\n//= https://www.rfc-editor.org/rfc/rfc6749#section-5.1\n//# The client MUST ignore unrecognized value names in the response.\nconst tokenResponse = zm.object({\n\tid_token: zm.string(),\n\taccess_token: zm.optional(zm.string()),\n\tkeys_jwe: zm.optional(zm.string()),\n});\n\nconst introspection = zm.object({\n\tactive: zm.boolean(),\n\tkind: zm.optional(zm.string()),\n\tclient_id: zm.optional(zm.string()),\n\tsub: zm.optional(zm.string()),\n\torg_id: zm.optional(zm.string()),\n\texp: zm.optional(zm.nullable(zm.number())),\n\tscope: zm.optional(zm.string()),\n\tapi_key_id: zm.optional(zm.string()),\n});\nexport type Introspection = zm.infer<typeof introspection>;\n\nconst errorBody = zm.object({\n\terror: zm.string(),\n\terror_description: zm.optional(zm.string()),\n});\n\nexport class OidcError extends Error {\n\tconstructor(readonly code: string, message: string) {\n\t\tsuper(message);\n\t}\n}\n\nexport type TokenAuthMethod =\n\t| 'client_secret_post'\n\t| 'client_secret_basic'\n\t| 'none';\n\nexport interface OidcClientOpts {\n\tissuer: string;\n\tclientId: string;\n\tclientSecret?: string;\n\ttokenAuthMethod: TokenAuthMethod;\n\tredirectUri: string;\n\tscopes: string[];\n}\n\nexport interface AuthorizeRequest {\n\tstate: string;\n\tnonce: string;\n\tverifier: string;\n\tkeysJwk?: string;\n}\n\nexport interface TokenSet {\n\tidToken: string;\n\taccessToken: string | null;\n\tkeysJwe: string | null;\n\tclaims: IdClaims;\n}\n\nfunction sameIssuer(a: string, b: string): boolean {\n\treturn a.replace(/\\/+$/, '') === b.replace(/\\/+$/, '');\n}\n\nexport function randomToken(bytes = 32): string {\n\treturn encodeBase64Url(crypto.getRandomValues(new Uint8Array(bytes)));\n}\n\n//= https://www.rfc-editor.org/rfc/rfc7636#section-4.2\n//# S256\n//# code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))\nexport async function codeChallenge(verifier: string): Promise<string> {\n\treturn encodeBase64Url(\n\t\tnew Uint8Array(\n\t\t\tawait crypto.subtle.digest('SHA-256', ENCODER.encode(verifier)),\n\t\t),\n\t);\n}\n\nfunction verifyParams(\n\talg: string,\n\tkey: Jwk,\n): {\n\timportAlg: RsaHashedImportParams | EcKeyImportParams;\n\tverify: AlgorithmIdentifier | EcdsaParams;\n} | null {\n\t//= https://www.rfc-editor.org/rfc/rfc7518#section-3.3\n\t//# The RSASSA-PKCS1-v1_5 SHA-256 digital signature for a JWS is\n\t//# validated as follows: submit the JWS Signing Input, the JWS\n\t//# Signature, and the public key corresponding to the private key used\n\t//# by the signer to the RSASSA-PKCS1-v1_5-VERIFY algorithm using SHA-256\n\t//# as the hash function.\n\tif (alg === 'RS256' && key.kty === 'RSA') {\n\t\treturn {\n\t\t\timportAlg: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },\n\t\t\tverify: 'RSASSA-PKCS1-v1_5',\n\t\t};\n\t}\n\t//= https://www.rfc-editor.org/rfc/rfc7518#section-3.4\n\t//# Submit the JWS Signing Input, R, S, and the public key (x, y) to\n\t//# the ECDSA P-256 SHA-256 validator.\n\tif (alg === 'ES256' && key.kty === 'EC' && key.crv === 'P-256') {\n\t\treturn {\n\t\t\timportAlg: { name: 'ECDSA', namedCurve: 'P-256' },\n\t\t\tverify: { name: 'ECDSA', hash: 'SHA-256' },\n\t\t};\n\t}\n\t//= https://www.rfc-editor.org/rfc/rfc7518#section-3.6\n\t//# Implementations MUST NOT accept Unsecured JWSs by default.\n\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-2\n\t//# ID Tokens MUST NOT use \"none\" as\n\t//# the \"alg\" value unless the Response Type used returns no ID Token\n\t//# from the Authorization Endpoint (such as when using the Authorization\n\t//# Code Flow) and the Client explicitly requested the use of \"none\" at\n\t//# Registration time.\n\t//= https://www.rfc-editor.org/rfc/rfc7519#section-7.2\n\t//# Even if a JWT can be successfully\n\t//# validated, unless the algorithms used in the JWT are acceptable to\n\t//# the application, it SHOULD reject the JWT.\n\treturn null;\n}\n\nexport class OidcClient {\n\t#discovery: Promise<Discovery> | null = null;\n\t#keys: Promise<Jwk[]> | null = null;\n\n\tconstructor(readonly opts: OidcClientOpts) {\n\t\tif (opts.tokenAuthMethod !== 'none' && !opts.clientSecret) {\n\t\t\tthrow new OidcError(\n\t\t\t\t'invalid_client',\n\t\t\t\t`${opts.tokenAuthMethod} needs a client secret`,\n\t\t\t);\n\t\t}\n\t}\n\n\tdiscovery(): Promise<Discovery> {\n\t\tthis.#discovery ??= (async () => {\n\t\t\tconst base = this.opts.issuer.endsWith('/')\n\t\t\t\t? this.opts.issuer\n\t\t\t\t: `${this.opts.issuer}/`;\n\t\t\tconst doc = parse(\n\t\t\t\tawait this.#json(\n\t\t\t\t\tawait fetch(new URL('.well-known/openid-configuration', base)),\n\t\t\t\t),\n\t\t\t\tdiscoveryDoc,\n\t\t\t);\n\t\t\tif (!sameIssuer(doc.issuer, this.opts.issuer)) {\n\t\t\t\tthrow new OidcError(\n\t\t\t\t\t'invalid_issuer',\n\t\t\t\t\t`discovery issuer ${doc.issuer} does not match ${this.opts.issuer}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn doc;\n\t\t})().catch((e) => {\n\t\t\tthis.#discovery = null;\n\t\t\tthrow e;\n\t\t});\n\t\treturn this.#discovery;\n\t}\n\n\tasync #json(res: Response): Promise<unknown> {\n\t\tconst text = await res.text();\n\t\tlet body: unknown;\n\t\ttry {\n\t\t\tbody = JSON.parse(text);\n\t\t} catch {\n\t\t\tthrow new OidcError(\n\t\t\t\t'invalid_response',\n\t\t\t\t`${res.url} answered ${res.status}: ${text.slice(0, 200)}`,\n\t\t\t);\n\t\t}\n\t\tif (!res.ok) {\n\t\t\tconst err = errorBody.safeParse(body);\n\t\t\tthrow new OidcError(\n\t\t\t\terr.success ? err.data.error : 'http_error',\n\t\t\t\terr.success\n\t\t\t\t\t? err.data.error_description ?? err.data.error\n\t\t\t\t\t: `${res.url} answered ${res.status}`,\n\t\t\t);\n\t\t}\n\t\treturn body;\n\t}\n\n\tasync authorizeUrl(req: AuthorizeRequest): Promise<string> {\n\t\tconst url = new URL((await this.discovery()).authorization_endpoint);\n\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1\n\t\t//# The client constructs the request URI by adding the following\n\t\t//# parameters to the query component of the authorization endpoint URI\n\t\t//# using the \"application/x-www-form-urlencoded\" format, per Appendix B:\n\t\tconst params = new URLSearchParams({\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1\n\t\t\t//# response_type\n\t\t\t//# REQUIRED. Value MUST be set to \"code\".\n\t\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.2.1\n\t\t\t//# When using the Authorization Code Flow, this value is \"code\".\n\t\t\tresponse_type: 'code',\n\t\t\tclient_id: this.opts.clientId,\n\t\t\tredirect_uri: this.opts.redirectUri,\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-3.3\n\t\t\t//# The value of the scope parameter is expressed as a list of space-\n\t\t\t//# delimited, case-sensitive strings.\n\t\t\tscope: this.opts.scopes.join(' '),\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1\n\t\t\t//# The parameter SHOULD be used for preventing\n\t\t\t//# cross-site request forgery as described in Section 10.12.\n\t\t\tstate: req.state,\n\t\t\tnonce: req.nonce,\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc7636#section-4.3\n\t\t\t//# code_challenge\n\t\t\t//# REQUIRED. Code challenge.\n\t\t\tcode_challenge: await codeChallenge(req.verifier),\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc7636#section-4.2\n\t\t\t//# If the client is capable of using \"S256\", it MUST use \"S256\", as\n\t\t\t//# \"S256\" is Mandatory To Implement (MTI) on the server.\n\t\t\tcode_challenge_method: 'S256',\n\t\t});\n\t\tif (req.keysJwk !== undefined) params.set('keys_jwk', req.keysJwk);\n\t\turl.search = params.toString();\n\t\treturn url.href;\n\t}\n\n\t#clientAuth(body: URLSearchParams): HeadersInit {\n\t\tconst { clientId, clientSecret, tokenAuthMethod } = this.opts;\n\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-3.2.1\n\t\t//# In the\n\t\t//# \"authorization_code\" \"grant_type\" request to the token endpoint, an\n\t\t//# unauthenticated client MUST send its \"client_id\" to prevent itself\n\t\t//# from inadvertently accepting a code intended for a client with a\n\t\t//# different \"client_id\".\n\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3\n\t\t//# client_id\n\t\t//# REQUIRED, if the client is not authenticating with the\n\t\t//# authorization server as described in Section 3.2.1.\n\t\tif (tokenAuthMethod === 'none') {\n\t\t\tbody.set('client_id', clientId);\n\t\t\treturn {};\n\t\t}\n\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-9\n\t\t//# Clients that have received a \"client_secret\" value from the\n\t\t//# Authorization Server, authenticate with the Authorization Server\n\t\t//# in accordance with Section 2.3.1 of OAuth 2.0 [RFC6749] by\n\t\t//# including the Client Credentials in the request body.\n\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-2.3.1\n\t\t//# The parameters can only\n\t\t//# be transmitted in the request-body and MUST NOT be included in the\n\t\t//# request URI.\n\t\tif (tokenAuthMethod === 'client_secret_post') {\n\t\t\tbody.set('client_id', clientId);\n\t\t\tbody.set('client_secret', clientSecret!);\n\t\t\treturn {};\n\t\t}\n\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-9\n\t\t//# Clients that have received a \"client_secret\" value from the\n\t\t//# Authorization Server authenticate with the Authorization Server in\n\t\t//# accordance with Section 2.3.1 of OAuth 2.0 [RFC6749] using the\n\t\t//# HTTP Basic authentication scheme.\n\t\tconst pair = `${encodeURIComponent(clientId)}:${\n\t\t\tencodeURIComponent(clientSecret!)\n\t\t}`;\n\t\treturn { authorization: `Basic ${btoa(pair)}` };\n\t}\n\n\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.1\n\t//# The Client sends the parameters to the Token Endpoint using the HTTP\n\t//# \"POST\" method and the Form Serialization, per Section 13.2, as\n\t//# described in Section 4.1.3 of OAuth 2.0 [RFC6749].\n\tasync #post(endpoint: string, body: URLSearchParams): Promise<unknown> {\n\t\tconst auth = this.#clientAuth(body);\n\t\treturn await this.#json(\n\t\t\tawait fetch(endpoint, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t...auth,\n\t\t\t\t\t'content-type': 'application/x-www-form-urlencoded',\n\t\t\t\t\taccept: 'application/json',\n\t\t\t\t},\n\t\t\t\tbody,\n\t\t\t}),\n\t\t);\n\t}\n\n\tasync exchange(\n\t\tcode: string,\n\t\treq: AuthorizeRequest,\n\t): Promise<TokenSet> {\n\t\tconst { token_endpoint } = await this.discovery();\n\t\tconst res = parse(\n\t\t\tawait this.#post(\n\t\t\t\ttoken_endpoint,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3\n\t\t\t\t\t//# grant_type\n\t\t\t\t\t//# REQUIRED. Value MUST be set to \"authorization_code\".\n\t\t\t\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.1\n\t\t\t\t\t//# A Client makes a Token Request by presenting its Authorization Grant\n\t\t\t\t\t//# (in the form of an Authorization Code) to the Token Endpoint using\n\t\t\t\t\t//# the \"grant_type\" value \"authorization_code\", as described in Section\n\t\t\t\t\t//# 4.1.3 of OAuth 2.0 [RFC6749].\n\t\t\t\t\tgrant_type: 'authorization_code',\n\t\t\t\t\tcode,\n\t\t\t\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3\n\t\t\t\t\t//# redirect_uri\n\t\t\t\t\t//# REQUIRED, if the \"redirect_uri\" parameter was included in the\n\t\t\t\t\t//# authorization request as described in Section 4.1.1, and their\n\t\t\t\t\t//# values MUST be identical.\n\t\t\t\t\tredirect_uri: this.opts.redirectUri,\n\t\t\t\t\t//= https://www.rfc-editor.org/rfc/rfc7636#section-4.5\n\t\t\t\t\t//# code_verifier\n\t\t\t\t\t//# REQUIRED. Code verifier\n\t\t\t\t\tcode_verifier: req.verifier,\n\t\t\t\t}),\n\t\t\t),\n\t\t\ttokenResponse,\n\t\t);\n\t\treturn {\n\t\t\tidToken: res.id_token,\n\t\t\taccessToken: res.access_token ?? null,\n\t\t\tkeysJwe: res.keys_jwe ?? null,\n\t\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.5\n\t\t\t//# Follow the ID Token validation rules in Section 3.1.3.7.\n\t\t\tclaims: await this.verifyIdToken(res.id_token, req.nonce),\n\t\t};\n\t}\n\n\tasync introspect(token: string): Promise<Introspection> {\n\t\tconst { introspection_endpoint } = await this.discovery();\n\t\tif (introspection_endpoint === undefined) {\n\t\t\tthrow new OidcError(\n\t\t\t\t'unsupported',\n\t\t\t\t'the identity provider has no introspection endpoint',\n\t\t\t);\n\t\t}\n\t\treturn parse(\n\t\t\tawait this.#post(introspection_endpoint, new URLSearchParams({ token })),\n\t\t\tintrospection,\n\t\t);\n\t}\n\n\tasync endSessionUrl(\n\t\tidTokenHint: string,\n\t\tpostLogoutRedirectUri: string,\n\t): Promise<string | null> {\n\t\tconst { end_session_endpoint } = await this.discovery();\n\t\tif (end_session_endpoint === undefined) return null;\n\t\tconst url = new URL(end_session_endpoint);\n\t\turl.search = new URLSearchParams({\n\t\t\tid_token_hint: idTokenHint,\n\t\t\tpost_logout_redirect_uri: postLogoutRedirectUri,\n\t\t\tclient_id: this.opts.clientId,\n\t\t}).toString();\n\t\treturn url.href;\n\t}\n\n\t#jwks(refresh: boolean): Promise<Jwk[]> {\n\t\tif (refresh) this.#keys = null;\n\t\tthis.#keys ??= (async () => {\n\t\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7\n\t\t\t//# The Client MUST use the keys provided by the Issuer.\n\t\t\tconst { jwks_uri } = await this.discovery();\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc7517#section-4.2\n\t\t\t//# The \"use\" parameter is employed to indicate whether\n\t\t\t//# a public key is used for encrypting data or verifying the signature\n\t\t\t//# on data.\n\t\t\treturn parse(await this.#json(await fetch(jwks_uri)), jwks).keys\n\t\t\t\t.filter((k) => k.use === undefined || k.use === 'sig');\n\t\t})().catch((e) => {\n\t\t\tthis.#keys = null;\n\t\t\tthrow e;\n\t\t});\n\t\treturn this.#keys;\n\t}\n\n\tasync #key(alg: string, kid: string | undefined): Promise<Jwk> {\n\t\t//= https://www.rfc-editor.org/rfc/rfc7517#section-4.5\n\t\t//# When used with JWS or JWE, the \"kid\" value is used to match a JWS or\n\t\t//# JWE \"kid\" Header Parameter value.\n\t\t//= https://www.rfc-editor.org/rfc/rfc7517#section-4.4\n\t\t//# The \"alg\" (algorithm) parameter identifies the algorithm intended for\n\t\t//# use with the key.\n\t\t//= https://www.rfc-editor.org/rfc/rfc7517#section-5\n\t\t//# Implementations SHOULD ignore JWKs within a JWK Set that use \"kty\"\n\t\t//# (key type) values that are not understood by them,\n\t\tconst find = (keys: Jwk[]) =>\n\t\t\tkeys.find((k) =>\n\t\t\t\t(kid === undefined || k.kid === kid) &&\n\t\t\t\t(k.alg === undefined || k.alg === alg) && verifyParams(alg, k) !== null\n\t\t\t);\n\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-10.1.1\n\t\t//# The\n\t\t//# verifier knows to go back to the \"jwks_uri\" location to re-retrieve\n\t\t//# the keys when it sees an unfamiliar \"kid\" value.\n\t\tconst key = find(await this.#jwks(false)) ?? find(await this.#jwks(true));\n\t\tif (key === undefined) {\n\t\t\tthrow new OidcError('invalid_token', `no signing key ${kid ?? alg}`);\n\t\t}\n\t\treturn key;\n\t}\n\n\tasync verifyIdToken(token: string, nonce: string | null): Promise<IdClaims> {\n\t\tconst parts = token.split('.');\n\t\t//= https://www.rfc-editor.org/rfc/rfc7519#section-7.2\n\t\t//# Verify that the JWT contains at least one period ('.')\n\t\t//# character.\n\t\tif (parts.length !== 3) throw new OidcError('invalid_token', 'not a JWS');\n\t\tconst [h, p, s] = parts;\n\t\tlet head, claims;\n\t\ttry {\n\t\t\thead = parse(\n\t\t\t\tJSON.parse(DECODER.decode(decodeBase64Url(h))),\n\t\t\t\theader,\n\t\t\t);\n\t\t\tclaims = parse(\n\t\t\t\tJSON.parse(DECODER.decode(decodeBase64Url(p))),\n\t\t\t\tidClaims,\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tthrow new OidcError('invalid_token', `malformed id token: ${e}`);\n\t\t}\n\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7\n\t\t//# The Client MUST validate\n\t\t//# the signature of all other ID Tokens according to JWS [JWS]\n\t\t//# using the algorithm specified in the JWT \"alg\" Header Parameter.\n\t\tconst key = await this.#key(head.alg, head.kid);\n\t\tconst params = verifyParams(head.alg, key)!;\n\t\tconst cryptoKey = await crypto.subtle.importKey(\n\t\t\t'jwk',\n\t\t\tkey as JsonWebKey,\n\t\t\tparams.importAlg,\n\t\t\tfalse,\n\t\t\t['verify'],\n\t\t);\n\t\tconst ok = await crypto.subtle.verify(\n\t\t\tparams.verify,\n\t\t\tcryptoKey,\n\t\t\tdecodeBase64Url(s),\n\t\t\tENCODER.encode(`${h}.${p}`),\n\t\t);\n\t\tif (!ok) throw new OidcError('invalid_token', 'bad id token signature');\n\t\tconst { issuer } = await this.discovery();\n\t\tconst aud = typeof claims.aud === 'string' ? [claims.aud] : claims.aud;\n\t\tconst now = Date.now() / 1000;\n\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7\n\t\t//# The Issuer Identifier for the OpenID Provider (which is\n\t\t//# typically obtained during Discovery) MUST exactly match the\n\t\t//# value of the \"iss\" (issuer) Claim.\n\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-16.15\n\t\t//# The issuer returned by discovery MUST exactly match the\n\t\t//# value of \"iss\" in the ID Token.\n\t\tif (claims.iss !== issuer) {\n\t\t\tthrow new OidcError('invalid_token', `unexpected issuer ${claims.iss}`);\n\t\t}\n\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7\n\t\t//# The Client MUST validate that the \"aud\" (audience) Claim\n\t\t//# contains its \"client_id\" value registered at the Issuer\n\t\t//# identified by the \"iss\" (issuer) Claim as an audience.\n\t\t//= https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3\n\t\t//# If the principal processing the claim does not identify itself with a\n\t\t//# value in the \"aud\" claim when this claim is present, then the JWT MUST\n\t\t//# be rejected.\n\t\tif (\n\t\t\t!aud.includes(this.opts.clientId) ||\n\t\t\t(aud.length > 1 && claims.azp !== this.opts.clientId)\n\t\t) {\n\t\t\tthrow new OidcError('invalid_token', 'id token is for another client');\n\t\t}\n\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7\n\t\t//# The current time MUST be before the time represented by the\n\t\t//# \"exp\" Claim.\n\t\t//= https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4\n\t\t//# Implementers MAY provide for some small leeway, usually no more than\n\t\t//# a few minutes, to account for clock skew.\n\t\tif (claims.exp + SKEW_S < now || claims.iat - SKEW_S > now) {\n\t\t\tthrow new OidcError('invalid_token', 'id token expired');\n\t\t}\n\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.3.7\n\t\t//# If a nonce value was sent in the Authentication Request, a\n\t\t//# \"nonce\" Claim MUST be present and its value checked to verify\n\t\t//# that it is the same value as the one that was sent in the\n\t\t//# Authentication Request.\n\t\tif (nonce !== null && claims.nonce !== nonce) {\n\t\t\tthrow new OidcError('invalid_token', 'id token nonce mismatch');\n\t\t}\n\t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,CAAC,eAAe,EAAE,kBAAkB,CAAC;IACzD;IACA;IACA;IACA;IACA;IACA;IACA,IAAI,KAAK,KAAK,IAAI,IAAI,MAAM,CAAC,KAAK,KAAK,KAAK,EAAE;MAC7C,MAAM,IAAI,SAAS,CAAC,eAAe,EAAE,yBAAyB,CAAC;IAChE;IACA,OAAO,MAAM;EACd;AACD","ignoreList":[]}
package/keys.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import * as zm from 'zod/mini';
2
+ export declare const APP_KEY_SCOPE_PREFIX = "app_key:";
3
+ export type KeysErrorCode = 'malformed' | 'unsupported' | 'invalid_key' | 'decrypt' | 'missing';
4
+ export declare class KeysError extends Error {
5
+ readonly code: KeysErrorCode;
6
+ constructor(code: KeysErrorCode, message: string);
7
+ }
8
+ declare const recipientJwk: zm.ZodMiniObject<{
9
+ kty: zm.ZodMiniLiteral<"EC">;
10
+ crv: zm.ZodMiniLiteral<"P-256">;
11
+ x: zm.ZodMiniString<string>;
12
+ y: zm.ZodMiniString<string>;
13
+ d: zm.ZodMiniString<string>;
14
+ }, zm.z.core.$strip>;
15
+ export type RecipientJwk = zm.infer<typeof recipientJwk>;
16
+ export interface AppKey {
17
+ scope: string;
18
+ kid: string;
19
+ key: Uint8Array<ArrayBuffer>;
20
+ }
21
+ export declare function checkKeysJwk(keysJwk: string): string;
22
+ export declare function appKeyScope(scopeId: string): string;
23
+ export declare class KeysRecipient {
24
+ #private;
25
+ private constructor();
26
+ static generate(): Promise<KeysRecipient>;
27
+ static fromJwk(jwk: unknown): KeysRecipient;
28
+ toJwk(): RecipientJwk;
29
+ keysJwk(): string;
30
+ decrypt(keysJwe: string): Promise<Uint8Array<ArrayBuffer>>;
31
+ appKeys(keysJwe: string): Promise<Map<string, AppKey>>;
32
+ appKey(keysJwe: string, scope: string): Promise<AppKey>;
33
+ }
34
+ export {};
package/keys.js ADDED
@@ -0,0 +1,313 @@
1
+ import { decodeBase64Url, encodeBase64Url } from '@std/encoding/base64url';
2
+ import * as zm from 'zod/mini';
3
+ const ENCODER = new TextEncoder();
4
+ const DECODER = new TextDecoder();
5
+ const ECDH = {
6
+ name: 'ECDH',
7
+ namedCurve: 'P-256'
8
+ };
9
+ const COORD_BYTES = 32;
10
+ const IV_BYTES = 12;
11
+ const TAG_BYTES = 16;
12
+ const KEY_BYTES = 32;
13
+ export const APP_KEY_SCOPE_PREFIX = 'app_key:';
14
+ export class KeysError extends Error {
15
+ constructor(code, message) {
16
+ super(message);
17
+ this.code = code;
18
+ }
19
+ }
20
+ const recipientJwk = zm.object({
21
+ kty: zm.literal('EC'),
22
+ crv: zm.literal('P-256'),
23
+ x: zm.string(),
24
+ y: zm.string(),
25
+ d: zm.string()
26
+ });
27
+ const publicJwk = zm.strictObject({
28
+ kty: zm.literal('EC'),
29
+ crv: zm.literal('P-256'),
30
+ x: zm.string(),
31
+ y: zm.string()
32
+ });
33
+ const jweHeader = zm.object({
34
+ alg: zm.string(),
35
+ enc: zm.string(),
36
+ epk: zm.optional(zm.object({
37
+ kty: zm.optional(zm.string()),
38
+ crv: zm.optional(zm.string()),
39
+ x: zm.optional(zm.string()),
40
+ y: zm.optional(zm.string())
41
+ }))
42
+ });
43
+
44
+ //= https://www.rfc-editor.org/rfc/rfc7517#section-4
45
+ //# Additional members can be present in the JWK; if not understood by
46
+ //# implementations encountering them, they MUST be ignored.
47
+ const appKeyJwk = zm.object({
48
+ kid: zm.string(),
49
+ k: zm.string()
50
+ });
51
+ const appKeys = zm.record(zm.string(), appKeyJwk);
52
+ function b64(value) {
53
+ try {
54
+ return decodeBase64Url(value);
55
+ } catch {
56
+ throw new KeysError('malformed', 'keys_jwe is not base64url');
57
+ }
58
+ }
59
+ function u32(value) {
60
+ const out = new Uint8Array(4);
61
+ new DataView(out.buffer).setUint32(0, value);
62
+ return out;
63
+ }
64
+ function concat(...parts) {
65
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
66
+ let at = 0;
67
+ for (const part of parts) {
68
+ out.set(part, at);
69
+ at += part.length;
70
+ }
71
+ return out;
72
+ }
73
+
74
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-4.6
75
+ //# In Direct Key Agreement mode, the output of the Concat KDF MUST be a
76
+ //# key of the same length as that used by the "enc" algorithm.
77
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-4.6.2
78
+ //# Key derivation is performed using the Concat KDF, as defined in
79
+ //# Section 5.8.1 of [NIST.800-56A], where the Digest Method is SHA-256.
80
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-4.6.2
81
+ //# In the Direct Key Agreement case,
82
+ //# Data is set to the octets of the ASCII representation of the "enc"
83
+ //# Header Parameter value.
84
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-4.6.2
85
+ //# Otherwise, Datalen is set to 0 and Data is set to
86
+ //# the empty octet sequence.
87
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-4.6.2
88
+ //# This is set to the keydatalen represented as a 32-bit big-endian
89
+ //# integer.
90
+ async function a256gcmKey(shared) {
91
+ const enc = ENCODER.encode('A256GCM');
92
+ const raw = await crypto.subtle.digest('SHA-256', concat(u32(1), shared, u32(enc.length), enc, u32(0), u32(0), u32(KEY_BYTES * 8)));
93
+ return await crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['decrypt']);
94
+ }
95
+
96
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-6.2.1.2
97
+ //# The length of this octet string MUST
98
+ //# be the full size of a coordinate for the curve specified in the "crv"
99
+ //# parameter.
100
+ export function checkKeysJwk(keysJwk) {
101
+ let jwk;
102
+ try {
103
+ jwk = publicJwk.parse(JSON.parse(DECODER.decode(decodeBase64Url(keysJwk))));
104
+ } catch {
105
+ throw new KeysError('invalid_key', 'keys_jwk is not a P-256 public JWK');
106
+ }
107
+ if (keysJwk.includes('=') || b64(jwk.x).length !== COORD_BYTES || b64(jwk.y).length !== COORD_BYTES) {
108
+ throw new KeysError('invalid_key', 'keys_jwk is not a P-256 public JWK');
109
+ }
110
+ return keysJwk;
111
+ }
112
+ export function appKeyScope(scopeId) {
113
+ return `${APP_KEY_SCOPE_PREFIX}${scopeId}`;
114
+ }
115
+ export class KeysRecipient {
116
+ #jwk;
117
+ constructor(jwk) {
118
+ this.#jwk = jwk;
119
+ }
120
+ static async generate() {
121
+ const pair = await crypto.subtle.generateKey(ECDH, true, ['deriveBits']);
122
+ return KeysRecipient.fromJwk(await crypto.subtle.exportKey('jwk', pair.privateKey));
123
+ }
124
+ static fromJwk(jwk) {
125
+ const parsed = recipientJwk.safeParse(jwk);
126
+ if (!parsed.success) {
127
+ throw new KeysError('invalid_key', 'not a P-256 private JWK');
128
+ }
129
+ const {
130
+ kty,
131
+ crv,
132
+ x,
133
+ y,
134
+ d
135
+ } = parsed.data;
136
+ return new KeysRecipient({
137
+ kty,
138
+ crv,
139
+ x,
140
+ y,
141
+ d
142
+ });
143
+ }
144
+ toJwk() {
145
+ return {
146
+ ...this.#jwk
147
+ };
148
+ }
149
+
150
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-6.2.1
151
+ //# The following members MUST be present for all
152
+ //# Elliptic Curve public keys:
153
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-6.2.1
154
+ //# The following member MUST also be present for Elliptic Curve public
155
+ //# keys for the three curves defined in the following section:
156
+ keysJwk() {
157
+ const {
158
+ kty,
159
+ crv,
160
+ x,
161
+ y
162
+ } = this.#jwk;
163
+ return encodeBase64Url(JSON.stringify({
164
+ kty,
165
+ crv,
166
+ x,
167
+ y
168
+ }));
169
+ }
170
+ async decrypt(keysJwe) {
171
+ //= https://www.rfc-editor.org/rfc/rfc7516#section-5.2
172
+ //# When using the JWE Compact
173
+ //# Serialization, the JWE Protected Header, the JWE Encrypted Key, the
174
+ //# JWE Initialization Vector, the JWE Ciphertext, and the JWE
175
+ //# Authentication Tag are represented as base64url-encoded values
176
+ //# in that order, with each value being separated from the next by
177
+ //# a single period ('.') character, resulting in exactly four
178
+ //# delimiting period characters being used.
179
+ const parts = keysJwe.split('.');
180
+ if (parts.length !== 5) {
181
+ throw new KeysError('malformed', 'keys_jwe is not a compact JWE');
182
+ }
183
+ const [headerB64, encryptedKey, ivB64, ciphertextB64, tagB64] = parts;
184
+ //= https://www.rfc-editor.org/rfc/rfc7516#section-5.2
185
+ //# When Direct Key Agreement or Direct Encryption are employed,
186
+ //# verify that the JWE Encrypted Key value is an empty octet
187
+ //# sequence.
188
+ if (encryptedKey !== '') {
189
+ throw new KeysError('unsupported', 'keys_jwe carries an encrypted key');
190
+ }
191
+ //= https://www.rfc-editor.org/rfc/rfc7516#section-5.2
192
+ //# Verify that the octet sequence resulting from decoding the
193
+ //# encoded JWE Protected Header is a UTF-8-encoded representation
194
+ //# of a completely valid JSON object conforming to RFC 7159
195
+ //# [RFC7159]; let the JWE Protected Header be this JSON object.
196
+ let header;
197
+ try {
198
+ header = jweHeader.parse(JSON.parse(DECODER.decode(b64(headerB64))));
199
+ } catch {
200
+ throw new KeysError('malformed', 'keys_jwe has a malformed header');
201
+ }
202
+ //= https://www.rfc-editor.org/rfc/rfc7516#section-4.1.1
203
+ //# The encrypted content
204
+ //# is not usable if the "alg" value does not represent a supported
205
+ //# algorithm, or if the recipient does not have a key that can be used
206
+ //# with that algorithm.
207
+ //= https://www.rfc-editor.org/rfc/rfc7516#section-4.1.2
208
+ //# The encrypted content is not usable if the "enc" value does
209
+ //# not represent a supported algorithm.
210
+ if (header.alg !== 'ECDH-ES' || header.enc !== 'A256GCM') {
211
+ throw new KeysError('unsupported', `keys_jwe uses ${header.alg} with ${header.enc}`);
212
+ }
213
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-4.6.1.1
214
+ //# This
215
+ //# Header Parameter MUST be present and MUST be understood and processed
216
+ //# by implementations when these algorithms are used.
217
+ const epk = header.epk;
218
+ if (epk === undefined || epk.x === undefined || epk.y === undefined) {
219
+ throw new KeysError('malformed', 'keys_jwe has no ephemeral key');
220
+ }
221
+ if (epk.kty !== 'EC' || epk.crv !== 'P-256') {
222
+ throw new KeysError('unsupported', 'keys_jwe ephemeral key is not P-256');
223
+ }
224
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-6.2.1.2
225
+ //# The length of this octet string MUST
226
+ //# be the full size of a coordinate for the curve specified in the "crv"
227
+ //# parameter.
228
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-6.2.1.3
229
+ //# The length of this octet string MUST
230
+ //# be the full size of a coordinate for the curve specified in the "crv"
231
+ //# parameter.
232
+ if (b64(epk.x).length !== COORD_BYTES || b64(epk.y).length !== COORD_BYTES) {
233
+ throw new KeysError('invalid_key', 'keys_jwe ephemeral key is truncated');
234
+ }
235
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-5.3
236
+ //# Use of an IV of size 96 bits is REQUIRED with this algorithm.
237
+ const iv = b64(ivB64);
238
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-5.3
239
+ //# The requested size of the Authentication Tag output MUST be 128 bits,
240
+ //# regardless of the key size.
241
+ const tag = b64(tagB64);
242
+ if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) {
243
+ throw new KeysError('malformed', 'keys_jwe has a bad IV or tag size');
244
+ }
245
+ const ciphertext = b64(ciphertextB64);
246
+ let shared;
247
+ try {
248
+ const [own, peer] = await Promise.all([crypto.subtle.importKey('jwk', this.#jwk, ECDH, false, ['deriveBits']), crypto.subtle.importKey('jwk', {
249
+ kty: 'EC',
250
+ crv: 'P-256',
251
+ x: epk.x,
252
+ y: epk.y
253
+ }, ECDH, false, [])]);
254
+ //= https://www.rfc-editor.org/rfc/rfc7516#section-5.2
255
+ //# When Direct Key Agreement or Key Agreement with Key Wrapping are
256
+ //# employed, use the key agreement algorithm to compute the value
257
+ //# of the agreed upon key. When Direct Key Agreement is employed,
258
+ //# let the CEK be the agreed upon key.
259
+ shared = new Uint8Array(await crypto.subtle.deriveBits({
260
+ name: 'ECDH',
261
+ public: peer
262
+ }, own, COORD_BYTES * 8));
263
+ } catch {
264
+ throw new KeysError('invalid_key', 'keys_jwe key agreement failed');
265
+ }
266
+ try {
267
+ //= https://www.rfc-editor.org/rfc/rfc7516#section-5.2
268
+ //# Let the Additional Authenticated Data encryption parameter be
269
+ //# ASCII(Encoded Protected Header).
270
+ return new Uint8Array(await crypto.subtle.decrypt({
271
+ name: 'AES-GCM',
272
+ iv,
273
+ additionalData: ENCODER.encode(headerB64),
274
+ tagLength: TAG_BYTES * 8
275
+ }, await a256gcmKey(shared), concat(ciphertext, tag)));
276
+ } catch {
277
+ throw new KeysError('decrypt', 'keys_jwe decryption failed');
278
+ }
279
+ }
280
+ async appKeys(keysJwe) {
281
+ const plain = await this.decrypt(keysJwe);
282
+ let keys;
283
+ try {
284
+ keys = appKeys.parse(JSON.parse(DECODER.decode(plain)));
285
+ } catch {
286
+ throw new KeysError('malformed', 'keys_jwe does not hold app keys');
287
+ }
288
+ const out = new Map();
289
+ for (const [scope, jwk] of Object.entries(keys)) {
290
+ //= https://www.rfc-editor.org/rfc/rfc7518#section-6.4.1
291
+ //# It is represented as the base64url
292
+ //# encoding of the octet sequence containing the key value.
293
+ const key = b64(jwk.k);
294
+ if (key.length !== KEY_BYTES) {
295
+ throw new KeysError('malformed', `${scope} is not a 256-bit key`);
296
+ }
297
+ out.set(scope, {
298
+ scope,
299
+ kid: jwk.kid,
300
+ key
301
+ });
302
+ }
303
+ return out;
304
+ }
305
+ async appKey(keysJwe, scope) {
306
+ const key = (await this.appKeys(keysJwe)).get(scope);
307
+ if (key === undefined) {
308
+ throw new KeysError('missing', `keys_jwe has no ${scope}`);
309
+ }
310
+ return key;
311
+ }
312
+ }
313
+ //# sourceMappingURL=keys.js.map
package/keys.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"names":[],"sources":["keys.ts"],"sourcesContent":["import { decodeBase64Url, encodeBase64Url } from '@std/encoding/base64url';\nimport * as zm from 'zod/mini';\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\nconst ECDH: EcKeyImportParams = { name: 'ECDH', namedCurve: 'P-256' };\nconst COORD_BYTES = 32;\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\nconst KEY_BYTES = 32;\n\nexport const APP_KEY_SCOPE_PREFIX = 'app_key:';\n\nexport type KeysErrorCode =\n\t| 'malformed'\n\t| 'unsupported'\n\t| 'invalid_key'\n\t| 'decrypt'\n\t| 'missing';\n\nexport class KeysError extends Error {\n\tconstructor(readonly code: KeysErrorCode, message: string) {\n\t\tsuper(message);\n\t}\n}\n\nconst recipientJwk = zm.object({\n\tkty: zm.literal('EC'),\n\tcrv: zm.literal('P-256'),\n\tx: zm.string(),\n\ty: zm.string(),\n\td: zm.string(),\n});\nexport type RecipientJwk = zm.infer<typeof recipientJwk>;\n\nconst publicJwk = zm.strictObject({\n\tkty: zm.literal('EC'),\n\tcrv: zm.literal('P-256'),\n\tx: zm.string(),\n\ty: zm.string(),\n});\n\nconst jweHeader = zm.object({\n\talg: zm.string(),\n\tenc: zm.string(),\n\tepk: zm.optional(zm.object({\n\t\tkty: zm.optional(zm.string()),\n\t\tcrv: zm.optional(zm.string()),\n\t\tx: zm.optional(zm.string()),\n\t\ty: zm.optional(zm.string()),\n\t})),\n});\n\n//= https://www.rfc-editor.org/rfc/rfc7517#section-4\n//# Additional members can be present in the JWK; if not understood by\n//# implementations encountering them, they MUST be ignored.\nconst appKeyJwk = zm.object({ kid: zm.string(), k: zm.string() });\nconst appKeys = zm.record(zm.string(), appKeyJwk);\n\nexport interface AppKey {\n\tscope: string;\n\tkid: string;\n\tkey: Uint8Array<ArrayBuffer>;\n}\n\nfunction b64(value: string): Uint8Array<ArrayBuffer> {\n\ttry {\n\t\treturn decodeBase64Url(value) as Uint8Array<ArrayBuffer>;\n\t} catch {\n\t\tthrow new KeysError('malformed', 'keys_jwe is not base64url');\n\t}\n}\n\nfunction u32(value: number): Uint8Array<ArrayBuffer> {\n\tconst out = new Uint8Array(4);\n\tnew DataView(out.buffer).setUint32(0, value);\n\treturn out;\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n\tconst out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n\tlet at = 0;\n\tfor (const part of parts) {\n\t\tout.set(part, at);\n\t\tat += part.length;\n\t}\n\treturn out;\n}\n\n//= https://www.rfc-editor.org/rfc/rfc7518#section-4.6\n//# In Direct Key Agreement mode, the output of the Concat KDF MUST be a\n//# key of the same length as that used by the \"enc\" algorithm.\n//= https://www.rfc-editor.org/rfc/rfc7518#section-4.6.2\n//# Key derivation is performed using the Concat KDF, as defined in\n//# Section 5.8.1 of [NIST.800-56A], where the Digest Method is SHA-256.\n//= https://www.rfc-editor.org/rfc/rfc7518#section-4.6.2\n//# In the Direct Key Agreement case,\n//# Data is set to the octets of the ASCII representation of the \"enc\"\n//# Header Parameter value.\n//= https://www.rfc-editor.org/rfc/rfc7518#section-4.6.2\n//# Otherwise, Datalen is set to 0 and Data is set to\n//# the empty octet sequence.\n//= https://www.rfc-editor.org/rfc/rfc7518#section-4.6.2\n//# This is set to the keydatalen represented as a 32-bit big-endian\n//# integer.\nasync function a256gcmKey(shared: Uint8Array): Promise<CryptoKey> {\n\tconst enc = ENCODER.encode('A256GCM');\n\tconst raw = await crypto.subtle.digest(\n\t\t'SHA-256',\n\t\tconcat(\n\t\t\tu32(1),\n\t\t\tshared,\n\t\t\tu32(enc.length),\n\t\t\tenc,\n\t\t\tu32(0),\n\t\t\tu32(0),\n\t\t\tu32(KEY_BYTES * 8),\n\t\t),\n\t);\n\treturn await crypto.subtle.importKey('raw', raw, 'AES-GCM', false, [\n\t\t'decrypt',\n\t]);\n}\n\n//= https://www.rfc-editor.org/rfc/rfc7518#section-6.2.1.2\n//# The length of this octet string MUST\n//# be the full size of a coordinate for the curve specified in the \"crv\"\n//# parameter.\nexport function checkKeysJwk(keysJwk: string): string {\n\tlet jwk;\n\ttry {\n\t\tjwk = publicJwk.parse(JSON.parse(DECODER.decode(decodeBase64Url(keysJwk))));\n\t} catch {\n\t\tthrow new KeysError('invalid_key', 'keys_jwk is not a P-256 public JWK');\n\t}\n\tif (\n\t\tkeysJwk.includes('=') || b64(jwk.x).length !== COORD_BYTES ||\n\t\tb64(jwk.y).length !== COORD_BYTES\n\t) {\n\t\tthrow new KeysError('invalid_key', 'keys_jwk is not a P-256 public JWK');\n\t}\n\treturn keysJwk;\n}\n\nexport function appKeyScope(scopeId: string): string {\n\treturn `${APP_KEY_SCOPE_PREFIX}${scopeId}`;\n}\n\nexport class KeysRecipient {\n\treadonly #jwk: RecipientJwk;\n\n\tprivate constructor(jwk: RecipientJwk) {\n\t\tthis.#jwk = jwk;\n\t}\n\n\tstatic async generate(): Promise<KeysRecipient> {\n\t\tconst pair = await crypto.subtle.generateKey(ECDH, true, ['deriveBits']);\n\t\treturn KeysRecipient.fromJwk(\n\t\t\tawait crypto.subtle.exportKey('jwk', pair.privateKey),\n\t\t);\n\t}\n\n\tstatic fromJwk(jwk: unknown): KeysRecipient {\n\t\tconst parsed = recipientJwk.safeParse(jwk);\n\t\tif (!parsed.success) {\n\t\t\tthrow new KeysError('invalid_key', 'not a P-256 private JWK');\n\t\t}\n\t\tconst { kty, crv, x, y, d } = parsed.data;\n\t\treturn new KeysRecipient({ kty, crv, x, y, d });\n\t}\n\n\ttoJwk(): RecipientJwk {\n\t\treturn { ...this.#jwk };\n\t}\n\n\t//= https://www.rfc-editor.org/rfc/rfc7518#section-6.2.1\n\t//# The following members MUST be present for all\n\t//# Elliptic Curve public keys:\n\t//= https://www.rfc-editor.org/rfc/rfc7518#section-6.2.1\n\t//# The following member MUST also be present for Elliptic Curve public\n\t//# keys for the three curves defined in the following section:\n\tkeysJwk(): string {\n\t\tconst { kty, crv, x, y } = this.#jwk;\n\t\treturn encodeBase64Url(JSON.stringify({ kty, crv, x, y }));\n\t}\n\n\tasync decrypt(keysJwe: string): Promise<Uint8Array<ArrayBuffer>> {\n\t\t//= https://www.rfc-editor.org/rfc/rfc7516#section-5.2\n\t\t//# When using the JWE Compact\n\t\t//# Serialization, the JWE Protected Header, the JWE Encrypted Key, the\n\t\t//# JWE Initialization Vector, the JWE Ciphertext, and the JWE\n\t\t//# Authentication Tag are represented as base64url-encoded values\n\t\t//# in that order, with each value being separated from the next by\n\t\t//# a single period ('.') character, resulting in exactly four\n\t\t//# delimiting period characters being used.\n\t\tconst parts = keysJwe.split('.');\n\t\tif (parts.length !== 5) {\n\t\t\tthrow new KeysError('malformed', 'keys_jwe is not a compact JWE');\n\t\t}\n\t\tconst [headerB64, encryptedKey, ivB64, ciphertextB64, tagB64] = parts;\n\t\t//= https://www.rfc-editor.org/rfc/rfc7516#section-5.2\n\t\t//# When Direct Key Agreement or Direct Encryption are employed,\n\t\t//# verify that the JWE Encrypted Key value is an empty octet\n\t\t//# sequence.\n\t\tif (encryptedKey !== '') {\n\t\t\tthrow new KeysError('unsupported', 'keys_jwe carries an encrypted key');\n\t\t}\n\t\t//= https://www.rfc-editor.org/rfc/rfc7516#section-5.2\n\t\t//# Verify that the octet sequence resulting from decoding the\n\t\t//# encoded JWE Protected Header is a UTF-8-encoded representation\n\t\t//# of a completely valid JSON object conforming to RFC 7159\n\t\t//# [RFC7159]; let the JWE Protected Header be this JSON object.\n\t\tlet header;\n\t\ttry {\n\t\t\theader = jweHeader.parse(JSON.parse(DECODER.decode(b64(headerB64))));\n\t\t} catch {\n\t\t\tthrow new KeysError('malformed', 'keys_jwe has a malformed header');\n\t\t}\n\t\t//= https://www.rfc-editor.org/rfc/rfc7516#section-4.1.1\n\t\t//# The encrypted content\n\t\t//# is not usable if the \"alg\" value does not represent a supported\n\t\t//# algorithm, or if the recipient does not have a key that can be used\n\t\t//# with that algorithm.\n\t\t//= https://www.rfc-editor.org/rfc/rfc7516#section-4.1.2\n\t\t//# The encrypted content is not usable if the \"enc\" value does\n\t\t//# not represent a supported algorithm.\n\t\tif (header.alg !== 'ECDH-ES' || header.enc !== 'A256GCM') {\n\t\t\tthrow new KeysError(\n\t\t\t\t'unsupported',\n\t\t\t\t`keys_jwe uses ${header.alg} with ${header.enc}`,\n\t\t\t);\n\t\t}\n\t\t//= https://www.rfc-editor.org/rfc/rfc7518#section-4.6.1.1\n\t\t//# This\n\t\t//# Header Parameter MUST be present and MUST be understood and processed\n\t\t//# by implementations when these algorithms are used.\n\t\tconst epk = header.epk;\n\t\tif (epk === undefined || epk.x === undefined || epk.y === undefined) {\n\t\t\tthrow new KeysError('malformed', 'keys_jwe has no ephemeral key');\n\t\t}\n\t\tif (epk.kty !== 'EC' || epk.crv !== 'P-256') {\n\t\t\tthrow new KeysError('unsupported', 'keys_jwe ephemeral key is not P-256');\n\t\t}\n\t\t//= https://www.rfc-editor.org/rfc/rfc7518#section-6.2.1.2\n\t\t//# The length of this octet string MUST\n\t\t//# be the full size of a coordinate for the curve specified in the \"crv\"\n\t\t//# parameter.\n\t\t//= https://www.rfc-editor.org/rfc/rfc7518#section-6.2.1.3\n\t\t//# The length of this octet string MUST\n\t\t//# be the full size of a coordinate for the curve specified in the \"crv\"\n\t\t//# parameter.\n\t\tif (\n\t\t\tb64(epk.x).length !== COORD_BYTES || b64(epk.y).length !== COORD_BYTES\n\t\t) {\n\t\t\tthrow new KeysError('invalid_key', 'keys_jwe ephemeral key is truncated');\n\t\t}\n\t\t//= https://www.rfc-editor.org/rfc/rfc7518#section-5.3\n\t\t//# Use of an IV of size 96 bits is REQUIRED with this algorithm.\n\t\tconst iv = b64(ivB64);\n\t\t//= https://www.rfc-editor.org/rfc/rfc7518#section-5.3\n\t\t//# The requested size of the Authentication Tag output MUST be 128 bits,\n\t\t//# regardless of the key size.\n\t\tconst tag = b64(tagB64);\n\t\tif (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) {\n\t\t\tthrow new KeysError('malformed', 'keys_jwe has a bad IV or tag size');\n\t\t}\n\t\tconst ciphertext = b64(ciphertextB64);\n\n\t\tlet shared;\n\t\ttry {\n\t\t\tconst [own, peer] = await Promise.all([\n\t\t\t\tcrypto.subtle.importKey('jwk', this.#jwk, ECDH, false, ['deriveBits']),\n\t\t\t\tcrypto.subtle.importKey(\n\t\t\t\t\t'jwk',\n\t\t\t\t\t{ kty: 'EC', crv: 'P-256', x: epk.x, y: epk.y },\n\t\t\t\t\tECDH,\n\t\t\t\t\tfalse,\n\t\t\t\t\t[],\n\t\t\t\t),\n\t\t\t]);\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc7516#section-5.2\n\t\t\t//# When Direct Key Agreement or Key Agreement with Key Wrapping are\n\t\t\t//# employed, use the key agreement algorithm to compute the value\n\t\t\t//# of the agreed upon key. When Direct Key Agreement is employed,\n\t\t\t//# let the CEK be the agreed upon key.\n\t\t\tshared = new Uint8Array(\n\t\t\t\tawait crypto.subtle.deriveBits(\n\t\t\t\t\t{ name: 'ECDH', public: peer },\n\t\t\t\t\town,\n\t\t\t\t\tCOORD_BYTES * 8,\n\t\t\t\t),\n\t\t\t);\n\t\t} catch {\n\t\t\tthrow new KeysError('invalid_key', 'keys_jwe key agreement failed');\n\t\t}\n\t\ttry {\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc7516#section-5.2\n\t\t\t//# Let the Additional Authenticated Data encryption parameter be\n\t\t\t//# ASCII(Encoded Protected Header).\n\t\t\treturn new Uint8Array(\n\t\t\t\tawait crypto.subtle.decrypt(\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\t\tiv,\n\t\t\t\t\t\tadditionalData: ENCODER.encode(headerB64),\n\t\t\t\t\t\ttagLength: TAG_BYTES * 8,\n\t\t\t\t\t},\n\t\t\t\t\tawait a256gcmKey(shared),\n\t\t\t\t\tconcat(ciphertext, tag),\n\t\t\t\t),\n\t\t\t);\n\t\t} catch {\n\t\t\tthrow new KeysError('decrypt', 'keys_jwe decryption failed');\n\t\t}\n\t}\n\n\tasync appKeys(keysJwe: string): Promise<Map<string, AppKey>> {\n\t\tconst plain = await this.decrypt(keysJwe);\n\t\tlet keys;\n\t\ttry {\n\t\t\tkeys = appKeys.parse(JSON.parse(DECODER.decode(plain)));\n\t\t} catch {\n\t\t\tthrow new KeysError('malformed', 'keys_jwe does not hold app keys');\n\t\t}\n\t\tconst out = new Map<string, AppKey>();\n\t\tfor (const [scope, jwk] of Object.entries(keys)) {\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc7518#section-6.4.1\n\t\t\t//# It is represented as the base64url\n\t\t\t//# encoding of the octet sequence containing the key value.\n\t\t\tconst key = b64(jwk.k);\n\t\t\tif (key.length !== KEY_BYTES) {\n\t\t\t\tthrow new KeysError('malformed', `${scope} is not a 256-bit key`);\n\t\t\t}\n\t\t\tout.set(scope, { scope, kid: jwk.kid, key });\n\t\t}\n\t\treturn out;\n\t}\n\n\tasync appKey(keysJwe: string, scope: string): Promise<AppKey> {\n\t\tconst key = (await this.appKeys(keysJwe)).get(scope);\n\t\tif (key === undefined) {\n\t\t\tthrow new KeysError('missing', `keys_jwe has no ${scope}`);\n\t\t}\n\t\treturn key;\n\t}\n}\n"],"mappings":"AAAA,SAAS,eAAe,EAAE,eAAe,QAAQ,yBAAyB;AAC1E,OAAO,KAAK,EAAE,MAAM,UAAU;AAE9B,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,CAAC;AACjC,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,CAAC;AACjC,MAAM,IAAuB,GAAG;EAAE,IAAI,EAAE,MAAM;EAAE,UAAU,EAAE;AAAQ,CAAC;AACrE,MAAM,WAAW,GAAG,EAAE;AACtB,MAAM,QAAQ,GAAG,EAAE;AACnB,MAAM,SAAS,GAAG,EAAE;AACpB,MAAM,SAAS,GAAG,EAAE;AAEpB,OAAO,MAAM,oBAAoB,GAAG,UAAU;AAS9C,OAAO,MAAM,SAAS,SAAS,KAAK,CAAC;EACpC,WAAW,CAAU,IAAmB,EAAE,OAAe,EAAE;IAC1D,KAAK,CAAC,OAAO,CAAC;IAAC,KADK,IAAmB,GAAnB,IAAmB;EAExC;AACD;AAEA,MAAM,YAAY,GAAG,EAAE,CAAC,MAAM,CAAC;EAC9B,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,I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;IAC3D;IACA,OAAO,GAAG;EACX;AACD","ignoreList":[]}
package/login.d.ts CHANGED
@@ -12,6 +12,9 @@ export interface LoginFlowOpts {
12
12
  startPath: string;
13
13
  ttlMs?: number;
14
14
  }
15
+ export interface LoginStartOpts {
16
+ keysJwk?: string;
17
+ }
15
18
  export interface LoginStart {
16
19
  url: string;
17
20
  cookies: string[];
@@ -20,6 +23,7 @@ export interface LoginFinish {
20
23
  next: string;
21
24
  idToken: string;
22
25
  accessToken: string | null;
26
+ keysJwe: string | null;
23
27
  claims: IdClaims;
24
28
  cookies: string[];
25
29
  }
@@ -30,6 +34,6 @@ export declare class LoginFlow {
30
34
  readonly secure: boolean;
31
35
  constructor(opts: LoginFlowOpts);
32
36
  cookie(name: string, value: string, attrs: string): string;
33
- start(req: Request, next: string): Promise<LoginStart>;
37
+ start(req: Request, next: string, opts?: LoginStartOpts): Promise<LoginStart>;
34
38
  finish(req: Request, url?: URL): Promise<LoginFinish>;
35
39
  }
package/login.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as zm from 'zod/mini';
2
2
  import { OidcError, randomToken } from "./client.js";
3
3
  import { cookie, cookieValue } from "./cookie.js";
4
+ import { checkKeysJwk, KeysError } from "./keys.js";
4
5
  import { parse } from "./parse.js";
5
6
  import { seal, unseal } from "./sealed.js";
6
7
  const loginState = zm.object({
@@ -15,6 +16,10 @@ export class LoginError extends Error {
15
16
  this.status = status;
16
17
  }
17
18
  }
19
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-10.15
20
+ //# The authorization server, authorization endpoint, and client
21
+ //# redirection endpoint can be improperly configured and operate as open
22
+ //# redirectors.
18
23
  export function safeNext(next) {
19
24
  return next && next.startsWith('/') && !next.startsWith('//') && !next.startsWith('/\\') ? next : '/';
20
25
  }
@@ -31,7 +36,7 @@ export class LoginFlow {
31
36
  cookie(name, value, attrs) {
32
37
  return cookie(name, value, attrs, this.secure);
33
38
  }
34
- async start(req, next) {
39
+ async start(req, next, opts = {}) {
35
40
  const target = safeNext(next);
36
41
  if (new URL(req.url).host !== this.#base.host) {
37
42
  const url = new URL(this.opts.startPath, this.#base);
@@ -41,15 +46,52 @@ export class LoginFlow {
41
46
  cookies: []
42
47
  };
43
48
  }
49
+ let keysJwk;
50
+ try {
51
+ keysJwk = opts.keysJwk === undefined ? undefined : checkKeysJwk(opts.keysJwk);
52
+ } catch (e) {
53
+ if (e instanceof KeysError) throw new LoginError(400, e.message);
54
+ throw e;
55
+ }
44
56
  const login = {
57
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-10.12
58
+ //# The binding value used for CSRF
59
+ //# protection MUST contain a non-guessable value (as described in
60
+ //# Section 10.10),
45
61
  state: randomToken(),
62
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.2.1
63
+ //# Sufficient entropy MUST be present in the "nonce" values
64
+ //# used to prevent attackers from guessing values.
65
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-15.5.2
66
+ //# The "nonce" parameter value needs to include per-session state and be
67
+ //# unguessable to attackers.
46
68
  nonce: randomToken(),
69
+ //= https://www.rfc-editor.org/rfc/rfc7636#section-4.1
70
+ //# The client first creates a code verifier, "code_verifier", for each
71
+ //# OAuth 2.0 [RFC6749] Authorization Request, in the following manner:
72
+ //= https://www.rfc-editor.org/rfc/rfc7636#section-4.1
73
+ //# code_verifier = high-entropy cryptographic random STRING using the
74
+ //# unreserved characters [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"
75
+ //# from Section 2.3 of [RFC3986], with a minimum length of 43 characters
76
+ //# and a maximum length of 128 characters.
77
+ //= https://www.rfc-editor.org/rfc/rfc7636#section-7.1
78
+ //# The client SHOULD create a "code_verifier" with a minimum of 256 bits
79
+ //# of entropy.
47
80
  verifier: randomToken(48),
48
81
  next: target
49
82
  };
50
83
  return {
51
- url: await this.opts.client.authorizeUrl(login),
52
- cookies: [this.cookie(this.opts.cookieName, await seal(this.opts.signer, 'oidc-login', login, this.#ttlMs), `Path=/; Max-Age=${Math.floor(this.#ttlMs / 1000)}`)]
84
+ url: await this.opts.client.authorizeUrl({
85
+ ...login,
86
+ keysJwk
87
+ }),
88
+ cookies: [
89
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-10.12
90
+ //# and the user-agent's authenticated state (e.g.,
91
+ //# session cookie, HTML5 local storage) MUST be kept in a location
92
+ //# accessible only to the client and the user-agent (i.e., protected by
93
+ //# same-origin policy).
94
+ this.cookie(this.opts.cookieName, await seal(this.opts.signer, 'oidc-login', login, this.#ttlMs), `Path=/; Max-Age=${Math.floor(this.#ttlMs / 1000)}`)]
53
95
  };
54
96
  }
55
97
  async finish(req, url = new URL(req.url)) {
@@ -63,13 +105,21 @@ export class LoginFlow {
63
105
  if (error !== null) {
64
106
  throw new LoginError(403, params.get('error_description') ?? error);
65
107
  }
108
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2
109
+ //# The client MUST ignore unrecognized response parameters.
66
110
  const code = params.get('code');
111
+ //= https://www.rfc-editor.org/rfc/rfc6749#section-10.12
112
+ //# The client MUST implement CSRF protection for its redirection URI.
113
+ //= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.2.7
114
+ //# When using the Authorization Code Flow, the Client MUST validate the
115
+ //# response according to RFC 6749, especially Sections 4.1.2 and 10.12.
67
116
  if (code === null || params.get('state') !== login.state) {
68
117
  throw new LoginError(400, 'The login response does not match.');
69
118
  }
70
119
  const {
71
120
  idToken,
72
121
  accessToken,
122
+ keysJwe,
73
123
  claims
74
124
  } = await this.opts.client.exchange(code, login).catch(e => {
75
125
  if (e instanceof OidcError) throw new LoginError(403, e.message);
@@ -79,6 +129,7 @@ export class LoginFlow {
79
129
  next: safeNext(login.next),
80
130
  idToken,
81
131
  accessToken,
132
+ keysJwe,
82
133
  claims,
83
134
  cookies: [this.cookie(this.opts.cookieName, '', 'Path=/; Max-Age=0')]
84
135
  };
package/login.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":[],"sources":["login.ts"],"sourcesContent":["import * as zm from 'zod/mini';\nimport {\n\ttype IdClaims,\n\ttype OidcClient,\n\tOidcError,\n\trandomToken,\n} from './client.ts';\nimport { cookie, cookieValue } from './cookie.ts';\nimport { parse } from './parse.ts';\nimport { seal, unseal } from './sealed.ts';\nimport type { TokenSigner } from './signer.ts';\n\nconst loginState = zm.object({\n\tstate: zm.string(),\n\tnonce: zm.string(),\n\tverifier: zm.string(),\n\tnext: zm.string(),\n});\n\nexport class LoginError extends Error {\n\tconstructor(readonly status: number, message: string) {\n\t\tsuper(message);\n\t}\n}\n\nexport interface LoginFlowOpts {\n\tclient: OidcClient;\n\tsigner: TokenSigner<'oidc-login'>;\n\tredirectBase: string;\n\tcookieName: string;\n\tstartPath: string;\n\tttlMs?: number;\n}\n\nexport interface LoginStart {\n\turl: string;\n\tcookies: string[];\n}\n\nexport interface LoginFinish {\n\tnext: string;\n\tidToken: string;\n\taccessToken: string | null;\n\tclaims: IdClaims;\n\tcookies: string[];\n}\n\nexport function safeNext(next: string | null | undefined): string {\n\treturn next && next.startsWith('/') && !next.startsWith('//') &&\n\t\t\t!next.startsWith('/\\\\')\n\t\t? next\n\t\t: '/';\n}\n\nexport class LoginFlow {\n\treadonly secure: boolean;\n\treadonly #base: URL;\n\treadonly #ttlMs: number;\n\n\tconstructor(readonly opts: LoginFlowOpts) {\n\t\tthis.#base = new URL(opts.redirectBase);\n\t\tthis.secure = this.#base.protocol === 'https:';\n\t\tthis.#ttlMs = opts.ttlMs ?? 10 * 60_000;\n\t}\n\n\tcookie(name: string, value: string, attrs: string): string {\n\t\treturn cookie(name, value, attrs, this.secure);\n\t}\n\n\tasync start(req: Request, next: string): Promise<LoginStart> {\n\t\tconst target = safeNext(next);\n\t\tif (new URL(req.url).host !== this.#base.host) {\n\t\t\tconst url = new URL(this.opts.startPath, this.#base);\n\t\t\turl.searchParams.set('next', target);\n\t\t\treturn { url: url.href, cookies: [] };\n\t\t}\n\t\tconst login = {\n\t\t\tstate: randomToken(),\n\t\t\tnonce: randomToken(),\n\t\t\tverifier: randomToken(48),\n\t\t\tnext: target,\n\t\t};\n\t\treturn {\n\t\t\turl: await this.opts.client.authorizeUrl(login),\n\t\t\tcookies: [\n\t\t\t\tthis.cookie(\n\t\t\t\t\tthis.opts.cookieName,\n\t\t\t\t\tawait seal(this.opts.signer, 'oidc-login', login, this.#ttlMs),\n\t\t\t\t\t`Path=/; Max-Age=${Math.floor(this.#ttlMs / 1000)}`,\n\t\t\t\t),\n\t\t\t],\n\t\t};\n\t}\n\n\tasync finish(\n\t\treq: Request,\n\t\turl: URL = new URL(req.url),\n\t): Promise<LoginFinish> {\n\t\tconst raw = await unseal(\n\t\t\tthis.opts.signer,\n\t\t\t'oidc-login',\n\t\t\tcookieValue(req, this.opts.cookieName),\n\t\t);\n\t\tif (raw === null) {\n\t\t\tthrow new LoginError(400, 'The login expired, start it again.');\n\t\t}\n\t\tconst login = parse(raw, loginState);\n\t\tconst params = url.searchParams;\n\t\tconst error = params.get('error');\n\t\tif (error !== null) {\n\t\t\tthrow new LoginError(403, params.get('error_description') ?? error);\n\t\t}\n\t\tconst code = params.get('code');\n\t\tif (code === null || params.get('state') !== login.state) {\n\t\t\tthrow new LoginError(400, 'The login response does not match.');\n\t\t}\n\t\tconst { idToken, accessToken, claims } = await this.opts.client.exchange(\n\t\t\tcode,\n\t\t\tlogin,\n\t\t)\n\t\t\t.catch((e) => {\n\t\t\t\tif (e instanceof OidcError) throw new LoginError(403, e.message);\n\t\t\t\tthrow e;\n\t\t\t});\n\t\treturn {\n\t\t\tnext: safeNext(login.next),\n\t\t\tidToken,\n\t\t\taccessToken,\n\t\t\tclaims,\n\t\t\tcookies: [this.cookie(this.opts.cookieName, '', 'Path=/; Max-Age=0')],\n\t\t};\n\t}\n}\n"],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,UAAU;AAC9B,SAGC,SAAS,EACT,WAAW,QACL,aAAa;AACpB,SAAS,MAAM,EAAE,WAAW,QAAQ,aAAa;AACjD,SAAS,KAAK,QA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names":[],"sources":["login.ts"],"sourcesContent":["import * as zm from 'zod/mini';\nimport {\n\ttype IdClaims,\n\ttype OidcClient,\n\tOidcError,\n\trandomToken,\n} from './client.ts';\nimport { cookie, cookieValue } from './cookie.ts';\nimport { checkKeysJwk, KeysError } from './keys.ts';\nimport { parse } from './parse.ts';\nimport { seal, unseal } from './sealed.ts';\nimport type { TokenSigner } from './signer.ts';\n\nconst loginState = zm.object({\n\tstate: zm.string(),\n\tnonce: zm.string(),\n\tverifier: zm.string(),\n\tnext: zm.string(),\n});\n\nexport class LoginError extends Error {\n\tconstructor(readonly status: number, message: string) {\n\t\tsuper(message);\n\t}\n}\n\nexport interface LoginFlowOpts {\n\tclient: OidcClient;\n\tsigner: TokenSigner<'oidc-login'>;\n\tredirectBase: string;\n\tcookieName: string;\n\tstartPath: string;\n\tttlMs?: number;\n}\n\nexport interface LoginStartOpts {\n\tkeysJwk?: string;\n}\n\nexport interface LoginStart {\n\turl: string;\n\tcookies: string[];\n}\n\nexport interface LoginFinish {\n\tnext: string;\n\tidToken: string;\n\taccessToken: string | null;\n\tkeysJwe: string | null;\n\tclaims: IdClaims;\n\tcookies: string[];\n}\n\n//= https://www.rfc-editor.org/rfc/rfc6749#section-10.15\n//# The authorization server, authorization endpoint, and client\n//# redirection endpoint can be improperly configured and operate as open\n//# redirectors.\nexport function safeNext(next: string | null | undefined): string {\n\treturn next && next.startsWith('/') && !next.startsWith('//') &&\n\t\t\t!next.startsWith('/\\\\')\n\t\t? next\n\t\t: '/';\n}\n\nexport class LoginFlow {\n\treadonly secure: boolean;\n\treadonly #base: URL;\n\treadonly #ttlMs: number;\n\n\tconstructor(readonly opts: LoginFlowOpts) {\n\t\tthis.#base = new URL(opts.redirectBase);\n\t\tthis.secure = this.#base.protocol === 'https:';\n\t\tthis.#ttlMs = opts.ttlMs ?? 10 * 60_000;\n\t}\n\n\tcookie(name: string, value: string, attrs: string): string {\n\t\treturn cookie(name, value, attrs, this.secure);\n\t}\n\n\tasync start(\n\t\treq: Request,\n\t\tnext: string,\n\t\topts: LoginStartOpts = {},\n\t): Promise<LoginStart> {\n\t\tconst target = safeNext(next);\n\t\tif (new URL(req.url).host !== this.#base.host) {\n\t\t\tconst url = new URL(this.opts.startPath, this.#base);\n\t\t\turl.searchParams.set('next', target);\n\t\t\treturn { url: url.href, cookies: [] };\n\t\t}\n\t\tlet keysJwk;\n\t\ttry {\n\t\t\tkeysJwk = opts.keysJwk === undefined\n\t\t\t\t? undefined\n\t\t\t\t: checkKeysJwk(opts.keysJwk);\n\t\t} catch (e) {\n\t\t\tif (e instanceof KeysError) throw new LoginError(400, e.message);\n\t\t\tthrow e;\n\t\t}\n\t\tconst login = {\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-10.12\n\t\t\t//# The binding value used for CSRF\n\t\t\t//# protection MUST contain a non-guessable value (as described in\n\t\t\t//# Section 10.10),\n\t\t\tstate: randomToken(),\n\t\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.2.1\n\t\t\t//# Sufficient entropy MUST be present in the \"nonce\" values\n\t\t\t//# used to prevent attackers from guessing values.\n\t\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-15.5.2\n\t\t\t//# The \"nonce\" parameter value needs to include per-session state and be\n\t\t\t//# unguessable to attackers.\n\t\t\tnonce: randomToken(),\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc7636#section-4.1\n\t\t\t//# The client first creates a code verifier, \"code_verifier\", for each\n\t\t\t//# OAuth 2.0 [RFC6749] Authorization Request, in the following manner:\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc7636#section-4.1\n\t\t\t//# code_verifier = high-entropy cryptographic random STRING using the\n\t\t\t//# unreserved characters [A-Z] / [a-z] / [0-9] / \"-\" / \".\" / \"_\" / \"~\"\n\t\t\t//# from Section 2.3 of [RFC3986], with a minimum length of 43 characters\n\t\t\t//# and a maximum length of 128 characters.\n\t\t\t//= https://www.rfc-editor.org/rfc/rfc7636#section-7.1\n\t\t\t//# The client SHOULD create a \"code_verifier\" with a minimum of 256 bits\n\t\t\t//# of entropy.\n\t\t\tverifier: randomToken(48),\n\t\t\tnext: target,\n\t\t};\n\t\treturn {\n\t\t\turl: await this.opts.client.authorizeUrl({\n\t\t\t\t...login,\n\t\t\t\tkeysJwk,\n\t\t\t}),\n\t\t\tcookies: [\n\t\t\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-10.12\n\t\t\t\t//# and the user-agent's authenticated state (e.g.,\n\t\t\t\t//# session cookie, HTML5 local storage) MUST be kept in a location\n\t\t\t\t//# accessible only to the client and the user-agent (i.e., protected by\n\t\t\t\t//# same-origin policy).\n\t\t\t\tthis.cookie(\n\t\t\t\t\tthis.opts.cookieName,\n\t\t\t\t\tawait seal(this.opts.signer, 'oidc-login', login, this.#ttlMs),\n\t\t\t\t\t`Path=/; Max-Age=${Math.floor(this.#ttlMs / 1000)}`,\n\t\t\t\t),\n\t\t\t],\n\t\t};\n\t}\n\n\tasync finish(\n\t\treq: Request,\n\t\turl: URL = new URL(req.url),\n\t): Promise<LoginFinish> {\n\t\tconst raw = await unseal(\n\t\t\tthis.opts.signer,\n\t\t\t'oidc-login',\n\t\t\tcookieValue(req, this.opts.cookieName),\n\t\t);\n\t\tif (raw === null) {\n\t\t\tthrow new LoginError(400, 'The login expired, start it again.');\n\t\t}\n\t\tconst login = parse(raw, loginState);\n\t\tconst params = url.searchParams;\n\t\tconst error = params.get('error');\n\t\tif (error !== null) {\n\t\t\tthrow new LoginError(403, params.get('error_description') ?? error);\n\t\t}\n\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2\n\t\t//# The client MUST ignore unrecognized response parameters.\n\t\tconst code = params.get('code');\n\t\t//= https://www.rfc-editor.org/rfc/rfc6749#section-10.12\n\t\t//# The client MUST implement CSRF protection for its redirection URI.\n\t\t//= https://openid.net/specs/openid-connect-core-1_0.txt#section-3.1.2.7\n\t\t//# When using the Authorization Code Flow, the Client MUST validate the\n\t\t//# response according to RFC 6749, especially Sections 4.1.2 and 10.12.\n\t\tif (code === null || params.get('state') !== login.state) {\n\t\t\tthrow new LoginError(400, 'The login response does not match.');\n\t\t}\n\t\tconst { idToken, accessToken, keysJwe, claims } = await this.opts.client\n\t\t\t.exchange(code, login)\n\t\t\t.catch((e) => {\n\t\t\t\tif (e instanceof OidcError) throw new LoginError(403, e.message);\n\t\t\t\tthrow e;\n\t\t\t});\n\t\treturn {\n\t\t\tnext: safeNext(login.next),\n\t\t\tidToken,\n\t\t\taccessToken,\n\t\t\tkeysJwe,\n\t\t\tclaims,\n\t\t\tcookies: [this.cookie(this.opts.cookieName, '', 'Path=/; Max-Age=0')],\n\t\t};\n\t}\n}\n"],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,UAAU;AAC9B,SAGC,SAAS,EACT,WAAW,QACL,aAAa;AACpB,SAAS,MAAM,EAAE,WAAW,QAAQ,aAAa;AACjD,SAAS,YAAY,EAAE,SAAS,QAAQ,WAAW;AACnD,SAAS,KAAK,QAAQ,YAAY;AAClC,SAAS,IAAI,EAAE,MAAM,QAAQ,aAAa;AAG1C,MAAM,UAAU,GAAG,EAAE,CAAC,MAAM,CAAC;EAC5B,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;EAClB,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;EAClB,QAAQ,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;EACrB,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC;AACjB,CAAC,CAAC;AAEF,OAAO,MAAM,UAAU,SAAS,KAAK,CAAC;EACrC,WAAW,CAAU,MAAc,EAAE,OAAe,EAAE;IACrD,KAAK,CAAC,OAAO,CAAC;IAAC,KADK,MAAc,GAAd,MAAc;EAEnC;AACD;AA6BA;AACA;AACA;AACA;AACA,OAAO,SAAS,QAAQ,CAAC,IAA+B,EAAU;EACjE,OAAO,IAAI,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CA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cookie.js";
4
+ export * from "./keys.js";
4
5
  export * from "./login.js";
5
6
  export * from "./sealed.js";
6
7
  export * from "./signer.js";
package/mod.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from "./backend.js";
2
2
  export * from "./client.js";
3
3
  export * from "./cookie.js";
4
+ export * from "./keys.js";
4
5
  export * from "./login.js";
5
6
  export * from "./sealed.js";
6
7
  export * from "./signer.js";
package/mod.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":[],"sources":["mod.ts"],"sourcesContent":["export * from './backend.ts';\nexport * from './client.ts';\nexport * from './cookie.ts';\nexport * from './login.ts';\nexport * from './sealed.ts';\nexport * from './signer.ts';\n"],"mappings":"AAAA,cAAc,cAAc;AAC5B,cAAc,aAAa;AAC3B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,aAAa","ignoreList":[]}
1
+ {"version":3,"names":[],"sources":["mod.ts"],"sourcesContent":["export * from './backend.ts';\nexport * from './client.ts';\nexport * from './cookie.ts';\nexport * from './keys.ts';\nexport * from './login.ts';\nexport * from './sealed.ts';\nexport * from './signer.ts';\n"],"mappings":"AAAA,cAAc,cAAc;AAC5B,cAAc,aAAa;AAC3B,cAAc,aAAa;AAC3B,cAAc,WAAW;AACzB,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,aAAa","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deltarocks/pykrete-oidc",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "OpenID Connect relying party for pykrete",
5
5
  "type": "module",
6
6
  "exports": {
@@ -20,6 +20,10 @@
20
20
  "types": "./cookie.d.ts",
21
21
  "default": "./cookie.js"
22
22
  },
23
+ "./keys": {
24
+ "types": "./keys.d.ts",
25
+ "default": "./keys.js"
26
+ },
23
27
  "./login": {
24
28
  "types": "./login.d.ts",
25
29
  "default": "./login.js"
@@ -48,6 +52,9 @@
48
52
  "cookie.d.ts",
49
53
  "cookie.js",
50
54
  "cookie.js.map",
55
+ "keys.d.ts",
56
+ "keys.js",
57
+ "keys.js.map",
51
58
  "login.d.ts",
52
59
  "login.js",
53
60
  "login.js.map",