@pod-os/elements 0.32.0 → 0.32.1-rc.494c386.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2044 @@
1
+ var crypto$1 = crypto;
2
+ const isCryptoKey = (key) => key instanceof CryptoKey;
3
+
4
+ const digest = async (algorithm, data) => {
5
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
6
+ return new Uint8Array(await crypto$1.subtle.digest(subtleDigest, data));
7
+ };
8
+ var digest$1 = digest;
9
+
10
+ const encoder = new TextEncoder();
11
+ const decoder = new TextDecoder();
12
+ function concat(...buffers) {
13
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
14
+ const buf = new Uint8Array(size);
15
+ let i = 0;
16
+ for (const buffer of buffers) {
17
+ buf.set(buffer, i);
18
+ i += buffer.length;
19
+ }
20
+ return buf;
21
+ }
22
+
23
+ const encodeBase64 = (input) => {
24
+ let unencoded = input;
25
+ if (typeof unencoded === 'string') {
26
+ unencoded = encoder.encode(unencoded);
27
+ }
28
+ const CHUNK_SIZE = 0x8000;
29
+ const arr = [];
30
+ for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {
31
+ arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));
32
+ }
33
+ return btoa(arr.join(''));
34
+ };
35
+ const encode = (input) => {
36
+ return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
37
+ };
38
+ const decodeBase64 = (encoded) => {
39
+ const binary = atob(encoded);
40
+ const bytes = new Uint8Array(binary.length);
41
+ for (let i = 0; i < binary.length; i++) {
42
+ bytes[i] = binary.charCodeAt(i);
43
+ }
44
+ return bytes;
45
+ };
46
+ const decode$1 = (input) => {
47
+ let encoded = input;
48
+ if (encoded instanceof Uint8Array) {
49
+ encoded = decoder.decode(encoded);
50
+ }
51
+ encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
52
+ try {
53
+ return decodeBase64(encoded);
54
+ }
55
+ catch {
56
+ throw new TypeError('The input to be decoded is not correctly encoded.');
57
+ }
58
+ };
59
+
60
+ class JOSEError extends Error {
61
+ constructor(message, options) {
62
+ super(message, options);
63
+ this.code = 'ERR_JOSE_GENERIC';
64
+ this.name = this.constructor.name;
65
+ Error.captureStackTrace?.(this, this.constructor);
66
+ }
67
+ }
68
+ JOSEError.code = 'ERR_JOSE_GENERIC';
69
+ class JWTClaimValidationFailed extends JOSEError {
70
+ constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {
71
+ super(message, { cause: { claim, reason, payload } });
72
+ this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
73
+ this.claim = claim;
74
+ this.reason = reason;
75
+ this.payload = payload;
76
+ }
77
+ }
78
+ JWTClaimValidationFailed.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
79
+ class JWTExpired extends JOSEError {
80
+ constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {
81
+ super(message, { cause: { claim, reason, payload } });
82
+ this.code = 'ERR_JWT_EXPIRED';
83
+ this.claim = claim;
84
+ this.reason = reason;
85
+ this.payload = payload;
86
+ }
87
+ }
88
+ JWTExpired.code = 'ERR_JWT_EXPIRED';
89
+ class JOSEAlgNotAllowed extends JOSEError {
90
+ constructor() {
91
+ super(...arguments);
92
+ this.code = 'ERR_JOSE_ALG_NOT_ALLOWED';
93
+ }
94
+ }
95
+ JOSEAlgNotAllowed.code = 'ERR_JOSE_ALG_NOT_ALLOWED';
96
+ class JOSENotSupported extends JOSEError {
97
+ constructor() {
98
+ super(...arguments);
99
+ this.code = 'ERR_JOSE_NOT_SUPPORTED';
100
+ }
101
+ }
102
+ JOSENotSupported.code = 'ERR_JOSE_NOT_SUPPORTED';
103
+ class JWEDecryptionFailed extends JOSEError {
104
+ constructor(message = 'decryption operation failed', options) {
105
+ super(message, options);
106
+ this.code = 'ERR_JWE_DECRYPTION_FAILED';
107
+ }
108
+ }
109
+ JWEDecryptionFailed.code = 'ERR_JWE_DECRYPTION_FAILED';
110
+ class JWEInvalid extends JOSEError {
111
+ constructor() {
112
+ super(...arguments);
113
+ this.code = 'ERR_JWE_INVALID';
114
+ }
115
+ }
116
+ JWEInvalid.code = 'ERR_JWE_INVALID';
117
+ class JWSInvalid extends JOSEError {
118
+ constructor() {
119
+ super(...arguments);
120
+ this.code = 'ERR_JWS_INVALID';
121
+ }
122
+ }
123
+ JWSInvalid.code = 'ERR_JWS_INVALID';
124
+ class JWTInvalid extends JOSEError {
125
+ constructor() {
126
+ super(...arguments);
127
+ this.code = 'ERR_JWT_INVALID';
128
+ }
129
+ }
130
+ JWTInvalid.code = 'ERR_JWT_INVALID';
131
+ class JWKInvalid extends JOSEError {
132
+ constructor() {
133
+ super(...arguments);
134
+ this.code = 'ERR_JWK_INVALID';
135
+ }
136
+ }
137
+ JWKInvalid.code = 'ERR_JWK_INVALID';
138
+ class JWKSInvalid extends JOSEError {
139
+ constructor() {
140
+ super(...arguments);
141
+ this.code = 'ERR_JWKS_INVALID';
142
+ }
143
+ }
144
+ JWKSInvalid.code = 'ERR_JWKS_INVALID';
145
+ class JWKSNoMatchingKey extends JOSEError {
146
+ constructor(message = 'no applicable key found in the JSON Web Key Set', options) {
147
+ super(message, options);
148
+ this.code = 'ERR_JWKS_NO_MATCHING_KEY';
149
+ }
150
+ }
151
+ JWKSNoMatchingKey.code = 'ERR_JWKS_NO_MATCHING_KEY';
152
+ class JWKSMultipleMatchingKeys extends JOSEError {
153
+ constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {
154
+ super(message, options);
155
+ this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
156
+ }
157
+ }
158
+ JWKSMultipleMatchingKeys.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
159
+ class JWKSTimeout extends JOSEError {
160
+ constructor(message = 'request timed out', options) {
161
+ super(message, options);
162
+ this.code = 'ERR_JWKS_TIMEOUT';
163
+ }
164
+ }
165
+ JWKSTimeout.code = 'ERR_JWKS_TIMEOUT';
166
+ class JWSSignatureVerificationFailed extends JOSEError {
167
+ constructor(message = 'signature verification failed', options) {
168
+ super(message, options);
169
+ this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
170
+ }
171
+ }
172
+ JWSSignatureVerificationFailed.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
173
+
174
+ function unusable(name, prop = 'algorithm.name') {
175
+ return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
176
+ }
177
+ function isAlgorithm(algorithm, name) {
178
+ return algorithm.name === name;
179
+ }
180
+ function getHashLength(hash) {
181
+ return parseInt(hash.name.slice(4), 10);
182
+ }
183
+ function getNamedCurve(alg) {
184
+ switch (alg) {
185
+ case 'ES256':
186
+ return 'P-256';
187
+ case 'ES384':
188
+ return 'P-384';
189
+ case 'ES512':
190
+ return 'P-521';
191
+ default:
192
+ throw new Error('unreachable');
193
+ }
194
+ }
195
+ function checkUsage(key, usages) {
196
+ if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {
197
+ let msg = 'CryptoKey does not support this operation, its usages must include ';
198
+ if (usages.length > 2) {
199
+ const last = usages.pop();
200
+ msg += `one of ${usages.join(', ')}, or ${last}.`;
201
+ }
202
+ else if (usages.length === 2) {
203
+ msg += `one of ${usages[0]} or ${usages[1]}.`;
204
+ }
205
+ else {
206
+ msg += `${usages[0]}.`;
207
+ }
208
+ throw new TypeError(msg);
209
+ }
210
+ }
211
+ function checkSigCryptoKey(key, alg, ...usages) {
212
+ switch (alg) {
213
+ case 'HS256':
214
+ case 'HS384':
215
+ case 'HS512': {
216
+ if (!isAlgorithm(key.algorithm, 'HMAC'))
217
+ throw unusable('HMAC');
218
+ const expected = parseInt(alg.slice(2), 10);
219
+ const actual = getHashLength(key.algorithm.hash);
220
+ if (actual !== expected)
221
+ throw unusable(`SHA-${expected}`, 'algorithm.hash');
222
+ break;
223
+ }
224
+ case 'RS256':
225
+ case 'RS384':
226
+ case 'RS512': {
227
+ if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))
228
+ throw unusable('RSASSA-PKCS1-v1_5');
229
+ const expected = parseInt(alg.slice(2), 10);
230
+ const actual = getHashLength(key.algorithm.hash);
231
+ if (actual !== expected)
232
+ throw unusable(`SHA-${expected}`, 'algorithm.hash');
233
+ break;
234
+ }
235
+ case 'PS256':
236
+ case 'PS384':
237
+ case 'PS512': {
238
+ if (!isAlgorithm(key.algorithm, 'RSA-PSS'))
239
+ throw unusable('RSA-PSS');
240
+ const expected = parseInt(alg.slice(2), 10);
241
+ const actual = getHashLength(key.algorithm.hash);
242
+ if (actual !== expected)
243
+ throw unusable(`SHA-${expected}`, 'algorithm.hash');
244
+ break;
245
+ }
246
+ case 'EdDSA': {
247
+ if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {
248
+ throw unusable('Ed25519 or Ed448');
249
+ }
250
+ break;
251
+ }
252
+ case 'Ed25519': {
253
+ if (!isAlgorithm(key.algorithm, 'Ed25519'))
254
+ throw unusable('Ed25519');
255
+ break;
256
+ }
257
+ case 'ES256':
258
+ case 'ES384':
259
+ case 'ES512': {
260
+ if (!isAlgorithm(key.algorithm, 'ECDSA'))
261
+ throw unusable('ECDSA');
262
+ const expected = getNamedCurve(alg);
263
+ const actual = key.algorithm.namedCurve;
264
+ if (actual !== expected)
265
+ throw unusable(expected, 'algorithm.namedCurve');
266
+ break;
267
+ }
268
+ default:
269
+ throw new TypeError('CryptoKey does not support this operation');
270
+ }
271
+ checkUsage(key, usages);
272
+ }
273
+
274
+ function message(msg, actual, ...types) {
275
+ types = types.filter(Boolean);
276
+ if (types.length > 2) {
277
+ const last = types.pop();
278
+ msg += `one of type ${types.join(', ')}, or ${last}.`;
279
+ }
280
+ else if (types.length === 2) {
281
+ msg += `one of type ${types[0]} or ${types[1]}.`;
282
+ }
283
+ else {
284
+ msg += `of type ${types[0]}.`;
285
+ }
286
+ if (actual == null) {
287
+ msg += ` Received ${actual}`;
288
+ }
289
+ else if (typeof actual === 'function' && actual.name) {
290
+ msg += ` Received function ${actual.name}`;
291
+ }
292
+ else if (typeof actual === 'object' && actual != null) {
293
+ if (actual.constructor?.name) {
294
+ msg += ` Received an instance of ${actual.constructor.name}`;
295
+ }
296
+ }
297
+ return msg;
298
+ }
299
+ var invalidKeyInput = (actual, ...types) => {
300
+ return message('Key must be ', actual, ...types);
301
+ };
302
+ function withAlg(alg, actual, ...types) {
303
+ return message(`Key for the ${alg} algorithm must be `, actual, ...types);
304
+ }
305
+
306
+ var isKeyLike = (key) => {
307
+ if (isCryptoKey(key)) {
308
+ return true;
309
+ }
310
+ return key?.[Symbol.toStringTag] === 'KeyObject';
311
+ };
312
+ const types = ['CryptoKey'];
313
+
314
+ const isDisjoint = (...headers) => {
315
+ const sources = headers.filter(Boolean);
316
+ if (sources.length === 0 || sources.length === 1) {
317
+ return true;
318
+ }
319
+ let acc;
320
+ for (const header of sources) {
321
+ const parameters = Object.keys(header);
322
+ if (!acc || acc.size === 0) {
323
+ acc = new Set(parameters);
324
+ continue;
325
+ }
326
+ for (const parameter of parameters) {
327
+ if (acc.has(parameter)) {
328
+ return false;
329
+ }
330
+ acc.add(parameter);
331
+ }
332
+ }
333
+ return true;
334
+ };
335
+ var isDisjoint$1 = isDisjoint;
336
+
337
+ function isObjectLike(value) {
338
+ return typeof value === 'object' && value !== null;
339
+ }
340
+ function isObject(input) {
341
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {
342
+ return false;
343
+ }
344
+ if (Object.getPrototypeOf(input) === null) {
345
+ return true;
346
+ }
347
+ let proto = input;
348
+ while (Object.getPrototypeOf(proto) !== null) {
349
+ proto = Object.getPrototypeOf(proto);
350
+ }
351
+ return Object.getPrototypeOf(input) === proto;
352
+ }
353
+
354
+ var checkKeyLength = (alg, key) => {
355
+ if (alg.startsWith('RS') || alg.startsWith('PS')) {
356
+ const { modulusLength } = key.algorithm;
357
+ if (typeof modulusLength !== 'number' || modulusLength < 2048) {
358
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
359
+ }
360
+ }
361
+ };
362
+
363
+ function isJWK(key) {
364
+ return isObject(key) && typeof key.kty === 'string';
365
+ }
366
+ function isPrivateJWK(key) {
367
+ return key.kty !== 'oct' && typeof key.d === 'string';
368
+ }
369
+ function isPublicJWK(key) {
370
+ return key.kty !== 'oct' && typeof key.d === 'undefined';
371
+ }
372
+ function isSecretJWK(key) {
373
+ return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string';
374
+ }
375
+
376
+ function subtleMapping(jwk) {
377
+ let algorithm;
378
+ let keyUsages;
379
+ switch (jwk.kty) {
380
+ case 'RSA': {
381
+ switch (jwk.alg) {
382
+ case 'PS256':
383
+ case 'PS384':
384
+ case 'PS512':
385
+ algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };
386
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
387
+ break;
388
+ case 'RS256':
389
+ case 'RS384':
390
+ case 'RS512':
391
+ algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };
392
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
393
+ break;
394
+ case 'RSA-OAEP':
395
+ case 'RSA-OAEP-256':
396
+ case 'RSA-OAEP-384':
397
+ case 'RSA-OAEP-512':
398
+ algorithm = {
399
+ name: 'RSA-OAEP',
400
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,
401
+ };
402
+ keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];
403
+ break;
404
+ default:
405
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
406
+ }
407
+ break;
408
+ }
409
+ case 'EC': {
410
+ switch (jwk.alg) {
411
+ case 'ES256':
412
+ algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
413
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
414
+ break;
415
+ case 'ES384':
416
+ algorithm = { name: 'ECDSA', namedCurve: 'P-384' };
417
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
418
+ break;
419
+ case 'ES512':
420
+ algorithm = { name: 'ECDSA', namedCurve: 'P-521' };
421
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
422
+ break;
423
+ case 'ECDH-ES':
424
+ case 'ECDH-ES+A128KW':
425
+ case 'ECDH-ES+A192KW':
426
+ case 'ECDH-ES+A256KW':
427
+ algorithm = { name: 'ECDH', namedCurve: jwk.crv };
428
+ keyUsages = jwk.d ? ['deriveBits'] : [];
429
+ break;
430
+ default:
431
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
432
+ }
433
+ break;
434
+ }
435
+ case 'OKP': {
436
+ switch (jwk.alg) {
437
+ case 'Ed25519':
438
+ algorithm = { name: 'Ed25519' };
439
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
440
+ break;
441
+ case 'EdDSA':
442
+ algorithm = { name: jwk.crv };
443
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
444
+ break;
445
+ case 'ECDH-ES':
446
+ case 'ECDH-ES+A128KW':
447
+ case 'ECDH-ES+A192KW':
448
+ case 'ECDH-ES+A256KW':
449
+ algorithm = { name: jwk.crv };
450
+ keyUsages = jwk.d ? ['deriveBits'] : [];
451
+ break;
452
+ default:
453
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
454
+ }
455
+ break;
456
+ }
457
+ default:
458
+ throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
459
+ }
460
+ return { algorithm, keyUsages };
461
+ }
462
+ const parse = async (jwk) => {
463
+ if (!jwk.alg) {
464
+ throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
465
+ }
466
+ const { algorithm, keyUsages } = subtleMapping(jwk);
467
+ const rest = [
468
+ algorithm,
469
+ jwk.ext ?? false,
470
+ jwk.key_ops ?? keyUsages,
471
+ ];
472
+ const keyData = { ...jwk };
473
+ delete keyData.alg;
474
+ delete keyData.use;
475
+ return crypto$1.subtle.importKey('jwk', keyData, ...rest);
476
+ };
477
+ var asKeyObject = parse;
478
+
479
+ const exportKeyValue = (k) => decode$1(k);
480
+ let privCache;
481
+ let pubCache;
482
+ const isKeyObject = (key) => {
483
+ return key?.[Symbol.toStringTag] === 'KeyObject';
484
+ };
485
+ const importAndCache = async (cache, key, jwk, alg, freeze = false) => {
486
+ let cached = cache.get(key);
487
+ if (cached?.[alg]) {
488
+ return cached[alg];
489
+ }
490
+ const cryptoKey = await asKeyObject({ ...jwk, alg });
491
+ if (freeze)
492
+ Object.freeze(key);
493
+ if (!cached) {
494
+ cache.set(key, { [alg]: cryptoKey });
495
+ }
496
+ else {
497
+ cached[alg] = cryptoKey;
498
+ }
499
+ return cryptoKey;
500
+ };
501
+ const normalizePublicKey = (key, alg) => {
502
+ if (isKeyObject(key)) {
503
+ let jwk = key.export({ format: 'jwk' });
504
+ delete jwk.d;
505
+ delete jwk.dp;
506
+ delete jwk.dq;
507
+ delete jwk.p;
508
+ delete jwk.q;
509
+ delete jwk.qi;
510
+ if (jwk.k) {
511
+ return exportKeyValue(jwk.k);
512
+ }
513
+ pubCache || (pubCache = new WeakMap());
514
+ return importAndCache(pubCache, key, jwk, alg);
515
+ }
516
+ if (isJWK(key)) {
517
+ if (key.k)
518
+ return decode$1(key.k);
519
+ pubCache || (pubCache = new WeakMap());
520
+ const cryptoKey = importAndCache(pubCache, key, key, alg, true);
521
+ return cryptoKey;
522
+ }
523
+ return key;
524
+ };
525
+ const normalizePrivateKey = (key, alg) => {
526
+ if (isKeyObject(key)) {
527
+ let jwk = key.export({ format: 'jwk' });
528
+ if (jwk.k) {
529
+ return exportKeyValue(jwk.k);
530
+ }
531
+ privCache || (privCache = new WeakMap());
532
+ return importAndCache(privCache, key, jwk, alg);
533
+ }
534
+ if (isJWK(key)) {
535
+ if (key.k)
536
+ return decode$1(key.k);
537
+ privCache || (privCache = new WeakMap());
538
+ const cryptoKey = importAndCache(privCache, key, key, alg, true);
539
+ return cryptoKey;
540
+ }
541
+ return key;
542
+ };
543
+ var normalize = { normalizePublicKey, normalizePrivateKey };
544
+
545
+ async function importJWK(jwk, alg) {
546
+ if (!isObject(jwk)) {
547
+ throw new TypeError('JWK must be an object');
548
+ }
549
+ alg || (alg = jwk.alg);
550
+ switch (jwk.kty) {
551
+ case 'oct':
552
+ if (typeof jwk.k !== 'string' || !jwk.k) {
553
+ throw new TypeError('missing "k" (Key Value) Parameter value');
554
+ }
555
+ return decode$1(jwk.k);
556
+ case 'RSA':
557
+ if ('oth' in jwk && jwk.oth !== undefined) {
558
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
559
+ }
560
+ case 'EC':
561
+ case 'OKP':
562
+ return asKeyObject({ ...jwk, alg });
563
+ default:
564
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
565
+ }
566
+ }
567
+
568
+ const tag = (key) => key?.[Symbol.toStringTag];
569
+ const jwkMatchesOp = (alg, key, usage) => {
570
+ if (key.use !== undefined && key.use !== 'sig') {
571
+ throw new TypeError('Invalid key for this operation, when present its use must be sig');
572
+ }
573
+ if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) {
574
+ throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`);
575
+ }
576
+ if (key.alg !== undefined && key.alg !== alg) {
577
+ throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`);
578
+ }
579
+ return true;
580
+ };
581
+ const symmetricTypeCheck = (alg, key, usage, allowJwk) => {
582
+ if (key instanceof Uint8Array)
583
+ return;
584
+ if (allowJwk && isJWK(key)) {
585
+ if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
586
+ return;
587
+ throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
588
+ }
589
+ if (!isKeyLike(key)) {
590
+ throw new TypeError(withAlg(alg, key, ...types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null));
591
+ }
592
+ if (key.type !== 'secret') {
593
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
594
+ }
595
+ };
596
+ const asymmetricTypeCheck = (alg, key, usage, allowJwk) => {
597
+ if (allowJwk && isJWK(key)) {
598
+ switch (usage) {
599
+ case 'sign':
600
+ if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
601
+ return;
602
+ throw new TypeError(`JSON Web Key for this operation be a private JWK`);
603
+ case 'verify':
604
+ if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
605
+ return;
606
+ throw new TypeError(`JSON Web Key for this operation be a public JWK`);
607
+ }
608
+ }
609
+ if (!isKeyLike(key)) {
610
+ throw new TypeError(withAlg(alg, key, ...types, allowJwk ? 'JSON Web Key' : null));
611
+ }
612
+ if (key.type === 'secret') {
613
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
614
+ }
615
+ if (usage === 'sign' && key.type === 'public') {
616
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
617
+ }
618
+ if (usage === 'decrypt' && key.type === 'public') {
619
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
620
+ }
621
+ if (key.algorithm && usage === 'verify' && key.type === 'private') {
622
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
623
+ }
624
+ if (key.algorithm && usage === 'encrypt' && key.type === 'private') {
625
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
626
+ }
627
+ };
628
+ function checkKeyType(allowJwk, alg, key, usage) {
629
+ const symmetric = alg.startsWith('HS') ||
630
+ alg === 'dir' ||
631
+ alg.startsWith('PBES2') ||
632
+ /^A\d{3}(?:GCM)?KW$/.test(alg);
633
+ if (symmetric) {
634
+ symmetricTypeCheck(alg, key, usage, allowJwk);
635
+ }
636
+ else {
637
+ asymmetricTypeCheck(alg, key, usage, allowJwk);
638
+ }
639
+ }
640
+ checkKeyType.bind(undefined, false);
641
+ const checkKeyTypeWithJwk = checkKeyType.bind(undefined, true);
642
+
643
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
644
+ if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
645
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
646
+ }
647
+ if (!protectedHeader || protectedHeader.crit === undefined) {
648
+ return new Set();
649
+ }
650
+ if (!Array.isArray(protectedHeader.crit) ||
651
+ protectedHeader.crit.length === 0 ||
652
+ protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {
653
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
654
+ }
655
+ let recognized;
656
+ if (recognizedOption !== undefined) {
657
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
658
+ }
659
+ else {
660
+ recognized = recognizedDefault;
661
+ }
662
+ for (const parameter of protectedHeader.crit) {
663
+ if (!recognized.has(parameter)) {
664
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
665
+ }
666
+ if (joseHeader[parameter] === undefined) {
667
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
668
+ }
669
+ if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {
670
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
671
+ }
672
+ }
673
+ return new Set(protectedHeader.crit);
674
+ }
675
+
676
+ const validateAlgorithms = (option, algorithms) => {
677
+ if (algorithms !== undefined &&
678
+ (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {
679
+ throw new TypeError(`"${option}" option must be an array of strings`);
680
+ }
681
+ if (!algorithms) {
682
+ return undefined;
683
+ }
684
+ return new Set(algorithms);
685
+ };
686
+ var validateAlgorithms$1 = validateAlgorithms;
687
+
688
+ const keyToJWK = async (key) => {
689
+ if (key instanceof Uint8Array) {
690
+ return {
691
+ kty: 'oct',
692
+ k: encode(key),
693
+ };
694
+ }
695
+ if (!isCryptoKey(key)) {
696
+ throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
697
+ }
698
+ if (!key.extractable) {
699
+ throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK');
700
+ }
701
+ const { ext, key_ops, alg, use, ...jwk } = await crypto$1.subtle.exportKey('jwk', key);
702
+ return jwk;
703
+ };
704
+ var keyToJWK$1 = keyToJWK;
705
+
706
+ async function exportJWK(key) {
707
+ return keyToJWK$1(key);
708
+ }
709
+
710
+ function subtleDsa(alg, algorithm) {
711
+ const hash = `SHA-${alg.slice(-3)}`;
712
+ switch (alg) {
713
+ case 'HS256':
714
+ case 'HS384':
715
+ case 'HS512':
716
+ return { hash, name: 'HMAC' };
717
+ case 'PS256':
718
+ case 'PS384':
719
+ case 'PS512':
720
+ return { hash, name: 'RSA-PSS', saltLength: alg.slice(-3) >> 3 };
721
+ case 'RS256':
722
+ case 'RS384':
723
+ case 'RS512':
724
+ return { hash, name: 'RSASSA-PKCS1-v1_5' };
725
+ case 'ES256':
726
+ case 'ES384':
727
+ case 'ES512':
728
+ return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };
729
+ case 'Ed25519':
730
+ return { name: 'Ed25519' };
731
+ case 'EdDSA':
732
+ return { name: algorithm.name };
733
+ default:
734
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
735
+ }
736
+ }
737
+
738
+ async function getCryptoKey(alg, key, usage) {
739
+ if (usage === 'sign') {
740
+ key = await normalize.normalizePrivateKey(key, alg);
741
+ }
742
+ if (usage === 'verify') {
743
+ key = await normalize.normalizePublicKey(key, alg);
744
+ }
745
+ if (isCryptoKey(key)) {
746
+ checkSigCryptoKey(key, alg, usage);
747
+ return key;
748
+ }
749
+ if (key instanceof Uint8Array) {
750
+ if (!alg.startsWith('HS')) {
751
+ throw new TypeError(invalidKeyInput(key, ...types));
752
+ }
753
+ return crypto$1.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);
754
+ }
755
+ throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array', 'JSON Web Key'));
756
+ }
757
+
758
+ const verify = async (alg, key, signature, data) => {
759
+ const cryptoKey = await getCryptoKey(alg, key, 'verify');
760
+ checkKeyLength(alg, cryptoKey);
761
+ const algorithm = subtleDsa(alg, cryptoKey.algorithm);
762
+ try {
763
+ return await crypto$1.subtle.verify(algorithm, cryptoKey, signature, data);
764
+ }
765
+ catch {
766
+ return false;
767
+ }
768
+ };
769
+ var verify$1 = verify;
770
+
771
+ async function flattenedVerify(jws, key, options) {
772
+ if (!isObject(jws)) {
773
+ throw new JWSInvalid('Flattened JWS must be an object');
774
+ }
775
+ if (jws.protected === undefined && jws.header === undefined) {
776
+ throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
777
+ }
778
+ if (jws.protected !== undefined && typeof jws.protected !== 'string') {
779
+ throw new JWSInvalid('JWS Protected Header incorrect type');
780
+ }
781
+ if (jws.payload === undefined) {
782
+ throw new JWSInvalid('JWS Payload missing');
783
+ }
784
+ if (typeof jws.signature !== 'string') {
785
+ throw new JWSInvalid('JWS Signature missing or incorrect type');
786
+ }
787
+ if (jws.header !== undefined && !isObject(jws.header)) {
788
+ throw new JWSInvalid('JWS Unprotected Header incorrect type');
789
+ }
790
+ let parsedProt = {};
791
+ if (jws.protected) {
792
+ try {
793
+ const protectedHeader = decode$1(jws.protected);
794
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
795
+ }
796
+ catch {
797
+ throw new JWSInvalid('JWS Protected Header is invalid');
798
+ }
799
+ }
800
+ if (!isDisjoint$1(parsedProt, jws.header)) {
801
+ throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
802
+ }
803
+ const joseHeader = {
804
+ ...parsedProt,
805
+ ...jws.header,
806
+ };
807
+ const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);
808
+ let b64 = true;
809
+ if (extensions.has('b64')) {
810
+ b64 = parsedProt.b64;
811
+ if (typeof b64 !== 'boolean') {
812
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
813
+ }
814
+ }
815
+ const { alg } = joseHeader;
816
+ if (typeof alg !== 'string' || !alg) {
817
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
818
+ }
819
+ const algorithms = options && validateAlgorithms$1('algorithms', options.algorithms);
820
+ if (algorithms && !algorithms.has(alg)) {
821
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
822
+ }
823
+ if (b64) {
824
+ if (typeof jws.payload !== 'string') {
825
+ throw new JWSInvalid('JWS Payload must be a string');
826
+ }
827
+ }
828
+ else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {
829
+ throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');
830
+ }
831
+ let resolvedKey = false;
832
+ if (typeof key === 'function') {
833
+ key = await key(parsedProt, jws);
834
+ resolvedKey = true;
835
+ checkKeyTypeWithJwk(alg, key, 'verify');
836
+ if (isJWK(key)) {
837
+ key = await importJWK(key, alg);
838
+ }
839
+ }
840
+ else {
841
+ checkKeyTypeWithJwk(alg, key, 'verify');
842
+ }
843
+ const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload);
844
+ let signature;
845
+ try {
846
+ signature = decode$1(jws.signature);
847
+ }
848
+ catch {
849
+ throw new JWSInvalid('Failed to base64url decode the signature');
850
+ }
851
+ const verified = await verify$1(alg, key, signature, data);
852
+ if (!verified) {
853
+ throw new JWSSignatureVerificationFailed();
854
+ }
855
+ let payload;
856
+ if (b64) {
857
+ try {
858
+ payload = decode$1(jws.payload);
859
+ }
860
+ catch {
861
+ throw new JWSInvalid('Failed to base64url decode the payload');
862
+ }
863
+ }
864
+ else if (typeof jws.payload === 'string') {
865
+ payload = encoder.encode(jws.payload);
866
+ }
867
+ else {
868
+ payload = jws.payload;
869
+ }
870
+ const result = { payload };
871
+ if (jws.protected !== undefined) {
872
+ result.protectedHeader = parsedProt;
873
+ }
874
+ if (jws.header !== undefined) {
875
+ result.unprotectedHeader = jws.header;
876
+ }
877
+ if (resolvedKey) {
878
+ return { ...result, key };
879
+ }
880
+ return result;
881
+ }
882
+
883
+ async function compactVerify(jws, key, options) {
884
+ if (jws instanceof Uint8Array) {
885
+ jws = decoder.decode(jws);
886
+ }
887
+ if (typeof jws !== 'string') {
888
+ throw new JWSInvalid('Compact JWS must be a string or Uint8Array');
889
+ }
890
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');
891
+ if (length !== 3) {
892
+ throw new JWSInvalid('Invalid Compact JWS');
893
+ }
894
+ const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
895
+ const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
896
+ if (typeof key === 'function') {
897
+ return { ...result, key: verified.key };
898
+ }
899
+ return result;
900
+ }
901
+
902
+ var epoch = (date) => Math.floor(date.getTime() / 1000);
903
+
904
+ const minute = 60;
905
+ const hour = minute * 60;
906
+ const day = hour * 24;
907
+ const week = day * 7;
908
+ const year = day * 365.25;
909
+ const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
910
+ var secs = (str) => {
911
+ const matched = REGEX.exec(str);
912
+ if (!matched || (matched[4] && matched[1])) {
913
+ throw new TypeError('Invalid time period format');
914
+ }
915
+ const value = parseFloat(matched[2]);
916
+ const unit = matched[3].toLowerCase();
917
+ let numericDate;
918
+ switch (unit) {
919
+ case 'sec':
920
+ case 'secs':
921
+ case 'second':
922
+ case 'seconds':
923
+ case 's':
924
+ numericDate = Math.round(value);
925
+ break;
926
+ case 'minute':
927
+ case 'minutes':
928
+ case 'min':
929
+ case 'mins':
930
+ case 'm':
931
+ numericDate = Math.round(value * minute);
932
+ break;
933
+ case 'hour':
934
+ case 'hours':
935
+ case 'hr':
936
+ case 'hrs':
937
+ case 'h':
938
+ numericDate = Math.round(value * hour);
939
+ break;
940
+ case 'day':
941
+ case 'days':
942
+ case 'd':
943
+ numericDate = Math.round(value * day);
944
+ break;
945
+ case 'week':
946
+ case 'weeks':
947
+ case 'w':
948
+ numericDate = Math.round(value * week);
949
+ break;
950
+ default:
951
+ numericDate = Math.round(value * year);
952
+ break;
953
+ }
954
+ if (matched[1] === '-' || matched[4] === 'ago') {
955
+ return -numericDate;
956
+ }
957
+ return numericDate;
958
+ };
959
+
960
+ const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, '');
961
+ const checkAudiencePresence = (audPayload, audOption) => {
962
+ if (typeof audPayload === 'string') {
963
+ return audOption.includes(audPayload);
964
+ }
965
+ if (Array.isArray(audPayload)) {
966
+ return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
967
+ }
968
+ return false;
969
+ };
970
+ var jwtPayload = (protectedHeader, encodedPayload, options = {}) => {
971
+ let payload;
972
+ try {
973
+ payload = JSON.parse(decoder.decode(encodedPayload));
974
+ }
975
+ catch {
976
+ }
977
+ if (!isObject(payload)) {
978
+ throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');
979
+ }
980
+ const { typ } = options;
981
+ if (typ &&
982
+ (typeof protectedHeader.typ !== 'string' ||
983
+ normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
984
+ throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed');
985
+ }
986
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
987
+ const presenceCheck = [...requiredClaims];
988
+ if (maxTokenAge !== undefined)
989
+ presenceCheck.push('iat');
990
+ if (audience !== undefined)
991
+ presenceCheck.push('aud');
992
+ if (subject !== undefined)
993
+ presenceCheck.push('sub');
994
+ if (issuer !== undefined)
995
+ presenceCheck.push('iss');
996
+ for (const claim of new Set(presenceCheck.reverse())) {
997
+ if (!(claim in payload)) {
998
+ throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing');
999
+ }
1000
+ }
1001
+ if (issuer &&
1002
+ !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
1003
+ throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed');
1004
+ }
1005
+ if (subject && payload.sub !== subject) {
1006
+ throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed');
1007
+ }
1008
+ if (audience &&
1009
+ !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {
1010
+ throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed');
1011
+ }
1012
+ let tolerance;
1013
+ switch (typeof options.clockTolerance) {
1014
+ case 'string':
1015
+ tolerance = secs(options.clockTolerance);
1016
+ break;
1017
+ case 'number':
1018
+ tolerance = options.clockTolerance;
1019
+ break;
1020
+ case 'undefined':
1021
+ tolerance = 0;
1022
+ break;
1023
+ default:
1024
+ throw new TypeError('Invalid clockTolerance option type');
1025
+ }
1026
+ const { currentDate } = options;
1027
+ const now = epoch(currentDate || new Date());
1028
+ if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {
1029
+ throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid');
1030
+ }
1031
+ if (payload.nbf !== undefined) {
1032
+ if (typeof payload.nbf !== 'number') {
1033
+ throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid');
1034
+ }
1035
+ if (payload.nbf > now + tolerance) {
1036
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed');
1037
+ }
1038
+ }
1039
+ if (payload.exp !== undefined) {
1040
+ if (typeof payload.exp !== 'number') {
1041
+ throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid');
1042
+ }
1043
+ if (payload.exp <= now - tolerance) {
1044
+ throw new JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed');
1045
+ }
1046
+ }
1047
+ if (maxTokenAge) {
1048
+ const age = now - payload.iat;
1049
+ const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);
1050
+ if (age - tolerance > max) {
1051
+ throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');
1052
+ }
1053
+ if (age < 0 - tolerance) {
1054
+ throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');
1055
+ }
1056
+ }
1057
+ return payload;
1058
+ };
1059
+
1060
+ async function jwtVerify(jwt, key, options) {
1061
+ const verified = await compactVerify(jwt, key, options);
1062
+ if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
1063
+ throw new JWTInvalid('JWTs MUST NOT use unencoded payload');
1064
+ }
1065
+ const payload = jwtPayload(verified.protectedHeader, verified.payload, options);
1066
+ const result = { payload, protectedHeader: verified.protectedHeader };
1067
+ if (typeof key === 'function') {
1068
+ return { ...result, key: verified.key };
1069
+ }
1070
+ return result;
1071
+ }
1072
+
1073
+ const sign = async (alg, key, data) => {
1074
+ const cryptoKey = await getCryptoKey(alg, key, 'sign');
1075
+ checkKeyLength(alg, cryptoKey);
1076
+ const signature = await crypto$1.subtle.sign(subtleDsa(alg, cryptoKey.algorithm), cryptoKey, data);
1077
+ return new Uint8Array(signature);
1078
+ };
1079
+ var sign$1 = sign;
1080
+
1081
+ class FlattenedSign {
1082
+ constructor(payload) {
1083
+ if (!(payload instanceof Uint8Array)) {
1084
+ throw new TypeError('payload must be an instance of Uint8Array');
1085
+ }
1086
+ this._payload = payload;
1087
+ }
1088
+ setProtectedHeader(protectedHeader) {
1089
+ if (this._protectedHeader) {
1090
+ throw new TypeError('setProtectedHeader can only be called once');
1091
+ }
1092
+ this._protectedHeader = protectedHeader;
1093
+ return this;
1094
+ }
1095
+ setUnprotectedHeader(unprotectedHeader) {
1096
+ if (this._unprotectedHeader) {
1097
+ throw new TypeError('setUnprotectedHeader can only be called once');
1098
+ }
1099
+ this._unprotectedHeader = unprotectedHeader;
1100
+ return this;
1101
+ }
1102
+ async sign(key, options) {
1103
+ if (!this._protectedHeader && !this._unprotectedHeader) {
1104
+ throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');
1105
+ }
1106
+ if (!isDisjoint$1(this._protectedHeader, this._unprotectedHeader)) {
1107
+ throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
1108
+ }
1109
+ const joseHeader = {
1110
+ ...this._protectedHeader,
1111
+ ...this._unprotectedHeader,
1112
+ };
1113
+ const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader);
1114
+ let b64 = true;
1115
+ if (extensions.has('b64')) {
1116
+ b64 = this._protectedHeader.b64;
1117
+ if (typeof b64 !== 'boolean') {
1118
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
1119
+ }
1120
+ }
1121
+ const { alg } = joseHeader;
1122
+ if (typeof alg !== 'string' || !alg) {
1123
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
1124
+ }
1125
+ checkKeyTypeWithJwk(alg, key, 'sign');
1126
+ let payload = this._payload;
1127
+ if (b64) {
1128
+ payload = encoder.encode(encode(payload));
1129
+ }
1130
+ let protectedHeader;
1131
+ if (this._protectedHeader) {
1132
+ protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader)));
1133
+ }
1134
+ else {
1135
+ protectedHeader = encoder.encode('');
1136
+ }
1137
+ const data = concat(protectedHeader, encoder.encode('.'), payload);
1138
+ const signature = await sign$1(alg, key, data);
1139
+ const jws = {
1140
+ signature: encode(signature),
1141
+ payload: '',
1142
+ };
1143
+ if (b64) {
1144
+ jws.payload = decoder.decode(payload);
1145
+ }
1146
+ if (this._unprotectedHeader) {
1147
+ jws.header = this._unprotectedHeader;
1148
+ }
1149
+ if (this._protectedHeader) {
1150
+ jws.protected = decoder.decode(protectedHeader);
1151
+ }
1152
+ return jws;
1153
+ }
1154
+ }
1155
+
1156
+ class CompactSign {
1157
+ constructor(payload) {
1158
+ this._flattened = new FlattenedSign(payload);
1159
+ }
1160
+ setProtectedHeader(protectedHeader) {
1161
+ this._flattened.setProtectedHeader(protectedHeader);
1162
+ return this;
1163
+ }
1164
+ async sign(key, options) {
1165
+ const jws = await this._flattened.sign(key, options);
1166
+ if (jws.payload === undefined) {
1167
+ throw new TypeError('use the flattened module for creating JWS with b64: false');
1168
+ }
1169
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
1170
+ }
1171
+ }
1172
+
1173
+ function validateInput(label, input) {
1174
+ if (!Number.isFinite(input)) {
1175
+ throw new TypeError(`Invalid ${label} input`);
1176
+ }
1177
+ return input;
1178
+ }
1179
+ class ProduceJWT {
1180
+ constructor(payload = {}) {
1181
+ if (!isObject(payload)) {
1182
+ throw new TypeError('JWT Claims Set MUST be an object');
1183
+ }
1184
+ this._payload = payload;
1185
+ }
1186
+ setIssuer(issuer) {
1187
+ this._payload = { ...this._payload, iss: issuer };
1188
+ return this;
1189
+ }
1190
+ setSubject(subject) {
1191
+ this._payload = { ...this._payload, sub: subject };
1192
+ return this;
1193
+ }
1194
+ setAudience(audience) {
1195
+ this._payload = { ...this._payload, aud: audience };
1196
+ return this;
1197
+ }
1198
+ setJti(jwtId) {
1199
+ this._payload = { ...this._payload, jti: jwtId };
1200
+ return this;
1201
+ }
1202
+ setNotBefore(input) {
1203
+ if (typeof input === 'number') {
1204
+ this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) };
1205
+ }
1206
+ else if (input instanceof Date) {
1207
+ this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) };
1208
+ }
1209
+ else {
1210
+ this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) };
1211
+ }
1212
+ return this;
1213
+ }
1214
+ setExpirationTime(input) {
1215
+ if (typeof input === 'number') {
1216
+ this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) };
1217
+ }
1218
+ else if (input instanceof Date) {
1219
+ this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) };
1220
+ }
1221
+ else {
1222
+ this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) };
1223
+ }
1224
+ return this;
1225
+ }
1226
+ setIssuedAt(input) {
1227
+ if (typeof input === 'undefined') {
1228
+ this._payload = { ...this._payload, iat: epoch(new Date()) };
1229
+ }
1230
+ else if (input instanceof Date) {
1231
+ this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) };
1232
+ }
1233
+ else if (typeof input === 'string') {
1234
+ this._payload = {
1235
+ ...this._payload,
1236
+ iat: validateInput('setIssuedAt', epoch(new Date()) + secs(input)),
1237
+ };
1238
+ }
1239
+ else {
1240
+ this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) };
1241
+ }
1242
+ return this;
1243
+ }
1244
+ }
1245
+
1246
+ class SignJWT extends ProduceJWT {
1247
+ setProtectedHeader(protectedHeader) {
1248
+ this._protectedHeader = protectedHeader;
1249
+ return this;
1250
+ }
1251
+ async sign(key, options) {
1252
+ const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)));
1253
+ sig.setProtectedHeader(this._protectedHeader);
1254
+ if (Array.isArray(this._protectedHeader?.crit) &&
1255
+ this._protectedHeader.crit.includes('b64') &&
1256
+ this._protectedHeader.b64 === false) {
1257
+ throw new JWTInvalid('JWTs MUST NOT use unencoded payload');
1258
+ }
1259
+ return sig.sign(key, options);
1260
+ }
1261
+ }
1262
+
1263
+ const check = (value, description) => {
1264
+ if (typeof value !== 'string' || !value) {
1265
+ throw new JWKInvalid(`${description} missing or invalid`);
1266
+ }
1267
+ };
1268
+ async function calculateJwkThumbprint(jwk, digestAlgorithm) {
1269
+ if (!isObject(jwk)) {
1270
+ throw new TypeError('JWK must be an object');
1271
+ }
1272
+ digestAlgorithm ?? (digestAlgorithm = 'sha256');
1273
+ if (digestAlgorithm !== 'sha256' &&
1274
+ digestAlgorithm !== 'sha384' &&
1275
+ digestAlgorithm !== 'sha512') {
1276
+ throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
1277
+ }
1278
+ let components;
1279
+ switch (jwk.kty) {
1280
+ case 'EC':
1281
+ check(jwk.crv, '"crv" (Curve) Parameter');
1282
+ check(jwk.x, '"x" (X Coordinate) Parameter');
1283
+ check(jwk.y, '"y" (Y Coordinate) Parameter');
1284
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
1285
+ break;
1286
+ case 'OKP':
1287
+ check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
1288
+ check(jwk.x, '"x" (Public Key) Parameter');
1289
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
1290
+ break;
1291
+ case 'RSA':
1292
+ check(jwk.e, '"e" (Exponent) Parameter');
1293
+ check(jwk.n, '"n" (Modulus) Parameter');
1294
+ components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
1295
+ break;
1296
+ case 'oct':
1297
+ check(jwk.k, '"k" (Key Value) Parameter');
1298
+ components = { k: jwk.k, kty: jwk.kty };
1299
+ break;
1300
+ default:
1301
+ throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
1302
+ }
1303
+ const data = encoder.encode(JSON.stringify(components));
1304
+ return encode(await digest$1(digestAlgorithm, data));
1305
+ }
1306
+
1307
+ function getKtyFromAlg(alg) {
1308
+ switch (typeof alg === 'string' && alg.slice(0, 2)) {
1309
+ case 'RS':
1310
+ case 'PS':
1311
+ return 'RSA';
1312
+ case 'ES':
1313
+ return 'EC';
1314
+ case 'Ed':
1315
+ return 'OKP';
1316
+ default:
1317
+ throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
1318
+ }
1319
+ }
1320
+ function isJWKSLike(jwks) {
1321
+ return (jwks &&
1322
+ typeof jwks === 'object' &&
1323
+ Array.isArray(jwks.keys) &&
1324
+ jwks.keys.every(isJWKLike));
1325
+ }
1326
+ function isJWKLike(key) {
1327
+ return isObject(key);
1328
+ }
1329
+ function clone(obj) {
1330
+ if (typeof structuredClone === 'function') {
1331
+ return structuredClone(obj);
1332
+ }
1333
+ return JSON.parse(JSON.stringify(obj));
1334
+ }
1335
+ class LocalJWKSet {
1336
+ constructor(jwks) {
1337
+ this._cached = new WeakMap();
1338
+ if (!isJWKSLike(jwks)) {
1339
+ throw new JWKSInvalid('JSON Web Key Set malformed');
1340
+ }
1341
+ this._jwks = clone(jwks);
1342
+ }
1343
+ async getKey(protectedHeader, token) {
1344
+ const { alg, kid } = { ...protectedHeader, ...token?.header };
1345
+ const kty = getKtyFromAlg(alg);
1346
+ const candidates = this._jwks.keys.filter((jwk) => {
1347
+ let candidate = kty === jwk.kty;
1348
+ if (candidate && typeof kid === 'string') {
1349
+ candidate = kid === jwk.kid;
1350
+ }
1351
+ if (candidate && typeof jwk.alg === 'string') {
1352
+ candidate = alg === jwk.alg;
1353
+ }
1354
+ if (candidate && typeof jwk.use === 'string') {
1355
+ candidate = jwk.use === 'sig';
1356
+ }
1357
+ if (candidate && Array.isArray(jwk.key_ops)) {
1358
+ candidate = jwk.key_ops.includes('verify');
1359
+ }
1360
+ if (candidate) {
1361
+ switch (alg) {
1362
+ case 'ES256':
1363
+ candidate = jwk.crv === 'P-256';
1364
+ break;
1365
+ case 'ES256K':
1366
+ candidate = jwk.crv === 'secp256k1';
1367
+ break;
1368
+ case 'ES384':
1369
+ candidate = jwk.crv === 'P-384';
1370
+ break;
1371
+ case 'ES512':
1372
+ candidate = jwk.crv === 'P-521';
1373
+ break;
1374
+ case 'Ed25519':
1375
+ candidate = jwk.crv === 'Ed25519';
1376
+ break;
1377
+ case 'EdDSA':
1378
+ candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448';
1379
+ break;
1380
+ }
1381
+ }
1382
+ return candidate;
1383
+ });
1384
+ const { 0: jwk, length } = candidates;
1385
+ if (length === 0) {
1386
+ throw new JWKSNoMatchingKey();
1387
+ }
1388
+ if (length !== 1) {
1389
+ const error = new JWKSMultipleMatchingKeys();
1390
+ const { _cached } = this;
1391
+ error[Symbol.asyncIterator] = async function* () {
1392
+ for (const jwk of candidates) {
1393
+ try {
1394
+ yield await importWithAlgCache(_cached, jwk, alg);
1395
+ }
1396
+ catch { }
1397
+ }
1398
+ };
1399
+ throw error;
1400
+ }
1401
+ return importWithAlgCache(this._cached, jwk, alg);
1402
+ }
1403
+ }
1404
+ async function importWithAlgCache(cache, jwk, alg) {
1405
+ const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
1406
+ if (cached[alg] === undefined) {
1407
+ const key = await importJWK({ ...jwk, ext: true }, alg);
1408
+ if (key instanceof Uint8Array || key.type !== 'public') {
1409
+ throw new JWKSInvalid('JSON Web Key Set members must be public keys');
1410
+ }
1411
+ cached[alg] = key;
1412
+ }
1413
+ return cached[alg];
1414
+ }
1415
+ function createLocalJWKSet(jwks) {
1416
+ const set = new LocalJWKSet(jwks);
1417
+ const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
1418
+ Object.defineProperties(localJWKSet, {
1419
+ jwks: {
1420
+ value: () => clone(set._jwks),
1421
+ enumerable: true,
1422
+ configurable: false,
1423
+ writable: false,
1424
+ },
1425
+ });
1426
+ return localJWKSet;
1427
+ }
1428
+
1429
+ const fetchJwks = async (url, timeout, options) => {
1430
+ let controller;
1431
+ let id;
1432
+ let timedOut = false;
1433
+ if (typeof AbortController === 'function') {
1434
+ controller = new AbortController();
1435
+ id = setTimeout(() => {
1436
+ timedOut = true;
1437
+ controller.abort();
1438
+ }, timeout);
1439
+ }
1440
+ const response = await fetch(url.href, {
1441
+ signal: controller ? controller.signal : undefined,
1442
+ redirect: 'manual',
1443
+ headers: options.headers,
1444
+ }).catch((err) => {
1445
+ if (timedOut)
1446
+ throw new JWKSTimeout();
1447
+ throw err;
1448
+ });
1449
+ if (id !== undefined)
1450
+ clearTimeout(id);
1451
+ if (response.status !== 200) {
1452
+ throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');
1453
+ }
1454
+ try {
1455
+ return await response.json();
1456
+ }
1457
+ catch {
1458
+ throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');
1459
+ }
1460
+ };
1461
+ var fetchJwks$1 = fetchJwks;
1462
+
1463
+ function isCloudflareWorkers() {
1464
+ return (typeof WebSocketPair !== 'undefined' ||
1465
+ (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
1466
+ (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
1467
+ }
1468
+ let USER_AGENT;
1469
+ if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
1470
+ const NAME = 'jose';
1471
+ const VERSION = 'v5.10.0';
1472
+ USER_AGENT = `${NAME}/${VERSION}`;
1473
+ }
1474
+ const jwksCache = Symbol();
1475
+ function isFreshJwksCache(input, cacheMaxAge) {
1476
+ if (typeof input !== 'object' || input === null) {
1477
+ return false;
1478
+ }
1479
+ if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {
1480
+ return false;
1481
+ }
1482
+ if (!('jwks' in input) ||
1483
+ !isObject(input.jwks) ||
1484
+ !Array.isArray(input.jwks.keys) ||
1485
+ !Array.prototype.every.call(input.jwks.keys, isObject)) {
1486
+ return false;
1487
+ }
1488
+ return true;
1489
+ }
1490
+ class RemoteJWKSet {
1491
+ constructor(url, options) {
1492
+ if (!(url instanceof URL)) {
1493
+ throw new TypeError('url must be an instance of URL');
1494
+ }
1495
+ this._url = new URL(url.href);
1496
+ this._options = { agent: options?.agent, headers: options?.headers };
1497
+ this._timeoutDuration =
1498
+ typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;
1499
+ this._cooldownDuration =
1500
+ typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;
1501
+ this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;
1502
+ if (options?.[jwksCache] !== undefined) {
1503
+ this._cache = options?.[jwksCache];
1504
+ if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) {
1505
+ this._jwksTimestamp = this._cache.uat;
1506
+ this._local = createLocalJWKSet(this._cache.jwks);
1507
+ }
1508
+ }
1509
+ }
1510
+ coolingDown() {
1511
+ return typeof this._jwksTimestamp === 'number'
1512
+ ? Date.now() < this._jwksTimestamp + this._cooldownDuration
1513
+ : false;
1514
+ }
1515
+ fresh() {
1516
+ return typeof this._jwksTimestamp === 'number'
1517
+ ? Date.now() < this._jwksTimestamp + this._cacheMaxAge
1518
+ : false;
1519
+ }
1520
+ async getKey(protectedHeader, token) {
1521
+ if (!this._local || !this.fresh()) {
1522
+ await this.reload();
1523
+ }
1524
+ try {
1525
+ return await this._local(protectedHeader, token);
1526
+ }
1527
+ catch (err) {
1528
+ if (err instanceof JWKSNoMatchingKey) {
1529
+ if (this.coolingDown() === false) {
1530
+ await this.reload();
1531
+ return this._local(protectedHeader, token);
1532
+ }
1533
+ }
1534
+ throw err;
1535
+ }
1536
+ }
1537
+ async reload() {
1538
+ if (this._pendingFetch && isCloudflareWorkers()) {
1539
+ this._pendingFetch = undefined;
1540
+ }
1541
+ const headers = new Headers(this._options.headers);
1542
+ if (USER_AGENT && !headers.has('User-Agent')) {
1543
+ headers.set('User-Agent', USER_AGENT);
1544
+ this._options.headers = Object.fromEntries(headers.entries());
1545
+ }
1546
+ this._pendingFetch || (this._pendingFetch = fetchJwks$1(this._url, this._timeoutDuration, this._options)
1547
+ .then((json) => {
1548
+ this._local = createLocalJWKSet(json);
1549
+ if (this._cache) {
1550
+ this._cache.uat = Date.now();
1551
+ this._cache.jwks = json;
1552
+ }
1553
+ this._jwksTimestamp = Date.now();
1554
+ this._pendingFetch = undefined;
1555
+ })
1556
+ .catch((err) => {
1557
+ this._pendingFetch = undefined;
1558
+ throw err;
1559
+ }));
1560
+ await this._pendingFetch;
1561
+ }
1562
+ }
1563
+ function createRemoteJWKSet(url, options) {
1564
+ const set = new RemoteJWKSet(url, options);
1565
+ const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
1566
+ Object.defineProperties(remoteJWKSet, {
1567
+ coolingDown: {
1568
+ get: () => set.coolingDown(),
1569
+ enumerable: true,
1570
+ configurable: false,
1571
+ },
1572
+ fresh: {
1573
+ get: () => set.fresh(),
1574
+ enumerable: true,
1575
+ configurable: false,
1576
+ },
1577
+ reload: {
1578
+ value: () => set.reload(),
1579
+ enumerable: true,
1580
+ configurable: false,
1581
+ writable: false,
1582
+ },
1583
+ reloading: {
1584
+ get: () => !!set._pendingFetch,
1585
+ enumerable: true,
1586
+ configurable: false,
1587
+ },
1588
+ jwks: {
1589
+ value: () => set._local?.jwks(),
1590
+ enumerable: true,
1591
+ configurable: false,
1592
+ writable: false,
1593
+ },
1594
+ });
1595
+ return remoteJWKSet;
1596
+ }
1597
+
1598
+ const decode = decode$1;
1599
+
1600
+ function decodeJwt(jwt) {
1601
+ if (typeof jwt !== 'string')
1602
+ throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string');
1603
+ const { 1: payload, length } = jwt.split('.');
1604
+ if (length === 5)
1605
+ throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded');
1606
+ if (length !== 3)
1607
+ throw new JWTInvalid('Invalid JWT');
1608
+ if (!payload)
1609
+ throw new JWTInvalid('JWTs must contain a payload');
1610
+ let decoded;
1611
+ try {
1612
+ decoded = decode(payload);
1613
+ }
1614
+ catch {
1615
+ throw new JWTInvalid('Failed to base64url decode the payload');
1616
+ }
1617
+ let result;
1618
+ try {
1619
+ result = JSON.parse(decoder.decode(decoded));
1620
+ }
1621
+ catch {
1622
+ throw new JWTInvalid('Failed to parse the decoded payload as JSON');
1623
+ }
1624
+ if (!isObject(result))
1625
+ throw new JWTInvalid('Invalid JWT Claims Set');
1626
+ return result;
1627
+ }
1628
+
1629
+ const renewTokens = async (sessionDatabase) => {
1630
+ // remember session details
1631
+ try {
1632
+ await sessionDatabase.init();
1633
+ const client_id = await sessionDatabase.getItem("client_id");
1634
+ const token_endpoint = await sessionDatabase.getItem("token_endpoint");
1635
+ const key_pair = await sessionDatabase.getItem("dpop_keypair");
1636
+ const refresh_token = await sessionDatabase.getItem("refresh_token");
1637
+ if (client_id === null || token_endpoint === null || key_pair === null || refresh_token === null) {
1638
+ // we can not restore the old session
1639
+ throw new Error("Could not refresh tokens: details missing from database.");
1640
+ }
1641
+ const token_response = await requestFreshTokens(refresh_token, client_id, token_endpoint, key_pair)
1642
+ .then((response) => {
1643
+ if (!response.ok) {
1644
+ throw new Error(`HTTP error! Status: ${response.status}`);
1645
+ }
1646
+ return response.json();
1647
+ });
1648
+ // verify access_token // ! Solid-OIDC specification says it should be a dpop-bound `id token` but implementations provide a dpop-bound `access token`
1649
+ const accessToken = token_response["access_token"];
1650
+ const idp = await sessionDatabase.getItem("idp");
1651
+ if (idp === null) {
1652
+ throw new Error("Access Token validation preparation - Could not find in sessionDatabase: idp");
1653
+ }
1654
+ const jwks_uri = await sessionDatabase.getItem("jwks_uri");
1655
+ if (jwks_uri === null) {
1656
+ throw new Error("Access Token validation preparation - Could not find in sessionDatabase: jwks_uri");
1657
+ }
1658
+ const jwks = createRemoteJWKSet(new URL(jwks_uri));
1659
+ const { payload } = await jwtVerify(accessToken, jwks, {
1660
+ issuer: idp, // RFC 9207
1661
+ audience: "solid", // RFC 7519 // ! "solid" as per implementations ...
1662
+ // exp, nbf, iat - handled automatically
1663
+ });
1664
+ // check dpop thumbprint
1665
+ const dpopThumbprint = await calculateJwkThumbprint(await exportJWK(key_pair.publicKey));
1666
+ if (payload["cnf"]["jkt"] !== dpopThumbprint) {
1667
+ throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - " + payload["cnf"]["jkt"] + " !== " + dpopThumbprint);
1668
+ }
1669
+ // check client_id
1670
+ if (payload["client_id"] !== client_id) {
1671
+ throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - " + payload["client_id"] + " !== " + client_id);
1672
+ }
1673
+ // set new refresh token for token rotation
1674
+ await sessionDatabase.setItem("refresh_token", token_response["refresh_token"]);
1675
+ return {
1676
+ ...token_response,
1677
+ dpop_key_pair: key_pair,
1678
+ };
1679
+ }
1680
+ finally {
1681
+ sessionDatabase.close();
1682
+ }
1683
+ };
1684
+ /**
1685
+ * Request an dpop-bound access token from a token endpoint using a refresh token
1686
+ * @param authorization_code
1687
+ * @param pkce_code_verifier
1688
+ * @param redirect_uri
1689
+ * @param client_id
1690
+ * @param token_endpoint
1691
+ * @param key_pair
1692
+ * @returns
1693
+ */
1694
+ const requestFreshTokens = async (refresh_token, client_id, token_endpoint, key_pair) => {
1695
+ // prepare public key to bind access token to
1696
+ const jwk_public_key = await exportJWK(key_pair.publicKey);
1697
+ jwk_public_key.alg = "ES256";
1698
+ // sign the access token request DPoP token
1699
+ const dpop = await new SignJWT({
1700
+ htu: token_endpoint,
1701
+ htm: "POST",
1702
+ })
1703
+ .setIssuedAt()
1704
+ .setJti(self.crypto.randomUUID())
1705
+ .setProtectedHeader({
1706
+ alg: "ES256",
1707
+ typ: "dpop+jwt",
1708
+ jwk: jwk_public_key,
1709
+ })
1710
+ .sign(key_pair.privateKey);
1711
+ return fetch(token_endpoint, {
1712
+ method: "POST",
1713
+ headers: {
1714
+ dpop,
1715
+ "Content-Type": "application/x-www-form-urlencoded",
1716
+ },
1717
+ body: new URLSearchParams({
1718
+ grant_type: "refresh_token",
1719
+ refresh_token,
1720
+ client_id
1721
+ }),
1722
+ });
1723
+ };
1724
+
1725
+ /**
1726
+ * A simple IndexedDB wrapper.
1727
+ */
1728
+ class SessionIDB {
1729
+ dbName;
1730
+ storeName;
1731
+ dbVersion;
1732
+ db = null;
1733
+ /**
1734
+ * Creates a new instance
1735
+ * @param dbName The name of the IndexedDB database
1736
+ * @param storeName The name of the object store
1737
+ * @param dbVersion The database version
1738
+ */
1739
+ constructor(dbName = 'soidc', storeName = 'session', dbVersion = 1) {
1740
+ this.dbName = dbName;
1741
+ this.storeName = storeName;
1742
+ this.dbVersion = dbVersion;
1743
+ }
1744
+ /**
1745
+ * Initializes the IndexedDB database
1746
+ * @returns Promise that resolves when the database is ready
1747
+ */
1748
+ async init() {
1749
+ return new Promise((resolve, reject) => {
1750
+ const request = indexedDB.open(this.dbName, this.dbVersion);
1751
+ request.onerror = (event) => {
1752
+ reject(new Error(`Database error: ${event.target.error}`));
1753
+ };
1754
+ request.onsuccess = (event) => {
1755
+ this.db = event.target.result;
1756
+ resolve(this);
1757
+ };
1758
+ request.onupgradeneeded = (event) => {
1759
+ const db = event.target.result;
1760
+ // Check if the object store already exists, if not create it
1761
+ if (!db.objectStoreNames.contains(this.storeName)) {
1762
+ db.createObjectStore(this.storeName);
1763
+ }
1764
+ };
1765
+ });
1766
+ }
1767
+ /**
1768
+ * Stores any value in the database with the given ID as key
1769
+ * @param id The identifier/key for the value
1770
+ * @param value The value to store
1771
+ */
1772
+ async setItem(id, value) {
1773
+ if (!this.db) {
1774
+ await this.init();
1775
+ }
1776
+ return new Promise((resolve, reject) => {
1777
+ const transaction = this.db.transaction(this.storeName, 'readwrite');
1778
+ // Handle transation
1779
+ transaction.oncomplete = () => {
1780
+ resolve();
1781
+ };
1782
+ transaction.onerror = (event) => {
1783
+ reject(new Error(`Transaction error for setItem(${id},...): ${event.target.error}`));
1784
+ };
1785
+ transaction.onabort = (event) => {
1786
+ reject(new Error(`Transaction aborted for setItem(${id},...): ${event.target.error}`));
1787
+ };
1788
+ // Perform the request within the transaction
1789
+ const store = transaction.objectStore(this.storeName);
1790
+ store.put(value, id);
1791
+ });
1792
+ }
1793
+ /**
1794
+ * Retrieves a value from the database by ID
1795
+ * @param id The identifier/key for the value
1796
+ * @returns The stored value or null if not found
1797
+ */
1798
+ async getItem(id) {
1799
+ if (!this.db) {
1800
+ await this.init();
1801
+ }
1802
+ return new Promise((resolve, reject) => {
1803
+ const transaction = this.db.transaction(this.storeName, 'readonly');
1804
+ // Handle transation
1805
+ transaction.onerror = (event) => {
1806
+ reject(new Error(`Transaction error for getItem(${id}): ${event.target.error}`));
1807
+ };
1808
+ transaction.onabort = (event) => {
1809
+ reject(new Error(`Transaction aborted for getItem(${id}): ${event.target.error}`));
1810
+ };
1811
+ // Perform the request within the transaction
1812
+ const store = transaction.objectStore(this.storeName);
1813
+ const request = store.get(id);
1814
+ request.onsuccess = () => {
1815
+ resolve(request.result || null);
1816
+ };
1817
+ });
1818
+ }
1819
+ /**
1820
+ * Removes an item from the database
1821
+ * @param id The identifier of the item to remove
1822
+ */
1823
+ async deleteItem(id) {
1824
+ if (!this.db) {
1825
+ await this.init();
1826
+ }
1827
+ return new Promise((resolve, reject) => {
1828
+ const transaction = this.db.transaction(this.storeName, 'readwrite');
1829
+ // Handle transation
1830
+ transaction.oncomplete = () => {
1831
+ resolve();
1832
+ };
1833
+ transaction.onerror = (event) => {
1834
+ reject(new Error(`Transaction error for deleteItem(${id}): ${event.target.error}`));
1835
+ };
1836
+ transaction.onabort = (event) => {
1837
+ reject(new Error(`Transaction aborted for deleteItem(${id}): ${event.target.error}`));
1838
+ };
1839
+ // Perform the request within the transaction
1840
+ const store = transaction.objectStore(this.storeName);
1841
+ store.delete(id);
1842
+ });
1843
+ }
1844
+ /**
1845
+ * Clears all items from the database
1846
+ */
1847
+ async clear() {
1848
+ if (!this.db) {
1849
+ await this.init();
1850
+ }
1851
+ return new Promise((resolve, reject) => {
1852
+ const transaction = this.db.transaction(this.storeName, 'readwrite');
1853
+ // Handle transation
1854
+ transaction.oncomplete = () => {
1855
+ resolve();
1856
+ };
1857
+ transaction.onerror = (event) => {
1858
+ reject(new Error(`Transaction error for clear(): ${event.target.error}`));
1859
+ };
1860
+ transaction.onabort = (event) => {
1861
+ reject(new Error(`Transaction aborted for clear(): ${event.target.error}`));
1862
+ };
1863
+ // Perform the request within the transaction
1864
+ const store = transaction.objectStore(this.storeName);
1865
+ store.clear();
1866
+ });
1867
+ }
1868
+ /**
1869
+ * Closes the database connection
1870
+ */
1871
+ close() {
1872
+ if (this.db) {
1873
+ this.db.close();
1874
+ this.db = null;
1875
+ }
1876
+ }
1877
+ }
1878
+
1879
+ var RefreshMessageTypes;
1880
+ (function (RefreshMessageTypes) {
1881
+ RefreshMessageTypes["SCHEDULE"] = "SCHEDULE";
1882
+ RefreshMessageTypes["REFRESH"] = "REFRESH";
1883
+ RefreshMessageTypes["STOP"] = "STOP";
1884
+ RefreshMessageTypes["DISCONNECT"] = "DISCONNECT";
1885
+ RefreshMessageTypes["TOKEN_DETAILS"] = "TOKEN_DETAILS";
1886
+ RefreshMessageTypes["ERROR_ON_REFRESH"] = "ERROR_ON_REFRESH";
1887
+ RefreshMessageTypes["EXPIRED"] = "EXPIRED";
1888
+ })(RefreshMessageTypes || (RefreshMessageTypes = {}));
1889
+ // A Set to store all connected ports (tabs)
1890
+ const ports = new Set();
1891
+ const broadcast = (message) => {
1892
+ for (const p of ports) {
1893
+ p.postMessage(message);
1894
+ }
1895
+ };
1896
+ let refresher;
1897
+ self.onconnect = (event) => {
1898
+ const port = event.ports[0];
1899
+ ports.add(port);
1900
+ // lazy init
1901
+ if (!refresher) {
1902
+ refresher = new Refresher(broadcast, new SessionIDB());
1903
+ }
1904
+ // handle messages
1905
+ port.onmessage = (event) => {
1906
+ const { type, payload } = event.data;
1907
+ switch (type) {
1908
+ case RefreshMessageTypes.SCHEDULE:
1909
+ refresher.handleSchedule(payload);
1910
+ break;
1911
+ case RefreshMessageTypes.REFRESH:
1912
+ refresher.handleRefresh(port);
1913
+ break;
1914
+ case RefreshMessageTypes.STOP:
1915
+ refresher.handleStop();
1916
+ break;
1917
+ case RefreshMessageTypes.DISCONNECT:
1918
+ ports.delete(port);
1919
+ break;
1920
+ }
1921
+ };
1922
+ port.onmessageerror = () => ports.delete(port);
1923
+ port.start();
1924
+ };
1925
+ class Refresher {
1926
+ tokenDetails;
1927
+ exp;
1928
+ refreshTimeout;
1929
+ finalLogoutTimeout;
1930
+ timersAreRunning = false;
1931
+ broadcast;
1932
+ database;
1933
+ refreshPromise;
1934
+ constructor(broadcast, database) {
1935
+ this.broadcast = broadcast;
1936
+ this.database = database;
1937
+ }
1938
+ async handleSchedule(tokenDetails) {
1939
+ this.tokenDetails = tokenDetails;
1940
+ this.exp = decodeJwt(this.tokenDetails.access_token).exp;
1941
+ this.broadcast({
1942
+ type: RefreshMessageTypes.TOKEN_DETAILS,
1943
+ payload: { tokenDetails: this.tokenDetails }
1944
+ });
1945
+ console.log(`[RefreshWorker] Scheduling timers, expiry in ${this.tokenDetails.expires_in}s`);
1946
+ this.scheduleTimers(this.tokenDetails.expires_in);
1947
+ this.timersAreRunning = true;
1948
+ }
1949
+ async handleRefresh(requestingPort) {
1950
+ if (this.tokenDetails && this.exp && !this.isTokenExpired(this.exp)) {
1951
+ console.log(`[RefreshWorker] Providing current tokens`);
1952
+ requestingPort.postMessage({
1953
+ type: RefreshMessageTypes.TOKEN_DETAILS,
1954
+ payload: { tokenDetails: this.tokenDetails }
1955
+ });
1956
+ }
1957
+ else {
1958
+ console.log(`[RefreshWorker] Refreshing tokens`);
1959
+ this.performRefresh();
1960
+ }
1961
+ }
1962
+ handleStop() {
1963
+ if (!this.tokenDetails) {
1964
+ console.log('[RefreshWorker] Received STOP, being idle');
1965
+ return;
1966
+ }
1967
+ this.broadcast({ type: RefreshMessageTypes.EXPIRED });
1968
+ this.tokenDetails = undefined;
1969
+ this.exp = undefined;
1970
+ this.refreshPromise = undefined;
1971
+ console.log('[RefreshWorker] Received STOP, clearing timers');
1972
+ this.clearAllTimers();
1973
+ }
1974
+ async performRefresh() {
1975
+ if (this.refreshPromise) {
1976
+ console.log('[RefreshWorker] Refresh already in progress, waiting...');
1977
+ return this.refreshPromise;
1978
+ }
1979
+ this.refreshPromise = this.doRefresh();
1980
+ return this.refreshPromise;
1981
+ }
1982
+ async doRefresh() {
1983
+ try {
1984
+ this.tokenDetails = await renewTokens(this.database);
1985
+ this.exp = decodeJwt(this.tokenDetails.access_token).exp;
1986
+ this.broadcast({
1987
+ type: RefreshMessageTypes.TOKEN_DETAILS,
1988
+ payload: { tokenDetails: this.tokenDetails }
1989
+ });
1990
+ console.log(`[RefreshWorker] Token refreshed`);
1991
+ console.log(`[RefreshWorker] Scheduling timers, expiry in ${this.tokenDetails.expires_in}s`);
1992
+ this.scheduleTimers(this.tokenDetails.expires_in);
1993
+ }
1994
+ catch (error) {
1995
+ this.broadcast({
1996
+ type: RefreshMessageTypes.ERROR_ON_REFRESH,
1997
+ error: error.message
1998
+ });
1999
+ console.log(`[RefreshWorker]`, error.message);
2000
+ }
2001
+ finally {
2002
+ this.refreshPromise = undefined;
2003
+ }
2004
+ }
2005
+ clearAllTimers() {
2006
+ if (this.refreshTimeout)
2007
+ clearTimeout(this.refreshTimeout);
2008
+ if (this.finalLogoutTimeout)
2009
+ clearTimeout(this.finalLogoutTimeout);
2010
+ this.timersAreRunning = false;
2011
+ }
2012
+ scheduleTimers(expiresIn) {
2013
+ this.clearAllTimers();
2014
+ this.timersAreRunning = true;
2015
+ const expiresInMs = expiresIn * 1000;
2016
+ const REFRESH_THRESHOLD_RATIO = 0.8;
2017
+ const MINIMUM_REFRESH_BUFFER_MS = 30 * 1000;
2018
+ const timeUntilRefresh = REFRESH_THRESHOLD_RATIO * expiresInMs;
2019
+ if (timeUntilRefresh > MINIMUM_REFRESH_BUFFER_MS) {
2020
+ this.refreshTimeout = setTimeout(() => this.performRefresh(), timeUntilRefresh);
2021
+ }
2022
+ const LOGOUT_WARNING_BUFFER_MS = 5 * 1000;
2023
+ const timeUntilLogout = expiresInMs - LOGOUT_WARNING_BUFFER_MS;
2024
+ this.finalLogoutTimeout = setTimeout(() => {
2025
+ this.tokenDetails = undefined;
2026
+ this.broadcast({ type: RefreshMessageTypes.EXPIRED });
2027
+ }, timeUntilLogout);
2028
+ }
2029
+ isTokenExpired(exp, bufferSeconds = 0) {
2030
+ if (typeof exp !== 'number' || isNaN(exp)) {
2031
+ return true;
2032
+ }
2033
+ const currentTimeSeconds = Math.floor(Date.now() / 1000);
2034
+ return exp < (currentTimeSeconds + bufferSeconds);
2035
+ }
2036
+ setTokenDetails(tokenDetails) {
2037
+ this.tokenDetails = tokenDetails;
2038
+ }
2039
+ // For testing
2040
+ getTimersAreRunning() { return this.timersAreRunning; }
2041
+ getTokenDetails() { return this.tokenDetails; }
2042
+ }
2043
+
2044
+ export { RefreshMessageTypes, Refresher };