@fgv/ts-web-extras 5.1.0-18 → 5.1.0-19

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 (64) hide show
  1. package/.rush/temp/{680645452ebdb4d7f294f08d3b45f143d69c3f5d.tar.log → 42a7a953924ae898114e7b6231a2408228d92433.tar.log} +8 -2
  2. package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +19 -17
  3. package/.rush/temp/operation/build/all.log +19 -17
  4. package/.rush/temp/operation/build/log-chunks.jsonl +19 -17
  5. package/.rush/temp/operation/build/state.json +1 -1
  6. package/dist/packlets/crypto-utils/browserCryptoProvider.js +118 -1
  7. package/dist/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
  8. package/dist/test/unit/browserCryptoProvider.wrapBytes.test.js +221 -0
  9. package/dist/test/unit/browserCryptoProvider.wrapBytes.test.js.map +1 -0
  10. package/dist/ts-web-extras.d.ts +19 -0
  11. package/docs/CryptoUtils/classes/BrowserCryptoProvider.md +28 -0
  12. package/docs/CryptoUtils/classes/BrowserCryptoProvider.unwrapBytes.md +27 -0
  13. package/docs/CryptoUtils/classes/BrowserCryptoProvider.wrapBytes.md +28 -0
  14. package/docs/classes/BrowserCryptoProvider.md +28 -0
  15. package/docs/classes/BrowserCryptoProvider.unwrapBytes.md +27 -0
  16. package/docs/classes/BrowserCryptoProvider.wrapBytes.md +28 -0
  17. package/etc/ts-web-extras.api.md +5 -0
  18. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts +19 -0
  19. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts.map +1 -1
  20. package/lib/packlets/crypto-utils/browserCryptoProvider.js +118 -1
  21. package/lib/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
  22. package/lib/test/unit/browserCryptoProvider.wrapBytes.test.d.ts +2 -0
  23. package/lib/test/unit/browserCryptoProvider.wrapBytes.test.d.ts.map +1 -0
  24. package/lib/test/unit/browserCryptoProvider.wrapBytes.test.js +223 -0
  25. package/lib/test/unit/browserCryptoProvider.wrapBytes.test.js.map +1 -0
  26. package/package.json +14 -14
  27. package/rush-logs/ts-web-extras.build.cache.log +1 -1
  28. package/rush-logs/ts-web-extras.build.log +19 -17
  29. package/src/packlets/crypto-utils/browserCryptoProvider.ts +168 -1
  30. package/src/test/unit/browserCryptoProvider.wrapBytes.test.ts +325 -0
  31. package/temp/build/typescript/ts_8nwakTlr.json +1 -1
  32. package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +508 -7
  33. package/temp/coverage/crypto-utils/browserHashProvider.ts.html +1 -1
  34. package/temp/coverage/crypto-utils/index.html +9 -9
  35. package/temp/coverage/file-tree/directoryHandleStore.ts.html +1 -1
  36. package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +1 -1
  37. package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +1 -1
  38. package/temp/coverage/file-tree/httpTreeAccessors.ts.html +1 -1
  39. package/temp/coverage/file-tree/index.html +1 -1
  40. package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +1 -1
  41. package/temp/coverage/helpers/fileTreeHelpers.ts.html +1 -1
  42. package/temp/coverage/helpers/index.html +1 -1
  43. package/temp/coverage/index.html +10 -10
  44. package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +508 -7
  45. package/temp/coverage/lcov-report/crypto-utils/browserHashProvider.ts.html +1 -1
  46. package/temp/coverage/lcov-report/crypto-utils/index.html +9 -9
  47. package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +1 -1
  48. package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +1 -1
  49. package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +1 -1
  50. package/temp/coverage/lcov-report/file-tree/httpTreeAccessors.ts.html +1 -1
  51. package/temp/coverage/lcov-report/file-tree/index.html +1 -1
  52. package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +1 -1
  53. package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +1 -1
  54. package/temp/coverage/lcov-report/helpers/index.html +1 -1
  55. package/temp/coverage/lcov-report/index.html +10 -10
  56. package/temp/coverage/lcov-report/url-utils/index.html +1 -1
  57. package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +1 -1
  58. package/temp/coverage/lcov.info +236 -25
  59. package/temp/coverage/url-utils/index.html +1 -1
  60. package/temp/coverage/url-utils/urlParams.ts.html +1 -1
  61. package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
  62. package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +1 -1
  63. package/temp/ts-web-extras.api.json +212 -0
  64. package/temp/ts-web-extras.api.md +5 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fgv/ts-web-extras",
