@fgv/ts-web-extras 5.1.0-17 → 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.
- package/.rush/temp/{edc66e6a37414a0b69e52d768684c18c9d5825e3.tar.log → 42a7a953924ae898114e7b6231a2408228d92433.tar.log} +8 -2
- package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +19 -17
- package/.rush/temp/operation/build/all.log +19 -17
- package/.rush/temp/operation/build/log-chunks.jsonl +19 -17
- package/.rush/temp/operation/build/state.json +1 -1
- package/dist/packlets/crypto-utils/browserCryptoProvider.js +176 -18
- package/dist/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
- package/dist/test/unit/browserCryptoProvider.wrapBytes.test.js +221 -0
- package/dist/test/unit/browserCryptoProvider.wrapBytes.test.js.map +1 -0
- package/dist/ts-web-extras.d.ts +46 -6
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.exportPublicKeyJwk.md +24 -0
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.generateKeyPair.md +25 -0
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.importPublicKeyJwk.md +25 -0
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.md +67 -0
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.unwrapBytes.md +27 -0
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.wrapBytes.md +28 -0
- package/docs/classes/BrowserCryptoProvider.exportPublicKeyJwk.md +24 -0
- package/docs/classes/BrowserCryptoProvider.generateKeyPair.md +25 -0
- package/docs/classes/BrowserCryptoProvider.importPublicKeyJwk.md +25 -0
- package/docs/classes/BrowserCryptoProvider.md +67 -0
- package/docs/classes/BrowserCryptoProvider.unwrapBytes.md +27 -0
- package/docs/classes/BrowserCryptoProvider.wrapBytes.md +28 -0
- package/etc/ts-web-extras.api.md +10 -5
- package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts +46 -5
- package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/browserCryptoProvider.js +175 -17
- package/lib/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
- package/lib/test/unit/browserCryptoProvider.wrapBytes.test.d.ts +2 -0
- package/lib/test/unit/browserCryptoProvider.wrapBytes.test.d.ts.map +1 -0
- package/lib/test/unit/browserCryptoProvider.wrapBytes.test.js +223 -0
- package/lib/test/unit/browserCryptoProvider.wrapBytes.test.js.map +1 -0
- package/package.json +14 -14
- package/rush-logs/ts-web-extras.build.cache.log +1 -1
- package/rush-logs/ts-web-extras.build.log +19 -17
- package/src/packlets/crypto-utils/browserCryptoProvider.ts +244 -23
- package/src/test/unit/browserCryptoProvider.wrapBytes.test.ts +325 -0
- package/temp/build/typescript/ts_8nwakTlr.json +1 -1
- package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +692 -29
- package/temp/coverage/crypto-utils/browserHashProvider.ts.html +1 -1
- package/temp/coverage/crypto-utils/index.html +9 -9
- package/temp/coverage/file-tree/directoryHandleStore.ts.html +1 -1
- package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +1 -1
- package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +1 -1
- package/temp/coverage/file-tree/httpTreeAccessors.ts.html +1 -1
- package/temp/coverage/file-tree/index.html +1 -1
- package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +1 -1
- package/temp/coverage/helpers/fileTreeHelpers.ts.html +1 -1
- package/temp/coverage/helpers/index.html +1 -1
- package/temp/coverage/index.html +10 -10
- package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +692 -29
- package/temp/coverage/lcov-report/crypto-utils/browserHashProvider.ts.html +1 -1
- package/temp/coverage/lcov-report/crypto-utils/index.html +9 -9
- package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/httpTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/index.html +1 -1
- package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +1 -1
- package/temp/coverage/lcov-report/helpers/index.html +1 -1
- package/temp/coverage/lcov-report/index.html +10 -10
- package/temp/coverage/lcov-report/url-utils/index.html +1 -1
- package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +1 -1
- package/temp/coverage/lcov.info +294 -23
- package/temp/coverage/url-utils/index.html +1 -1
- package/temp/coverage/url-utils/urlParams.ts.html +1 -1
- package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
- package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +1 -1
- package/temp/ts-web-extras.api.json +465 -4
- package/temp/ts-web-extras.api.md +10 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browserCryptoProvider.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/browserCryptoProvider.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ,2FAA2F;AAC3F,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,OAAO,EAAU,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACvF,OAAO,EAAE,WAAW,EAAE,MAAM,g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C;QACpE,CAAC;IACH,CAAC;IAED;;;;OAIG;IACI,QAAQ,CAAC,IAAgB;QAC9B,sDAAsD;QACtD,IAAI,MAAM,GAAG,EAAE,CAAC;QAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACrC,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACzC,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACI,UAAU,CAAC,MAAc;QAC9B,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YAC5B,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAC5C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACvC,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAClC,CAAC;YACD,OAAO,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC7B,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,OAAO,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,2BAA2B;IACzC,OAAO,aAAa,CAAC,GAAG,EAAE,CAAC,IAAI,qBAAqB,EAAE,CAAC,CAAC;AAC1D,CAAC;AACD,oBAAoB","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/* c8 ignore start - Browser-only implementation cannot be tested in Node.js environment */\nimport { captureResult, fail, Failure, Result, succeed, Success } from '@fgv/ts-utils';\nimport { CryptoUtils } from '@fgv/ts-extras';\n\ntype ICryptoProvider = CryptoUtils.ICryptoProvider;\ntype IEncryptionResult = CryptoUtils.IEncryptionResult;\nconst CryptoConstants = CryptoUtils.Constants;\n\n/**\n * Extracts an `ArrayBuffer` from a Uint8Array, handling the potential SharedArrayBuffer case.\n * @param arr - The Uint8Array to extract from\n * @returns An `ArrayBuffer` containing a copy of the data.\n */\nfunction toArrayBuffer(arr: Uint8Array): ArrayBuffer {\n // Create a new ArrayBuffer and copy the data - this handles both ArrayBuffer and SharedArrayBuffer\n const buffer = new ArrayBuffer(arr.byteLength);\n new Uint8Array(buffer).set(arr);\n return buffer;\n}\n\n/**\n * Browser implementation of `ICryptoProvider` using the Web Crypto API.\n * Uses AES-256-GCM for authenticated encryption.\n *\n * Note: This provider requires a browser environment with Web Crypto API support.\n * In Node.js 15+, Web Crypto is available via globalThis.crypto or require('crypto').webcrypto.\n *\n * @public\n */\nexport class BrowserCryptoProvider implements ICryptoProvider {\n private readonly _crypto: Crypto;\n\n /**\n * Creates a new {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider}.\n * @param cryptoApi - Optional Crypto instance (defaults to globalThis.crypto)\n */\n public constructor(cryptoApi?: Crypto) {\n if (cryptoApi) {\n this._crypto = cryptoApi;\n } else if (typeof globalThis !== 'undefined' && globalThis.crypto) {\n this._crypto = globalThis.crypto;\n } else if (typeof window !== 'undefined' && window.crypto) {\n this._crypto = window.crypto;\n } else {\n throw new Error('Web Crypto API not available');\n }\n }\n\n /**\n * Encrypts plaintext using AES-256-GCM.\n * @param plaintext - UTF-8 string to encrypt\n * @param key - 32-byte encryption key\n * @returns `Success` with encryption result, or `Failure` with an error.\n */\n public async encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>> {\n if (key.length !== CryptoConstants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoConstants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n try {\n // Generate random IV\n const iv = this._crypto.getRandomValues(new Uint8Array(CryptoConstants.GCM_IV_SIZE));\n\n // Import the key\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toArrayBuffer(key),\n { name: 'AES-GCM' },\n false,\n ['encrypt']\n );\n\n // Encode plaintext to bytes\n const encoder = new TextEncoder();\n const plaintextBytes = encoder.encode(plaintext);\n\n // Encrypt (Web Crypto appends auth tag to ciphertext)\n const encryptedWithTag = await this._crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: iv,\n tagLength: CryptoConstants.GCM_AUTH_TAG_SIZE * 8 // bits\n },\n cryptoKey,\n plaintextBytes\n );\n\n // Split ciphertext and auth tag (auth tag is last 16 bytes)\n const encryptedArray = new Uint8Array(encryptedWithTag);\n const encryptedData = encryptedArray.slice(\n 0,\n encryptedArray.length - CryptoConstants.GCM_AUTH_TAG_SIZE\n );\n const authTag = encryptedArray.slice(encryptedArray.length - CryptoConstants.GCM_AUTH_TAG_SIZE);\n return Success.with({\n iv,\n authTag,\n encryptedData\n });\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Encryption failed: ${message}`);\n }\n }\n\n /**\n * Decrypts ciphertext using AES-256-GCM.\n * @param encryptedData - Encrypted bytes\n * @param key - 32-byte decryption key\n * @param iv - Initialization vector (12 bytes)\n * @param authTag - GCM authentication tag (16 bytes)\n * @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.\n */\n public async decrypt(\n encryptedData: Uint8Array,\n key: Uint8Array,\n iv: Uint8Array,\n authTag: Uint8Array\n ): Promise<Result<string>> {\n if (key.length !== CryptoConstants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoConstants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n if (iv.length !== CryptoConstants.GCM_IV_SIZE) {\n return Failure.with(`IV must be ${CryptoConstants.GCM_IV_SIZE} bytes, got ${iv.length}`);\n }\n if (authTag.length !== CryptoConstants.GCM_AUTH_TAG_SIZE) {\n return Failure.with(\n `Auth tag must be ${CryptoConstants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`\n );\n }\n\n try {\n // Import the key\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toArrayBuffer(key),\n { name: 'AES-GCM' },\n false,\n ['decrypt']\n );\n\n // Web Crypto expects ciphertext + auth tag concatenated\n const encryptedWithTag = new Uint8Array(encryptedData.length + authTag.length);\n encryptedWithTag.set(encryptedData);\n encryptedWithTag.set(authTag, encryptedData.length);\n\n // Decrypt\n const decrypted = await this._crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: toArrayBuffer(iv),\n tagLength: CryptoConstants.GCM_AUTH_TAG_SIZE * 8 // bits\n },\n cryptoKey,\n encryptedWithTag\n );\n\n // Decode to string\n const decoder = new TextDecoder();\n return Success.with(decoder.decode(decrypted));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Decryption failed: ${message}`);\n }\n }\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns Success with generated key, or Failure with error\n */\n public async generateKey(): Promise<Result<Uint8Array>> {\n try {\n return Success.with(this._crypto.getRandomValues(new Uint8Array(CryptoConstants.AES_256_KEY_SIZE)));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Key generation failed: ${message}`);\n }\n }\n\n /**\n * Derives a key from a password using PBKDF2.\n * @param password - Password string\n * @param salt - Salt bytes (should be at least 16 bytes)\n * @param iterations - Number of iterations (recommend 100000+)\n * @returns Success with derived 32-byte key, or Failure with error\n */\n public async deriveKey(\n password: string,\n salt: Uint8Array,\n iterations: number\n ): Promise<Result<Uint8Array>> {\n if (iterations < 1) {\n return Failure.with('Iterations must be at least 1');\n }\n if (salt.length < 8) {\n return Failure.with('Salt should be at least 8 bytes');\n }\n\n try {\n // Encode password\n const encoder = new TextEncoder();\n const passwordBytes = encoder.encode(password);\n\n // Import password as key material\n const keyMaterial = await this._crypto.subtle.importKey('raw', passwordBytes, 'PBKDF2', false, [\n 'deriveBits'\n ]);\n\n // Derive key bits\n const derivedBits = await this._crypto.subtle.deriveBits(\n {\n name: 'PBKDF2',\n salt: toArrayBuffer(salt),\n iterations: iterations,\n hash: 'SHA-256'\n },\n keyMaterial,\n CryptoConstants.AES_256_KEY_SIZE * 8 // bits\n );\n\n return Success.with(new Uint8Array(derivedBits));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Key derivation failed: ${message}`);\n }\n }\n\n /**\n * Computes a SHA-256 hash of the given data.\n * @param data - UTF-8 string to hash\n * @returns `Success` with hex-encoded hash string, or `Failure` with an error.\n */\n public async sha256(data: string): Promise<Result<string>> {\n try {\n const encoder = new TextEncoder();\n const dataBuffer = encoder.encode(data);\n const hashBuffer = await this._crypto.subtle.digest('SHA-256', dataBuffer);\n const hashArray = new Uint8Array(hashBuffer);\n const hashHex = Array.from(hashArray)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n return succeed(hashHex);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return fail(`SHA-256 hash failed: ${message}`);\n }\n }\n\n // ============================================================================\n // Platform Utility Methods\n // ============================================================================\n\n /**\n * Generates cryptographically secure random bytes.\n * @param length - Number of bytes to generate\n * @returns Success with random bytes, or Failure with error\n */\n public generateRandomBytes(length: number): Result<Uint8Array> {\n if (length < 1) {\n return Failure.with('Length must be at least 1');\n }\n try {\n return Success.with(this._crypto.getRandomValues(new Uint8Array(length)));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Random bytes generation failed: ${message}`);\n }\n }\n\n /**\n * Encodes binary data to base64 string.\n * @param data - Binary data to encode\n * @returns Base64-encoded string\n */\n public toBase64(data: Uint8Array): string {\n // Convert Uint8Array to binary string, then to base64\n let binary = '';\n for (let i = 0; i < data.length; i++) {\n binary += String.fromCharCode(data[i]);\n }\n return btoa(binary);\n }\n\n /**\n * Decodes base64 string to binary data.\n * @param base64 - Base64-encoded string\n * @returns Success with decoded bytes, or Failure if invalid base64\n */\n public fromBase64(base64: string): Result<Uint8Array> {\n try {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return Success.with(bytes);\n } catch (e) {\n return Failure.with('Invalid base64 string');\n }\n }\n}\n\n/**\n * Creates a {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider} if Web\n * Crypto API is available.\n * @returns `Success` with provider, or `Failure` if not available\n * @public\n */\nexport function createBrowserCryptoProvider(): Result<BrowserCryptoProvider> {\n return captureResult(() => new BrowserCryptoProvider());\n}\n/* c8 ignore stop */\n"]}
|
|
1
|
+
{"version":3,"file":"browserCryptoProvider.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/browserCryptoProvider.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF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E,CAAC;CACF;AAED;;;;;;;;;;;;;GAaG;AACH,SAAS,aAAa,CAAC,GAAc,EAAE,OAA6B,EAAE,KAAa;IACjF,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QAClC,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,uCAAuC,GAAG,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,CAAC;IAC7F,CAAC;IACD,MAAM,UAAU,GAAI,GAAG,CAAC,SAA4B,CAAC,UAAU,CAAC;IAChE,IAAI,UAAU,KAAK,OAAO,EAAE,CAAC;QAC3B,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,mCAAmC,UAAU,IAAI,CAAC,CAAC;IACjF,CAAC;IACD,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACzB,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,cAAc,OAAO,oBAAoB,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;IACrF,CAAC;IACD,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC;AACtB,CAAC;AAED,4FAA4F;AAC5F;;;;;GAKG;AACH,MAAM,UAAU,2BAA2B;IACzC,OAAO,aAAa,CAAC,GAAG,EAAE,CAAC,IAAI,qBAAqB,EAAE,CAAC,CAAC;AAC1D,CAAC;AACD,oBAAoB","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { captureAsyncResult, captureResult, fail, Failure, Result, succeed, Success } from '@fgv/ts-utils';\nimport { CryptoUtils } from '@fgv/ts-extras';\n\n/* c8 ignore start - Used only by browser-only methods that cannot be tested in Node.js environment */\n/**\n * Extracts an `ArrayBuffer` from a Uint8Array, handling the potential SharedArrayBuffer case.\n * @param arr - The Uint8Array to extract from\n * @returns An `ArrayBuffer` containing a copy of the data.\n */\nfunction toArrayBuffer(arr: Uint8Array): ArrayBuffer {\n // Create a new ArrayBuffer and copy the data - this handles both ArrayBuffer and SharedArrayBuffer\n const buffer = new ArrayBuffer(arr.byteLength);\n new Uint8Array(buffer).set(arr);\n return buffer;\n}\n/* c8 ignore stop */\n\n/**\n * Returns a fresh Uint8Array view over a non-shared ArrayBuffer copy of `arr`.\n * Used by {@link BrowserCryptoProvider.wrapBytes | wrapBytes} and\n * {@link BrowserCryptoProvider.unwrapBytes | unwrapBytes}: Node 20's\n * webcrypto.subtle rejects raw `ArrayBuffer` for several `BufferSource`\n * parameters with \"is not instance of ArrayBuffer, Buffer, TypedArray, or\n * DataView\" even though `ArrayBuffer` should be valid per the spec; a\n * TypedArray view is accepted on Node 20+ and on browsers, and the explicit\n * `Uint8Array<ArrayBuffer>` return type also satisfies TypeScript's `BufferSource`\n * (which excludes the `SharedArrayBuffer` branch of `Uint8Array`'s buffer type).\n */\nfunction toBufferView(arr: Uint8Array): Uint8Array<ArrayBuffer> {\n const buffer = new ArrayBuffer(arr.byteLength);\n const view = new Uint8Array(buffer);\n view.set(arr);\n return view;\n}\n\n/**\n * Browser implementation of `ICryptoProvider` using the Web Crypto API.\n * Uses AES-256-GCM for authenticated encryption.\n *\n * Note: This provider requires a browser environment with Web Crypto API support.\n * In Node.js 15+, Web Crypto is available via globalThis.crypto or require('crypto').webcrypto.\n *\n * @public\n */\nexport class BrowserCryptoProvider implements CryptoUtils.ICryptoProvider {\n private readonly _crypto: Crypto;\n\n /* c8 ignore start - Existing browser-only methods cannot be tested in Node.js environment */\n /**\n * Creates a new {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider}.\n * @param cryptoApi - Optional Crypto instance (defaults to globalThis.crypto)\n */\n public constructor(cryptoApi?: Crypto) {\n if (cryptoApi) {\n this._crypto = cryptoApi;\n } else if (typeof globalThis !== 'undefined' && globalThis.crypto) {\n this._crypto = globalThis.crypto;\n } else if (typeof window !== 'undefined' && window.crypto) {\n this._crypto = window.crypto;\n } else {\n throw new Error('Web Crypto API not available');\n }\n }\n\n /**\n * Encrypts plaintext using AES-256-GCM.\n * @param plaintext - UTF-8 string to encrypt\n * @param key - 32-byte encryption key\n * @returns `Success` with encryption result, or `Failure` with an error.\n */\n public async encrypt(plaintext: string, key: Uint8Array): Promise<Result<CryptoUtils.IEncryptionResult>> {\n if (key.length !== CryptoUtils.Constants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n try {\n // Generate random IV\n const iv = this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.GCM_IV_SIZE));\n\n // Import the key\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toArrayBuffer(key),\n { name: 'AES-GCM' },\n false,\n ['encrypt']\n );\n\n // Encode plaintext to bytes\n const encoder = new TextEncoder();\n const plaintextBytes = encoder.encode(plaintext);\n\n // Encrypt (Web Crypto appends auth tag to ciphertext)\n const encryptedWithTag = await this._crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: iv,\n tagLength: CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits\n },\n cryptoKey,\n plaintextBytes\n );\n\n // Split ciphertext and auth tag (auth tag is last 16 bytes)\n const encryptedArray = new Uint8Array(encryptedWithTag);\n const encryptedData = encryptedArray.slice(\n 0,\n encryptedArray.length - CryptoUtils.Constants.GCM_AUTH_TAG_SIZE\n );\n const authTag = encryptedArray.slice(encryptedArray.length - CryptoUtils.Constants.GCM_AUTH_TAG_SIZE);\n return Success.with({\n iv,\n authTag,\n encryptedData\n });\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Encryption failed: ${message}`);\n }\n }\n\n /**\n * Decrypts ciphertext using AES-256-GCM.\n * @param encryptedData - Encrypted bytes\n * @param key - 32-byte decryption key\n * @param iv - Initialization vector (12 bytes)\n * @param authTag - GCM authentication tag (16 bytes)\n * @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.\n */\n public async decrypt(\n encryptedData: Uint8Array,\n key: Uint8Array,\n iv: Uint8Array,\n authTag: Uint8Array\n ): Promise<Result<string>> {\n if (key.length !== CryptoUtils.Constants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n if (iv.length !== CryptoUtils.Constants.GCM_IV_SIZE) {\n return Failure.with(`IV must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes, got ${iv.length}`);\n }\n if (authTag.length !== CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {\n return Failure.with(\n `Auth tag must be ${CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`\n );\n }\n\n try {\n // Import the key\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toArrayBuffer(key),\n { name: 'AES-GCM' },\n false,\n ['decrypt']\n );\n\n // Web Crypto expects ciphertext + auth tag concatenated\n const encryptedWithTag = new Uint8Array(encryptedData.length + authTag.length);\n encryptedWithTag.set(encryptedData);\n encryptedWithTag.set(authTag, encryptedData.length);\n\n // Decrypt\n const decrypted = await this._crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: toArrayBuffer(iv),\n tagLength: CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits\n },\n cryptoKey,\n encryptedWithTag\n );\n\n // Decode to string\n const decoder = new TextDecoder();\n return Success.with(decoder.decode(decrypted));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Decryption failed: ${message}`);\n }\n }\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns Success with generated key, or Failure with error\n */\n public async generateKey(): Promise<Result<Uint8Array>> {\n try {\n return Success.with(\n this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.AES_256_KEY_SIZE))\n );\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Key generation failed: ${message}`);\n }\n }\n\n /**\n * Derives a key from a password using PBKDF2.\n * @param password - Password string\n * @param salt - Salt bytes (should be at least 16 bytes)\n * @param iterations - Number of iterations (recommend 100000+)\n * @returns Success with derived 32-byte key, or Failure with error\n */\n public async deriveKey(\n password: string,\n salt: Uint8Array,\n iterations: number\n ): Promise<Result<Uint8Array>> {\n if (iterations < 1) {\n return Failure.with('Iterations must be at least 1');\n }\n if (salt.length < 8) {\n return Failure.with('Salt should be at least 8 bytes');\n }\n\n try {\n // Encode password\n const encoder = new TextEncoder();\n const passwordBytes = encoder.encode(password);\n\n // Import password as key material\n const keyMaterial = await this._crypto.subtle.importKey('raw', passwordBytes, 'PBKDF2', false, [\n 'deriveBits'\n ]);\n\n // Derive key bits\n const derivedBits = await this._crypto.subtle.deriveBits(\n {\n name: 'PBKDF2',\n salt: toArrayBuffer(salt),\n iterations: iterations,\n hash: 'SHA-256'\n },\n keyMaterial,\n CryptoUtils.Constants.AES_256_KEY_SIZE * 8 // bits\n );\n\n return Success.with(new Uint8Array(derivedBits));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Key derivation failed: ${message}`);\n }\n }\n\n /**\n * Computes a SHA-256 hash of the given data.\n * @param data - UTF-8 string to hash\n * @returns `Success` with hex-encoded hash string, or `Failure` with an error.\n */\n public async sha256(data: string): Promise<Result<string>> {\n try {\n const encoder = new TextEncoder();\n const dataBuffer = encoder.encode(data);\n const hashBuffer = await this._crypto.subtle.digest('SHA-256', dataBuffer);\n const hashArray = new Uint8Array(hashBuffer);\n const hashHex = Array.from(hashArray)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n return succeed(hashHex);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return fail(`SHA-256 hash failed: ${message}`);\n }\n }\n\n // ============================================================================\n // Platform Utility Methods\n // ============================================================================\n\n /**\n * Generates cryptographically secure random bytes.\n * @param length - Number of bytes to generate\n * @returns Success with random bytes, or Failure with error\n */\n public generateRandomBytes(length: number): Result<Uint8Array> {\n if (length < 1) {\n return Failure.with('Length must be at least 1');\n }\n try {\n return Success.with(this._crypto.getRandomValues(new Uint8Array(length)));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Random bytes generation failed: ${message}`);\n }\n }\n\n /**\n * Encodes binary data to base64 string.\n * @param data - Binary data to encode\n * @returns Base64-encoded string\n */\n public toBase64(data: Uint8Array): string {\n // Convert Uint8Array to binary string, then to base64\n let binary = '';\n for (let i = 0; i < data.length; i++) {\n binary += String.fromCharCode(data[i]);\n }\n return btoa(binary);\n }\n\n /**\n * Decodes base64 string to binary data.\n * @param base64 - Base64-encoded string\n * @returns Success with decoded bytes, or Failure if invalid base64\n */\n public fromBase64(base64: string): Result<Uint8Array> {\n try {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return Success.with(bytes);\n } catch (e) {\n return Failure.with('Invalid base64 string');\n }\n }\n\n // ============================================================================\n // Asymmetric Key Operations\n // ============================================================================\n\n /**\n * Generates a new asymmetric keypair via Web Crypto.\n * @param algorithm - The algorithm to use.\n * @param extractable - Whether the resulting keys may be exported.\n * @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.\n */\n public async generateKeyPair(\n algorithm: CryptoUtils.KeyPairAlgorithm,\n extractable: boolean\n ): Promise<Result<CryptoKeyPair>> {\n const params = CryptoUtils.keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n this._crypto.subtle.generateKey(params.generateKey, extractable, params.keyPairUsages)\n );\n return result.withErrorFormat((e) => `Failed to generate ${algorithm} keypair: ${e}`);\n }\n\n /**\n * Exports a public `CryptoKey` as a JSON Web Key.\n * @remarks\n * Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`\n * does not enforce public-vs-private; without this guard a caller that\n * passed an extractable private key would receive its private fields\n * (`d`, `p`, `q`, ...) as JWK, defeating the method's name.\n * @param publicKey - Extractable public key to export.\n * @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.\n */\n public async exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>> {\n if (publicKey.type !== 'public') {\n return Failure.with(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);\n }\n const result = await captureAsyncResult(() => this._crypto.subtle.exportKey('jwk', publicKey));\n return result.withErrorFormat((e) => `Failed to export public key as JWK: ${e}`);\n }\n\n /**\n * Imports a public-key JWK as a `CryptoKey` for the requested algorithm.\n * @param jwk - The JSON Web Key produced by a prior export.\n * @param algorithm - The algorithm the key was generated for.\n * @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.\n */\n public async importPublicKeyJwk(\n jwk: JsonWebKey,\n algorithm: CryptoUtils.KeyPairAlgorithm\n ): Promise<Result<CryptoKey>> {\n const params = CryptoUtils.keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n this._crypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages)\n );\n return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);\n }\n /* c8 ignore stop */\n\n /**\n * Wraps `plaintext` for the holder of `recipientPublicKey` using\n * ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.\n * @param plaintext - The bytes to wrap.\n * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.\n * @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.\n * @returns `Success` with the wrapped payload, or `Failure` with an error.\n */\n public async wrapBytes(\n plaintext: Uint8Array,\n recipientPublicKey: CryptoKey,\n options: CryptoUtils.IWrapBytesOptions\n ): Promise<Result<CryptoUtils.IWrappedBytes>> {\n const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');\n if (recipientCheck.isFailure()) {\n return Failure.with(`wrapBytes failed: ${recipientCheck.message}`);\n }\n const subtle = this._crypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [\n 'deriveKey'\n ])) as CryptoKeyPair;\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: recipientPublicKey },\n ephemeral.privateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt']\n );\n const nonce = this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.GCM_IV_SIZE));\n const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, toBufferView(plaintext));\n const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);\n return {\n ephemeralPublicKey,\n nonce: this.toBase64(nonce),\n ciphertext: this.toBase64(new Uint8Array(ctBuf))\n };\n });\n return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);\n }\n\n /**\n * Unwraps a payload produced by `wrapBytes` using the recipient's private\n * key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.\n * @param wrapped - The wrapped payload.\n * @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.\n * @param options - HKDF salt and info matching the wrap call.\n * @returns `Success` with the original `plaintext`, or `Failure` with an error.\n */\n public async unwrapBytes(\n wrapped: CryptoUtils.IWrappedBytes,\n recipientPrivateKey: CryptoKey,\n options: CryptoUtils.IWrapBytesOptions\n ): Promise<Result<Uint8Array>> {\n const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');\n if (recipientCheck.isFailure()) {\n return Failure.with(`unwrapBytes failed: ${recipientCheck.message}`);\n }\n const nonceResult = this.fromBase64(wrapped.nonce);\n if (nonceResult.isFailure()) {\n return Failure.with(`unwrapBytes failed: nonce: ${nonceResult.message}`);\n }\n if (nonceResult.value.length !== CryptoUtils.Constants.GCM_IV_SIZE) {\n return Failure.with(\n `unwrapBytes failed: nonce must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`\n );\n }\n const ciphertextResult = this.fromBase64(wrapped.ciphertext);\n if (ciphertextResult.isFailure()) {\n return Failure.with(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);\n }\n if (ciphertextResult.value.length < CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {\n return Failure.with(\n `unwrapBytes failed: ciphertext must be at least ${CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`\n );\n }\n const subtle = this._crypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeralPub = await subtle.importKey(\n 'jwk',\n wrapped.ephemeralPublicKey,\n { name: 'ECDH', namedCurve: 'P-256' },\n false,\n []\n );\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: ephemeralPub },\n recipientPrivateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['decrypt']\n );\n const ptBuf = await subtle.decrypt(\n { name: 'AES-GCM', iv: toBufferView(nonceResult.value) },\n wrapKey,\n toBufferView(ciphertextResult.value)\n );\n return new Uint8Array(ptBuf);\n });\n return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);\n }\n}\n\n/**\n * Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`\n * (public or private). Used by the wrap/unwrap methods to surface a clean\n * `Failure` instead of letting the WebCrypto deriveKey call throw a less\n * informative error later in the pipeline. Key usages are intentionally not\n * checked here: WebCrypto already produces a specific error if `deriveKey` is\n * not in `usages`, and `deriveBits` is an equally valid alternative usage that\n * an explicit check would have to track.\n * @param key - The CryptoKey to validate.\n * @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).\n * @param label - Human-readable role label included in the failure message.\n * @returns `Success` with the key (unchanged) when the algorithm, curve, and\n * type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.\n */\nfunction checkEcdhP256(key: CryptoKey, keyType: 'public' | 'private', label: string): Result<CryptoKey> {\n if (key.algorithm.name !== 'ECDH') {\n return Failure.with(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);\n }\n const namedCurve = (key.algorithm as EcKeyAlgorithm).namedCurve;\n if (namedCurve !== 'P-256') {\n return Failure.with(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);\n }\n if (key.type !== keyType) {\n return Failure.with(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);\n }\n return succeed(key);\n}\n\n/* c8 ignore start - Constructs a provider; only meaningful in a real browser environment */\n/**\n * Creates a {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider} if Web\n * Crypto API is available.\n * @returns `Success` with provider, or `Failure` if not available\n * @public\n */\nexport function createBrowserCryptoProvider(): Result<BrowserCryptoProvider> {\n return captureResult(() => new BrowserCryptoProvider());\n}\n/* c8 ignore stop */\n"]}
|
|
@@ -0,0 +1,221 @@
|
|
|
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
|
+
import '@fgv/ts-utils-jest';
|
|
23
|
+
import { BrowserCryptoProvider } from '../../packlets/crypto-utils';
|
|
24
|
+
const provider = new BrowserCryptoProvider();
|
|
25
|
+
const subtle = globalThis.crypto.subtle;
|
|
26
|
+
async function generateEcdhPair(curve = 'P-256') {
|
|
27
|
+
return (await subtle.generateKey({ name: 'ECDH', namedCurve: curve }, true, [
|
|
28
|
+
'deriveKey',
|
|
29
|
+
'deriveBits'
|
|
30
|
+
]));
|
|
31
|
+
}
|
|
32
|
+
async function generateEcdsaPair() {
|
|
33
|
+
return (await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [
|
|
34
|
+
'sign',
|
|
35
|
+
'verify'
|
|
36
|
+
]));
|
|
37
|
+
}
|
|
38
|
+
describe('BrowserCryptoProvider — wrapBytes/unwrapBytes', () => {
|
|
39
|
+
const defaultOptions = {
|
|
40
|
+
salt: new TextEncoder().encode('test-salt'),
|
|
41
|
+
info: new TextEncoder().encode('test-info')
|
|
42
|
+
};
|
|
43
|
+
describe('round-trip', () => {
|
|
44
|
+
test.each([
|
|
45
|
+
['32-byte plaintext (AES-256 key shape)', globalThis.crypto.getRandomValues(new Uint8Array(32))],
|
|
46
|
+
['1-byte plaintext', new Uint8Array([0x42])],
|
|
47
|
+
['1KB plaintext', globalThis.crypto.getRandomValues(new Uint8Array(1024))],
|
|
48
|
+
['empty plaintext', new Uint8Array(0)],
|
|
49
|
+
['high-bit-set bytes', new Uint8Array(64).fill(0xff)]
|
|
50
|
+
])('round-trips %s', async (__label, plaintext) => {
|
|
51
|
+
const pair = await generateEcdhPair();
|
|
52
|
+
const wrapped = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();
|
|
53
|
+
expect(wrapped.ephemeralPublicKey.kty).toBe('EC');
|
|
54
|
+
expect(wrapped.ephemeralPublicKey.crv).toBe('P-256');
|
|
55
|
+
const recovered = (await provider.unwrapBytes(wrapped, pair.privateKey, defaultOptions)).orThrow();
|
|
56
|
+
expect(new Uint8Array(recovered)).toEqual(plaintext);
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
describe('determinism / freshness', () => {
|
|
60
|
+
test('two wraps of identical inputs produce different ephemeral keys and ciphertexts', async () => {
|
|
61
|
+
const pair = await generateEcdhPair();
|
|
62
|
+
const plaintext = new TextEncoder().encode('same payload');
|
|
63
|
+
const w1 = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();
|
|
64
|
+
const w2 = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();
|
|
65
|
+
expect(w1.ephemeralPublicKey).not.toEqual(w2.ephemeralPublicKey);
|
|
66
|
+
expect(w1.ciphertext).not.toEqual(w2.ciphertext);
|
|
67
|
+
expect(w1.nonce).not.toEqual(w2.nonce);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
describe('tampering', () => {
|
|
71
|
+
test('flipping a bit in the nonce fails GCM authentication', async () => {
|
|
72
|
+
const pair = await generateEcdhPair();
|
|
73
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
74
|
+
const nonce = provider.fromBase64(wrapped.nonce).orThrow();
|
|
75
|
+
nonce[0] ^= 0xff;
|
|
76
|
+
const tampered = Object.assign(Object.assign({}, wrapped), { nonce: provider.toBase64(nonce) });
|
|
77
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(/unwrapBytes failed/i);
|
|
78
|
+
});
|
|
79
|
+
test('flipping a bit in the ciphertext fails GCM authentication', async () => {
|
|
80
|
+
const pair = await generateEcdhPair();
|
|
81
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
82
|
+
const ct = provider.fromBase64(wrapped.ciphertext).orThrow();
|
|
83
|
+
ct[0] ^= 0x01;
|
|
84
|
+
const tampered = Object.assign(Object.assign({}, wrapped), { ciphertext: provider.toBase64(ct) });
|
|
85
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(/unwrapBytes failed/i);
|
|
86
|
+
});
|
|
87
|
+
test('truncating ciphertext by one byte fails GCM authentication (still ≥ 16 bytes)', async () => {
|
|
88
|
+
const pair = await generateEcdhPair();
|
|
89
|
+
// 16-byte plaintext → 32-byte ciphertext (16 ct + 16 tag); truncate by 1 → 31 bytes ≥ 16
|
|
90
|
+
const wrapped = (await provider.wrapBytes(new Uint8Array(16).fill(0xab), pair.publicKey, defaultOptions)).orThrow();
|
|
91
|
+
const ct = provider.fromBase64(wrapped.ciphertext).orThrow();
|
|
92
|
+
const truncated = ct.slice(0, ct.length - 1);
|
|
93
|
+
const tampered = Object.assign(Object.assign({}, wrapped), { ciphertext: provider.toBase64(truncated) });
|
|
94
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(/unwrapBytes failed/i);
|
|
95
|
+
});
|
|
96
|
+
test('substituting a different ephemeral public key fails authentication', async () => {
|
|
97
|
+
const pair = await generateEcdhPair();
|
|
98
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
99
|
+
const other = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
100
|
+
const tampered = Object.assign(Object.assign({}, wrapped), { ephemeralPublicKey: other.ephemeralPublicKey });
|
|
101
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(/unwrapBytes failed/i);
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
describe('wrong-key / wrong-options', () => {
|
|
105
|
+
test('unwrap with a different recipient private key fails', async () => {
|
|
106
|
+
const pair = await generateEcdhPair();
|
|
107
|
+
const other = await generateEcdhPair();
|
|
108
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
109
|
+
expect(await provider.unwrapBytes(wrapped, other.privateKey, defaultOptions)).toFailWith(/unwrapBytes failed/i);
|
|
110
|
+
});
|
|
111
|
+
test('unwrap with a different HKDF salt fails authentication', async () => {
|
|
112
|
+
const pair = await generateEcdhPair();
|
|
113
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
114
|
+
const wrongSalt = {
|
|
115
|
+
salt: new TextEncoder().encode('different-salt'),
|
|
116
|
+
info: defaultOptions.info
|
|
117
|
+
};
|
|
118
|
+
expect(await provider.unwrapBytes(wrapped, pair.privateKey, wrongSalt)).toFailWith(/unwrapBytes failed/i);
|
|
119
|
+
});
|
|
120
|
+
test('unwrap with a different HKDF info fails authentication', async () => {
|
|
121
|
+
const pair = await generateEcdhPair();
|
|
122
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
123
|
+
const wrongInfo = {
|
|
124
|
+
salt: defaultOptions.salt,
|
|
125
|
+
info: new TextEncoder().encode('different-info')
|
|
126
|
+
};
|
|
127
|
+
expect(await provider.unwrapBytes(wrapped, pair.privateKey, wrongInfo)).toFailWith(/unwrapBytes failed/i);
|
|
128
|
+
});
|
|
129
|
+
test('empty salt and info round-trip when both sides agree', async () => {
|
|
130
|
+
const pair = await generateEcdhPair();
|
|
131
|
+
const empty = { salt: new Uint8Array(0), info: new Uint8Array(0) };
|
|
132
|
+
const plaintext = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
133
|
+
const wrapped = (await provider.wrapBytes(plaintext, pair.publicKey, empty)).orThrow();
|
|
134
|
+
const recovered = (await provider.unwrapBytes(wrapped, pair.privateKey, empty)).orThrow();
|
|
135
|
+
expect(new Uint8Array(recovered)).toEqual(plaintext);
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
describe('malformed input', () => {
|
|
139
|
+
test('malformed ephemeralPublicKey JWK fails', async () => {
|
|
140
|
+
const pair = await generateEcdhPair();
|
|
141
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
142
|
+
const bogus = Object.assign(Object.assign({}, wrapped), { ephemeralPublicKey: { kty: 'EC', crv: 'P-256' } });
|
|
143
|
+
expect(await provider.unwrapBytes(bogus, pair.privateKey, defaultOptions)).toFailWith(/unwrapBytes failed/i);
|
|
144
|
+
});
|
|
145
|
+
test('ephemeralPublicKey on the wrong curve (P-384) fails', async () => {
|
|
146
|
+
const pair = await generateEcdhPair();
|
|
147
|
+
const wrongCurve = await generateEcdhPair('P-384');
|
|
148
|
+
const wrongJwk = await subtle.exportKey('jwk', wrongCurve.publicKey);
|
|
149
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
150
|
+
const tampered = Object.assign(Object.assign({}, wrapped), { ephemeralPublicKey: wrongJwk });
|
|
151
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(/unwrapBytes failed/i);
|
|
152
|
+
});
|
|
153
|
+
test('non-base64 nonce fails with a clean error', async () => {
|
|
154
|
+
const pair = await generateEcdhPair();
|
|
155
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
156
|
+
const tampered = Object.assign(Object.assign({}, wrapped), { nonce: 'not!base64!' });
|
|
157
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(/unwrapBytes failed: nonce/i);
|
|
158
|
+
});
|
|
159
|
+
test('non-base64 ciphertext fails with a clean error', async () => {
|
|
160
|
+
const pair = await generateEcdhPair();
|
|
161
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
162
|
+
const tampered = Object.assign(Object.assign({}, wrapped), { ciphertext: 'not!base64!' });
|
|
163
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(/unwrapBytes failed: ciphertext/i);
|
|
164
|
+
});
|
|
165
|
+
test('wrong-length nonce (after base64 decode) fails before reaching AES-GCM', async () => {
|
|
166
|
+
const pair = await generateEcdhPair();
|
|
167
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
168
|
+
const shortNonce = new Uint8Array(8);
|
|
169
|
+
const tampered = Object.assign(Object.assign({}, wrapped), { nonce: provider.toBase64(shortNonce) });
|
|
170
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(/unwrapBytes failed: nonce must be 12 bytes \(got 8\)/i);
|
|
171
|
+
});
|
|
172
|
+
test('ciphertext shorter than the GCM auth tag fails before reaching AES-GCM', async () => {
|
|
173
|
+
const pair = await generateEcdhPair();
|
|
174
|
+
const wrapped = (await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)).orThrow();
|
|
175
|
+
const shortCt = new Uint8Array(8);
|
|
176
|
+
const tampered = Object.assign(Object.assign({}, wrapped), { ciphertext: provider.toBase64(shortCt) });
|
|
177
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(/unwrapBytes failed: ciphertext must be at least 16 bytes \(got 8\)/i);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
describe('algorithm / type mismatch on recipient key', () => {
|
|
181
|
+
test('wrap fails when recipient public key is RSA-OAEP, not ECDH', async () => {
|
|
182
|
+
const rsa = (await subtle.generateKey({
|
|
183
|
+
name: 'RSA-OAEP',
|
|
184
|
+
modulusLength: 2048,
|
|
185
|
+
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
|
186
|
+
hash: 'SHA-256'
|
|
187
|
+
}, true, ['encrypt', 'decrypt']));
|
|
188
|
+
const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), rsa.publicKey, defaultOptions);
|
|
189
|
+
expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*RSA-OAEP/i);
|
|
190
|
+
});
|
|
191
|
+
test('wrap fails when recipient public key is ECDSA P-256, not ECDH', async () => {
|
|
192
|
+
const ecdsa = await generateEcdsaPair();
|
|
193
|
+
const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), ecdsa.publicKey, defaultOptions);
|
|
194
|
+
expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*ECDSA/i);
|
|
195
|
+
});
|
|
196
|
+
test('wrap fails when recipient public key is ECDH P-384, not P-256', async () => {
|
|
197
|
+
const wrongCurve = await generateEcdhPair('P-384');
|
|
198
|
+
const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), wrongCurve.publicKey, defaultOptions);
|
|
199
|
+
expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*P-384/i);
|
|
200
|
+
});
|
|
201
|
+
test('unwrap fails when recipient private key is ECDH P-384, not P-256', async () => {
|
|
202
|
+
const pair = await generateEcdhPair();
|
|
203
|
+
const wrapped = (await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.publicKey, defaultOptions)).orThrow();
|
|
204
|
+
const wrongCurve = await generateEcdhPair('P-384');
|
|
205
|
+
const result = await provider.unwrapBytes(wrapped, wrongCurve.privateKey, defaultOptions);
|
|
206
|
+
expect(result).toFailWith(/unwrapBytes failed: recipient private key must be ECDH P-256.*P-384/i);
|
|
207
|
+
});
|
|
208
|
+
test('wrap fails when recipient is an ECDH private key (not public)', async () => {
|
|
209
|
+
const pair = await generateEcdhPair();
|
|
210
|
+
const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.privateKey, defaultOptions);
|
|
211
|
+
expect(result).toFailWith(/wrapBytes failed: recipient public key must be a public CryptoKey \(got 'private'\)/i);
|
|
212
|
+
});
|
|
213
|
+
test('unwrap fails when recipient is an ECDH public key (not private)', async () => {
|
|
214
|
+
const pair = await generateEcdhPair();
|
|
215
|
+
const wrapped = (await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.publicKey, defaultOptions)).orThrow();
|
|
216
|
+
const result = await provider.unwrapBytes(wrapped, pair.publicKey, defaultOptions);
|
|
217
|
+
expect(result).toFailWith(/unwrapBytes failed: recipient private key must be a private CryptoKey \(got 'public'\)/i);
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
//# sourceMappingURL=browserCryptoProvider.wrapBytes.test.js.map
|
|
@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;YACZ,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,WAAW,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;YACnF,MAAM,CAAC,MAAM,CAAC,CAAC,UAAU,CACvB,yFAAyF,CAC1F,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport '@fgv/ts-utils-jest';\n\nimport { CryptoUtils } from '@fgv/ts-extras';\nimport { BrowserCryptoProvider } from '../../packlets/crypto-utils';\n\nconst provider = new BrowserCryptoProvider();\nconst subtle = globalThis.crypto.subtle;\n\nasync function generateEcdhPair(curve: 'P-256' | 'P-384' = 'P-256'): Promise<CryptoKeyPair> {\n return (await subtle.generateKey({ name: 'ECDH', namedCurve: curve }, true, [\n 'deriveKey',\n 'deriveBits'\n ])) as CryptoKeyPair;\n}\n\nasync function generateEcdsaPair(): Promise<CryptoKeyPair> {\n return (await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify'\n ])) as CryptoKeyPair;\n}\n\ndescribe('BrowserCryptoProvider — wrapBytes/unwrapBytes', () => {\n const defaultOptions: CryptoUtils.IWrapBytesOptions = {\n salt: new TextEncoder().encode('test-salt'),\n info: new TextEncoder().encode('test-info')\n };\n\n describe('round-trip', () => {\n test.each<[string, Uint8Array]>([\n ['32-byte plaintext (AES-256 key shape)', globalThis.crypto.getRandomValues(new Uint8Array(32))],\n ['1-byte plaintext', new Uint8Array([0x42])],\n ['1KB plaintext', globalThis.crypto.getRandomValues(new Uint8Array(1024))],\n ['empty plaintext', new Uint8Array(0)],\n ['high-bit-set bytes', new Uint8Array(64).fill(0xff)]\n ])('round-trips %s', async (__label, plaintext) => {\n const pair = await generateEcdhPair();\n const wrapped = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();\n expect(wrapped.ephemeralPublicKey.kty).toBe('EC');\n expect(wrapped.ephemeralPublicKey.crv).toBe('P-256');\n const recovered = (await provider.unwrapBytes(wrapped, pair.privateKey, defaultOptions)).orThrow();\n expect(new Uint8Array(recovered)).toEqual(plaintext);\n });\n });\n\n describe('determinism / freshness', () => {\n test('two wraps of identical inputs produce different ephemeral keys and ciphertexts', async () => {\n const pair = await generateEcdhPair();\n const plaintext = new TextEncoder().encode('same payload');\n const w1 = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();\n const w2 = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();\n expect(w1.ephemeralPublicKey).not.toEqual(w2.ephemeralPublicKey);\n expect(w1.ciphertext).not.toEqual(w2.ciphertext);\n expect(w1.nonce).not.toEqual(w2.nonce);\n });\n });\n\n describe('tampering', () => {\n test('flipping a bit in the nonce fails GCM authentication', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const nonce = provider.fromBase64(wrapped.nonce).orThrow();\n nonce[0] ^= 0xff;\n const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, nonce: provider.toBase64(nonce) };\n expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(\n /unwrapBytes failed/i\n );\n });\n\n test('flipping a bit in the ciphertext fails GCM authentication', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const ct = provider.fromBase64(wrapped.ciphertext).orThrow();\n ct[0] ^= 0x01;\n const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: provider.toBase64(ct) };\n expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(\n /unwrapBytes failed/i\n );\n });\n\n test('truncating ciphertext by one byte fails GCM authentication (still ≥ 16 bytes)', async () => {\n const pair = await generateEcdhPair();\n // 16-byte plaintext → 32-byte ciphertext (16 ct + 16 tag); truncate by 1 → 31 bytes ≥ 16\n const wrapped = (\n await provider.wrapBytes(new Uint8Array(16).fill(0xab), pair.publicKey, defaultOptions)\n ).orThrow();\n const ct = provider.fromBase64(wrapped.ciphertext).orThrow();\n const truncated = ct.slice(0, ct.length - 1);\n const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: provider.toBase64(truncated) };\n expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(\n /unwrapBytes failed/i\n );\n });\n\n test('substituting a different ephemeral public key fails authentication', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const other = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const tampered: CryptoUtils.IWrappedBytes = {\n ...wrapped,\n ephemeralPublicKey: other.ephemeralPublicKey\n };\n expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(\n /unwrapBytes failed/i\n );\n });\n });\n\n describe('wrong-key / wrong-options', () => {\n test('unwrap with a different recipient private key fails', async () => {\n const pair = await generateEcdhPair();\n const other = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n expect(await provider.unwrapBytes(wrapped, other.privateKey, defaultOptions)).toFailWith(\n /unwrapBytes failed/i\n );\n });\n\n test('unwrap with a different HKDF salt fails authentication', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const wrongSalt: CryptoUtils.IWrapBytesOptions = {\n salt: new TextEncoder().encode('different-salt'),\n info: defaultOptions.info\n };\n expect(await provider.unwrapBytes(wrapped, pair.privateKey, wrongSalt)).toFailWith(\n /unwrapBytes failed/i\n );\n });\n\n test('unwrap with a different HKDF info fails authentication', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const wrongInfo: CryptoUtils.IWrapBytesOptions = {\n salt: defaultOptions.salt,\n info: new TextEncoder().encode('different-info')\n };\n expect(await provider.unwrapBytes(wrapped, pair.privateKey, wrongInfo)).toFailWith(\n /unwrapBytes failed/i\n );\n });\n\n test('empty salt and info round-trip when both sides agree', async () => {\n const pair = await generateEcdhPair();\n const empty: CryptoUtils.IWrapBytesOptions = { salt: new Uint8Array(0), info: new Uint8Array(0) };\n const plaintext = globalThis.crypto.getRandomValues(new Uint8Array(16));\n const wrapped = (await provider.wrapBytes(plaintext, pair.publicKey, empty)).orThrow();\n const recovered = (await provider.unwrapBytes(wrapped, pair.privateKey, empty)).orThrow();\n expect(new Uint8Array(recovered)).toEqual(plaintext);\n });\n });\n\n describe('malformed input', () => {\n test('malformed ephemeralPublicKey JWK fails', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const bogus: CryptoUtils.IWrappedBytes = {\n ...wrapped,\n ephemeralPublicKey: { kty: 'EC', crv: 'P-256' } as JsonWebKey\n };\n expect(await provider.unwrapBytes(bogus, pair.privateKey, defaultOptions)).toFailWith(\n /unwrapBytes failed/i\n );\n });\n\n test('ephemeralPublicKey on the wrong curve (P-384) fails', async () => {\n const pair = await generateEcdhPair();\n const wrongCurve = await generateEcdhPair('P-384');\n const wrongJwk = await subtle.exportKey('jwk', wrongCurve.publicKey);\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ephemeralPublicKey: wrongJwk };\n expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(\n /unwrapBytes failed/i\n );\n });\n\n test('non-base64 nonce fails with a clean error', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, nonce: 'not!base64!' };\n expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(\n /unwrapBytes failed: nonce/i\n );\n });\n\n test('non-base64 ciphertext fails with a clean error', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: 'not!base64!' };\n expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(\n /unwrapBytes failed: ciphertext/i\n );\n });\n\n test('wrong-length nonce (after base64 decode) fails before reaching AES-GCM', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const shortNonce = new Uint8Array(8);\n const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, nonce: provider.toBase64(shortNonce) };\n expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(\n /unwrapBytes failed: nonce must be 12 bytes \\(got 8\\)/i\n );\n });\n\n test('ciphertext shorter than the GCM auth tag fails before reaching AES-GCM', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)\n ).orThrow();\n const shortCt = new Uint8Array(8);\n const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: provider.toBase64(shortCt) };\n expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(\n /unwrapBytes failed: ciphertext must be at least 16 bytes \\(got 8\\)/i\n );\n });\n });\n\n describe('algorithm / type mismatch on recipient key', () => {\n test('wrap fails when recipient public key is RSA-OAEP, not ECDH', async () => {\n const rsa = (await subtle.generateKey(\n {\n name: 'RSA-OAEP',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: 'SHA-256'\n },\n true,\n ['encrypt', 'decrypt']\n )) as CryptoKeyPair;\n const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), rsa.publicKey, defaultOptions);\n expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*RSA-OAEP/i);\n });\n\n test('wrap fails when recipient public key is ECDSA P-256, not ECDH', async () => {\n const ecdsa = await generateEcdsaPair();\n const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), ecdsa.publicKey, defaultOptions);\n expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*ECDSA/i);\n });\n\n test('wrap fails when recipient public key is ECDH P-384, not P-256', async () => {\n const wrongCurve = await generateEcdhPair('P-384');\n const result = await provider.wrapBytes(\n new Uint8Array([1, 2, 3]),\n wrongCurve.publicKey,\n defaultOptions\n );\n expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*P-384/i);\n });\n\n test('unwrap fails when recipient private key is ECDH P-384, not P-256', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.publicKey, defaultOptions)\n ).orThrow();\n const wrongCurve = await generateEcdhPair('P-384');\n const result = await provider.unwrapBytes(wrapped, wrongCurve.privateKey, defaultOptions);\n expect(result).toFailWith(/unwrapBytes failed: recipient private key must be ECDH P-256.*P-384/i);\n });\n\n test('wrap fails when recipient is an ECDH private key (not public)', async () => {\n const pair = await generateEcdhPair();\n const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.privateKey, defaultOptions);\n expect(result).toFailWith(\n /wrapBytes failed: recipient public key must be a public CryptoKey \\(got 'private'\\)/i\n );\n });\n\n test('unwrap fails when recipient is an ECDH public key (not private)', async () => {\n const pair = await generateEcdhPair();\n const wrapped = (\n await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.publicKey, defaultOptions)\n ).orThrow();\n const result = await provider.unwrapBytes(wrapped, pair.publicKey, defaultOptions);\n expect(result).toFailWith(\n /unwrapBytes failed: recipient private key must be a private CryptoKey \\(got 'public'\\)/i\n );\n });\n });\n});\n"]}
|
package/dist/ts-web-extras.d.ts
CHANGED
|
@@ -24,7 +24,7 @@ import { Result } from '@fgv/ts-utils';
|
|
|
24
24
|
*
|
|
25
25
|
* @public
|
|
26
26
|
*/
|
|
27
|
-
declare class BrowserCryptoProvider implements ICryptoProvider {
|
|
27
|
+
declare class BrowserCryptoProvider implements CryptoUtils_2.ICryptoProvider {
|
|
28
28
|
private readonly _crypto;
|
|
29
29
|
/**
|
|
30
30
|
* Creates a new {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider}.
|
|
@@ -37,7 +37,7 @@ declare class BrowserCryptoProvider implements ICryptoProvider {
|
|
|
37
37
|
* @param key - 32-byte encryption key
|
|
38
38
|
* @returns `Success` with encryption result, or `Failure` with an error.
|
|
39
39
|
*/
|
|
40
|
-
encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>>;
|
|
40
|
+
encrypt(plaintext: string, key: Uint8Array): Promise<Result<CryptoUtils_2.IEncryptionResult>>;
|
|
41
41
|
/**
|
|
42
42
|
* Decrypts ciphertext using AES-256-GCM.
|
|
43
43
|
* @param encryptedData - Encrypted bytes
|
|
@@ -84,6 +84,50 @@ declare class BrowserCryptoProvider implements ICryptoProvider {
|
|
|
84
84
|
* @returns Success with decoded bytes, or Failure if invalid base64
|
|
85
85
|
*/
|
|
86
86
|
fromBase64(base64: string): Result<Uint8Array>;
|
|
87
|
+
/**
|
|
88
|
+
* Generates a new asymmetric keypair via Web Crypto.
|
|
89
|
+
* @param algorithm - The algorithm to use.
|
|
90
|
+
* @param extractable - Whether the resulting keys may be exported.
|
|
91
|
+
* @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.
|
|
92
|
+
*/
|
|
93
|
+
generateKeyPair(algorithm: CryptoUtils_2.KeyPairAlgorithm, extractable: boolean): Promise<Result<CryptoKeyPair>>;
|
|
94
|
+
/**
|
|
95
|
+
* Exports a public `CryptoKey` as a JSON Web Key.
|
|
96
|
+
* @remarks
|
|
97
|
+
* Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`
|
|
98
|
+
* does not enforce public-vs-private; without this guard a caller that
|
|
99
|
+
* passed an extractable private key would receive its private fields
|
|
100
|
+
* (`d`, `p`, `q`, ...) as JWK, defeating the method's name.
|
|
101
|
+
* @param publicKey - Extractable public key to export.
|
|
102
|
+
* @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.
|
|
103
|
+
*/
|
|
104
|
+
exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>>;
|
|
105
|
+
/**
|
|
106
|
+
* Imports a public-key JWK as a `CryptoKey` for the requested algorithm.
|
|
107
|
+
* @param jwk - The JSON Web Key produced by a prior export.
|
|
108
|
+
* @param algorithm - The algorithm the key was generated for.
|
|
109
|
+
* @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.
|
|
110
|
+
*/
|
|
111
|
+
importPublicKeyJwk(jwk: JsonWebKey, algorithm: CryptoUtils_2.KeyPairAlgorithm): Promise<Result<CryptoKey>>;
|
|
112
|
+
/**
|
|
113
|
+
* Wraps `plaintext` for the holder of `recipientPublicKey` using
|
|
114
|
+
* ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See
|
|
115
|
+
* {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.
|
|
116
|
+
* @param plaintext - The bytes to wrap.
|
|
117
|
+
* @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.
|
|
118
|
+
* @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.
|
|
119
|
+
* @returns `Success` with the wrapped payload, or `Failure` with an error.
|
|
120
|
+
*/
|
|
121
|
+
wrapBytes(plaintext: Uint8Array, recipientPublicKey: CryptoKey, options: CryptoUtils_2.IWrapBytesOptions): Promise<Result<CryptoUtils_2.IWrappedBytes>>;
|
|
122
|
+
/**
|
|
123
|
+
* Unwraps a payload produced by `wrapBytes` using the recipient's private
|
|
124
|
+
* key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.
|
|
125
|
+
* @param wrapped - The wrapped payload.
|
|
126
|
+
* @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.
|
|
127
|
+
* @param options - HKDF salt and info matching the wrap call.
|
|
128
|
+
* @returns `Success` with the original `plaintext`, or `Failure` with an error.
|
|
129
|
+
*/
|
|
130
|
+
unwrapBytes(wrapped: CryptoUtils_2.IWrappedBytes, recipientPrivateKey: CryptoKey, options: CryptoUtils_2.IWrapBytesOptions): Promise<Result<Uint8Array>>;
|
|
87
131
|
}
|
|
88
132
|
|
|
89
133
|
/**
|
|
@@ -751,8 +795,6 @@ declare function extractFileListMetadata(fileList: FileList): Array<IFileMetadat
|
|
|
751
795
|
private static _requestWithParams;
|
|
752
796
|
}
|
|
753
797
|
|
|
754
|
-
declare type ICryptoProvider = CryptoUtils_2.ICryptoProvider;
|
|
755
|
-
|
|
756
798
|
/**
|
|
757
799
|
* Tree initializer for File System Access API directory handles.
|
|
758
800
|
* @public
|
|
@@ -763,8 +805,6 @@ declare function extractFileListMetadata(fileList: FileList): Array<IFileMetadat
|
|
|
763
805
|
readonly nonRecursive?: boolean;
|
|
764
806
|
}
|
|
765
807
|
|
|
766
|
-
declare type IEncryptionResult = CryptoUtils_2.IEncryptionResult;
|
|
767
|
-
|
|
768
808
|
/**
|
|
769
809
|
* Tree initializer for File System Access API file handles.
|
|
770
810
|
* @public
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[Home](../../README.md) > [CryptoUtils](../README.md) > [BrowserCryptoProvider](./BrowserCryptoProvider.md) > exportPublicKeyJwk
|
|
2
|
+
|
|
3
|
+
## BrowserCryptoProvider.exportPublicKeyJwk() method
|
|
4
|
+
|
|
5
|
+
Exports a public `CryptoKey` as a JSON Web Key.
|
|
6
|
+
|
|
7
|
+
**Signature:**
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>>;
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
**Parameters:**
|
|
14
|
+
|
|
15
|
+
<table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th></tr></thead>
|
|
16
|
+
<tbody>
|
|
17
|
+
<tr><td>publicKey</td><td>CryptoKey</td><td>Extractable public key to export.</td></tr>
|
|
18
|
+
</tbody></table>
|
|
19
|
+
|
|
20
|
+
**Returns:**
|
|
21
|
+
|
|
22
|
+
Promise<Result<JsonWebKey>>
|
|
23
|
+
|
|
24
|
+
`Success` with the JWK, or `Failure` if not a public key or if export fails.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[Home](../../README.md) > [CryptoUtils](../README.md) > [BrowserCryptoProvider](./BrowserCryptoProvider.md) > generateKeyPair
|
|
2
|
+
|
|
3
|
+
## BrowserCryptoProvider.generateKeyPair() method
|
|
4
|
+
|
|
5
|
+
Generates a new asymmetric keypair via Web Crypto.
|
|
6
|
+
|
|
7
|
+
**Signature:**
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
generateKeyPair(algorithm: KeyPairAlgorithm, extractable: boolean): Promise<Result<CryptoKeyPair>>;
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
**Parameters:**
|
|
14
|
+
|
|
15
|
+
<table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th></tr></thead>
|
|
16
|
+
<tbody>
|
|
17
|
+
<tr><td>algorithm</td><td>KeyPairAlgorithm</td><td>The algorithm to use.</td></tr>
|
|
18
|
+
<tr><td>extractable</td><td>boolean</td><td>Whether the resulting keys may be exported.</td></tr>
|
|
19
|
+
</tbody></table>
|
|
20
|
+
|
|
21
|
+
**Returns:**
|
|
22
|
+
|
|
23
|
+
Promise<Result<CryptoKeyPair>>
|
|
24
|
+
|
|
25
|
+
`Success` with the generated `CryptoKeyPair`, or `Failure` with an error.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[Home](../../README.md) > [CryptoUtils](../README.md) > [BrowserCryptoProvider](./BrowserCryptoProvider.md) > importPublicKeyJwk
|
|
2
|
+
|
|
3
|
+
## BrowserCryptoProvider.importPublicKeyJwk() method
|
|
4
|
+
|
|
5
|
+
Imports a public-key JWK as a `CryptoKey` for the requested algorithm.
|
|
6
|
+
|
|
7
|
+
**Signature:**
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
importPublicKeyJwk(jwk: JsonWebKey, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>>;
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
**Parameters:**
|
|
14
|
+
|
|
15
|
+
<table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th></tr></thead>
|
|
16
|
+
<tbody>
|
|
17
|
+
<tr><td>jwk</td><td>JsonWebKey</td><td>The JSON Web Key produced by a prior export.</td></tr>
|
|
18
|
+
<tr><td>algorithm</td><td>KeyPairAlgorithm</td><td>The algorithm the key was generated for.</td></tr>
|
|
19
|
+
</tbody></table>
|
|
20
|
+
|
|
21
|
+
**Returns:**
|
|
22
|
+
|
|
23
|
+
Promise<Result<CryptoKey>>
|
|
24
|
+
|
|
25
|
+
`Success` with the imported public `CryptoKey`, or `Failure` with an error.
|