@ocap/mcrypto 1.30.24 → 1.30.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 (51) hide show
  1. package/esm/crypter/aes-legacy.d.mts +11 -0
  2. package/esm/crypter/aes-legacy.mjs +67 -15
  3. package/esm/crypter/aes.d.mts +14 -2
  4. package/esm/crypter/aes.mjs +69 -3
  5. package/esm/encode.mjs +1 -1
  6. package/esm/hasher/keccak.mjs +7 -2
  7. package/esm/hasher/sha2.d.mts +1 -1
  8. package/esm/hasher/sha2.mjs +26 -11
  9. package/esm/hasher/sha3.d.mts +1 -1
  10. package/esm/hasher/sha3.mjs +21 -6
  11. package/esm/index.d.mts +1 -1
  12. package/esm/signer/ed25519.d.mts +1 -1
  13. package/esm/signer/ed25519.mjs +143 -16
  14. package/esm/signer/ethereum.mjs +7 -3
  15. package/esm/signer/secp256k1.mjs +3 -2
  16. package/esm/webauthn.d.mts +68 -2
  17. package/esm/webauthn.mjs +64 -16
  18. package/lib/_vendor/@noble/curves/LICENSE +21 -0
  19. package/lib/_vendor/@noble/curves/abstract/curve.cjs +373 -0
  20. package/lib/_vendor/@noble/curves/abstract/modular.cjs +616 -0
  21. package/lib/_vendor/@noble/curves/abstract/weierstrass.cjs +1020 -0
  22. package/lib/_vendor/@noble/curves/nist.cjs +91 -0
  23. package/lib/_vendor/@noble/curves/secp256k1.cjs +73 -0
  24. package/lib/_vendor/@noble/curves/utils.cjs +463 -0
  25. package/lib/_vendor/@noble/ed25519/LICENSE +21 -0
  26. package/lib/_vendor/@noble/ed25519/index.cjs +512 -0
  27. package/lib/_vendor/@noble/hashes/LICENSE +21 -0
  28. package/lib/_vendor/@noble/hashes/_md.cjs +230 -0
  29. package/lib/_vendor/@noble/hashes/_u64.cjs +67 -0
  30. package/lib/_vendor/@noble/hashes/hmac.cjs +86 -0
  31. package/lib/_vendor/@noble/hashes/sha2.cjs +477 -0
  32. package/lib/_vendor/@noble/hashes/sha3.cjs +329 -0
  33. package/lib/_vendor/@noble/hashes/utils.cjs +410 -0
  34. package/lib/crypter/aes-legacy.cjs +68 -21
  35. package/lib/crypter/aes-legacy.d.cts +11 -0
  36. package/lib/crypter/aes.cjs +69 -2
  37. package/lib/crypter/aes.d.cts +14 -2
  38. package/lib/encode.cjs +1 -1
  39. package/lib/hasher/keccak.cjs +13 -8
  40. package/lib/hasher/sha2.cjs +32 -17
  41. package/lib/hasher/sha2.d.cts +1 -1
  42. package/lib/hasher/sha3.cjs +27 -12
  43. package/lib/hasher/sha3.d.cts +1 -1
  44. package/lib/index.d.cts +1 -1
  45. package/lib/signer/ed25519.cjs +146 -20
  46. package/lib/signer/ed25519.d.cts +1 -1
  47. package/lib/signer/ethereum.cjs +16 -12
  48. package/lib/signer/secp256k1.cjs +11 -10
  49. package/lib/webauthn.cjs +80 -31
  50. package/lib/webauthn.d.cts +68 -2
  51. package/package.json +6 -7
@@ -1,8 +1,19 @@
1
1
  import _default$1 from "../protocols/crypter.mjs";
2
2
 
3
3
  //#region src/crypter/aes-legacy.d.ts
4
+
5
+ /**
6
+ * @deprecated Legacy OpenSSL `Salted__` AES-256-CBC crypter kept only for backward compatibility
7
+ * with historical ciphertexts. Do not use for new encryption; use `@ocap/mcrypto/lib/crypter/aes` (AES-256-GCM).
8
+ */
4
9
  declare class AesCrypter extends _default$1 {
10
+ /**
11
+ * @deprecated Use `@ocap/mcrypto/lib/crypter/aes` (AES-256-GCM) for new data encryption.
12
+ */
5
13
  encrypt(message: string | object, secret: string): string;
14
+ /**
15
+ * @deprecated Legacy OpenSSL `Salted__` AES-256-CBC decryption.
16
+ */
6
17
  decrypt(cipher: string, secret: string, outputEncoding?: string): string;
7
18
  }
8
19
  declare const _default: AesCrypter;
@@ -1,26 +1,78 @@
1
1
  import crypter_default from "../protocols/crypter.mjs";
