@fgv/ts-extras 5.1.0-24 → 5.1.0-26

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 (38) hide show
  1. package/dist/packlets/crypto-utils/index.browser.js +2 -0
  2. package/dist/packlets/crypto-utils/index.browser.js.map +1 -1
  3. package/dist/packlets/crypto-utils/index.js +2 -0
  4. package/dist/packlets/crypto-utils/index.js.map +1 -1
  5. package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js +8 -0
  6. package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -1
  7. package/dist/packlets/crypto-utils/model.js +2 -1
  8. package/dist/packlets/crypto-utils/model.js.map +1 -1
  9. package/dist/packlets/crypto-utils/nodeCryptoProvider.js +25 -0
  10. package/dist/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -1
  11. package/dist/packlets/crypto-utils/spkiHelpers.js +130 -0
  12. package/dist/packlets/crypto-utils/spkiHelpers.js.map +1 -0
  13. package/dist/ts-extras.d.ts +100 -7
  14. package/lib/packlets/crypto-utils/index.browser.d.ts +1 -0
  15. package/lib/packlets/crypto-utils/index.browser.d.ts.map +1 -1
  16. package/lib/packlets/crypto-utils/index.browser.js +7 -1
  17. package/lib/packlets/crypto-utils/index.browser.js.map +1 -1
  18. package/lib/packlets/crypto-utils/index.d.ts +1 -0
  19. package/lib/packlets/crypto-utils/index.d.ts.map +1 -1
  20. package/lib/packlets/crypto-utils/index.js +7 -1
  21. package/lib/packlets/crypto-utils/index.js.map +1 -1
  22. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts +10 -6
  23. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts.map +1 -1
  24. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js +8 -0
  25. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -1
  26. package/lib/packlets/crypto-utils/model.d.ts +19 -1
  27. package/lib/packlets/crypto-utils/model.d.ts.map +1 -1
  28. package/lib/packlets/crypto-utils/model.js +2 -1
  29. package/lib/packlets/crypto-utils/model.js.map +1 -1
  30. package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts +13 -0
  31. package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts.map +1 -1
  32. package/lib/packlets/crypto-utils/nodeCryptoProvider.js +25 -0
  33. package/lib/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -1
  34. package/lib/packlets/crypto-utils/spkiHelpers.d.ts +53 -0
  35. package/lib/packlets/crypto-utils/spkiHelpers.d.ts.map +1 -0
  36. package/lib/packlets/crypto-utils/spkiHelpers.js +136 -0
  37. package/lib/packlets/crypto-utils/spkiHelpers.js.map +1 -0
  38. package/package.json +7 -7
@@ -260,6 +260,31 @@ class NodeCryptoProvider {
260
260
  const result = await (0, ts_utils_1.captureAsyncResult)(() => crypto.webcrypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages));
261
261
  return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);
262
262
  }
