@agnostack/verifyd 2.5.0-alpha.4 → 2.5.0-beta.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.
Files changed (73) hide show
  1. package/dist/esm/lib/index.js +3 -3
  2. package/dist/esm/lib/utils/index.js +1 -1
  3. package/dist/esm/lib/utils/rawbody.js +1 -1
  4. package/dist/esm/lib/verification.js +6 -6
  5. package/dist/esm/react/hooks/index.js +1 -1
  6. package/dist/esm/react/hooks/useVerification.js +1 -1
  7. package/dist/esm/react/index.js +2 -2
  8. package/dist/esm/shared/WebCrypto.js +26 -8
  9. package/dist/esm/shared/authorization.js +2 -2
  10. package/dist/esm/shared/index.js +5 -5
  11. package/dist/esm/shared/request.js +1 -1
  12. package/dist/esm/shared/verification.js +4 -4
  13. package/dist/lib/index.d.ts +3 -3
  14. package/dist/lib/index.d.ts.map +1 -1
  15. package/dist/lib/index.js +3 -3
  16. package/dist/lib/index.js.map +1 -1
  17. package/dist/lib/types.d.ts +2 -2
  18. package/dist/lib/types.d.ts.map +1 -1
  19. package/dist/lib/utils/index.d.ts +1 -1
  20. package/dist/lib/utils/index.js +1 -1
  21. package/dist/lib/utils/index.js.map +1 -1
  22. package/dist/lib/utils/rawbody.js +2 -2
  23. package/dist/lib/utils/rawbody.js.map +1 -1
  24. package/dist/lib/verification.d.ts +2 -2
  25. package/dist/lib/verification.d.ts.map +1 -1
  26. package/dist/lib/verification.js +20 -20
  27. package/dist/lib/verification.js.map +1 -1
  28. package/dist/react/hooks/index.d.ts +1 -1
  29. package/dist/react/hooks/index.js +1 -1
  30. package/dist/react/hooks/index.js.map +1 -1
  31. package/dist/react/hooks/useVerification.js +4 -4
  32. package/dist/react/hooks/useVerification.js.map +1 -1
  33. package/dist/react/index.d.ts +2 -2
  34. package/dist/react/index.d.ts.map +1 -1
  35. package/dist/react/index.js +2 -2
  36. package/dist/react/index.js.map +1 -1
  37. package/dist/shared/WebCrypto.d.ts +55 -59
  38. package/dist/shared/WebCrypto.d.ts.map +1 -1
  39. package/dist/shared/WebCrypto.js +32 -14
  40. package/dist/shared/WebCrypto.js.map +1 -1
  41. package/dist/shared/authorization.d.ts +2 -2
  42. package/dist/shared/authorization.js +4 -4
  43. package/dist/shared/authorization.js.map +1 -1
  44. package/dist/shared/index.d.ts +5 -5
  45. package/dist/shared/index.d.ts.map +1 -1
  46. package/dist/shared/index.js +5 -5
  47. package/dist/shared/index.js.map +1 -1
  48. package/dist/shared/request.js +5 -5
  49. package/dist/shared/request.js.map +1 -1
  50. package/dist/shared/verification.d.ts +3 -6
  51. package/dist/shared/verification.d.ts.map +1 -1
  52. package/dist/shared/verification.js +19 -19
  53. package/dist/shared/verification.js.map +1 -1
  54. package/dist/umd/index.js +406 -471
  55. package/dist/umd/index.js.map +1 -1
  56. package/dist/umd/lib/index.d.ts +3 -3
  57. package/dist/umd/lib/index.d.ts.map +1 -1
  58. package/dist/umd/lib/types.d.ts +2 -2
  59. package/dist/umd/lib/types.d.ts.map +1 -1
  60. package/dist/umd/lib/utils/index.d.ts +1 -1
  61. package/dist/umd/lib/verification.d.ts +2 -2
  62. package/dist/umd/lib/verification.d.ts.map +1 -1
  63. package/dist/umd/react/hooks/index.d.ts +1 -1
  64. package/dist/umd/react/index.d.ts +2 -2
  65. package/dist/umd/react/index.d.ts.map +1 -1
  66. package/dist/umd/shared/WebCrypto.d.ts +55 -59
  67. package/dist/umd/shared/WebCrypto.d.ts.map +1 -1
  68. package/dist/umd/shared/authorization.d.ts +2 -2
  69. package/dist/umd/shared/index.d.ts +5 -5
  70. package/dist/umd/shared/index.d.ts.map +1 -1
  71. package/dist/umd/shared/verification.d.ts +3 -6
  72. package/dist/umd/shared/verification.d.ts.map +1 -1
  73. package/package.json +1 -1
package/dist/umd/index.js CHANGED
@@ -276,477 +276,442 @@
276
276
  };
277
277
  // #endregion lib-utils-js
278
278
 