2
- import AES from "crypto-js/aes.js";
3
- import encBase64 from "crypto-js/enc-base64.js";
4
- import encHex from "crypto-js/enc-hex.js";
5
- import encLatin1 from "crypto-js/enc-latin1.js";
6
- import encUtf8 from "crypto-js/enc-utf8.js";
7
- import encUtf16 from "crypto-js/enc-utf16.js";
2
+ import crypto from "node:crypto";
8
3
 
9
4
  //#region src/crypter/aes-legacy.ts
10
- const encoders = {
11
- latin1: encLatin1,
12
- utf8: encUtf8,
13
- hex: encHex,
14
- utf16: encUtf16,
15
- base64: encBase64
16
- };
5
+ const OPENSSL_SALT_MAGIC = Buffer.from("Salted__", "latin1");
6
+ /**
7
+ * OpenSSL EVP_BytesToKey (MD5, 1 iteration) key + IV derivation for backward
8
+ * compatibility with historical `crypto-js` `Salted__` AES-256-CBC ciphertexts.
9
+ */
10
+ function evpBytesToKey(password, salt) {
11
+ const blocks = [];
12
+ let prev = Buffer.alloc(0);
13
+ while (Buffer.concat(blocks).length < 48) {
14
+ const hash = crypto.createHash("md5");
15
+ if (prev.length > 0) hash.update(prev);
16
+ hash.update(password);
17
+ hash.update(salt);
18
+ prev = hash.digest();
19
+ blocks.push(prev);
20
+ }
21
+ const derived = Buffer.concat(blocks);
22
+ return {
23
+ key: derived.subarray(0, 32),
24
+ iv: derived.subarray(32, 48)
25
+ };
26
+ }
27
+ function encodeOutput(buf, outputEncoding = "utf8") {
28
+ switch (outputEncoding) {
29
+ case "utf8": return buf.toString("utf8");
30
+ case "hex": return buf.toString("hex");
31
+ case "latin1": return buf.toString("latin1");
32
+ case "base64": return buf.toString("base64");
33
+ case "utf16": {
34
+ let str = "";
35
+ for (let i = 0; i < buf.length; i += 2) {
36
+ const hi = buf[i] ?? 0;
37
+ const lo = buf[i + 1] ?? 0;
38
+ str += String.fromCharCode(hi << 8 | lo);
39
+ }
40
+ return str;
41
+ }
42
+ default: throw new Error(`Unsupported output encoding: ${outputEncoding}`);
43
+ }
44
+ }
45
+ /**
46
+ * @deprecated Legacy OpenSSL `Salted__` AES-256-CBC crypter kept only for backward compatibility
47
+ * with historical ciphertexts. Do not use for new encryption; use `@ocap/mcrypto/lib/crypter/aes` (AES-256-GCM).
48
+ */
17
49
  var AesCrypter = class extends crypter_default {
50
+ /**
51
+ * @deprecated Use `@ocap/mcrypto/lib/crypter/aes` (AES-256-GCM) for new data encryption.
52
+ */
18
53
  encrypt(message, secret) {
19
54
  const text = typeof message === "string" ? message : JSON.stringify(message);
20
- return AES.encrypt(text, secret).toString();
55
+ const salt = crypto.randomBytes(8);
56
+ const { key, iv } = evpBytesToKey(Buffer.from(secret, "utf8"), salt);
57
+ const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
58
+ const encrypted = Buffer.concat([cipher.update(Buffer.from(text, "utf8")), cipher.final()]);
59
+ return Buffer.concat([
60
+ OPENSSL_SALT_MAGIC,
61
+ salt,
62
+ encrypted
63
+ ]).toString("base64");
21
64
  }
65
+ /**
66
+ * @deprecated Legacy OpenSSL `Salted__` AES-256-CBC decryption.
67
+ */
22
68
  decrypt(cipher, secret, outputEncoding = "utf8") {
23
- return AES.decrypt(cipher, secret).toString(encoders[outputEncoding]);
69
+ const raw = Buffer.from(cipher, "base64");
70
+ if (raw.length < 16 || !raw.subarray(0, 8).equals(OPENSSL_SALT_MAGIC)) return "";
71
+ const salt = raw.subarray(8, 16);
72
+ const ciphertext = raw.subarray(16);
73
+ const { key, iv } = evpBytesToKey(Buffer.from(secret, "utf8"), salt);
74
+ const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
75
+ return encodeOutput(Buffer.concat([decipher.update(ciphertext), decipher.final()]), outputEncoding);
24
76
  }
25
77
  };
26
78
  var aes_legacy_default = new AesCrypter();
@@ -2,10 +2,22 @@ import _default$1 from "../protocols/crypter.mjs";
2
2
  import { BytesType, EncodingType } from "@ocap/util";
3
3
 
4
4
  //#region src/crypter/aes.d.ts