263
+ /**
264
+ * Exports a public `CryptoKey` as a DER-encoded SPKI blob.
265
+ * @param publicKey - The public `CryptoKey` to export.
266
+ * @returns `Success` with the raw SPKI bytes, or `Failure` with error context.
267
+ */
268
+ async exportPublicKeySpki(publicKey) {
269
+ if (publicKey.type !== 'public') {
270
+ return (0, ts_utils_1.fail)(`exportPublicKeySpki requires a public CryptoKey, got '${publicKey.type}'`);
271
+ }
272
+ const result = await (0, ts_utils_1.captureAsyncResult)(() => crypto.webcrypto.subtle.exportKey('spki', publicKey));
273
+ return result
274
+ .withErrorFormat((e) => `exportPublicKeySpki: failed to export key: ${e}`)
275
+ .onSuccess((buf) => (0, ts_utils_1.succeed)(new Uint8Array(buf)));
276
+ }
277
+ /**
278
+ * Imports a public key from a DER-encoded SPKI blob.
279
+ * @param spkiBytes - The raw SPKI bytes.
280
+ * @param algorithm - The algorithm the key was generated for.
281
+ * @returns `Success` with the imported public `CryptoKey`, or `Failure` with error context.
282
+ */
283
+ async importPublicKeySpki(spkiBytes, algorithm) {
284
+ const params = keyPairAlgorithmParams_1.keyPairAlgorithmParams[algorithm];
285
+ const result = await (0, ts_utils_1.captureAsyncResult)(() => crypto.webcrypto.subtle.importKey('spki', spkiBytes, params.importPublicKey, true, [...params.publicKeyUsages]));
286
+ return result.withErrorFormat((e) => `importPublicKeySpki: failed to import ${algorithm} public key from SPKI: ${e}`);
287
+ }
263
288
  /**
264
289
  * Wraps `plaintext` for the holder of `recipientPublicKey` using
265
290
  * ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See
@@ -1 +1 @@
1
- {"version":3,"file":"nodeCryptoProvider.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/nodeCryptoProvider.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,+CAAiC;AACjC,4CAUuB;AACvB,uDAAyC;AACzC,qEAAkE;AASlE;;;;GAIG;AACH,MAAa,kBAAkB;IAC7B;;;;;OAKG;IACI,KAAK,CAAC,OAAO,CAAC,SAAiB,EAAE,GAAe;QACrD,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE;YACxB,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,gBAAgB,EAAE,CAAC;gBAC9C,MAAM,IAAI,KAAK,CAAC,eAAe,SAAS,CAAC,gBAAgB,eAAe,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;YACxF,CAAC;YAED,qBAAqB;YACrB,MAAM,EAAE,GAAG,MAAM,CAA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,OAAO,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,CAAC,CAAC;IACnE,CAAC;CACF;AA1WD,gDA0WC;AAED;;;;;;;;;;;;;GAaG;AACH,SAAS,aAAa,CAAC,GAAc,EAAE,OAA6B,EAAE,KAAa;IACjF,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QAClC,OAAO,IAAA,eAAI,EAAC,GAAG,KAAK,uCAAuC,GAAG,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,CAAC;IACrF,CAAC;IACD,MAAM,UAAU,GAAI,GAAG,CAAC,SAA4B,CAAC,UAAU,CAAC;IAChE,IAAI,UAAU,KAAK,OAAO,EAAE,CAAC;QAC3B,OAAO,IAAA,eAAI,EAAC,GAAG,KAAK,mCAAmC,UAAU,IAAI,CAAC,CAAC;IACzE,CAAC;IACD,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACzB,OAAO,IAAA,eAAI,EAAC,GAAG,KAAK,cAAc,OAAO,oBAAoB,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;AACtB,CAAC;AAED;;;GAGG;AACU,QAAA,kBAAkB,GAAuB,IAAI,kBAAkB,EAAE,CAAC","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 * as crypto from 'crypto';\nimport {\n captureAsyncResult,\n captureResult,\n fail,\n Failure,\n generateUuid,\n Result,\n succeed,\n Success,\n Uuid\n} from '@fgv/ts-utils';\nimport * as Constants from './constants';\nimport { keyPairAlgorithmParams } from './keyPairAlgorithmParams';\nimport {\n ICryptoProvider,\n IEncryptionResult,\n IWrapBytesOptions,\n IWrappedBytes,\n KeyPairAlgorithm\n} from './model';\n\n/**\n * Node.js implementation of {@link CryptoUtils.ICryptoProvider} using the built-in crypto module.\n * Uses AES-256-GCM for authenticated encryption.\n * @public\n */\nexport class NodeCryptoProvider implements ICryptoProvider {\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 return captureResult(() => {\n if (key.length !== Constants.AES_256_KEY_SIZE) {\n throw new Error(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n // Generate random IV\n const iv = crypto.randomBytes(Constants.GCM_IV_SIZE);\n\n // Create cipher\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);\n\n // Encrypt\n const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);\n\n // Get auth tag\n const authTag = cipher.getAuthTag();\n\n return {\n iv: new Uint8Array(iv),\n authTag: new Uint8Array(authTag),\n encryptedData: new Uint8Array(encrypted)\n };\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 !== Constants.AES_256_KEY_SIZE) {\n return fail(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n if (iv.length !== Constants.GCM_IV_SIZE) {\n return fail(`IV must be ${Constants.GCM_IV_SIZE} bytes, got ${iv.length}`);\n }\n if (authTag.length !== Constants.GCM_AUTH_TAG_SIZE) {\n return fail(`Auth tag must be ${Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`);\n }\n\n return captureResult(() => {\n // Create decipher\n const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(key), Buffer.from(iv));\n\n // Set auth tag\n decipher.setAuthTag(Buffer.from(authTag));\n\n // Decrypt\n const decrypted = Buffer.concat([decipher.update(Buffer.from(encryptedData)), decipher.final()]);\n\n return decrypted.toString('utf8');\n }).withErrorFormat((e) => `Decryption failed: ${e}`);\n }\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns `Success` with generated key, or `Failure` with an error.\n */\n public async generateKey(): Promise<Result<Uint8Array>> {\n return captureResult(() => {\n const key = crypto.randomBytes(Constants.AES_256_KEY_SIZE);\n return new Uint8Array(key);\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 an 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 fail('Iterations must be at least 1');\n }\n if (salt.length < 8) {\n return fail('Salt should be at least 8 bytes');\n }\n\n return new Promise((resolve) => {\n crypto.pbkdf2(\n password,\n Buffer.from(salt),\n iterations,\n Constants.AES_256_KEY_SIZE,\n 'sha256',\n (err, derivedKey) => {\n /* c8 ignore next 3 - PBKDF2 internal errors are hard to trigger with valid parameters */\n if (err) {\n resolve(fail(`Key derivation failed: ${err.message}`));\n } else {\n resolve(succeed(new Uint8Array(derivedKey)));\n }\n }\n );\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 return captureResult(() => {\n const hash = crypto.createHash('sha256');\n hash.update(data, 'utf8');\n return hash.digest('hex');\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 return captureResult(() => new Uint8Array(crypto.randomBytes(length)));\n }\n\n /**\n * Generates a cryptographically random UUIDv4 via the platform Web Crypto API.\n * @returns `Success` with the generated UUID, or `Failure` if the runtime\n * does not expose `globalThis.crypto.randomUUID`.\n */\n public generateUuid(): Result<Uuid> {\n return captureResult(() => generateUuid());\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 return Buffer.from(data).toString('base64');\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 // Check for obviously invalid characters\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64)) {\n return Failure.with('Invalid base64 string');\n }\n return Success.with(new Uint8Array(Buffer.from(base64, 'base64')));\n }\n\n // ============================================================================\n // Asymmetric Key Operations\n // ============================================================================\n\n /**\n * Generates a new asymmetric keypair using Node's WebCrypto.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | 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: KeyPairAlgorithm,\n extractable: boolean\n ): Promise<Result<CryptoKeyPair>> {\n const params = keyPairAlgorithmParams[algorithm];\n // Widening upcast to `AlgorithmIdentifier` steers TS to subtle.generateKey's\n // broad overload, which accepts the Ed25519 `{ name: 'Ed25519' }` shape and\n // returns `CryptoKey | CryptoKeyPair`. The narrowing back to `CryptoKeyPair`\n // is a runtime check via the `in` operator, not a type assertion.\n const result = await captureAsyncResult(async () => {\n const generated = await crypto.webcrypto.subtle.generateKey(\n params.generateKey as AlgorithmIdentifier,\n extractable,\n [...params.keyPairUsages]\n );\n if ('privateKey' in generated && 'publicKey' in generated) {\n return generated;\n }\n /* c8 ignore next - unreachable: every entry in keyPairAlgorithmParams produces a keypair */\n throw new Error(`${algorithm} unexpectedly produced a single CryptoKey`);\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 fail(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);\n }\n const result = await captureAsyncResult(() => crypto.webcrypto.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(jwk: JsonWebKey, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>> {\n const params = keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n crypto.webcrypto.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\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: IWrapBytesOptions\n ): Promise<Result<IWrappedBytes>> {\n const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');\n if (recipientCheck.isFailure()) {\n return fail(`wrapBytes failed: ${recipientCheck.message}`);\n }\n const subtle = crypto.webcrypto.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: options.salt, info: options.info, hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt']\n );\n const nonce = crypto.randomBytes(Constants.GCM_IV_SIZE);\n const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, 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: IWrappedBytes,\n recipientPrivateKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<Uint8Array>> {\n const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');\n if (recipientCheck.isFailure()) {\n return fail(`unwrapBytes failed: ${recipientCheck.message}`);\n }\n const nonceResult = this.fromBase64(wrapped.nonce);\n if (nonceResult.isFailure()) {\n return fail(`unwrapBytes failed: nonce: ${nonceResult.message}`);\n }\n if (nonceResult.value.length !== Constants.GCM_IV_SIZE) {\n return fail(\n `unwrapBytes failed: nonce must be ${Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`\n );\n }\n const ciphertextResult = this.fromBase64(wrapped.ciphertext);\n if (ciphertextResult.isFailure()) {\n return fail(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);\n }\n if (ciphertextResult.value.length < Constants.GCM_AUTH_TAG_SIZE) {\n return fail(\n `unwrapBytes failed: ciphertext must be at least ${Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`\n );\n }\n const subtle = crypto.webcrypto.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: options.salt, info: 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: nonceResult.value },\n wrapKey,\n 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 fail(`${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 fail(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);\n }\n if (key.type !== keyType) {\n return fail(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);\n }\n return succeed(key);\n}\n\n/**\n * Singleton instance of {@link CryptoUtils.NodeCryptoProvider}.\n * @public\n */\nexport const nodeCryptoProvider: NodeCryptoProvider = new NodeCryptoProvider();\n"]}
1
+ {"version":3,"file":"nodeCryptoProvider.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/nodeCryptoProvider.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,+CAAiC;AACjC,4CAUuB;AACvB,uDAAyC;AACzC,qEAAkE;AASlE;;;;GAIG;AACH,MAAa,kBAAkB;IAC7B;;;;;OAKG;IACI,KAAK,CAAC,OAAO,CAAC,SAAiB,EAAE,GAAe;QACrD,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE;YACxB,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,gBAAgB,EAAE,CAAC;gBAC9C,MAAM,IAAI,KAAK,CAAC,eAAe,SAAS,CAAC,gBAAgB,eAAe,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;YACxF,CAAC;YAED,qBAAqB;YACrB,MAAM,EAAE,GAAG,MAAM,CAAC,WAAW,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;YAErD,gBAAgB;YAChB,MAAM,MAAM,GAAG,MAAM,CAAC,cAAc,CAAC,aAAa,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;YAE7D,UAAU;YACV,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,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AAI,UAAU,KAAK,OAAO,EAAE,CAAC;QAC3B,OAAO,IAAA,eAAI,EAAC,GAAG,KAAK,mCAAmC,UAAU,IAAI,CAAC,CAAC;IACzE,CAAC;IACD,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACzB,OAAO,IAAA,eAAI,EAAC,GAAG,KAAK,cAAc,OAAO,oBAAoB,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;AACtB,CAAC;AAED;;;GAGG;AACU,QAAA,kBAAkB,GAAuB,IAAI,kBAAkB,EAAE,CAAC","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 * as crypto from 'crypto';\nimport {\n captureAsyncResult,\n captureResult,\n fail,\n Failure,\n generateUuid,\n Result,\n succeed,\n Success,\n Uuid\n} from '@fgv/ts-utils';\nimport * as Constants from './constants';\nimport { keyPairAlgorithmParams } from './keyPairAlgorithmParams';\nimport {\n ICryptoProvider,\n IEncryptionResult,\n IWrapBytesOptions,\n IWrappedBytes,\n KeyPairAlgorithm\n} from './model';\n\n/**\n * Node.js implementation of {@link CryptoUtils.ICryptoProvider} using the built-in crypto module.\n * Uses AES-256-GCM for authenticated encryption.\n * @public\n */\nexport class NodeCryptoProvider implements ICryptoProvider {\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 return captureResult(() => {\n if (key.length !== Constants.AES_256_KEY_SIZE) {\n throw new Error(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n // Generate random IV\n const iv = crypto.randomBytes(Constants.GCM_IV_SIZE);\n\n // Create cipher\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);\n\n // Encrypt\n const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);\n\n // Get auth tag\n const authTag = cipher.getAuthTag();\n\n return {\n iv: new Uint8Array(iv),\n authTag: new Uint8Array(authTag),\n encryptedData: new Uint8Array(encrypted)\n };\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 !== Constants.AES_256_KEY_SIZE) {\n return fail(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n if (iv.length !== Constants.GCM_IV_SIZE) {\n return fail(`IV must be ${Constants.GCM_IV_SIZE} bytes, got ${iv.length}`);\n }\n if (authTag.length !== Constants.GCM_AUTH_TAG_SIZE) {\n return fail(`Auth tag must be ${Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`);\n }\n\n return captureResult(() => {\n // Create decipher\n const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(key), Buffer.from(iv));\n\n // Set auth tag\n decipher.setAuthTag(Buffer.from(authTag));\n\n // Decrypt\n const decrypted = Buffer.concat([decipher.update(Buffer.from(encryptedData)), decipher.final()]);\n\n return decrypted.toString('utf8');\n }).withErrorFormat((e) => `Decryption failed: ${e}`);\n }\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns `Success` with generated key, or `Failure` with an error.\n */\n public async generateKey(): Promise<Result<Uint8Array>> {\n return captureResult(() => {\n const key = crypto.randomBytes(Constants.AES_256_KEY_SIZE);\n return new Uint8Array(key);\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 an 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 fail('Iterations must be at least 1');\n }\n if (salt.length < 8) {\n return fail('Salt should be at least 8 bytes');\n }\n\n return new Promise((resolve) => {\n crypto.pbkdf2(\n password,\n Buffer.from(salt),\n iterations,\n Constants.AES_256_KEY_SIZE,\n 'sha256',\n (err, derivedKey) => {\n /* c8 ignore next 3 - PBKDF2 internal errors are hard to trigger with valid parameters */\n if (err) {\n resolve(fail(`Key derivation failed: ${err.message}`));\n } else {\n resolve(succeed(new Uint8Array(derivedKey)));\n }\n }\n );\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 return captureResult(() => {\n const hash = crypto.createHash('sha256');\n hash.update(data, 'utf8');\n return hash.digest('hex');\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 return captureResult(() => new Uint8Array(crypto.randomBytes(length)));\n }\n\n /**\n * Generates a cryptographically random UUIDv4 via the platform Web Crypto API.\n * @returns `Success` with the generated UUID, or `Failure` if the runtime\n * does not expose `globalThis.crypto.randomUUID`.\n */\n public generateUuid(): Result<Uuid> {\n return captureResult(() => generateUuid());\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 return Buffer.from(data).toString('base64');\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 // Check for obviously invalid characters\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64)) {\n return Failure.with('Invalid base64 string');\n }\n return Success.with(new Uint8Array(Buffer.from(base64, 'base64')));\n }\n\n // ============================================================================\n // Asymmetric Key Operations\n // ============================================================================\n\n /**\n * Generates a new asymmetric keypair using Node's WebCrypto.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | 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: KeyPairAlgorithm,\n extractable: boolean\n ): Promise<Result<CryptoKeyPair>> {\n const params = keyPairAlgorithmParams[algorithm];\n // Widening upcast to `AlgorithmIdentifier` steers TS to subtle.generateKey's\n // broad overload, which accepts the Ed25519 `{ name: 'Ed25519' }` shape and\n // returns `CryptoKey | CryptoKeyPair`. The narrowing back to `CryptoKeyPair`\n // is a runtime check via the `in` operator, not a type assertion.\n const result = await captureAsyncResult(async () => {\n const generated = await crypto.webcrypto.subtle.generateKey(\n params.generateKey as AlgorithmIdentifier,\n extractable,\n [...params.keyPairUsages]\n );\n if ('privateKey' in generated && 'publicKey' in generated) {\n return generated;\n }\n /* c8 ignore next - unreachable: every entry in keyPairAlgorithmParams produces a keypair */\n throw new Error(`${algorithm} unexpectedly produced a single CryptoKey`);\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 fail(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);\n }\n const result = await captureAsyncResult(() => crypto.webcrypto.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(jwk: JsonWebKey, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>> {\n const params = keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n crypto.webcrypto.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\n /**\n * Exports a public `CryptoKey` as a DER-encoded SPKI blob.\n * @param publicKey - The public `CryptoKey` to export.\n * @returns `Success` with the raw SPKI bytes, or `Failure` with error context.\n */\n public async exportPublicKeySpki(publicKey: CryptoKey): Promise<Result<Uint8Array>> {\n if (publicKey.type !== 'public') {\n return fail(`exportPublicKeySpki requires a public CryptoKey, got '${publicKey.type}'`);\n }\n const result = await captureAsyncResult(() => crypto.webcrypto.subtle.exportKey('spki', publicKey));\n return result\n .withErrorFormat((e) => `exportPublicKeySpki: failed to export key: ${e}`)\n .onSuccess((buf) => succeed(new Uint8Array(buf)));\n }\n\n /**\n * Imports a public key from a DER-encoded SPKI blob.\n * @param spkiBytes - The raw SPKI bytes.\n * @param algorithm - The algorithm the key was generated for.\n * @returns `Success` with the imported public `CryptoKey`, or `Failure` with error context.\n */\n public async importPublicKeySpki(\n spkiBytes: Uint8Array,\n algorithm: KeyPairAlgorithm\n ): Promise<Result<CryptoKey>> {\n const params = keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n crypto.webcrypto.subtle.importKey(\n 'spki',\n spkiBytes,\n params.importPublicKey as AlgorithmIdentifier,\n true,\n [...params.publicKeyUsages]\n )\n );\n return result.withErrorFormat(\n (e) => `importPublicKeySpki: failed to import ${algorithm} public key from SPKI: ${e}`\n );\n }\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: IWrapBytesOptions\n ): Promise<Result<IWrappedBytes>> {\n const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');\n if (recipientCheck.isFailure()) {\n return fail(`wrapBytes failed: ${recipientCheck.message}`);\n }\n const subtle = crypto.webcrypto.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: options.salt, info: options.info, hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt']\n );\n const nonce = crypto.randomBytes(Constants.GCM_IV_SIZE);\n const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, 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: IWrappedBytes,\n recipientPrivateKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<Uint8Array>> {\n const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');\n if (recipientCheck.isFailure()) {\n return fail(`unwrapBytes failed: ${recipientCheck.message}`);\n }\n const nonceResult = this.fromBase64(wrapped.nonce);\n if (nonceResult.isFailure()) {\n return fail(`unwrapBytes failed: nonce: ${nonceResult.message}`);\n }\n if (nonceResult.value.length !== Constants.GCM_IV_SIZE) {\n return fail(\n `unwrapBytes failed: nonce must be ${Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`\n );\n }\n const ciphertextResult = this.fromBase64(wrapped.ciphertext);\n if (ciphertextResult.isFailure()) {\n return fail(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);\n }\n if (ciphertextResult.value.length < Constants.GCM_AUTH_TAG_SIZE) {\n return fail(\n `unwrapBytes failed: ciphertext must be at least ${Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`\n );\n }\n const subtle = crypto.webcrypto.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: options.salt, info: 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: nonceResult.value },\n wrapKey,\n 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 fail(`${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 fail(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);\n }\n if (key.type !== keyType) {\n return fail(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);\n }\n return succeed(key);\n}\n\n/**\n * Singleton instance of {@link CryptoUtils.NodeCryptoProvider}.\n * @public\n */\nexport const nodeCryptoProvider: NodeCryptoProvider = new NodeCryptoProvider();\n"]}
@@ -0,0 +1,53 @@
1
+ import { Result } from '@fgv/ts-utils';
2
+ import { ICryptoProvider, KeyPairAlgorithm } from './model';
3
+ /**
4
+ * Encodes a `Uint8Array` as a multibase base64url (no-padding) string.
5
+ *
6
+ * The multibase prefix `'m'` identifies the encoding as RFC 4648 base64url
7
+ * without padding. The body uses base64url alphabet: `+` → `-`, `/` → `_`,
8
+ * and trailing `=` padding is stripped.
9
+ *
10
+ * @param data - The binary data to encode.
11
+ * @returns A multibase-prefixed base64url string (`'m' + base64url-no-pad`).
12
+ * @public
13
+ */
14
+ export declare function multibaseBase64UrlEncode(data: Uint8Array): string;
15
+ /**
16
+ * Decodes a multibase base64url (no-padding) string back to a `Uint8Array`.
17
+ *
18
+ * Validates that the first character is `'m'` (the multibase prefix for
19
+ * RFC 4648 base64url without padding), then decodes the remaining body.
20
+ *
21
+ * @param encoded - A multibase-prefixed base64url string.
22
+ * @returns `Success` with the decoded bytes, or `Failure` with error context.
23
+ * @public
24
+ */
25
+ export declare function multibaseBase64UrlDecode(encoded: string): Result<Uint8Array>;
26
+ /**
27
+ * Exports a public `CryptoKey` as a multibase base64url-encoded SPKI blob.
28
+ *
29
+ * The SPKI (SubjectPublicKeyInfo) format is the standard DER-encoded structure
30
+ * for public keys defined in RFC 5280, RFC 5480, and RFC 8410. It is
31
+ * algorithm-agnostic and suitable for storage and transmission.
32
+ *
33
+ * @param key - The `CryptoKey` to export. Must have `key.type === 'public'`.
34
+ * @param provider - The {@link CryptoUtils.ICryptoProvider} to use for the export operation.
35
+ * @returns `Success` with the multibase SPKI string, or `Failure` with error context.
36
+ * @public
37
+ */
38
+ export declare function exportPublicKeyAsMultibaseSpki(key: CryptoKey, provider: ICryptoProvider): Promise<Result<string>>;
39
+ /**
40
+ * Imports a public key from a multibase base64url-encoded SPKI blob.
41
+ *
42
+ * Decodes the multibase prefix, decodes the base64url body, then uses
43
+ * the provider to import the key with the algorithm parameters from
44
+ * {@link CryptoUtils.keyPairAlgorithmParams}.
45
+ *
46
+ * @param encoded - A multibase SPKI string produced by {@link CryptoUtils.exportPublicKeyAsMultibaseSpki}.
47
+ * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm} the key was generated for.
48
+ * @param provider - The {@link CryptoUtils.ICryptoProvider} to use for the import operation.
49
+ * @returns `Success` with the imported public `CryptoKey`, or `Failure` with error context.
50
+ * @public
51
+ */
52
+ export declare function importPublicKeyFromMultibaseSpki(encoded: string, algorithm: KeyPairAlgorithm, provider: ICryptoProvider): Promise<Result<CryptoKey>>;
53
+ //# sourceMappingURL=spkiHelpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spkiHelpers.d.ts","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/spkiHelpers.ts"],"names":[],"mappings":"AAoBA,OAAO,EAAE,MAAM,EAAiB,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAE5D;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM,CAgBjE;AAED;;;;;;;;;GASG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,CAiC5E;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,8BAA8B,CAClD,GAAG,EAAE,SAAS,EACd,QAAQ,EAAE,eAAe,GACxB,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAIzB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,gCAAgC,CACpD,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,gBAAgB,EAC3B,QAAQ,EAAE,eAAe,GACxB,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAQ5B"}
@@ -0,0 +1,136 @@
1
+ "use strict";
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
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.multibaseBase64UrlEncode = multibaseBase64UrlEncode;
23
+ exports.multibaseBase64UrlDecode = multibaseBase64UrlDecode;
24
+ exports.exportPublicKeyAsMultibaseSpki = exportPublicKeyAsMultibaseSpki;
25
+ exports.importPublicKeyFromMultibaseSpki = importPublicKeyFromMultibaseSpki;
26
+ const ts_utils_1 = require("@fgv/ts-utils");
27
+ /**
28
+ * Encodes a `Uint8Array` as a multibase base64url (no-padding) string.
29
+ *
30
+ * The multibase prefix `'m'` identifies the encoding as RFC 4648 base64url
31
+ * without padding. The body uses base64url alphabet: `+` → `-`, `/` → `_`,
32
+ * and trailing `=` padding is stripped.
33
+ *
34
+ * @param data - The binary data to encode.
35
+ * @returns A multibase-prefixed base64url string (`'m' + base64url-no-pad`).
36
+ * @public
37
+ */
38
+ function multibaseBase64UrlEncode(data) {
39
+ let base64;
40
+ if (typeof Buffer !== 'undefined') {
41
+ base64 = Buffer.from(data).toString('base64');
42
+ /* c8 ignore start - browser-only: btoa path not available in Node tests */
43
+ }
44
+ else {
45
+ let binary = '';
46
+ for (let i = 0; i < data.length; i++) {
47
+ binary += String.fromCharCode(data[i]);
48
+ }
49
+ base64 = btoa(binary);
50
+ }
51
+ /* c8 ignore stop */
52
+ // Convert to base64url: + → -, / → _, strip = padding
53
+ const base64url = base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
54
+ return 'm' + base64url;
55
+ }
56
+ /**
57
+ * Decodes a multibase base64url (no-padding) string back to a `Uint8Array`.
58
+ *
59
+ * Validates that the first character is `'m'` (the multibase prefix for
60
+ * RFC 4648 base64url without padding), then decodes the remaining body.
61
+ *
62
+ * @param encoded - A multibase-prefixed base64url string.
63
+ * @returns `Success` with the decoded bytes, or `Failure` with error context.
64
+ * @public
65
+ */
66
+ function multibaseBase64UrlDecode(encoded) {
67
+ var _a;
68
+ if (!encoded.startsWith('m')) {
69
+ return (0, ts_utils_1.fail)(`multibaseBase64UrlDecode: invalid multibase prefix '${(_a = encoded[0]) !== null && _a !== void 0 ? _a : '(empty)'}' — expected 'm' (base64url)`);
70
+ }
71
+ const body = encoded.slice(1);
72
+ if (!/^[A-Za-z0-9_-]*$/.test(body) || body.length % 4 === 1) {
73
+ return (0, ts_utils_1.fail)(`multibaseBase64UrlDecode: malformed base64url body`);
74
+ }
75
+ // Convert base64url back to standard base64 and restore padding
76
+ const base64 = body.replace(/-/g, '+').replace(/_/g, '/');
77
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
78
+ try {
79
+ let bytes;
80
+ if (typeof Buffer !== 'undefined') {
81
+ bytes = new Uint8Array(Buffer.from(padded, 'base64'));
82
+ /* c8 ignore start - browser-only: atob path not available in Node tests */
83
+ }
84
+ else {
85
+ const binary = atob(padded);
86
+ bytes = new Uint8Array(binary.length);
87
+ for (let i = 0; i < binary.length; i++) {
88
+ bytes[i] = binary.charCodeAt(i);
89
+ }
90
+ }
91
+ /* c8 ignore stop */
92
+ return (0, ts_utils_1.succeed)(bytes);
93
+ /* c8 ignore next 3 - defensive: regex validation above prevents invalid chars from reaching here */
94
+ }
95
+ catch (_b) {
96
+ return (0, ts_utils_1.fail)(`multibaseBase64UrlDecode: malformed base64url body`);
97
+ }
98
+ }
99
+ /**
100
+ * Exports a public `CryptoKey` as a multibase base64url-encoded SPKI blob.
101
+ *
102
+ * The SPKI (SubjectPublicKeyInfo) format is the standard DER-encoded structure
103
+ * for public keys defined in RFC 5280, RFC 5480, and RFC 8410. It is
104
+ * algorithm-agnostic and suitable for storage and transmission.
105
+ *
106
+ * @param key - The `CryptoKey` to export. Must have `key.type === 'public'`.
107
+ * @param provider - The {@link CryptoUtils.ICryptoProvider} to use for the export operation.
108
+ * @returns `Success` with the multibase SPKI string, or `Failure` with error context.
109
+ * @public
110
+ */
111
+ async function exportPublicKeyAsMultibaseSpki(key, provider) {
112
+ return (await provider.exportPublicKeySpki(key))
113
+ .withErrorFormat((e) => `exportPublicKeyAsMultibaseSpki: ${e}`)
114
+ .onSuccess((buf) => (0, ts_utils_1.succeed)(multibaseBase64UrlEncode(buf)));
115
+ }
116
+ /**
117
+ * Imports a public key from a multibase base64url-encoded SPKI blob.
118
+ *
119
+ * Decodes the multibase prefix, decodes the base64url body, then uses
120
+ * the provider to import the key with the algorithm parameters from
121
+ * {@link CryptoUtils.keyPairAlgorithmParams}.
122
+ *
123
+ * @param encoded - A multibase SPKI string produced by {@link CryptoUtils.exportPublicKeyAsMultibaseSpki}.
124
+ * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm} the key was generated for.
125
+ * @param provider - The {@link CryptoUtils.ICryptoProvider} to use for the import operation.
126
+ * @returns `Success` with the imported public `CryptoKey`, or `Failure` with error context.
127
+ * @public
128
+ */
129
+ async function importPublicKeyFromMultibaseSpki(encoded, algorithm, provider) {
130
+ const decodeResult = multibaseBase64UrlDecode(encoded);
131
+ if (decodeResult.isFailure()) {
132
+ return (0, ts_utils_1.fail)(`importPublicKeyFromMultibaseSpki: ${decodeResult.message}`);
133
+ }
134
+ return (await provider.importPublicKeySpki(decodeResult.value, algorithm)).withErrorFormat((e) => `importPublicKeyFromMultibaseSpki: ${e}`);
135
+ }
136
+ //# sourceMappingURL=spkiHelpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spkiHelpers.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/spkiHelpers.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;;AAgBZ,4DAgBC;AAYD,4DAiCC;AAcD,wEAOC;AAeD,4EAYC;AA3HD,4CAAsD;AAGtD;;;;;;;;;;GAUG;AACH,SAAgB,wBAAwB,CAAC,IAAgB;IACvD,IAAI,MAAc,CAAC;IACnB,IAAI,OAAO,MAAM,KAAK,WAAW,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AC,GAAG,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC;AAED;;;;;;;;;;;;GAYG;AACI,KAAK,UAAU,gCAAgC,CACpD,OAAe,EACf,SAA2B,EAC3B,QAAyB;IAEzB,MAAM,YAAY,GAAG,wBAAwB,CAAC,OAAO,CAAC,CAAC;IACvD,IAAI,YAAY,CAAC,SAAS,EAAE,EAAE,CAAC;QAC7B,OAAO,IAAA,eAAI,EAAC,qCAAqC,YAAY,CAAC,OAAO,EAAE,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,CAAC,MAAM,QAAQ,CAAC,mBAAmB,CAAC,YAAY,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,eAAe,CACxF,CAAC,CAAC,EAAE,EAAE,CAAC,qCAAqC,CAAC,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["// 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\nimport { Result, fail, succeed } from '@fgv/ts-utils';\nimport { ICryptoProvider, KeyPairAlgorithm } from './model';\n\n/**\n * Encodes a `Uint8Array` as a multibase base64url (no-padding) string.\n *\n * The multibase prefix `'m'` identifies the encoding as RFC 4648 base64url\n * without padding. The body uses base64url alphabet: `+` → `-`, `/` → `_`,\n * and trailing `=` padding is stripped.\n *\n * @param data - The binary data to encode.\n * @returns A multibase-prefixed base64url string (`'m' + base64url-no-pad`).\n * @public\n */\nexport function multibaseBase64UrlEncode(data: Uint8Array): string {\n let base64: string;\n if (typeof Buffer !== 'undefined') {\n base64 = Buffer.from(data).toString('base64');\n /* c8 ignore start - browser-only: btoa path not available in Node tests */\n } else {\n let binary = '';\n for (let i = 0; i < data.length; i++) {\n binary += String.fromCharCode(data[i]);\n }\n base64 = btoa(binary);\n }\n /* c8 ignore stop */\n // Convert to base64url: + → -, / → _, strip = padding\n const base64url = base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n return 'm' + base64url;\n}\n\n/**\n * Decodes a multibase base64url (no-padding) string back to a `Uint8Array`.\n *\n * Validates that the first character is `'m'` (the multibase prefix for\n * RFC 4648 base64url without padding), then decodes the remaining body.\n *\n * @param encoded - A multibase-prefixed base64url string.\n * @returns `Success` with the decoded bytes, or `Failure` with error context.\n * @public\n */\nexport function multibaseBase64UrlDecode(encoded: string): Result<Uint8Array> {\n if (!encoded.startsWith('m')) {\n return fail(\n `multibaseBase64UrlDecode: invalid multibase prefix '${\n encoded[0] ?? '(empty)'\n }' — expected 'm' (base64url)`\n );\n }\n const body = encoded.slice(1);\n if (!/^[A-Za-z0-9_-]*$/.test(body) || body.length % 4 === 1) {\n return fail(`multibaseBase64UrlDecode: malformed base64url body`);\n }\n // Convert base64url back to standard base64 and restore padding\n const base64 = body.replace(/-/g, '+').replace(/_/g, '/');\n const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);\n try {\n let bytes: Uint8Array;\n if (typeof Buffer !== 'undefined') {\n bytes = new Uint8Array(Buffer.from(padded, 'base64'));\n /* c8 ignore start - browser-only: atob path not available in Node tests */\n } else {\n const binary = atob(padded);\n bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n }\n /* c8 ignore stop */\n return succeed(bytes);\n /* c8 ignore next 3 - defensive: regex validation above prevents invalid chars from reaching here */\n } catch {\n return fail(`multibaseBase64UrlDecode: malformed base64url body`);\n }\n}\n\n/**\n * Exports a public `CryptoKey` as a multibase base64url-encoded SPKI blob.\n *\n * The SPKI (SubjectPublicKeyInfo) format is the standard DER-encoded structure\n * for public keys defined in RFC 5280, RFC 5480, and RFC 8410. It is\n * algorithm-agnostic and suitable for storage and transmission.\n *\n * @param key - The `CryptoKey` to export. Must have `key.type === 'public'`.\n * @param provider - The {@link CryptoUtils.ICryptoProvider} to use for the export operation.\n * @returns `Success` with the multibase SPKI string, or `Failure` with error context.\n * @public\n */\nexport async function exportPublicKeyAsMultibaseSpki(\n key: CryptoKey,\n provider: ICryptoProvider\n): Promise<Result<string>> {\n return (await provider.exportPublicKeySpki(key))\n .withErrorFormat((e) => `exportPublicKeyAsMultibaseSpki: ${e}`)\n .onSuccess((buf) => succeed(multibaseBase64UrlEncode(buf)));\n}\n\n/**\n * Imports a public key from a multibase base64url-encoded SPKI blob.\n *\n * Decodes the multibase prefix, decodes the base64url body, then uses\n * the provider to import the key with the algorithm parameters from\n * {@link CryptoUtils.keyPairAlgorithmParams}.\n *\n * @param encoded - A multibase SPKI string produced by {@link CryptoUtils.exportPublicKeyAsMultibaseSpki}.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm} the key was generated for.\n * @param provider - The {@link CryptoUtils.ICryptoProvider} to use for the import operation.\n * @returns `Success` with the imported public `CryptoKey`, or `Failure` with error context.\n * @public\n */\nexport async function importPublicKeyFromMultibaseSpki(\n encoded: string,\n algorithm: KeyPairAlgorithm,\n provider: ICryptoProvider\n): Promise<Result<CryptoKey>> {\n const decodeResult = multibaseBase64UrlDecode(encoded);\n if (decodeResult.isFailure()) {\n return fail(`importPublicKeyFromMultibaseSpki: ${decodeResult.message}`);\n }\n return (await provider.importPublicKeySpki(decodeResult.value, algorithm)).withErrorFormat(\n (e) => `importPublicKeyFromMultibaseSpki: ${e}`\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fgv/ts-extras",
3
- "version": "5.1.0-24",
3
+ "version": "5.1.0-26",
4
4
  "description": "Assorted Typescript Utilities",
5
5
  "main": "lib/index.js",
6
6
  "types": "dist/ts-extras.d.ts",
@@ -86,10 +86,10 @@
86
86
  "@types/js-yaml": "~4.0.9",
87
87
  "typedoc": "~0.28.16",
88
88
  "typedoc-plugin-markdown": "~4.9.0",
89
- "@fgv/heft-dual-rig": "5.1.0-24",
90
- "@fgv/typedoc-compact-theme": "5.1.0-24",
91
- "@fgv/ts-utils": "5.1.0-24",
92
- "@fgv/ts-utils-jest": "5.1.0-24"
89
+ "@fgv/heft-dual-rig": "5.1.0-26",
90
+ "@fgv/typedoc-compact-theme": "5.1.0-26",
91
+ "@fgv/ts-utils-jest": "5.1.0-26",
92
+ "@fgv/ts-utils": "5.1.0-26"
93
93
  },
94
94
  "dependencies": {
95
95
  "luxon": "^3.7.2",
@@ -97,10 +97,10 @@
97
97
  "papaparse": "^5.4.1",
98
98
  "fflate": "~0.8.2",
99
99
  "js-yaml": "~4.1.1",
100
- "@fgv/ts-json-base": "5.1.0-24"
100
+ "@fgv/ts-json-base": "5.1.0-26"
101
101
  },
102
102
  "peerDependencies": {
103
- "@fgv/ts-utils": "5.1.0-24"
103
+ "@fgv/ts-utils": "5.1.0-26"
104
104
  },
105
105
  "repository": {
106
106
  "type": "git",