@signature-kit/crypto 0.2.0 → 0.2.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ - Export English and pt-BR `cryptoErrorMessages` catalogs for code-keyed display
6
+ copy.
7
+
8
+ - Security: bound PKCS#12 MAC, PBKDF2, and legacy PBE iteration counts at 10M so
9
+ attacker-controlled `.pfx` files cannot pin the event loop before the password
10
+ is checked.
11
+ - Extend hardening coverage across PBES2/PBKDF2 encrypted-data, legacy PBE, and
12
+ the exact 10M boundary; runtime behavior is unchanged.
13
+
3
14
  ## 0.2.0
4
15
 
5
16
  - Fix SHA-512/SHA-384 message-length encoding for inputs ≥ 512 MiB (also corrects
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @signature-kit/crypto
2
2
 
3
- Shared cryptographic primitives for PKCS#12, PEM, base64, hashing, and cipher operations.
3
+ Shared cryptographic primitives for base64, PEM, PKCS#12, hashing, and cipher operations.
4
4
 
5
5
  ## Install
6
6
 
@@ -8,22 +8,39 @@ Shared cryptographic primitives for PKCS#12, PEM, base64, hashing, and cipher op
8
8
  bun add @signature-kit/crypto effect
9
9
  ```
10
10
 
11
- ## Exports
11
+ `effect` is a direct runtime dependency. This is a low-level support package; prefer higher-level SignatureKit packages unless you need the primitive directly.
12
12
 
13
- - `@signature-kit/crypto/base64`
14
- - `@signature-kit/crypto/config`
15
- - `@signature-kit/crypto/pem`
16
- - `@signature-kit/crypto/pkcs12`
13
+ ## Public surface
17
14
 
18
- ## Runtime model
15
+ - `@signature-kit/crypto/base64` — `bytesToBase64` and `base64ToBytes`.
16
+ - `@signature-kit/crypto/config` — `CryptoError`, `CryptoErrorCodeValue`, operation schemas, message catalogs, and `Pkcs12ResultSchema`.
17
+ - `@signature-kit/crypto/pem` — `pemToDer` and `derToPem`.
18
+ - `@signature-kit/crypto/pkcs12` — `parsePkcs12`.
19
19
 
20
- SignatureKit packages are Effect-native. Public APIs return typed `Effect.Effect` values; recoverable faults stay in the typed error channel; callers provide required services and layers explicitly at the application boundary.
20
+ ## Example
21
21
 
22
- This is a low-level support package: keep its surface narrow and prefer the higher-level SignatureKit packages unless you need the primitive directly.
22
+ ```ts
23
+ import { bytesToBase64 } from "@signature-kit/crypto/base64";
24
+ import { pemToDer } from "@signature-kit/crypto/pem";
25
+ import { Effect } from "effect";
23
26
 
24
- ## Version
27
+ declare const certificatePem: string;
25
28
 
26
- Current npm release line: `0.1.0`.
29
+ const program = Effect.gen(function* () {
30
+ const der = yield* pemToDer(certificatePem);
31
+
32
+ return {
33
+ der,
34
+ contentBase64: bytesToBase64(der),
35
+ };
36
+ });
37
+ ```
38
+
39
+ ## Errors and i18n
40
+
41
+ Crypto failures use the `CryptoError` code catalog and `cryptoErrorMessages`. Applications can render localized copy through `@signature-kit/i18n` by passing that catalog to `errorMessage`.
42
+
43
+ Docs: <https://signaturekit.dev/en-US/docs/concepts/document-formats>.
27
44
 
28
45
  ## License
29
46
 
package/dist/config.d.ts CHANGED
@@ -30,6 +30,34 @@ export declare const CryptoOperationValue: {
30
30
  cipherDes: "cipher.des";
31
31
  cipherRc2: "cipher.rc2";
32
32
  };
33
+ export declare const CryptoErrorMessageLocaleSchema: Schema.Literals<readonly ["en-US", "pt-BR"]>;
34
+ export type CryptoErrorMessageLocale = (typeof CryptoErrorMessageLocaleSchema)["Type"];
35
+ export declare const CryptoErrorMessagesSchema: Schema.$Record<Schema.Literals<readonly ["en-US", "pt-BR"]>, Schema.$Record<Schema.Literals<readonly ["crypto.DECODE_ERROR", "crypto.INVALID_FORMAT", "crypto.UNSUPPORTED_ALGORITHM", "crypto.WRONG_PASSWORD", "crypto.NO_CERTIFICATE", "crypto.NO_PRIVATE_KEY", "crypto.CORRUPTED_FILE", "crypto.CIPHER_ERROR", "crypto.UNKNOWN"]>, Schema.String>>;
36
+ export type CryptoErrorMessages = (typeof CryptoErrorMessagesSchema)["Type"];
37
+ export declare const cryptoErrorMessages: {
38
+ "en-US": {
39
+ "crypto.DECODE_ERROR": string;
40
+ "crypto.INVALID_FORMAT": string;
41
+ "crypto.UNSUPPORTED_ALGORITHM": string;
42
+ "crypto.WRONG_PASSWORD": string;
43
+ "crypto.NO_CERTIFICATE": string;
44
+ "crypto.NO_PRIVATE_KEY": string;
45
+ "crypto.CORRUPTED_FILE": string;
46
+ "crypto.CIPHER_ERROR": string;
47
+ "crypto.UNKNOWN": string;
48
+ };
49
+ "pt-BR": {
50
+ "crypto.DECODE_ERROR": string;
51
+ "crypto.INVALID_FORMAT": string;
52
+ "crypto.UNSUPPORTED_ALGORITHM": string;
53
+ "crypto.WRONG_PASSWORD": string;
54
+ "crypto.NO_CERTIFICATE": string;
55
+ "crypto.NO_PRIVATE_KEY": string;
56
+ "crypto.CORRUPTED_FILE": string;
57
+ "crypto.CIPHER_ERROR": string;
58
+ "crypto.UNKNOWN": string;
59
+ };
60
+ };
33
61
  declare const CryptoError_base: Schema.Class<CryptoError, Schema.TaggedStruct<"CryptoError", {
34
62
  readonly code: Schema.Literals<readonly ["crypto.DECODE_ERROR", "crypto.INVALID_FORMAT", "crypto.UNSUPPORTED_ALGORITHM", "crypto.WRONG_PASSWORD", "crypto.NO_CERTIFICATE", "crypto.NO_PRIVATE_KEY", "crypto.CORRUPTED_FILE", "crypto.CIPHER_ERROR", "crypto.UNKNOWN"]>;
35
63
  readonly reason: Schema.optional<Schema.String>;
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,eAAO,MAAM,qBAAqB,yPAUhC,CAAC;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,qBAAqB,CAAC,CAAC,MAAM,CAAC,CAAC;AACrE,eAAO,MAAM,oBAAoB;;;;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,OAAO,IAAI,MAAM,CAKpB;CACF;AAED,eAAO,MAAM,kBAAkB;;;;EAI7B,CAAC;AACH,MAAM,MAAM,YAAY,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC"}
package/dist/config.js CHANGED
@@ -47,32 +47,53 @@ export const CryptoOperationValue = {
47
47
  cipherDes: "cipher.des",
48
48
  cipherRc2: "cipher.rc2",
49
49
  };
50
+ export const CryptoErrorMessageLocaleSchema = Schema.Literals(["en-US", "pt-BR"]);
51
+ export const CryptoErrorMessagesSchema = Schema.Record(CryptoErrorMessageLocaleSchema, Schema.Record(CryptoErrorCodeSchema, Schema.String));
52
+ export const cryptoErrorMessages = {
53
+ "en-US": {
54
+ "crypto.DECODE_ERROR": "Failed to decode PKCS#12 ASN.1.",
55
+ "crypto.INVALID_FORMAT": "Unsupported PKCS#12 format.",
56
+ "crypto.UNSUPPORTED_ALGORITHM": "Unsupported PKCS#12 encryption algorithm.",
57
+ "crypto.WRONG_PASSWORD": "Wrong PKCS#12 password.",
58
+ "crypto.NO_CERTIFICATE": "No certificate found in PKCS#12 file.",
59
+ "crypto.NO_PRIVATE_KEY": "No private key found in PKCS#12 file.",
60
+ "crypto.CORRUPTED_FILE": "Corrupted PKCS#12 file.",
61
+ "crypto.CIPHER_ERROR": "Cipher operation failed.",
62
+ "crypto.UNKNOWN": "Unknown crypto failure.",
63
+ },
64
+ "pt-BR": {
65
+ "crypto.DECODE_ERROR": "Não foi possível ler os dados ASN.1 do PKCS#12.",
66
+ "crypto.INVALID_FORMAT": "Formato PKCS#12 não suportado.",
67
+ "crypto.UNSUPPORTED_ALGORITHM": "O certificado usa um algoritmo de criptografia não suportado.",
68
+ "crypto.WRONG_PASSWORD": "Senha do certificado incorreta.",
69
+ "crypto.NO_CERTIFICATE": "O arquivo não contém um certificado.",
70
+ "crypto.NO_PRIVATE_KEY": "O arquivo não contém uma chave privada.",
71
+ "crypto.CORRUPTED_FILE": "Arquivo PKCS#12 corrompido.",
72
+ "crypto.CIPHER_ERROR": "Falha na operação de criptografia.",
73
+ "crypto.UNKNOWN": "Falha de criptografia desconhecida.",
74
+ },
75
+ };
76
+ const cryptoErrorReasonOverridableByCode = {
77
+ "crypto.DECODE_ERROR": true,
78
+ "crypto.INVALID_FORMAT": true,
79
+ "crypto.UNSUPPORTED_ALGORITHM": true,
80
+ "crypto.WRONG_PASSWORD": false,
81
+ "crypto.NO_CERTIFICATE": false,
82
+ "crypto.NO_PRIVATE_KEY": false,
83
+ "crypto.CORRUPTED_FILE": true,
84
+ "crypto.CIPHER_ERROR": true,
85
+ "crypto.UNKNOWN": true,
86
+ };
50
87
  export class CryptoError extends Schema.TaggedErrorClass()("CryptoError", {
51
88
  code: CryptoErrorCodeSchema,
52
89
  reason: Schema.optional(Schema.String),
53
90
  operation: Schema.optional(CryptoOperationSchema),
54
91
  }) {
55
92
  get message() {
56
- switch (this.code) {
57
- case "crypto.DECODE_ERROR":
58
- return this.reason ?? "Failed to decode PKCS#12 ASN.1.";
59
- case "crypto.INVALID_FORMAT":
60
- return this.reason ?? "Unsupported PKCS#12 format.";
61
- case "crypto.UNSUPPORTED_ALGORITHM":
62
- return this.reason ?? "Unsupported PKCS#12 encryption algorithm.";
63
- case "crypto.WRONG_PASSWORD":
64
- return "Wrong PKCS#12 password.";
65
- case "crypto.NO_CERTIFICATE":
66
- return "No certificate found in PKCS#12 file.";
67
- case "crypto.NO_PRIVATE_KEY":
68
- return "No private key found in PKCS#12 file.";
69
- case "crypto.CORRUPTED_FILE":
70
- return this.reason ?? "Corrupted PKCS#12 file.";
71
- case "crypto.CIPHER_ERROR":
72
- return this.reason ?? "Cipher operation failed.";
73
- case "crypto.UNKNOWN":
74
- return this.reason ?? "Unknown crypto failure.";
75
- }
93
+ const defaultMessage = cryptoErrorMessages["en-US"][this.code];
94
+ return cryptoErrorReasonOverridableByCode[this.code]
95
+ ? (this.reason ?? defaultMessage)
96
+ : defaultMessage;
76
97
  }
77
98
  }
78
99
  export const Pkcs12ResultSchema = Schema.Struct({
@@ -1 +1 @@
1
- {"version":3,"file":"pkcs12.d.ts","sourceRoot":"","sources":["../src/pkcs12.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAYH,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAC1C,OAAO,EACL,WAAW,EAGX,KAAK,YAAY,EAClB,MAAM,UAAU,CAAC;AA0hBlB,gFAAgF;AAChF,eAAO,MAAM,WAAW,GACtB,MAAM,UAAU,EAChB,UAAU,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,KAClC,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,WAAW,CAyHvC,CAAC"}
1
+ {"version":3,"file":"pkcs12.d.ts","sourceRoot":"","sources":["../src/pkcs12.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAYH,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAC1C,OAAO,EACL,WAAW,EAGX,KAAK,YAAY,EAClB,MAAM,UAAU,CAAC;AAgjBlB,gFAAgF;AAChF,eAAO,MAAM,WAAW,GACtB,MAAM,UAAU,EAChB,UAAU,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,KAClC,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,WAAW,CAyHvC,CAAC"}
package/dist/pkcs12.js CHANGED
@@ -40,6 +40,17 @@ const OID_HMAC_SHA512 = "1.2.840.113549.2.11";
40
40
  const OID_SHA256 = "2.16.840.1.101.3.4.2.1";
41
41
  const OID_SHA384 = "2.16.840.1.101.3.4.2.2";
42
42
  const OID_SHA512 = "2.16.840.1.101.3.4.2.3";
43
+ // Iteration counts come from the (attacker-controlled) file; the KDFs run in
44
+ // pure JS, so an unbounded count pins the event loop before the password is
45
+ // even checked. OpenSSL defaults to 2048; 10M gives generous headroom.
46
+ const MAX_KDF_ITERATIONS = 10_000_000;
47
+ const boundedIterations = (iterations, label) => Number.isSafeInteger(iterations) && iterations >= 1 && iterations <= MAX_KDF_ITERATIONS
48
+ ? Effect.succeed(iterations)
49
+ : Effect.fail(new CryptoError({
50
+ code: CryptoErrorCodeValue.corruptedFile,
51
+ reason: `Unreasonable ${label} iteration count: ${iterations}.`,
52
+ operation: CryptoOperationValue.pkcs12Decode,
53
+ }));
43
54
  const elementAt = (nodes, index, label) => {
44
55
  const node = nodes[index];
45
56
  return node === undefined
@@ -189,9 +200,9 @@ const verifyMac = (macNode, authSafeData, bmpPassword) => Effect.gen(function* (
189
200
  const macAlgOid = yield* oidString(yield* elementAt(algorithmSeq, 0, "MAC algorithm OID"));
190
201
  const expectedDigest = yield* bytesOf(yield* elementAt(digestInfo, 1, "MAC digest"));
191
202
  const macSalt = yield* bytesOf(yield* elementAt(macFields, 1, "MAC salt"));
192
- const iterations = macFields.length >= 3
203
+ const iterations = yield* boundedIterations(macFields.length >= 3
193
204
  ? Number(yield* integerBigInt(yield* elementAt(macFields, 2, "MAC iterations")))
194
- : 1;
205
+ : 1, "MAC");
195
206
  const algorithm = macHashAlgorithm(macAlgOid);
196
207
  const macKey = pkcs12Kdf(bmpPassword, macSalt, iterations, 3, hashOutputLength(algorithm), algorithm);
197
208
  const computed = hmac(algorithm, macKey, authSafeData);
@@ -234,7 +245,7 @@ const decryptPbes2 = (encryptedData, params, passwordBytes) => Effect.gen(functi
234
245
  }
235
246
  const pbkdf2Params = yield* childrenOf(yield* elementAt(kdfInfo, 1, "PBKDF2-params"));
236
247
  const salt = yield* bytesOf(yield* elementAt(pbkdf2Params, 0, "PBKDF2 salt"));
237
- const iterations = Number(yield* integerBigInt(yield* elementAt(pbkdf2Params, 1, "PBKDF2 iterations")));
248
+ const iterations = yield* boundedIterations(Number(yield* integerBigInt(yield* elementAt(pbkdf2Params, 1, "PBKDF2 iterations"))), "PBKDF2");
238
249
  let prf = "sha1";
239
250
  for (let i = 2; i < pbkdf2Params.length; i++) {
240
251
  const param = pbkdf2Params[i];
@@ -265,7 +276,7 @@ const decryptPbe = (encryptedData, algorithmOid, algorithmParams, bmpPassword, p
265
276
  return Effect.gen(function* () {
266
277
  const params = yield* childrenOf(algorithmParams);
267
278
  const salt = yield* bytesOf(yield* elementAt(params, 0, "PBE salt"));
268
- const iterations = Number(yield* integerBigInt(yield* elementAt(params, 1, "PBE iterations")));
279
+ const iterations = yield* boundedIterations(Number(yield* integerBigInt(yield* elementAt(params, 1, "PBE iterations"))), "PBE");
269
280
  const derive = (length, purpose) => pkcs12Kdf(bmpPassword, salt, iterations, purpose, length, "sha1");
270
281
  if (algorithmOid === OID_PBE_SHA_3DES) {
271
282
  return yield* tripleDesCbcDecrypt(derive(24, 1), derive(8, 2), encryptedData);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@signature-kit/crypto",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -37,7 +37,7 @@
37
37
  "test": "vitest run"
38
38
  },
39
39
  "dependencies": {
40
- "@signature-kit/asn1": "^0.2.0",
40
+ "@signature-kit/asn1": "^0.2.1",
41
41
  "effect": "4.0.0-beta.86"
42
42
  },
43
43
  "nx": {