5
+
6
+ /**
7
+ * Authenticated AES-256-GCM Crypter with HKDF-SHA256 salted key derivation
8
+ * and backward-compatible read-only decryption for legacy AES-256-ECB payloads.
9
+ */
5
10
  declare class AesCrypter extends _default$1 {
6
11
  encrypt(message: BytesType, secret: BytesType, encoding?: EncodingType): BytesType;
7
- decrypt(message: BytesType, secret: BytesType, encoding?: EncodingType): BytesType;
12
+ /**
13
+ * @deprecated Legacy deterministic AES-256-ECB encryption kept only for compatibility test vectors.
14
+ * Do not use for new data; use `encrypt()` (AES-256-GCM) instead.
15
+ */
16
+ encryptLegacyEcb(message: BytesType, secret: BytesType, encoding?: EncodingType): BytesType;
17
+ decrypt(message: BytesType, secret: BytesType, encoding?: EncodingType, options?: {
18
+ allowLegacyEcb?: boolean;
19
+ }): BytesType;
8
20
  }
9
21
  declare const _default: AesCrypter;
10
22
  //#endregion
11
- export { AesCrypter, _default as default };
23
+ export { AesCrypter, AesCrypter as AesCrypterGCM, _default as default };
@@ -5,8 +5,57 @@ import { toBuffer } from "@ocap/util";
5
5
  import crypto from "node:crypto";
6
6
 
7
7
  //#region src/crypter/aes.ts