3
- "version": "5.1.0-18",
3
+ "version": "5.1.0-19",
4
4
  "description": "Browser-compatible utilities and FileTree implementations",
5
5
  "main": "lib/index.js",
6
6
  "types": "dist/ts-web-extras.d.ts",
@@ -46,19 +46,19 @@
46
46
  "@types/react": "~19.2.8",
47
47
  "typedoc": "~0.28.16",
48
48
  "typedoc-plugin-markdown": "~4.9.0",
49
- "@fgv/heft-dual-rig": "5.1.0-18",
50
- "@fgv/typedoc-compact-theme": "5.1.0-18",
51
- "@fgv/ts-json-base": "5.1.0-18",
52
- "@fgv/ts-utils": "5.1.0-18",
53
- "@fgv/ts-utils-jest": "5.1.0-18",
54
- "@fgv/ts-extras": "5.1.0-18"
49
+ "@fgv/heft-dual-rig": "5.1.0-19",
50
+ "@fgv/typedoc-compact-theme": "5.1.0-19",
51
+ "@fgv/ts-utils": "5.1.0-19",
52
+ "@fgv/ts-extras": "5.1.0-19",
53
+ "@fgv/ts-json-base": "5.1.0-19",
54
+ "@fgv/ts-utils-jest": "5.1.0-19"
55
55
  },
56
56
  "peerDependencies": {
57
57
  "react": ">=18 <20",
58
58
  "react-dom": ">=18 <20",
59
- "@fgv/ts-utils": "5.1.0-18",
60
- "@fgv/ts-json-base": "5.1.0-18",
61
- "@fgv/ts-extras": "5.1.0-18"
59
+ "@fgv/ts-extras": "5.1.0-19",
60
+ "@fgv/ts-utils": "5.1.0-19",
61
+ "@fgv/ts-json-base": "5.1.0-19"
62
62
  },