279
- class WebCrypto {
280
- constructor({ crypto: _crypto, util: _util } = {}) {
281
- this._crypto = _crypto ?? {};
282
- this._util = _util ?? {};
283
- }
284
-
285
- get subtle() {
286
- return this._crypto?.subtle
287
- }
279
+ /******************************************************************************
280
+ Copyright (c) Microsoft Corporation.
281
+
282
+ Permission to use, copy, modify, and/or distribute this software for any
283
+ purpose with or without fee is hereby granted.
284
+
285
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
286
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
287
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
288
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
289
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
290
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
291
+ PERFORMANCE OF THIS SOFTWARE.
292
+ ***************************************************************************** */
293
+
294
+ function __awaiter(thisArg, _arguments, P, generator) {
295
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
296
+ return new (P || (P = Promise))(function (resolve, reject) {
297
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
298
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
299
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
300
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
301
+ });
302
+ }
303
+
304
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
305
+ var e = new Error(message);
306
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
307
+ };
288
308
 
289
- async getWebCrypto() {
290
- if (!this._crypto?.subtle) {
291
- // 1. Try globalThis.crypto (available in all browsers and Node 18+)
292
- if ((typeof globalThis !== 'undefined') && globalThis.crypto?.subtle) {
293
- this._crypto = globalThis.crypto;
294
- }
309
+ class WebCrypto {
310
+ constructor({ crypto: _crypto, util: _util, encoding } = {}) {
311
+ this._crypto = _crypto !== null && _crypto !== void 0 ? _crypto : {};
312
+ this._util = _util !== null && _util !== void 0 ? _util : {};
313
+ this._encoding = encoding;
295
314
  }
296
-
297
- // 2. If still no subtle, fall back to polyfills (Node.js < 18, unusual environments)
298
- // NOTE: Module names are assigned to variables to prevent bundlers (esbuild, webpack, etc.)
299
- // from statically resolving these optional dynamic imports at bundle time.
300
- if (!this._crypto?.subtle) {
301
- const cryptoPolyfill = 'isomorphic-webcrypto';
302
- const nodeCrypto = 'crypto';
303
- try {
304
- this._crypto = (await import(cryptoPolyfill)).default;
305
- } catch (_ignore) {
306
- console.info('Failed to import isomorphic-webcrypto, retrying w/ node crypto');
307
- try {
308
- this._crypto = (await import(nodeCrypto)).default;
309
- } catch (error) {
310
- // eslint-disable-next-line max-len
311
- console.error(`Failed to import node crypto, ensure 'isomorphic-webcrypto' (or node 'crypto') is installed and/or pass in implementation via 'new WebCrypto({ crypto })'`);
312
- throw error
313
- }
314
- }
315
+ get subtle() {
316
+ var _a;
317
+ return (_a = this._crypto) === null || _a === void 0 ? void 0 : _a.subtle;
315
318
  }
316
-
317
- if (!this._crypto?.subtle) {
318
- throw new CryptoError('Invalid crypto, missing subtle')
319
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
320
+ getWebCrypto() {
321
+ return __awaiter(this, void 0, void 0, function* () {
322
+ var _a, _b, _c, _d;
323
+ if (!((_a = this._crypto) === null || _a === void 0 ? void 0 : _a.subtle)) {
324
+ // 1. Try globalThis.crypto (available in all browsers and Node 18+)
325
+ if ((typeof globalThis !== 'undefined') && ((_b = globalThis.crypto) === null || _b === void 0 ? void 0 : _b.subtle)) {
326
+ this._crypto = globalThis.crypto;
327
+ }
328
+ }
329
+ // 2. If still no subtle, fall back to polyfills (Node.js < 18, unusual environments)
330
+ // NOTE: Module names are assigned to variables to prevent bundlers (esbuild, webpack, etc.)
331
+ // from statically resolving these optional dynamic imports at bundle time.
332
+ if (!((_c = this._crypto) === null || _c === void 0 ? void 0 : _c.subtle)) {
333
+ const cryptoPolyfill = 'isomorphic-webcrypto';
334
+ const nodeCrypto = 'crypto';
335
+ try {
336
+ this._crypto = (yield import(cryptoPolyfill)).default;
337
+ }
338
+ catch (_ignore) {
339
+ console.info('Failed to import isomorphic-webcrypto, retrying w/ node crypto');
340
+ try {
341
+ this._crypto = (yield import(nodeCrypto)).default;
342
+ }
343
+ catch (error) {
344
+ // eslint-disable-next-line max-len
345
+ console.error(`Failed to import node crypto, ensure 'isomorphic-webcrypto' (or node 'crypto') is installed and/or pass in implementation via 'new WebCrypto({ crypto })'`);
346
+ throw error;
347
+ }
348
+ }
349
+ }
350
+ if (!((_d = this._crypto) === null || _d === void 0 ? void 0 : _d.subtle)) {
351
+ throw new CryptoError('Invalid crypto, missing subtle');
352
+ }
353
+ return this._crypto;
354
+ });
319
355
  }
320
-
321
- return this._crypto
322
- }
323
-
324
- async getTextDecoder() {
325
- if (this._util?.TextDecoder) {
326
- return this._util.TextDecoder
356
+ getTextDecoder() {
357
+ return __awaiter(this, void 0, void 0, function* () {
358
+ var _a;
359
+ if ((_a = this._util) === null || _a === void 0 ? void 0 : _a.TextDecoder) {
360
+ return this._util.TextDecoder;
361
+ }
362
+ if ((typeof globalThis !== 'undefined') && (typeof globalThis.TextDecoder === 'function')) {
363
+ return globalThis.TextDecoder;
364
+ }
365
+ if ((typeof window !== 'undefined') && (typeof window.TextDecoder === 'function')) {
366
+ return window.TextDecoder;
367
+ }
368
+ // NOTE: Module name assigned to variable to prevent bundlers (esbuild, webpack, etc.)
369
+ // from statically resolving this optional dynamic import at bundle time.
370
+ const nodeUtil = 'util';
371
+ try {
372
+ const TextDecoder = (yield import(nodeUtil)).TextDecoder;
373
+ this._util.TextDecoder = TextDecoder;
374
+ return TextDecoder;
375
+ }
376
+ catch (error) {
377
+ console.error(`Failed to import 'utils.TextDecoder', ensure 'util' is available and/or pass in implementation via 'new WebCrypto({ util })'`);
378
+ throw error;
379
+ }
380
+ });
327
381
  }
328
-
329
- if ((typeof globalThis !== 'undefined') && (typeof globalThis.TextDecoder === 'function')) {
330
- return globalThis.TextDecoder
382
+ getTextEncoder() {
383
+ return __awaiter(this, void 0, void 0, function* () {
384
+ var _a;
385
+ if ((_a = this._util) === null || _a === void 0 ? void 0 : _a.TextEncoder) {
386
+ return this._util.TextEncoder;
387
+ }
388
+ if ((typeof globalThis !== 'undefined') && (typeof globalThis.TextEncoder === 'function')) {
389
+ return globalThis.TextEncoder;
390
+ }
391
+ if ((typeof window !== 'undefined') && (typeof window.TextEncoder === 'function')) {
392
+ return window.TextEncoder;
393
+ }
394
+ // NOTE: Module name assigned to variable to prevent bundlers (esbuild, webpack, etc.)
395
+ // from statically resolving this optional dynamic import at bundle time.
396
+ const nodeUtil = 'util';
397
+ try {
398
+ const TextEncoder = (yield import(nodeUtil)).TextEncoder;
399
+ this._util.TextEncoder = TextEncoder;
400
+ return TextEncoder;
401
+ }
402
+ catch (error) {
403
+ console.error(`Failed to import 'utils.TextEncoder', ensure 'util' is available and/or pass in implementation via 'new WebCrypto({ util })'`);
404
+ throw error;
405
+ }
406
+ });
331
407
  }
332
-
333
- if ((typeof window !== 'undefined') && (typeof window.TextDecoder === 'function')) {
334
- return window.TextDecoder
408
+ timingSafeEqual(value1, value2) {
409
+ if ((value1 == undefined) ||
410
+ (value2 == undefined) ||
411
+ (value1.length !== value2.length)) {
412
+ return false;
413
+ }
414
+ let result = 0;
415
+ // eslint-disable-next-line no-plusplus
416
+ for (let i = 0; i < value1.length; i++) {
417
+ // eslint-disable-next-line no-bitwise
418
+ result |= value1[i] ^ value2[i];
419
+ }
420
+ return (result === 0);
335
421
  }
336
-
337
- // NOTE: Module name assigned to variable to prevent bundlers (esbuild, webpack, etc.)
338
- // from statically resolving this optional dynamic import at bundle time.
339
- const nodeUtil = 'util';
340
- try {
341
- const TextDecoder = (await import(nodeUtil)).TextDecoder;
342
- this._util.TextDecoder = TextDecoder;
343
-
344
- return TextDecoder
345
- } catch (error) {
346
- console.error(`Failed to import 'utils.TextDecoder', ensure 'util' is available and/or pass in implementation via 'new WebCrypto({ util })'`);
347
- throw error
422
+ stringToHex(stringValue) {
423
+ return (Array.from(ensureString(stringValue), (char) => (char.charCodeAt(0).toString(16).padStart(2, '0'))).join(''));
348
424
  }
349
- }
350
-
351
- async getTextEncoder() {
352
- if (this._util?.TextEncoder) {
353
- return this._util.TextEncoder
425
+ hexToString(hexValue) {
426
+ var _a;
427
+ if (!isString(hexValue)) {
428
+ throw new CryptoError('hexValue must be a string');
429
+ }
430
+ if (!/^(?:[0-9a-f]{2})+$/.test(hexValue)) {
431
+ throw new CryptoError('hexValue must be a valid hex string');
432
+ }
433
+ return ensureArray((_a = hexValue.match(/.{1,2}/g)) !== null && _a !== void 0 ? _a : [])
434
+ .map((byte) => String.fromCharCode(parseInt(byte, 16)))
435
+ .join('');
354
436
  }
355
-
356
- if ((typeof globalThis !== 'undefined') && (typeof globalThis.TextEncoder === 'function')) {
357
- return globalThis.TextEncoder
437
+ arrayBufferToString(arrayBuffer) {
438
+ return __awaiter(this, void 0, void 0, function* () {
439
+ const uint8Array = new Uint8Array(arrayBuffer);
440
+ const Decoder = yield this.getTextDecoder();
441
+ return new Decoder().decode(uint8Array);
442
+ });
358
443
  }
359
-
360
- if ((typeof window !== 'undefined') && (typeof window.TextEncoder === 'function')) {
361
- return window.TextEncoder
444
+ arrayToArrayBuffer(array) {
445
+ // Defensive `ArrayBuffer.from` check is vestigial (no such standard method),
446
+ // but preserved to keep this conversion behavior-identical to the .js source.
447
+ return (
448
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
449
+ (ArrayBuffer.from != undefined)
450
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
451
+ ? ArrayBuffer.from(array)
452
+ : new Uint8Array(array).buffer);
362
453
  }
363
-
364
- // NOTE: Module name assigned to variable to prevent bundlers (esbuild, webpack, etc.)
365
- // from statically resolving this optional dynamic import at bundle time.
366
- const nodeUtil = 'util';
367
- try {
368
- const TextEncoder = (await import(nodeUtil)).TextEncoder;
369
- this._util.TextEncoder = TextEncoder;
370
-
371
- return TextEncoder
372
- } catch (error) {
373
- console.error(`Failed to import 'utils.TextEncoder', ensure 'util' is available and/or pass in implementation via 'new WebCrypto({ util })'`);
374
- throw error
454
+ ensureArrayBuffer(arrayOrArrayBuffer) {
455
+ return ((arrayOrArrayBuffer instanceof ArrayBuffer)
456
+ ? arrayOrArrayBuffer
457
+ : this.arrayToArrayBuffer(arrayOrArrayBuffer));
375
458
  }
376
- }
377
-
378
- timingSafeEqual(value1, value2) {
379
- if (
380
- (value1 == undefined) ||
381
- (value2 == undefined) ||
382
- (value1.length !== value2.length)
383
- ) {
384
- return false
459
+ getKeyOperations(keyType) {
460
+ switch (keyType) {
461
+ case 'paired':
462
+ case 'private':
463
+ case 'privateKey': {
464
+ return ['deriveKey'];
465
+ }
466
+ case 'secret':
467
+ case 'secretKey':
468
+ case 'sharedSecret': {
469
+ return ['encrypt', 'decrypt'];
470
+ }
471
+ case 'hmac': {
472
+ return ['sign', 'verify'];
473
+ }
474
+ default: {
475
+ return [];
476
+ }
477
+ }
385
478
  }
386
-
387
- let result = 0;
388
- // eslint-disable-next-line no-plusplus
389
- for (let i = 0; i < value1.length; i++) {
390
- // eslint-disable-next-line no-bitwise
391
- result |= value1[i] ^ value2[i];
479
+ getKeyAlgorythm(keyType) {
480
+ switch (keyType) {
481
+ case 'derivedKey':
482
+ case 'derived':
483
+ case 'secret':
484
+ case 'secretKey':
485
+ case 'sharedSecret': {
486
+ return {
487
+ name: 'AES-GCM',
488
+ };
489
+ }
490
+ case 'hmac': {
491
+ return {
492
+ name: 'HMAC',
493
+ hash: { name: 'SHA-256' },
494
+ };
495
+ }
496
+ default: {
497
+ return {
498
+ name: 'ECDH',
499
+ namedCurve: 'P-256',
500
+ };
501
+ }
502
+ }
392
503
  }
393
-
394
- return (result === 0)
395
- }
396
-
397
- stringToHex(stringValue) {
398
- return (
399
- Array.from(ensureString(stringValue), (char) => (
400
- char.charCodeAt(0).toString(16).padStart(2, '0')
401
- )).join('')
402
- )
403
- }
404
-
405
- hexToString(hexValue) {
406
- if (!isString(hexValue)) {
407
- throw new CryptoError('hexValue must be a string')
504
+ generateKeyPair() {
505
+ return __awaiter(this, void 0, void 0, function* () {
506
+ const crypto = yield this.getWebCrypto();
507
+ const keyPair = yield crypto.subtle.generateKey(this.getKeyAlgorythm('paired'), true, this.getKeyOperations('paired'));
508
+ return keyPair;
509
+ });
408
510
  }
409
-
410
- if (!/^(?:[0-9a-f]{2})+$/.test(hexValue)) {
411
- throw new CryptoError('hexValue must be a valid hex string')
511
+ generateSharedSecret() {
512
+ return __awaiter(this, void 0, void 0, function* () {
513
+ const crypto = yield this.getWebCrypto();
514
+ const keyPair = yield crypto.subtle.generateKey(this.getKeyAlgorythm('sharedSecret'), true, this.getKeyOperations('sharedSecret'));
515
+ return keyPair;
516
+ });
412
517
  }
413
-
414
- return ensureArray(hexValue.match(/.{1,2}/g))
415
- .map((byte) => String.fromCharCode(parseInt(byte, 16)))
416
- .join('')
417
- }
418
-
419
- async arrayBufferToString(arrayBuffer) {
420
- const uint8Array = new Uint8Array(arrayBuffer);
421
- const Decoder = await this.getTextDecoder();
422
- return new Decoder().decode(uint8Array)
423
- }
424
-
425
- arrayToArrayBuffer(array) {
426
- return (
427
- (ArrayBuffer.from != undefined)
428
- ? ArrayBuffer.from(array)
429
- : new Uint8Array(array).buffer
430
- )
431
- }
432
-
433
- ensureArrayBuffer(arrayOrArrayBuffer) {
434
- return (
435
- (arrayOrArrayBuffer instanceof ArrayBuffer)
436
- ? arrayOrArrayBuffer
437
- : this.arrayToArrayBuffer(arrayOrArrayBuffer)
438
- )
439
- }
440
-
441
- getKeyOperations(keyType) {
442
- switch (keyType) {
443
- case 'paired':
444
- case 'private':
445
- case 'privateKey': {
446
- return ['deriveKey']
447
- }
448
-
449
- case 'secret':
450
- case 'secretKey':
451
- case 'sharedSecret': {
452
- return ['encrypt', 'decrypt']
453
- }
454
-
455
- case 'hmac': {
456
- return ['sign', 'verify']
457
- }
458
-
459
- default: {
460
- return []
461
- }
518
+ importRawKey(keyType_1, rawBytes_1) {
519
+ return __awaiter(this, arguments, void 0, function* (keyType, rawBytes, { extractable = true } = {}) {
520
+ const crypto = yield this.getWebCrypto();
521
+ return crypto.subtle.importKey('raw', rawBytes, this.getKeyAlgorythm(keyType), extractable, this.getKeyOperations(keyType));
522
+ });
462
523
  }
463
- }
464
-
465
- getKeyAlgorythm(keyType) {
466
- switch (keyType) {
467
- case 'derivedKey':
468
- case 'derived':
469
- case 'secret':
470
- case 'secretKey':
471
- case 'sharedSecret': {
472
- return {
473
- name: 'AES-GCM',
474
- }
475
- }
476
-
477
- case 'hmac': {
478
- return {
479
- name: 'HMAC',
480
- hash: { name: 'SHA-256' },
481
- }
482
- }
483
-
484
- default: {
485
- return {
486
- name: 'ECDH',
487
- namedCurve: 'P-256',
488
- }
489
- }
524
+ generateHMAC(message, derivedKey) {
525
+ return __awaiter(this, void 0, void 0, function* () {
526
+ if (!message || !derivedKey) {
527
+ return undefined;
528
+ }
529
+ const crypto = yield this.getWebCrypto();
530
+ const Encoder = yield this.getTextEncoder();
531
+ const signature = yield crypto.subtle.sign('HMAC', derivedKey, new Encoder().encode(message));
532
+ return this.stringToHex(yield this.arrayBufferToString(signature));
533
+ });
490
534
  }
491
- }
492
-
493
- async generateKeyPair() {
494
- const crypto = await this.getWebCrypto();
495
- const keyPair = await crypto.subtle.generateKey(
496
- this.getKeyAlgorythm('paired'),
497
- true,
498
- this.getKeyOperations('paired')
499
- );
500
-
501
- return keyPair
502
- }
503
-
504
- async generateSharedSecret() {
505
- const crypto = await this.getWebCrypto();
506
- const keyPair = await crypto.subtle.generateKey(
507
- this.getKeyAlgorythm('sharedSecret'),
508
- true,
509
- this.getKeyOperations('sharedSecret')
510
- );
511
-
512
- return keyPair
513
- }
514
-
515
- async importRawKey(keyType, rawBytes, { extractable = true } = {}) {
516
- const crypto = await this.getWebCrypto();
517
-
518
- return crypto.subtle.importKey(
519
- 'raw',
520
- rawBytes,
521
- this.getKeyAlgorythm(keyType),
522
- extractable,
523
- this.getKeyOperations(keyType)
524
- )
525
- }
526
-
527
- async generateHMAC(message, derivedKey) {
528
- if (!message || !derivedKey) {
529
- return undefined
530
- }
531
-
532
- const crypto = await this.getWebCrypto();
533
- const Encoder = await this.getTextEncoder();
534
-
535
- const signature = await crypto.subtle.sign(
536
- 'HMAC',
537
- derivedKey,
538
- new Encoder().encode(message)
539
- );
540
-
541
- return this.stringToHex(
542
- this.arrayBufferToString(signature)
543
- )
544
- }
545
-
546
- async verifyHMAC(message, derivedKey, verifiableHMAC) {
547
- const calculatedHMAC = await this.generateHMAC(message, derivedKey);
548
-
549
- return this.timingSafeEqual(calculatedHMAC, verifiableHMAC)
550
- }
551
-
552
- async createSignedToken(message, hmacKey, ttlSeconds) {
553
- const expiry = Math.floor(Date.now() / 1000) + ttlSeconds;
554
- const hmacHex = await this.generateHMAC(`${message}:${expiry}`, hmacKey);
555
-
556
- return `${expiry}.${hmacHex}`
557
- }
558
-
559
- async verifySignedToken(token, message, hmacKey) {
560
- if (!token || typeof token !== 'string') {
561
- return false
535
+ verifyHMAC(message, derivedKey, verifiableHMAC) {
536
+ return __awaiter(this, void 0, void 0, function* () {
537
+ const calculatedHMAC = yield this.generateHMAC(message, derivedKey);
538
+ return this.timingSafeEqual(calculatedHMAC, verifiableHMAC);
539
+ });
562
540
  }
563
-
564
- const dotIndex = token.indexOf('.');
565
- if (dotIndex === -1) {
566
- return false
541
+ createSignedToken(message, hmacKey, ttlSeconds) {
542
+ return __awaiter(this, void 0, void 0, function* () {
543
+ const expiry = Math.floor(Date.now() / 1000) + ttlSeconds;
544
+ const hmacHex = yield this.generateHMAC(`${message}:${expiry}`, hmacKey);
545
+ return `${expiry}.${hmacHex}`;
546
+ });
567
547
  }
568
-
569
- const expiryStr = token.substring(0, dotIndex);
570
- const signature = token.substring(dotIndex + 1);
571
-
572
- const expiry = parseInt(expiryStr, 10);
573
- if (isNaN(expiry) || expiry <= Math.floor(Date.now() / 1000)) {
574
- return false
548
+ verifySignedToken(token, message, hmacKey) {
549
+ return __awaiter(this, void 0, void 0, function* () {
550
+ if (!token || typeof token !== 'string') {
551
+ return false;
552
+ }
553
+ const dotIndex = token.indexOf('.');
554
+ if (dotIndex === -1) {
555
+ return false;
556
+ }
557
+ const expiryStr = token.substring(0, dotIndex);
558
+ const signature = token.substring(dotIndex + 1);
559
+ const expiry = parseInt(expiryStr, 10);
560
+ if (isNaN(expiry) || expiry <= Math.floor(Date.now() / 1000)) {
561
+ return false;
562
+ }
563
+ return this.verifyHMAC(`${message}:${expiryStr}`, hmacKey, signature);
564
+ });
575
565
  }
576
-
577
- return this.verifyHMAC(`${message}:${expiryStr}`, hmacKey, signature)
578
- }
579
-
580
- // NOTE: intentionally separated out as async to be able to .catch
581
- async getStorableKey(key) {
582
- const crypto = await this.getWebCrypto();
583
-
584
- const exportedJWK = await crypto.subtle.exportKey('jwk', key);
585
- return this.stringToHex(JSON.stringify(exportedJWK))
586
- }
587
-
588
- // NOTE: intentionally separated out as async to be able to .catch
589
- async parseStorableHex(storableHex) {
590
- return JSON.parse(this.hexToString(storableHex) || '{}')
591
- }
592
-
593
- async restoreStorableKey(keyType, storableHex) {
594
- // eslint-disable-next-line eqeqeq
595
- if (storableHex == undefined) {
596
- return undefined
566
+ // NOTE: intentionally separated out as async to be able to .catch
567
+ getStorableKey(key) {
568
+ return __awaiter(this, void 0, void 0, function* () {
569
+ const crypto = yield this.getWebCrypto();
570
+ const exportedJWK = yield crypto.subtle.exportKey('jwk', key);
571
+ return this.stringToHex(JSON.stringify(exportedJWK));
572
+ });
597
573
  }
598
- const crypto = await this.getWebCrypto();
599
-
600
- const exportedJWK = await this.parseStorableHex(storableHex).catch((ignore) => {
601
- console.error('Failed to parse storable hex value', ignore);
602
- return undefined
603
- });
604
- if (objectEmpty(exportedJWK)) {
605
- return undefined
574
+ // NOTE: intentionally separated out as async to be able to .catch
575
+ parseStorableHex(storableHex) {
576
+ return __awaiter(this, void 0, void 0, function* () {
577
+ return JSON.parse(this.hexToString(storableHex) || '{}');
578
+ });
606
579
  }
607
-
608
- return crypto.subtle.importKey(
609
- 'jwk',
610
- exportedJWK,
611
- this.getKeyAlgorythm(keyType),
612
- true,
613
- this.getKeyOperations(keyType)
614
- )
615
- }
616
-
617
- async getStorableKeyPair(keyPair) {
618
- const storableKeys = {};
619
-
620
- // eslint-disable-next-line no-restricted-syntax
621
- for (const [keyType, key] of Object.entries(keyPair)) {
622
- // eslint-disable-next-line no-await-in-loop
623
- storableKeys[keyType] = await this.getStorableKey(key);
580
+ restoreStorableKey(keyType, storableHex) {
581
+ return __awaiter(this, void 0, void 0, function* () {
582
+ // eslint-disable-next-line eqeqeq
583
+ if (storableHex == undefined) {
584
+ return undefined;
585
+ }
586
+ const crypto = yield this.getWebCrypto();
587
+ const exportedJWK = yield this.parseStorableHex(storableHex).catch((ignore) => {
588
+ console.error('Failed to parse storable hex value', ignore);
589
+ return undefined;
590
+ });
591
+ if (objectEmpty(exportedJWK)) {
592
+ return undefined;
593
+ }
594
+ return crypto.subtle.importKey('jwk', exportedJWK, this.getKeyAlgorythm(keyType), true, this.getKeyOperations(keyType));
595
+ });
624
596
  }
625
-
626
- return storableKeys
627
- }
628
-
629
- async restoreStorableKeyPair(keyPair) {
630
- const restoredKeys = {};
631
-
632
- // eslint-disable-next-line no-restricted-syntax
633
- for (const [keyType, key] of Object.entries(keyPair)) {
634
- // eslint-disable-next-line no-await-in-loop
635
- restoredKeys[keyType] = await this.restoreStorableKey(keyType, key);
597
+ getStorableKeyPair(keyPair) {
598
+ return __awaiter(this, void 0, void 0, function* () {
599
+ const storableKeys = {};
600
+ // eslint-disable-next-line no-restricted-syntax
601
+ for (const [keyType, key] of Object.entries(keyPair)) {
602
+ // eslint-disable-next-line no-await-in-loop
603
+ storableKeys[keyType] = yield this.getStorableKey(key);
604
+ }
605
+ return storableKeys;
606
+ });
636
607
  }
637
-
638
- return restoredKeys
639
- }
640
-
641
- async deriveSharedKey({ publicKey, privateKey }) {
642
- if (!publicKey || !privateKey) {
643
- return undefined
608
+ restoreStorableKeyPair(keyPair) {
609
+ return __awaiter(this, void 0, void 0, function* () {
610
+ const restoredKeys = {};
611
+ // eslint-disable-next-line no-restricted-syntax
612
+ for (const [keyType, key] of Object.entries(keyPair)) {
613
+ // eslint-disable-next-line no-await-in-loop
614
+ restoredKeys[keyType] = yield this.restoreStorableKey(keyType, key);
615
+ }
616
+ return restoredKeys;
617
+ });
644
618
  }
645
-
646
- const crypto = await this.getWebCrypto();
647
- const derivedKey = await crypto.subtle.deriveKey(
648
- {
649
- name: 'ECDH',
650
- public: publicKey,
651
- },
652
- privateKey,
653
- {
654
- name: 'AES-GCM',
655
- length: 256,
656
- },
657
- true,
658
- ['encrypt', 'decrypt']
659
- );
660
- return derivedKey
661
- }
662
-
663
- async deriveHMACKey({ publicKey, privateKey }) {
664
- if (!publicKey || !privateKey) {
665
- return undefined
619
+ deriveSharedKey(_a) {
620
+ return __awaiter(this, arguments, void 0, function* ({ publicKey, privateKey }) {
621
+ if (!publicKey || !privateKey) {
622
+ return undefined;
623
+ }
624
+ const crypto = yield this.getWebCrypto();
625
+ const derivedKey = yield crypto.subtle.deriveKey({
626
+ name: 'ECDH',
627
+ public: publicKey,
628
+ }, privateKey, {
629
+ name: 'AES-GCM',
630
+ length: 256,
631
+ }, true, ['encrypt', 'decrypt']);
632
+ return derivedKey;
633
+ });
666
634
  }
667
-
668
- const crypto = await this.getWebCrypto();
669
- const derivedKey = await crypto.subtle.deriveKey(
670
- {
671
- name: 'ECDH',
672
- public: publicKey,
673
- },
674
- privateKey,
675
- {
676
- name: 'HMAC',
677
- hash: { name: 'SHA-256' },
678
- length: 256, // Adjusted key length, e.g., 128 bits
679
- },
680
- true,
681
- ['sign', 'verify']
682
- );
683
- return derivedKey
684
- }
685
-
686
- async getVerificationKeys({ publicKey, privateKey }) {
687
- if (!publicKey || !privateKey) {
688
- return {}
635
+ deriveHMACKey(_a) {
636
+ return __awaiter(this, arguments, void 0, function* ({ publicKey, privateKey }) {
637
+ if (!publicKey || !privateKey) {
638
+ return undefined;
639
+ }
640
+ const crypto = yield this.getWebCrypto();
641
+ const derivedKey = yield crypto.subtle.deriveKey({
642
+ name: 'ECDH',
643
+ public: publicKey,
644
+ }, privateKey, {
645
+ name: 'HMAC',
646
+ hash: { name: 'SHA-256' },
647
+ length: 256, // Adjusted key length, e.g., 128 bits
648
+ }, true, ['sign', 'verify']);
649
+ return derivedKey;
650
+ });
689
651
  }
690
-
691
- const sharedKeyPair = await this.restoreStorableKeyPair({ publicKey, privateKey });
692
- const derivedHMACKey = await this.deriveHMACKey(sharedKeyPair);
693
- const derivedSecretKey = await this.deriveSharedKey(sharedKeyPair);
694
-
695
- return {
696
- derivedSecretKey,
697
- derivedHMACKey,
652
+ getVerificationKeys(_a) {
653
+ return __awaiter(this, arguments, void 0, function* ({ publicKey, privateKey }) {
654
+ if (!publicKey || !privateKey) {
655
+ return {};
656
+ }
657
+ const sharedKeyPair = yield this.restoreStorableKeyPair({ publicKey, privateKey });
658
+ const derivedHMACKey = yield this.deriveHMACKey(sharedKeyPair);
659
+ const derivedSecretKey = yield this.deriveSharedKey(sharedKeyPair);
660
+ return {
661
+ derivedSecretKey,
662
+ derivedHMACKey,
663
+ };
664
+ });
698
665
  }
699
- }
700
-
701
- async encryptMessage(decryptedMessage, derivedKey) {
702
- if (!decryptedMessage || !derivedKey) {
703
- return undefined
666
+ encryptMessage(decryptedMessage, derivedKey) {
667
+ return __awaiter(this, void 0, void 0, function* () {
668
+ if (!decryptedMessage || !derivedKey) {
669
+ return undefined;
670
+ }
671
+ const crypto = yield this.getWebCrypto();
672
+ const iv = crypto.getRandomValues(new Uint8Array(12));
673
+ const Encoder = yield this.getTextEncoder();
674
+ const encodedMessage = new Encoder().encode(decryptedMessage);
675
+ const ciphertext = yield crypto.subtle.encrypt({
676
+ name: 'AES-GCM',
677
+ iv,
678
+ }, derivedKey, encodedMessage);
679
+ const encryptedMessage = new Uint8Array([
680
+ ...iv,
681
+ ...new Uint8Array(ciphertext)
682
+ ]);
683
+ if (this._encoding === 'base64') {
684
+ // btoa is universal in browsers + Node 16+; no polyfill needed.
685
+ // String.fromCharCode + spread is safe for the small payloads we produce
686
+ // (IV + ciphertext + tag — typically < 100KB even for large messages).
687
+ return btoa(String.fromCharCode(...encryptedMessage));
688
+ }
689
+ return Array.from(encryptedMessage);
690
+ });
704
691
  }
705
-
706
- const crypto = await this.getWebCrypto();
707
- const iv = crypto.getRandomValues(new Uint8Array(12));
708
- const Encoder = await this.getTextEncoder();
709
- const encodedMessage = new Encoder().encode(decryptedMessage);
710
- const ciphertext = await crypto.subtle.encrypt(
711
- {
712
- name: 'AES-GCM',
713
- iv,
714
- },
715
- derivedKey,
716
- encodedMessage
717
- );
718
-
719
- const encryptedMessage = new Uint8Array([
720
- ...iv,
721
- ...new Uint8Array(ciphertext)
722
- ]);
723
- return Array.from(encryptedMessage)
724
- }
725
-
726
- async decryptMessage(encryptedMessage, derivedKey) {
727
- if (!encryptedMessage || !derivedKey) {
728
- return undefined
692
+ decryptMessage(encryptedMessage, derivedKey) {
693
+ return __awaiter(this, void 0, void 0, function* () {
694
+ if (!encryptedMessage || !derivedKey) {
695
+ return undefined;
696
+ }
697
+ const crypto = yield this.getWebCrypto();
698
+ // When encoding === 'base64', the input is a base64 string from a matching
699
+ // encryptMessage call on a peer instance with the same option. Otherwise,
700
+ // accept number[] / ArrayBuffer (existing behavior).
701
+ const encryptedArrayBuffer = (this._encoding === 'base64')
702
+ ? Uint8Array.from(atob(encryptedMessage), (c) => c.charCodeAt(0)).buffer
703
+ : this.ensureArrayBuffer(encryptedMessage);
704
+ const iv = encryptedArrayBuffer.slice(0, 12);
705
+ const ciphertext = encryptedArrayBuffer.slice(12);
706
+ const decryptedArrayBuffer = yield crypto.subtle.decrypt({
707
+ name: 'AES-GCM',
708
+ iv,
709
+ }, derivedKey, ciphertext);
710
+ const Decoder = yield this.getTextDecoder();
711
+ const decryptedMessage = new Decoder().decode(decryptedArrayBuffer);
712
+ return decryptedMessage;
713
+ });
729
714
  }
730
-
731
- const crypto = await this.getWebCrypto();
732
- // NOTE: this presumed an array or arrayBuffer coming in as encryptedMessage (will fail w/ IV error if its a string)
733
- const encryptedArrayBuffer = this.ensureArrayBuffer(encryptedMessage);
734
- const iv = encryptedArrayBuffer.slice(0, 12);
735
- const ciphertext = encryptedArrayBuffer.slice(12);
736
-
737
- const decryptedArrayBuffer = await crypto.subtle.decrypt(
738
- {
739
- name: 'AES-GCM',
740
- iv,
741
- },
742
- derivedKey,
743
- ciphertext
744
- );
745
-
746
- const Decoder = await this.getTextDecoder();
747
- const decryptedMessage = new Decoder().decode(decryptedArrayBuffer);
748
- return decryptedMessage
749
- }
750
715
  }
751
716
 
752
717
  const getAuthorizationHelpers = async (sharedSecret, { crypto: _crypto, util: _util } = {}) => {
@@ -994,36 +959,6 @@
994
959
  })
995
960
  );
996
961
 
997
- /******************************************************************************
998
- Copyright (c) Microsoft Corporation.
999
-
1000
- Permission to use, copy, modify, and/or distribute this software for any
1001
- purpose with or without fee is hereby granted.
1002
-
1003
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1004
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1005
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1006
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1007
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1008
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1009
- PERFORMANCE OF THIS SOFTWARE.
1010
- ***************************************************************************** */
1011
-
1012
- function __awaiter(thisArg, _arguments, P, generator) {
1013
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1014
- return new (P || (P = Promise))(function (resolve, reject) {
1015
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1016
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1017
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1018
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1019
- });
1020
- }
1021
-
1022
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
1023
- var e = new Error(message);
1024
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1025
- };
1026
-
1027
962
  const generateStorableKeyPairs = (...args_1) => __awaiter(void 0, [...args_1], void 0, function* ({ crypto: _crypto, util: _util } = {}) {
1028
963
  const webCrypto = new WebCrypto({ crypto: _crypto, util: _util });
1029
964
  const sharedKeyPair = yield webCrypto.generateKeyPair();
@@ -1068,7 +1003,7 @@
1068
1003
  publicKey: ephemeralPublicKey,
1069
1004
  privateKey: keyPairs.shared.privateKey,
1070
1005
  });
1071
- if (!verificationKeys) {
1006
+ if (!(verificationKeys === null || verificationKeys === void 0 ? void 0 : verificationKeys.derivedHMACKey) || !verificationKeys.derivedSecretKey) {
1072
1007
  throw new VerificationError('Invalid or missing verification', { code: 412 });
1073
1008
  }
1074
1009
  const verificationPayload = objectToSortedString(Object.assign({ method: getRequestMethod(rawBody, req.method), timestamp: customAuthTimestamp, body: requestBody }, normalizeURIParts(uri)));