8
+ /**
9
+ * Magic header for v2 AES-256-GCM authenticated ciphertexts ("GCM\x02").
10
+ * Binary format: [4B magic "GCM\x02"][16B salt][12B iv][ciphertext...][16B authTag]
11
+ */
12
+ const GCM_MAGIC = Buffer.from([
13
+ 71,
14
+ 67,
15
+ 77,
16
+ 2
17
+ ]);
18
+ const SALT_LENGTH = 16;
19
+ const IV_LENGTH = 12;
20
+ const AUTH_TAG_LENGTH = 16;
21
+ const MIN_GCM_ENVELOPE_LENGTH = GCM_MAGIC.length + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH;
22
+ const HKDF_INFO = Buffer.from("ocap-aes-gcm-v2", "utf8");
23
+ function deriveGcmKey(secret, salt) {
24
+ const secretBuf = toBuffer(secret);
25
+ const derived = crypto.hkdfSync("sha256", secretBuf, salt, HKDF_INFO, 32);
26
+ return new Uint8Array(derived);
27
+ }
28
+ function hasGcmMagic(data) {
29
+ if (data.length < MIN_GCM_ENVELOPE_LENGTH) return false;
30
+ return data[0] === GCM_MAGIC[0] && data[1] === GCM_MAGIC[1] && data[2] === GCM_MAGIC[2] && data[3] === GCM_MAGIC[3];
31
+ }
32
+ /**
33
+ * Authenticated AES-256-GCM Crypter with HKDF-SHA256 salted key derivation
34
+ * and backward-compatible read-only decryption for legacy AES-256-ECB payloads.
35
+ */
8
36
  var AesCrypter = class extends crypter_default {
9
37
  encrypt(message, secret, encoding = "hex") {
38
+ const salt = crypto.randomBytes(SALT_LENGTH);
39
+ const iv = crypto.randomBytes(IV_LENGTH);
40
+ const key = deriveGcmKey(secret, salt);
41
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
42
+ const plaintext = Uint8Array.from(toBuffer(message));
43
+ const encrypted = Buffer.concat([Uint8Array.from(cipher.update(plaintext)), Uint8Array.from(cipher.final())]);
44
+ const authTag = cipher.getAuthTag();
45
+ const envelope = Buffer.concat([
46
+ GCM_MAGIC,
47
+ salt,
48
+ iv,
49
+ encrypted,
50
+ authTag
51
+ ]);
52
+ return encode(Uint8Array.from(envelope), encoding);
53
+ }
54
+ /**
55
+ * @deprecated Legacy deterministic AES-256-ECB encryption kept only for compatibility test vectors.
56
+ * Do not use for new data; use `encrypt()` (AES-256-GCM) instead.
57
+ */
58
+ encryptLegacyEcb(message, secret, encoding = "hex") {
10
59
  const keyBuffer = sha3_default.hash256(secret, 1, "buffer");
11
60
  const key = Uint8Array.from(keyBuffer);
12
61
  const cipher = crypto.createCipheriv("aes-256-ecb", key, "");
@@ -14,16 +63,33 @@ var AesCrypter = class extends crypter_default {
14
63
  const output = cipher.update(Uint8Array.from(toBuffer(message)));
15
64
  return encode(Uint8Array.from(Buffer.concat([Uint8Array.from(output), Uint8Array.from(cipher.final())])), encoding);
16
65
  }
17
- decrypt(message, secret, encoding = "hex") {
66
+ decrypt(message, secret, encoding = "hex", options) {
67
+ const data = toBuffer(message);
68
+ if (hasGcmMagic(data)) {
69
+ const saltStart = GCM_MAGIC.length;
70
+ const ivStart = saltStart + SALT_LENGTH;
71
+ const cipherStart = ivStart + IV_LENGTH;
72
+ const tagStart = data.length - AUTH_TAG_LENGTH;
73
+ const salt = data.subarray(saltStart, ivStart);
74
+ const iv = data.subarray(ivStart, cipherStart);
75
+ const encrypted = data.subarray(cipherStart, tagStart);
76
+ const authTag = data.subarray(tagStart);
77
+ const key$1 = deriveGcmKey(secret, salt);
78
+ const decipher$1 = crypto.createDecipheriv("aes-256-gcm", key$1, iv);
79
+ decipher$1.setAuthTag(authTag);
80
+ const output$1 = decipher$1.update(Uint8Array.from(encrypted));
81
+ return encode(Uint8Array.from(Buffer.concat([Uint8Array.from(output$1), Uint8Array.from(decipher$1.final())])), encoding);
82
+ }
83
+ if (options?.allowLegacyEcb === false) throw new Error("Legacy unauthenticated AES-256-ECB ciphertext rejected");
18
84
  const keyBuffer = sha3_default.hash256(secret, 1, "buffer");
19
85
  const key = Uint8Array.from(keyBuffer);
20
86
  const decipher = crypto.createDecipheriv("aes-256-ecb", key, "");
21
87
  decipher.setAutoPadding(true);
22
- const output = decipher.update(Uint8Array.from(toBuffer(message)));
88
+ const output = decipher.update(Uint8Array.from(data));
23
89
  return encode(Uint8Array.from(Buffer.concat([Uint8Array.from(output), Uint8Array.from(decipher.final())])), encoding);
24
90
  }
25
91
  };
26
92
  var aes_default = new AesCrypter();
27
93
 
28
94
  //#endregion
29
- export { AesCrypter, aes_default as default };
95
+ export { AesCrypter, AesCrypter as AesCrypterGCM, aes_default as default };
package/esm/encode.mjs CHANGED
@@ -2,7 +2,7 @@ import { toBase58, toBase64, toBuffer, toHex, toUint8Array } from "@ocap/util";
2
2
 
3
3
  //#region src/encode.ts
4
4
  function encode(data, encoding = "hex") {
5
- if (["hex", "base16"].includes(encoding)) return toHex(data);
5
+ if (["hex", "base16"].includes(encoding)) return toHex(toUint8Array(data));
6
6
  if (encoding === "base58") return toBase58(data);
7
7
  if (encoding === "base64") return toBase64(data);
8
8
  if (encoding === "Uint8Array") return toUint8Array(data);
@@ -32,12 +32,17 @@ var KeccakHasher = class {
32
32
  };
33
33
  this[name] = (data, round = 1, encoding = "hex") => {
34
34
  let input;
35
- try {
35
+ if (data instanceof Uint8Array) input = data;
36
+ else try {
36
37
  input = toUint8Array(data);
37
38
  } catch (_err) {
38
39
  input = data;
39
40
  }
40
- return encode(`0x${bytesToHex(hashFn(input, round))}`, encoding);
41
+ const res = hashFn(input, round);
42
+ if (encoding === "hex" || encoding === "base16") return `0x${bytesToHex(res)}`;
43
+ if (encoding === "buffer" && typeof Buffer !== "undefined") return Buffer.from(res.buffer, res.byteOffset, res.byteLength);
44
+ if (encoding === "Uint8Array") return res;
45
+ return encode(res, encoding);
41
46
  };
42
47
  });
43
48
  }
@@ -4,7 +4,7 @@ import { BytesType, EncodingType } from "@ocap/util";
4
4
 
5
5
  /**
6
6
  * Sha2 support with different hash length
7
- * Uses @noble/hashes for better performance
7
+ * Uses native node:crypto when available with @noble/hashes fallback
8
8
  *
9
9
  * @class
10
10
  */
@@ -10,9 +10,10 @@ const hashFns = {
10
10
  sha384,
11
11
  sha512
12
12
  };
13
+ const createHash = (typeof process !== "undefined" ? process.getBuiltinModule?.("node:crypto") : void 0)?.createHash;
13
14
  /**
14
15
  * Sha2 support with different hash length
15
- * Uses @noble/hashes for better performance
16
+ * Uses native node:crypto when available with @noble/hashes fallback
16
17
  *
17
18
  * @class
18
19
  */
@@ -25,19 +26,33 @@ var Sha2Hasher = class {
25
26
  512
26
27
  ].forEach((x) => {
27
28
  const name = `hash${x}`;
28
- const hasher = hashFns[`sha${x}`];
29
- const hashFn = (input, round) => {
30
- let inputBytes;
31
- try {
32
- inputBytes = toUint8Array(input);
33
- } catch (_err) {
34
- inputBytes = input;
29
+ const alg = `sha${x}`;
30
+ const hasher = hashFns[alg];
31
+ const hashBytes = (input, round) => {
32
+ const rounds = Math.max(1, round | 0);
33
+ if (createHash) {
34
+ let res$1 = input;
35
+ for (let i = 0; i < rounds; i++) res$1 = createHash(alg).update(res$1).digest();
36
+ return res$1;
35
37
  }
36
- if (round === 1) return `0x${bytesToHex(hasher(inputBytes))}`;
37
- return hashFn(hashFn(inputBytes, 1), round - 1);
38
+ let res = input;
39
+ for (let i = 0; i < rounds; i++) res = hasher(res);
40
+ return res;
38
41
  };
39
42
  this[name] = (data, round = 2, encoding = "hex") => {
40
- return encode(hashFn(data, round), encoding);
43
+ let inputBytes;
44
+ if (data instanceof Uint8Array) inputBytes = data;
45
+ else try {
46
+ inputBytes = toUint8Array(data);
47
+ } catch (_err) {
48
+ inputBytes = data;
49
+ }
50
+ const res = hashBytes(inputBytes, round);
51
+ const isBuf = typeof Buffer !== "undefined" && Buffer.isBuffer(res);
52
+ if (encoding === "hex" || encoding === "base16") return isBuf ? `0x${res.toString("hex")}` : `0x${bytesToHex(res)}`;
53
+ if (encoding === "buffer" && typeof Buffer !== "undefined") return isBuf ? res : Buffer.from(res.buffer, res.byteOffset, res.byteLength);
54
+ if (encoding === "Uint8Array") return isBuf ? new Uint8Array(res) : res;
55
+ return encode(res, encoding);
41
56
  };
42
57
  });
43
58
  }
@@ -4,7 +4,7 @@ import { BytesType, EncodingType } from "@ocap/util";
4
4
 
5
5
  /**
6
6
  * Sha3 support with different hash length
7
- * Uses @noble/hashes for unified implementation
7
+ * Uses native node:crypto when available with @noble/hashes fallback
8
8
  *
9
9
  * @class Sha3Hasher
10
10
  */
@@ -10,9 +10,10 @@ const hashFns = {
10
10
  sha3_384,
11
11
  sha3_512
12
12
  };
13
+ const createHash = (typeof process !== "undefined" ? process.getBuiltinModule?.("node:crypto") : void 0)?.createHash;
13
14
  /**
14
15
  * Sha3 support with different hash length
15
- * Uses @noble/hashes for unified implementation
16
+ * Uses native node:crypto when available with @noble/hashes fallback
16
17
  *
17
18
  * @class Sha3Hasher
18
19
  */
@@ -25,19 +26,33 @@ var Sha3Hasher = class {
25
26
  512
26
27
  ].forEach((x) => {
27
28
  const name = `hash${x}`;
29
+ const alg = `sha3-${x}`;
28
30
  const hasher = hashFns[`sha3_${x}`];
29
- const hashFn = (input, round) => {
30
- if (round === 1) return hasher(input);
31
- return hashFn(hasher(input), round - 1);
31
+ const hashBytes = (input, round) => {
32
+ const rounds = Math.max(1, round | 0);
33
+ if (createHash) {
34
+ let res$1 = input;
35
+ for (let i = 0; i < rounds; i++) res$1 = createHash(alg).update(res$1).digest();
36
+ return res$1;
37
+ }
38
+ let res = input;
39
+ for (let i = 0; i < rounds; i++) res = hasher(res);
40
+ return res;
32
41
  };
33
42
  this[name] = (data, round = 1, encoding = "hex") => {
34
43
  let input;
35
- try {
44
+ if (data instanceof Uint8Array) input = data;
45
+ else try {
36
46
  input = toUint8Array(data);
37
47
  } catch (_err) {
38
48
  input = data;
39
49
  }
40
- return encode(`0x${bytesToHex(hashFn(input, round))}`, encoding);
50
+ const res = hashBytes(input, round);
51
+ const isBuf = typeof Buffer !== "undefined" && Buffer.isBuffer(res);
52
+ if (encoding === "hex" || encoding === "base16") return isBuf ? `0x${res.toString("hex")}` : `0x${bytesToHex(res)}`;
53
+ if (encoding === "buffer" && typeof Buffer !== "undefined") return isBuf ? res : Buffer.from(res.buffer, res.byteOffset, res.byteLength);
54
+ if (encoding === "Uint8Array") return isBuf ? new Uint8Array(res) : res;
55
+ return encode(res, encoding);
41
56
  };
42
57
  });
43
58
  }
package/esm/index.d.mts CHANGED
@@ -10,7 +10,7 @@ import { BytesType, EncodingType, KeyPairType } from "@ocap/util";
10
10
  import { LiteralUnion } from "type-fest";
11
11
 
12
12
  //#region src/index.d.ts
13
- type KeyType = LiteralUnion<'ED25519' | 'SECP256K1' | 'ETHEREUM', string>;
13
+ type KeyType = LiteralUnion<'ED25519' | 'SECP256K1' | 'ETHEREUM' | 'PASSKEY', string>;
14
14
  type HashType = LiteralUnion<'KECCAK' | 'SHA3' | 'KECCAK_384' | 'SHA3_384' | 'KECCAK_512' | 'SHA3_512' | 'SHA2', string>;
15
15
  type RoleType = LiteralUnion<'ROLE_ACCOUNT' | 'ROLE_NODE' | 'ROLE_DEVICE' | 'ROLE_APPLICATION' | 'ROLE_SMART_CONTRACT' | 'ROLE_BOT' | 'ROLE_ASSET' | 'ROLE_STAKE' | 'ROLE_VALIDATOR' | 'ROLE_GROUP' | 'ROLE_TX' | 'ROLE_TETHER' | 'ROLE_SWAP' | 'ROLE_DELEGATION' | 'ROLE_VC' | 'ROLE_BLOCKLET' | 'ROLE_STORE' | 'ROLE_TOKEN' | 'ROLE_FACTORY' | 'ROLE_ROLLUP' | 'ROLE_STORAGE' | 'ROLE_PROFILE' | 'ROLE_PASSKEY' | 'ROLE_TOKEN_FACTORY' | 'ROLE_PROVIDER' | 'ROLE_ANY', string>;
16
16
  type AddressType = LiteralUnion<'BASE16' | 'BASE58', string>;
@@ -4,7 +4,7 @@ import { BytesType, EncodingType, KeyPairType } from "@ocap/util";
4
4
  //#region src/signer/ed25519.d.ts
5
5
 
6
6
  /**
7
- * Signer implementation for ed25519, based on `@noble/ed25519`
7
+ * Signer implementation for ed25519, using native `node:crypto` with `@noble/ed25519` fallback
8
8
  *
9
9
  * @class Ed25519Signer
10
10
  */
@@ -2,13 +2,120 @@ import { encode } from "../encode.mjs";
2
2
  import signer_default from "../protocols/signer.mjs";
3
3
  import { toUint8Array } from "@ocap/util";
4
4
  import randomBytes from "randombytes";
5
+ import { bytesToHex } from "@noble/hashes/utils.js";
5
6
  import { sha512 } from "@noble/hashes/sha2.js";
6
7
  import * as ed from "@noble/ed25519";
7
8
 
8
9
  //#region src/signer/ed25519.ts
9
- ed.hashes.sha512 = (msg) => sha512(msg);
10
+ const nodeCrypto = typeof process !== "undefined" ? process.getBuiltinModule?.("node:crypto") : void 0;
11
+ ed.hashes.sha512 = nodeCrypto?.createHash ? (msg) => new Uint8Array(nodeCrypto.createHash("sha512").update(msg).digest()) : (msg) => sha512(msg);
12
+ const ED25519_PKCS8_PREFIX = new Uint8Array([
13
+ 48,
14
+ 46,
15
+ 2,
16
+ 1,
17
+ 0,
18
+ 48,
19
+ 5,
20
+ 6,
21
+ 3,
22
+ 43,
23
+ 101,
24
+ 112,
25
+ 4,
26
+ 34,
27
+ 4,
28
+ 32
29
+ ]);
30
+ const ED25519_SPKI_PREFIX = new Uint8Array([
31
+ 48,
32
+ 42,
33
+ 48,
34
+ 5,
35
+ 6,
36
+ 3,
37
+ 43,
38
+ 101,
39
+ 112,
40
+ 3,
41
+ 33,
42
+ 0
43
+ ]);
44
+ const MAX_KEY_CACHE_SIZE = 512;
45
+ const privateKeyCache = /* @__PURE__ */ new Map();
46
+ const publicKeyCache = /* @__PURE__ */ new Map();
47
+ function getNativePrivateKeyEntry(seed) {
48
+ if (typeof Buffer === "undefined" || !nodeCrypto?.createPrivateKey || !nodeCrypto?.createPublicKey || seed.byteLength !== 32) return null;
49
+ const cacheKey = Buffer.isBuffer(seed) ? seed.toString("hex") : bytesToHex(seed);
50
+ const cached = privateKeyCache.get(cacheKey);
51
+ if (cached) {
52
+ privateKeyCache.delete(cacheKey);
53
+ privateKeyCache.set(cacheKey, cached);
54
+ return cached;
55
+ }
56
+ try {
57
+ const der = Buffer.allocUnsafe(48);
58
+ der.set(ED25519_PKCS8_PREFIX, 0);
59
+ der.set(seed, 16);
60
+ const keyObject = nodeCrypto.createPrivateKey({
61
+ key: der,
62
+ format: "der",
63
+ type: "pkcs8"
64
+ });
65
+ const spki = nodeCrypto.createPublicKey(keyObject).export({
66
+ format: "der",
67
+ type: "spki"
68
+ });
69
+ const entry = {
70
+ keyObject,
71
+ publicKey: new Uint8Array(spki.buffer, spki.byteOffset + spki.byteLength - 32, 32).slice()
72
+ };
73
+ if (privateKeyCache.size >= MAX_KEY_CACHE_SIZE) {
74
+ const oldestKey = privateKeyCache.keys().next().value;
75
+ if (oldestKey !== void 0) privateKeyCache.delete(oldestKey);
76
+ }
77
+ privateKeyCache.set(cacheKey, entry);
78
+ return entry;
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+ function getNativePublicKeyObject(pkBytes) {
84
+ if (typeof Buffer === "undefined" || !nodeCrypto?.createPublicKey || pkBytes.byteLength !== 32) return null;
85
+ const cacheKey = Buffer.isBuffer(pkBytes) ? pkBytes.toString("hex") : bytesToHex(pkBytes);
86
+ const cached = publicKeyCache.get(cacheKey);
87
+ if (cached) {
88
+ publicKeyCache.delete(cacheKey);
89
+ publicKeyCache.set(cacheKey, cached);
90
+ return cached;
91
+ }
92
+ try {
93
+ const der = Buffer.allocUnsafe(44);
94
+ der.set(ED25519_SPKI_PREFIX, 0);
95
+ der.set(pkBytes, 12);
96
+ const keyObject = nodeCrypto.createPublicKey({
97
+ key: der,
98
+ format: "der",
99
+ type: "spki"
100
+ });
101
+ if (publicKeyCache.size >= MAX_KEY_CACHE_SIZE) {
102
+ const oldestKey = publicKeyCache.keys().next().value;
103
+ if (oldestKey !== void 0) publicKeyCache.delete(oldestKey);
104
+ }
105
+ publicKeyCache.set(cacheKey, keyObject);
106
+ return keyObject;
107
+ } catch {
108
+ return null;
109
+ }
110
+ }
111
+ const toBytes = (data) => data instanceof Uint8Array ? data : toUint8Array(data);
112
+ function derivePublicKeyBytes(seed) {
113
+ const nativeEntry = getNativePrivateKeyEntry(seed);
114
+ if (nativeEntry) return nativeEntry.publicKey;
115
+ return ed.getPublicKey(seed);
116
+ }
10
117
  /**
11
- * Signer implementation for ed25519, based on `@noble/ed25519`
118
+ * Signer implementation for ed25519, using native `node:crypto` with `@noble/ed25519` fallback
12
119
  *
13
120
  * @class Ed25519Signer
14
121
  */
@@ -29,9 +136,9 @@ var Ed25519Signer = class extends signer_default {
29
136
  * @memberof Ed25519Signer
30
137
  */
31
138
  genKeyPair(encoding = "hex", userSeed) {
32
- const seed = userSeed ? toUint8Array(userSeed) : new Uint8Array(randomBytes(32));
139
+ const seed = userSeed ? toBytes(userSeed) : new Uint8Array(randomBytes(32));
33
140
  if (seed.byteLength !== 32) throw new Error("Invalid seed to generate key pair");
34
- const publicKey = ed.getPublicKey(seed);
141
+ const publicKey = derivePublicKeyBytes(seed);
35
142
  const secretKey = new Uint8Array(64);
36
143
  secretKey.set(seed);
37
144
  secretKey.set(publicKey, 32);
@@ -50,11 +157,10 @@ var Ed25519Signer = class extends signer_default {
50
157
  * @throws {Error} if the key is not 64 bytes
51
158
  */
52
159
  validateKeyPair(sk) {
53
- const skBytes = toUint8Array(sk);
160
+ const skBytes = toBytes(sk);
54
161
  if (skBytes.byteLength !== 64) throw new Error("validateKeyPair requires a 64-byte key");
55
- const seed = skBytes.slice(0, 32);
56
- const derivedPk = ed.getPublicKey(seed);
57
- const embeddedPk = skBytes.slice(32, 64);
162
+ const derivedPk = derivePublicKeyBytes(skBytes.subarray(0, 32));
163
+ const embeddedPk = skBytes.subarray(32, 64);
58
164
  return derivedPk.length === embeddedPk.length && derivedPk.every((b, i) => b === embeddedPk[i]);
59
165
  }
60
166
  /**
@@ -64,9 +170,9 @@ var Ed25519Signer = class extends signer_default {
64
170
  * @returns {string} hex encoded publicKey
65
171
  */
66
172
  getPublicKey(sk, encoding = "hex") {
67
- const skBytes = toUint8Array(sk);
173
+ const skBytes = toBytes(sk);
68
174
  if (skBytes.byteLength === 64) return encode(skBytes.slice(32, 64), encoding);
69
- return encode(ed.getPublicKey(skBytes), encoding);
175
+ return encode(derivePublicKeyBytes(skBytes), encoding);
70
176
  }
71
177
  /**
72
178
  * Sign a message and get the signature hex
@@ -76,8 +182,18 @@ var Ed25519Signer = class extends signer_default {
76
182
  * @returns {string} hex encoded signature
77
183
  */
78
184
  sign(message, sk, encoding = "hex") {
79
- const seed = toUint8Array(sk).slice(0, 32);
80
- const messageBytes = toUint8Array(message);
185
+ const seed = toBytes(sk).subarray(0, 32);
186
+ const messageBytes = toBytes(message);
187
+ if (nodeCrypto?.sign && seed.byteLength === 32) {
188
+ const entry = getNativePrivateKeyEntry(seed);
189
+ if (entry) {
190
+ const sigBuf = nodeCrypto.sign(null, messageBytes, entry.keyObject);
191
+ if (encoding === "hex" || encoding === "base16") return `0x${sigBuf.toString("hex")}`;
192
+ if (encoding === "buffer") return sigBuf;
193
+ if (encoding === "Uint8Array") return new Uint8Array(sigBuf);
194
+ return encode(sigBuf, encoding);
195
+ }
196
+ }
81
197
  return encode(ed.sign(messageBytes, seed), encoding);
82
198
  }
83
199
  /**
@@ -89,10 +205,21 @@ var Ed25519Signer = class extends signer_default {
89
205
  * @returns {bool}
90
206
  */
91
207
  verify(message, signature, pk) {
92
- const pkBytes = toUint8Array(pk);
93
- const messageBytes = toUint8Array(message);
94
- const signatureBytes = toUint8Array(signature);
95
- return ed.verify(signatureBytes, messageBytes, pkBytes);
208
+ const pkBytes = toBytes(pk);
209
+ const messageBytes = toBytes(message);
210
+ const signatureBytes = toBytes(signature);
211
+ if (pkBytes.byteLength !== 32 || signatureBytes.byteLength !== 64) return false;
212
+ if (nodeCrypto?.verify) {
213
+ const pubKeyObject = getNativePublicKeyObject(pkBytes);
214
+ if (pubKeyObject) try {
215
+ if (nodeCrypto.verify(null, messageBytes, pubKeyObject, signatureBytes)) return true;
216
+ } catch {}
217
+ }
218
+ try {
219
+ return ed.verify(signatureBytes, messageBytes, pkBytes);
220
+ } catch {
221
+ return false;
222
+ }
96
223
  }
97
224
  };
98
225
  var ed25519_default = new Ed25519Signer();
@@ -40,11 +40,15 @@ var EthereumSigner = class extends Secp256k1Signer {
40
40
  return `0x${sig.toHex("compact")}${v}`;
41
41
  }
42
42
  ethRecover(data, signature) {
43
- const sigHex = signature.slice(2);
43
+ if (typeof data !== "string" || typeof signature !== "string") throw new Error("Invalid ethereum signature or data");
44
+ const sigHex = signature.replace(/^0x/i, "");
45
+ if (sigHex.length !== 130) throw new Error("Invalid ethereum signature length");
44
46
  const v = Number.parseInt(sigHex.slice(128, 130), 16);
45
- const recovery = v < 2 ? v : 1 - v % 2;
47
+ if (v !== 0 && v !== 1 && v !== 27 && v !== 28) throw new Error("Invalid ethereum signature recovery parameter");
48
+ const recovery = v < 2 ? v : v - 27;
46
49
  const sig = secp256k1.Signature.fromHex(sigHex.slice(0, 128), "compact").addRecoveryBit(recovery);
47
- const msgHash = new Uint8Array(Buffer.from(data.slice(2), "hex"));
50
+ if (sig.hasHighS()) throw new Error("Invalid ethereum high-S signature");
51
+ const msgHash = new Uint8Array(Buffer.from(data.replace(/^0x/i, ""), "hex"));
48
52
  const pubKeyHex = sig.recoverPublicKey(msgHash).toHex(false).slice(2);
49
53
  return toChecksumAddress(`0x${bytesToHex(keccak_256(Buffer.from(pubKeyHex, "hex"))).slice(-40)}`);
50
54
  }
@@ -67,9 +67,9 @@ var Secp256k1Signer = class extends signer_default {
67
67
  */
68
68
  verify(message, signature, pk) {
69
69
  const msg = toUint8Array(message);
70
- const sigHex = toHex(signature).replace(/^0x/i, "");
70
+ const sigHex = toHex(toUint8Array(signature)).replace(/^0x/i, "");
71
71
  let pkBytes = toUint8Array(pk);
72
- if (this.pkHasFormatPrefix === false && pkBytes[0] !== 4 && pkBytes.byteLength === 64) {
72
+ if (this.pkHasFormatPrefix === false && pkBytes.byteLength === 64) {
73
73
  const prefixed = new Uint8Array(65);
74
74
  prefixed[0] = 4;
75
75
  prefixed.set(pkBytes, 1);
@@ -77,6 +77,7 @@ var Secp256k1Signer = class extends signer_default {
77
77
  }
78
78
  try {
79
79
  const sigBytes = secp256k1.Signature.fromHex(sigHex, "der").toBytes("der");
80
+ if (bytesToHex(sigBytes) !== sigHex.toLowerCase()) return false;
80
81
  return secp256k1.verify(sigBytes, msg, pkBytes, {
81
82
  prehash: false,
82
83
  format: "der",