63
63
  "exports": {
64
64
  ".": {
@@ -81,14 +81,14 @@
81
81
  "idb-keyval": "^6.2.2"
82
82
  },
83
83
  "scripts": {
84
- "build": "heft test --clean",
84
+ "build": "NODE_OPTIONS=--disable-warning=DEP0040 heft test --clean",
85
85
  "clean": "heft clean",
86
- "test": "heft test --clean",
86
+ "test": "NODE_OPTIONS=--disable-warning=DEP0040 heft test --clean",
87
87
  "build-docs": "typedoc --options ./config/typedoc.json",
88
88
  "build-all": "rushx build; rushx build-docs",
89
- "test-handles": "jest --runInBand --detectOpenHandles",
89
+ "test-handles": "NODE_OPTIONS=--disable-warning=DEP0040 jest --runInBand --detectOpenHandles",
90
90
  "clean-jest": "jest --clear-cache",
91
- "coverage": "jest --coverage",
91
+ "coverage": "NODE_OPTIONS=--disable-warning=DEP0040 jest --coverage",
92
92
  "lint": "eslint src --ext .ts",
93
93
  "fixlint": "eslint src --ext .ts --fix"
94
94
  }
@@ -1,3 +1,3 @@
1
1
  Caching build output folders: dist, lib, temp, .rush/temp/operation/build
2
2
  Successfully set cache entry.
3
- Cache key: 680645452ebdb4d7f294f08d3b45f143d69c3f5d
3
+ Cache key: 42a7a953924ae898114e7b6231a2408228d92433
@@ -1,42 +1,44 @@
1
- Invoking: heft test --clean
1
+ Invoking: NODE_OPTIONS=--disable-warning=DEP0040 heft test --clean
2
2
  ---- build started ----
3
3
  [build:typescript] The TypeScript compiler version 5.9.3 is newer than the latest version that was tested with Heft (5.8); it may not work correctly.
4
4
  [build:typescript] Using TypeScript version 5.9.3
5
5
  [build:api-extractor] Using API Extractor version 7.57.7
6
6
  [build:api-extractor] Analysis will use the bundled TypeScript version 5.8.2
7
7
  [build:api-extractor] *** The target project appears to use TypeScript 5.9.3 which is newer than the bundled compiler engine; consider upgrading API Extractor.
8
- ---- build finished (24.801s) ----
8
+ ---- build finished (23.128s) ----
9
9
  ---- test started ----
10
10
  [test:jest] Using Jest version 29.5.0
11
11
  [test:jest]
12
- [test:jest] Run start. 9 test suites
12
+ [test:jest] Run start. 10 test suites
13
13
  [test:jest] START lib/test/unit/httpTreeAccessors.test.js
14
14
  [test:jest] START lib/test/unit/fileApiTreeAccessors.test.js
15
15
  [test:jest] START lib/test/unit/localStorageTreeAccessors.test.js
16
16
  [test:jest] START lib/test/unit/fileSystemAccessTreeAccessors.test.js
17
- [test:jest] PASS lib/test/unit/localStorageTreeAccessors.test.js (duration: 2.975s, 44 passed, 0 failed)
17
+ [test:jest] PASS lib/test/unit/localStorageTreeAccessors.test.js (duration: 1.702s, 44 passed, 0 failed)
18
18
  [test:jest] START lib/test/unit/fileTreeHelpers.test.js
19
- [test:jest] PASS lib/test/unit/httpTreeAccessors.test.js (duration: 3.203s, 61 passed, 0 failed)
19
+ [test:jest] PASS lib/test/unit/httpTreeAccessors.test.js (duration: 2.103s, 61 passed, 0 failed)
20
20
  [test:jest] START lib/test/unit/fileApiTypes.test.js
21
- [test:jest] PASS lib/test/unit/fileApiTreeAccessors.test.js (duration: 3.464s, 65 passed, 0 failed)
21
+ [test:jest] PASS lib/test/unit/fileApiTreeAccessors.test.js (duration: 2.550s, 65 passed, 0 failed)
22
22
  [test:jest] START lib/test/unit/urlParams.test.js
23
- [test:jest] PASS lib/test/unit/fileSystemAccessTreeAccessors.test.js (duration: 1.300s, 44 passed, 0 failed)
23
+ [test:jest] PASS lib/test/unit/fileSystemAccessTreeAccessors.test.js (duration: 1.592s, 44 passed, 0 failed)
24
+ [test:jest] START lib/test/unit/browserCryptoProvider.wrapBytes.test.js
25
+ [test:jest] PASS lib/test/unit/fileApiTypes.test.js (duration: 1.647s, 36 passed, 0 failed)
24
26
  [test:jest] START lib/test/unit/directoryHandleStore.test.js
25
- [test:jest] PASS lib/test/unit/fileTreeHelpers.test.js (duration: 1.819s, 35 passed, 0 failed)
27
+ [test:jest] PASS lib/test/unit/fileTreeHelpers.test.js (duration: 2.006s, 35 passed, 0 failed)
26
28
  [test:jest] START lib/test/unit/browserHashProvider.test.js
27
- [test:jest] PASS lib/test/unit/fileApiTypes.test.js (duration: 1.579s, 36 passed, 0 failed)
28
- [test:jest] PASS lib/test/unit/urlParams.test.js (duration: 1.586s, 60 passed, 0 failed)
29
- [test:jest] PASS lib/test/unit/directoryHandleStore.test.js (duration: 1.282s, 19 passed, 0 failed)
30
- [test:jest] PASS lib/test/unit/browserHashProvider.test.js (duration: 1.520s, 15 passed, 0 failed)
29
+ [test:jest] PASS lib/test/unit/directoryHandleStore.test.js (duration: 1.362s, 19 passed, 0 failed)
30
+ [test:jest] PASS lib/test/unit/urlParams.test.js (duration: 1.974s, 60 passed, 0 failed)
31
+ [test:jest] PASS lib/test/unit/browserCryptoProvider.wrapBytes.test.js (duration: 2.015s, 26 passed, 0 failed)
32
+ [test:jest] PASS lib/test/unit/browserHashProvider.test.js (duration: 1.383s, 15 passed, 0 failed)
31
33
  [test:jest]
32
34
  [test:jest] Tests finished:
33
- [test:jest] Successes: 379
35
+ [test:jest] Successes: 405
34
36
  [test:jest] Failures: 0
35
- [test:jest] Total: 380
37
+ [test:jest] Total: 406
36
38
  -----------------------------------|---------|----------|---------|---------|-------------------
37
39
  File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
38
40
  -----------------------------------|---------|----------|---------|---------|-------------------
39
- All files | 100 | 99.62 | 100 | 100 |
41
+ All files | 100 | 99.64 | 100 | 100 |
40
42
  crypto-utils | 100 | 100 | 100 | 100 |
41
43
  browserCryptoProvider.ts | 100 | 100 | 100 | 100 |
42
44
  browserHashProvider.ts | 100 | 100 | 100 | 100 |
@@ -51,5 +53,5 @@ All files | 100 | 99.62 | 100 | 100 |
51
53
  url-utils | 100 | 100 | 100 | 100 |
52
54
  urlParams.ts | 100 | 100 | 100 | 100 |
53
55
  -----------------------------------|---------|----------|---------|---------|-------------------
54
- ---- test finished (10.229s) ----
55
- -------------------- Finished (35.048s) --------------------
56
+ ---- test finished (9.881s) ----
57
+ -------------------- Finished (33.035s) --------------------
@@ -18,10 +18,10 @@
18
18
  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  // SOFTWARE.
20
20
 
21
- /* c8 ignore start - Browser-only implementation cannot be tested in Node.js environment */
22
21
  import { captureAsyncResult, captureResult, fail, Failure, Result, succeed, Success } from '@fgv/ts-utils';
23
22
  import { CryptoUtils } from '@fgv/ts-extras';
24
23
 
24
+ /* c8 ignore start - Used only by browser-only methods that cannot be tested in Node.js environment */
25
25
  /**
26
26
  * Extracts an `ArrayBuffer` from a Uint8Array, handling the potential SharedArrayBuffer case.
27
27
  * @param arr - The Uint8Array to extract from
@@ -33,6 +33,25 @@ function toArrayBuffer(arr: Uint8Array): ArrayBuffer {
33
33
  new Uint8Array(buffer).set(arr);
34
34
  return buffer;
35
35
  }
36
+ /* c8 ignore stop */
37
+
38
+ /**
39
+ * Returns a fresh Uint8Array view over a non-shared ArrayBuffer copy of `arr`.
40
+ * Used by {@link BrowserCryptoProvider.wrapBytes | wrapBytes} and
41
+ * {@link BrowserCryptoProvider.unwrapBytes | unwrapBytes}: Node 20's
42
+ * webcrypto.subtle rejects raw `ArrayBuffer` for several `BufferSource`
43
+ * parameters with "is not instance of ArrayBuffer, Buffer, TypedArray, or
44
+ * DataView" even though `ArrayBuffer` should be valid per the spec; a
45
+ * TypedArray view is accepted on Node 20+ and on browsers, and the explicit
46
+ * `Uint8Array<ArrayBuffer>` return type also satisfies TypeScript's `BufferSource`
47
+ * (which excludes the `SharedArrayBuffer` branch of `Uint8Array`'s buffer type).
48
+ */
49
+ function toBufferView(arr: Uint8Array): Uint8Array<ArrayBuffer> {
50
+ const buffer = new ArrayBuffer(arr.byteLength);
51
+ const view = new Uint8Array(buffer);
52
+ view.set(arr);
53
+ return view;
54
+ }
36
55
 
37
56
  /**
38
57
  * Browser implementation of `ICryptoProvider` using the Web Crypto API.
@@ -46,6 +65,7 @@ function toArrayBuffer(arr: Uint8Array): ArrayBuffer {
46
65
  export class BrowserCryptoProvider implements CryptoUtils.ICryptoProvider {
47
66
  private readonly _crypto: Crypto;
48
67
 
68
+ /* c8 ignore start - Existing browser-only methods cannot be tested in Node.js environment */
49
69
  /**
50
70
  * Creates a new {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider}.
51
71
  * @param cryptoApi - Optional Crypto instance (defaults to globalThis.crypto)
@@ -372,8 +392,155 @@ export class BrowserCryptoProvider implements CryptoUtils.ICryptoProvider {
372
392
  );
373
393
  return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);
374
394
  }
395
+ /* c8 ignore stop */
396
+
397
+ /**
398
+ * Wraps `plaintext` for the holder of `recipientPublicKey` using
399
+ * ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See
400
+ * {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.
401
+ * @param plaintext - The bytes to wrap.
402
+ * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.
403
+ * @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.
404
+ * @returns `Success` with the wrapped payload, or `Failure` with an error.
405
+ */
406
+ public async wrapBytes(
407
+ plaintext: Uint8Array,
408
+ recipientPublicKey: CryptoKey,
409
+ options: CryptoUtils.IWrapBytesOptions
410
+ ): Promise<Result<CryptoUtils.IWrappedBytes>> {
411
+ const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');
412
+ if (recipientCheck.isFailure()) {
413
+ return Failure.with(`wrapBytes failed: ${recipientCheck.message}`);
414
+ }
415
+ const subtle = this._crypto.subtle;
416
+ const result = await captureAsyncResult(async () => {
417
+ const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [
418
+ 'deriveKey'
419
+ ])) as CryptoKeyPair;
420
+ const hkdfBase = await subtle.deriveKey(
421
+ { name: 'ECDH', public: recipientPublicKey },
422
+ ephemeral.privateKey,
423
+ { name: 'HKDF' },
424
+ false,
425
+ ['deriveKey']
426
+ );
427
+ const wrapKey = await subtle.deriveKey(
428
+ { name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' },
429
+ hkdfBase,
430
+ { name: 'AES-GCM', length: 256 },
431
+ false,
432
+ ['encrypt']
433
+ );
434
+ const nonce = this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.GCM_IV_SIZE));
435
+ const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, toBufferView(plaintext));
436
+ const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);
437
+ return {
438
+ ephemeralPublicKey,
439
+ nonce: this.toBase64(nonce),
440
+ ciphertext: this.toBase64(new Uint8Array(ctBuf))
441
+ };
442
+ });
443
+ return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);
444
+ }
445
+
446
+ /**
447
+ * Unwraps a payload produced by `wrapBytes` using the recipient's private
448
+ * key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.
449
+ * @param wrapped - The wrapped payload.
450
+ * @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.
451
+ * @param options - HKDF salt and info matching the wrap call.
452
+ * @returns `Success` with the original `plaintext`, or `Failure` with an error.
453
+ */
454
+ public async unwrapBytes(
455
+ wrapped: CryptoUtils.IWrappedBytes,
456
+ recipientPrivateKey: CryptoKey,
457
+ options: CryptoUtils.IWrapBytesOptions
458
+ ): Promise<Result<Uint8Array>> {
459
+ const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');
460
+ if (recipientCheck.isFailure()) {
461
+ return Failure.with(`unwrapBytes failed: ${recipientCheck.message}`);
462
+ }
463
+ const nonceResult = this.fromBase64(wrapped.nonce);
464
+ if (nonceResult.isFailure()) {
465
+ return Failure.with(`unwrapBytes failed: nonce: ${nonceResult.message}`);
466
+ }
467
+ if (nonceResult.value.length !== CryptoUtils.Constants.GCM_IV_SIZE) {
468
+ return Failure.with(
469
+ `unwrapBytes failed: nonce must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`
470
+ );
471
+ }
472
+ const ciphertextResult = this.fromBase64(wrapped.ciphertext);
473
+ if (ciphertextResult.isFailure()) {
474
+ return Failure.with(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);
475
+ }
476
+ if (ciphertextResult.value.length < CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {
477
+ return Failure.with(
478
+ `unwrapBytes failed: ciphertext must be at least ${CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`
479
+ );
480
+ }
481
+ const subtle = this._crypto.subtle;
482
+ const result = await captureAsyncResult(async () => {
483
+ const ephemeralPub = await subtle.importKey(
484
+ 'jwk',
485
+ wrapped.ephemeralPublicKey,
486
+ { name: 'ECDH', namedCurve: 'P-256' },
487
+ false,
488
+ []
489
+ );
490
+ const hkdfBase = await subtle.deriveKey(
491
+ { name: 'ECDH', public: ephemeralPub },
492
+ recipientPrivateKey,
493
+ { name: 'HKDF' },
494
+ false,
495
+ ['deriveKey']
496
+ );
497
+ const wrapKey = await subtle.deriveKey(
498
+ { name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' },
499
+ hkdfBase,
500
+ { name: 'AES-GCM', length: 256 },
501
+ false,
502
+ ['decrypt']
503
+ );
504
+ const ptBuf = await subtle.decrypt(
505
+ { name: 'AES-GCM', iv: toBufferView(nonceResult.value) },
506
+ wrapKey,
507
+ toBufferView(ciphertextResult.value)
508
+ );
509
+ return new Uint8Array(ptBuf);
510
+ });
511
+ return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`
517
+ * (public or private). Used by the wrap/unwrap methods to surface a clean
518
+ * `Failure` instead of letting the WebCrypto deriveKey call throw a less
519
+ * informative error later in the pipeline. Key usages are intentionally not
520
+ * checked here: WebCrypto already produces a specific error if `deriveKey` is
521
+ * not in `usages`, and `deriveBits` is an equally valid alternative usage that
522
+ * an explicit check would have to track.
523
+ * @param key - The CryptoKey to validate.
524
+ * @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).
525
+ * @param label - Human-readable role label included in the failure message.
526
+ * @returns `Success` with the key (unchanged) when the algorithm, curve, and
527
+ * type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.
528
+ */
529
+ function checkEcdhP256(key: CryptoKey, keyType: 'public' | 'private', label: string): Result<CryptoKey> {
530
+ if (key.algorithm.name !== 'ECDH') {
531
+ return Failure.with(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);
532
+ }
533
+ const namedCurve = (key.algorithm as EcKeyAlgorithm).namedCurve;
534
+ if (namedCurve !== 'P-256') {
535
+ return Failure.with(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);
536
+ }
537
+ if (key.type !== keyType) {
538
+ return Failure.with(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);
539
+ }
540
+ return succeed(key);
375
541
  }
376
542
 
543
+ /* c8 ignore start - Constructs a provider; only meaningful in a real browser environment */
377
544
  /**
378
545
  * Creates a {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider} if Web
379
546
  * Crypto API is available.
@@ -0,0 +1,325 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ import '@fgv/ts-utils-jest';
24
+
25
+ import { CryptoUtils } from '@fgv/ts-extras';
26
+ import { BrowserCryptoProvider } from '../../packlets/crypto-utils';
27
+
28
+ const provider = new BrowserCryptoProvider();
29
+ const subtle = globalThis.crypto.subtle;
30
+
31
+ async function generateEcdhPair(curve: 'P-256' | 'P-384' = 'P-256'): Promise<CryptoKeyPair> {
32
+ return (await subtle.generateKey({ name: 'ECDH', namedCurve: curve }, true, [
33
+ 'deriveKey',
34
+ 'deriveBits'
35
+ ])) as CryptoKeyPair;
36
+ }
37
+
38
+ async function generateEcdsaPair(): Promise<CryptoKeyPair> {
39
+ return (await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [
40
+ 'sign',
41
+ 'verify'
42
+ ])) as CryptoKeyPair;
43
+ }
44
+
45
+ describe('BrowserCryptoProvider — wrapBytes/unwrapBytes', () => {
46
+ const defaultOptions: CryptoUtils.IWrapBytesOptions = {
47
+ salt: new TextEncoder().encode('test-salt'),
48
+ info: new TextEncoder().encode('test-info')
49
+ };
50
+
51
+ describe('round-trip', () => {
52
+ test.each<[string, Uint8Array]>([
53
+ ['32-byte plaintext (AES-256 key shape)', globalThis.crypto.getRandomValues(new Uint8Array(32))],
54
+ ['1-byte plaintext', new Uint8Array([0x42])],
55
+ ['1KB plaintext', globalThis.crypto.getRandomValues(new Uint8Array(1024))],
56
+ ['empty plaintext', new Uint8Array(0)],
57
+ ['high-bit-set bytes', new Uint8Array(64).fill(0xff)]
58
+ ])('round-trips %s', async (__label, plaintext) => {
59
+ const pair = await generateEcdhPair();
60
+ const wrapped = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();
61
+ expect(wrapped.ephemeralPublicKey.kty).toBe('EC');
62
+ expect(wrapped.ephemeralPublicKey.crv).toBe('P-256');
63
+ const recovered = (await provider.unwrapBytes(wrapped, pair.privateKey, defaultOptions)).orThrow();
64
+ expect(new Uint8Array(recovered)).toEqual(plaintext);
65
+ });
66
+ });
67
+
68
+ describe('determinism / freshness', () => {
69
+ test('two wraps of identical inputs produce different ephemeral keys and ciphertexts', async () => {
70
+ const pair = await generateEcdhPair();
71
+ const plaintext = new TextEncoder().encode('same payload');
72
+ const w1 = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();
73
+ const w2 = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();
74
+ expect(w1.ephemeralPublicKey).not.toEqual(w2.ephemeralPublicKey);
75
+ expect(w1.ciphertext).not.toEqual(w2.ciphertext);
76
+ expect(w1.nonce).not.toEqual(w2.nonce);
77
+ });
78
+ });
79
+
80
+ describe('tampering', () => {
81
+ test('flipping a bit in the nonce fails GCM authentication', async () => {
82
+ const pair = await generateEcdhPair();
83
+ const wrapped = (
84
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
85
+ ).orThrow();
86
+ const nonce = provider.fromBase64(wrapped.nonce).orThrow();
87
+ nonce[0] ^= 0xff;
88
+ const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, nonce: provider.toBase64(nonce) };
89
+ expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
90
+ /unwrapBytes failed/i
91
+ );
92
+ });
93
+
94
+ test('flipping a bit in the ciphertext fails GCM authentication', async () => {
95
+ const pair = await generateEcdhPair();
96
+ const wrapped = (
97
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
98
+ ).orThrow();
99
+ const ct = provider.fromBase64(wrapped.ciphertext).orThrow();
100
+ ct[0] ^= 0x01;
101
+ const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: provider.toBase64(ct) };
102
+ expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
103
+ /unwrapBytes failed/i
104
+ );
105
+ });
106
+
107
+ test('truncating ciphertext by one byte fails GCM authentication (still ≥ 16 bytes)', async () => {
108
+ const pair = await generateEcdhPair();
109
+ // 16-byte plaintext → 32-byte ciphertext (16 ct + 16 tag); truncate by 1 → 31 bytes ≥ 16
110
+ const wrapped = (
111
+ await provider.wrapBytes(new Uint8Array(16).fill(0xab), pair.publicKey, defaultOptions)
112
+ ).orThrow();
113
+ const ct = provider.fromBase64(wrapped.ciphertext).orThrow();
114
+ const truncated = ct.slice(0, ct.length - 1);
115
+ const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: provider.toBase64(truncated) };
116
+ expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
117
+ /unwrapBytes failed/i
118
+ );
119
+ });
120
+
121
+ test('substituting a different ephemeral public key fails authentication', async () => {
122
+ const pair = await generateEcdhPair();
123
+ const wrapped = (
124
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
125
+ ).orThrow();
126
+ const other = (
127
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
128
+ ).orThrow();
129
+ const tampered: CryptoUtils.IWrappedBytes = {
130
+ ...wrapped,
131
+ ephemeralPublicKey: other.ephemeralPublicKey
132
+ };
133
+ expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
134
+ /unwrapBytes failed/i
135
+ );
136
+ });
137
+ });
138
+
139
+ describe('wrong-key / wrong-options', () => {
140
+ test('unwrap with a different recipient private key fails', async () => {
141
+ const pair = await generateEcdhPair();
142
+ const other = await generateEcdhPair();
143
+ const wrapped = (
144
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
145
+ ).orThrow();
146
+ expect(await provider.unwrapBytes(wrapped, other.privateKey, defaultOptions)).toFailWith(
147
+ /unwrapBytes failed/i
148
+ );
149
+ });
150
+
151
+ test('unwrap with a different HKDF salt fails authentication', async () => {
152
+ const pair = await generateEcdhPair();
153
+ const wrapped = (
154
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
155
+ ).orThrow();
156
+ const wrongSalt: CryptoUtils.IWrapBytesOptions = {
157
+ salt: new TextEncoder().encode('different-salt'),
158
+ info: defaultOptions.info
159
+ };
160
+ expect(await provider.unwrapBytes(wrapped, pair.privateKey, wrongSalt)).toFailWith(
161
+ /unwrapBytes failed/i
162
+ );
163
+ });
164
+
165
+ test('unwrap with a different HKDF info fails authentication', async () => {
166
+ const pair = await generateEcdhPair();
167
+ const wrapped = (
168
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
169
+ ).orThrow();
170
+ const wrongInfo: CryptoUtils.IWrapBytesOptions = {
171
+ salt: defaultOptions.salt,
172
+ info: new TextEncoder().encode('different-info')
173
+ };
174
+ expect(await provider.unwrapBytes(wrapped, pair.privateKey, wrongInfo)).toFailWith(
175
+ /unwrapBytes failed/i
176
+ );
177
+ });
178
+
179
+ test('empty salt and info round-trip when both sides agree', async () => {
180
+ const pair = await generateEcdhPair();
181
+ const empty: CryptoUtils.IWrapBytesOptions = { salt: new Uint8Array(0), info: new Uint8Array(0) };
182
+ const plaintext = globalThis.crypto.getRandomValues(new Uint8Array(16));
183
+ const wrapped = (await provider.wrapBytes(plaintext, pair.publicKey, empty)).orThrow();
184
+ const recovered = (await provider.unwrapBytes(wrapped, pair.privateKey, empty)).orThrow();
185
+ expect(new Uint8Array(recovered)).toEqual(plaintext);
186
+ });
187
+ });
188
+
189
+ describe('malformed input', () => {
190
+ test('malformed ephemeralPublicKey JWK fails', async () => {
191
+ const pair = await generateEcdhPair();
192
+ const wrapped = (
193
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
194
+ ).orThrow();
195
+ const bogus: CryptoUtils.IWrappedBytes = {
196
+ ...wrapped,
197
+ ephemeralPublicKey: { kty: 'EC', crv: 'P-256' } as JsonWebKey
198
+ };
199
+ expect(await provider.unwrapBytes(bogus, pair.privateKey, defaultOptions)).toFailWith(
200
+ /unwrapBytes failed/i
201
+ );
202
+ });
203
+
204
+ test('ephemeralPublicKey on the wrong curve (P-384) fails', async () => {
205
+ const pair = await generateEcdhPair();
206
+ const wrongCurve = await generateEcdhPair('P-384');
207
+ const wrongJwk = await subtle.exportKey('jwk', wrongCurve.publicKey);
208
+ const wrapped = (
209
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
210
+ ).orThrow();
211
+ const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ephemeralPublicKey: wrongJwk };
212
+ expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
213
+ /unwrapBytes failed/i
214
+ );
215
+ });
216
+
217
+ test('non-base64 nonce fails with a clean error', async () => {
218
+ const pair = await generateEcdhPair();
219
+ const wrapped = (
220
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
221
+ ).orThrow();
222
+ const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, nonce: 'not!base64!' };
223
+ expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
224
+ /unwrapBytes failed: nonce/i
225
+ );
226
+ });
227
+
228
+ test('non-base64 ciphertext fails with a clean error', async () => {
229
+ const pair = await generateEcdhPair();
230
+ const wrapped = (
231
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
232
+ ).orThrow();
233
+ const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: 'not!base64!' };
234
+ expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
235
+ /unwrapBytes failed: ciphertext/i
236
+ );
237
+ });
238
+
239
+ test('wrong-length nonce (after base64 decode) fails before reaching AES-GCM', async () => {
240
+ const pair = await generateEcdhPair();
241
+ const wrapped = (
242
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
243
+ ).orThrow();
244
+ const shortNonce = new Uint8Array(8);
245
+ const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, nonce: provider.toBase64(shortNonce) };
246
+ expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
247
+ /unwrapBytes failed: nonce must be 12 bytes \(got 8\)/i
248
+ );
249
+ });
250
+
251
+ test('ciphertext shorter than the GCM auth tag fails before reaching AES-GCM', async () => {
252
+ const pair = await generateEcdhPair();
253
+ const wrapped = (
254
+ await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
255
+ ).orThrow();
256
+ const shortCt = new Uint8Array(8);
257
+ const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: provider.toBase64(shortCt) };
258
+ expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
259
+ /unwrapBytes failed: ciphertext must be at least 16 bytes \(got 8\)/i
260
+ );
261
+ });
262
+ });
263
+
264
+ describe('algorithm / type mismatch on recipient key', () => {
265
+ test('wrap fails when recipient public key is RSA-OAEP, not ECDH', async () => {
266
+ const rsa = (await subtle.generateKey(
267
+ {
268
+ name: 'RSA-OAEP',
269
+ modulusLength: 2048,
270
+ publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
271
+ hash: 'SHA-256'
272
+ },
273
+ true,
274
+ ['encrypt', 'decrypt']
275
+ )) as CryptoKeyPair;
276
+ const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), rsa.publicKey, defaultOptions);
277
+ expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*RSA-OAEP/i);
278
+ });
279
+
280
+ test('wrap fails when recipient public key is ECDSA P-256, not ECDH', async () => {
281
+ const ecdsa = await generateEcdsaPair();
282
+ const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), ecdsa.publicKey, defaultOptions);
283
+ expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*ECDSA/i);
284
+ });
285
+
286
+ test('wrap fails when recipient public key is ECDH P-384, not P-256', async () => {
287
+ const wrongCurve = await generateEcdhPair('P-384');
288
+ const result = await provider.wrapBytes(
289
+ new Uint8Array([1, 2, 3]),
290
+ wrongCurve.publicKey,
291
+ defaultOptions
292
+ );
293
+ expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*P-384/i);
294
+ });
295
+
296
+ test('unwrap fails when recipient private key is ECDH P-384, not P-256', async () => {
297
+ const pair = await generateEcdhPair();
298
+ const wrapped = (
299
+ await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.publicKey, defaultOptions)
300
+ ).orThrow();
301
+ const wrongCurve = await generateEcdhPair('P-384');
302
+ const result = await provider.unwrapBytes(wrapped, wrongCurve.privateKey, defaultOptions);
303
+ expect(result).toFailWith(/unwrapBytes failed: recipient private key must be ECDH P-256.*P-384/i);
304
+ });
305
+
306
+ test('wrap fails when recipient is an ECDH private key (not public)', async () => {
307
+ const pair = await generateEcdhPair();
308
+ const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.privateKey, defaultOptions);
309
+ expect(result).toFailWith(
310
+ /wrapBytes failed: recipient public key must be a public CryptoKey \(got 'private'\)/i
311
+ );
312
+ });
313
+
314
+ test('unwrap fails when recipient is an ECDH public key (not private)', async () => {
315
+ const pair = await generateEcdhPair();
316
+ const wrapped = (
317
+ await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.publicKey, defaultOptions)
318
+ ).orThrow();
319
+ const result = await provider.unwrapBytes(wrapped, pair.publicKey, defaultOptions);
320
+ expect(result).toFailWith(
321
+ /unwrapBytes failed: recipient private key must be a private CryptoKey \(got 'public'\)/i
322
+ );
323
+ });
324
+ });
325
+ });