@ocap/mpc-hsm 0.0.0-stage → 1.33.7

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 (74) hide show
  1. package/esm/bip39-english-wordlist.d.mts +11 -0
  2. package/esm/bip39-english-wordlist.mjs +31 -0
  3. package/esm/constants.d.mts +140 -0
  4. package/esm/constants.mjs +142 -0
  5. package/esm/dkg.d.mts +279 -0
  6. package/esm/dkg.mjs +903 -0
  7. package/esm/index.d.mts +17 -0
  8. package/esm/index.mjs +18 -0
  9. package/esm/mta.d.mts +63 -0
  10. package/esm/mta.mjs +275 -0
  11. package/esm/ocap-clear-signing.d.mts +125 -0
  12. package/esm/ocap-clear-signing.mjs +1170 -0
  13. package/esm/offline-ceremony.d.mts +127 -0
  14. package/esm/offline-ceremony.mjs +481 -0
  15. package/esm/ot.d.mts +193 -0
  16. package/esm/ot.mjs +726 -0
  17. package/esm/personal-vault.d.mts +1292 -0
  18. package/esm/personal-vault.mjs +3615 -0
  19. package/esm/personal.d.mts +10 -0
  20. package/esm/personal.mjs +11 -0
  21. package/esm/presign.d.mts +242 -0
  22. package/esm/presign.mjs +951 -0
  23. package/esm/rlp-eip1559.d.mts +75 -0
  24. package/esm/rlp-eip1559.mjs +293 -0
  25. package/esm/secp256k1-scalar.d.mts +141 -0
  26. package/esm/secp256k1-scalar.mjs +474 -0
  27. package/esm/sign.d.mts +113 -0
  28. package/esm/sign.mjs +225 -0
  29. package/esm/steel-mnemonic.d.mts +55 -0
  30. package/esm/steel-mnemonic.mjs +247 -0
  31. package/esm/tweak.d.mts +100 -0
  32. package/esm/tweak.mjs +168 -0
  33. package/esm/ves-backup.d.mts +296 -0
  34. package/esm/ves-backup.mjs +1025 -0
  35. package/esm/x402-agent-guard.d.mts +111 -0
  36. package/esm/x402-agent-guard.mjs +780 -0
  37. package/lib/bip39-english-wordlist.cjs +33 -0
  38. package/lib/bip39-english-wordlist.d.cts +11 -0
  39. package/lib/constants.cjs +264 -0
  40. package/lib/constants.d.cts +140 -0
  41. package/lib/dkg.cjs +910 -0
  42. package/lib/dkg.d.cts +279 -0
  43. package/lib/index.cjs +420 -0
  44. package/lib/index.d.cts +17 -0
  45. package/lib/mta.cjs +280 -0
  46. package/lib/mta.d.cts +63 -0
  47. package/lib/ocap-clear-signing.cjs +1176 -0
  48. package/lib/ocap-clear-signing.d.cts +125 -0
  49. package/lib/offline-ceremony.cjs +487 -0
  50. package/lib/offline-ceremony.d.cts +127 -0
  51. package/lib/ot.cjs +744 -0
  52. package/lib/ot.d.cts +193 -0
  53. package/lib/personal-vault.cjs +3725 -0
  54. package/lib/personal-vault.d.cts +1292 -0
  55. package/lib/personal.cjs +338 -0
  56. package/lib/personal.d.cts +10 -0
  57. package/lib/presign.cjs +954 -0
  58. package/lib/presign.d.cts +242 -0
  59. package/lib/rlp-eip1559.cjs +303 -0
  60. package/lib/rlp-eip1559.d.cts +75 -0
  61. package/lib/secp256k1-scalar.cjs +527 -0
  62. package/lib/secp256k1-scalar.d.cts +141 -0
  63. package/lib/sign.cjs +233 -0
  64. package/lib/sign.d.cts +113 -0
  65. package/lib/steel-mnemonic.cjs +253 -0
  66. package/lib/steel-mnemonic.d.cts +55 -0
  67. package/lib/tweak.cjs +178 -0
  68. package/lib/tweak.d.cts +100 -0
  69. package/lib/ves-backup.cjs +1053 -0
  70. package/lib/ves-backup.d.cts +296 -0
  71. package/lib/x402-agent-guard.cjs +788 -0
  72. package/lib/x402-agent-guard.d.cts +111 -0
  73. package/package.json +80 -4
  74. package/README.md +0 -3
@@ -0,0 +1,3725 @@
1
+ const require_constants = require('./constants.cjs');
2
+ const require_secp256k1_scalar = require('./secp256k1-scalar.cjs');
3
+ const require_tweak = require('./tweak.cjs');
4
+ const require_ot = require('./ot.cjs');
5
+ const require_presign = require('./presign.cjs');
6
+ const require_sign = require('./sign.cjs');
7
+ const require_steel_mnemonic = require('./steel-mnemonic.cjs');
8
+ const require_rlp_eip1559 = require('./rlp-eip1559.cjs');
9
+ let _noble_hashes_sha2_js = require("@noble/hashes/sha2.js");
10
+ let _noble_curves_ed25519_js = require("@noble/curves/ed25519.js");
11
+ let _noble_hashes_sha3_js = require("@noble/hashes/sha3.js");
12
+ let _noble_hashes_hkdf_js = require("@noble/hashes/hkdf.js");
13
+ let _noble_hashes_hmac_js = require("@noble/hashes/hmac.js");
14
+ let _noble_hashes_pbkdf2_js = require("@noble/hashes/pbkdf2.js");
15
+ let _noble_curves_nist_js = require("@noble/curves/nist.js");
16
+ let _noble_hashes_scrypt_js = require("@noble/hashes/scrypt.js");
17
+ let _noble_hashes_utils_js = require("@noble/hashes/utils.js");
18
+ let _noble_curves_secp256k1_js = require("@noble/curves/secp256k1.js");
19
+
20
+ //#region src/personal-vault.ts
21
+ const textDecoder = new TextDecoder("utf-8", { fatal: true });
22
+ function utf8DecodeStrict(bytes, errorCode = "INVALID_PARAMETER") {
23
+ try {
24
+ return textDecoder.decode(bytes);
25
+ } catch {
26
+ throw new require_constants.MpcProtocolError(errorCode, "Invalid UTF-8 byte sequence");
27
+ }
28
+ }
29
+ const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
30
+ const BASE64URL_LOOKUP = (() => {
31
+ const table = new Int16Array(128).fill(-1);
32
+ for (let i = 0; i < 64; i++) table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
33
+ return table;
34
+ })();
35
+ function base64UrlEncodeBytes(bytes) {
36
+ let out = "";
37
+ let i = 0;
38
+ for (; i + 2 < bytes.length; i += 3) {
39
+ const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
40
+ out += BASE64URL_ALPHABET[n >>> 18 & 63] + BASE64URL_ALPHABET[n >>> 12 & 63] + BASE64URL_ALPHABET[n >>> 6 & 63] + BASE64URL_ALPHABET[n & 63];
41
+ }
42
+ const rem = bytes.length - i;
43
+ if (rem === 1) {
44
+ const n = bytes[i] << 4;
45
+ out += BASE64URL_ALPHABET[n >>> 6 & 63] + BASE64URL_ALPHABET[n & 63];
46
+ } else if (rem === 2) {
47
+ const n = bytes[i] << 10 | bytes[i + 1] << 2;
48
+ out += BASE64URL_ALPHABET[n >>> 12 & 63] + BASE64URL_ALPHABET[n >>> 6 & 63] + BASE64URL_ALPHABET[n & 63];
49
+ }
50
+ return out;
51
+ }
52
+ function base64UrlDecodeBytes(encoded, errorCode = "PERSONAL_ACTOR_SIGNATURE_INVALID") {
53
+ if (typeof encoded !== "string") throw new require_constants.MpcProtocolError(errorCode, "Expected base64url string");
54
+ const len = encoded.length;
55
+ if (len % 4 === 1) throw new require_constants.MpcProtocolError(errorCode, "Invalid base64url length");
56
+ const vals = new Uint8Array(len);
57
+ for (let i$1 = 0; i$1 < len; i$1++) {
58
+ const code = encoded.charCodeAt(i$1);
59
+ if (code >= 128 || BASE64URL_LOOKUP[code] < 0) throw new require_constants.MpcProtocolError(errorCode, "Invalid character in base64url string");
60
+ vals[i$1] = BASE64URL_LOOKUP[code];
61
+ }
62
+ const rem = len % 4;
63
+ if (rem === 2 && (vals[len - 1] & 15) !== 0) throw new require_constants.MpcProtocolError(errorCode, "Non-canonical trailing bits in base64url string");
64
+ if (rem === 3 && (vals[len - 1] & 3) !== 0) throw new require_constants.MpcProtocolError(errorCode, "Non-canonical trailing bits in base64url string");
65
+ const outLen = Math.floor(len * 3 / 4);
66
+ const out = new Uint8Array(outLen);
67
+ let outIdx = 0;
68
+ let i = 0;
69
+ for (; i + 3 < len; i += 4) {
70
+ const n = vals[i] << 18 | vals[i + 1] << 12 | vals[i + 2] << 6 | vals[i + 3];
71
+ out[outIdx++] = n >>> 16 & 255;
72
+ out[outIdx++] = n >>> 8 & 255;
73
+ out[outIdx++] = n & 255;
74
+ }
75
+ if (rem === 2) out[outIdx++] = (vals[i] << 2 | vals[i + 1] >>> 4) & 255;
76
+ else if (rem === 3) {
77
+ const n = vals[i] << 10 | vals[i + 1] << 4 | vals[i + 2] >>> 2;
78
+ out[outIdx++] = n >>> 8 & 255;
79
+ out[outIdx++] = n & 255;
80
+ }
81
+ return out;
82
+ }
83
+ function toArrayBuffer(bytes) {
84
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
85
+ }
86
+ function getSubtleCrypto() {
87
+ const subtle = globalThis.crypto?.subtle;
88
+ if (!subtle) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "WebCrypto SubtleCrypto is unavailable");
89
+ return subtle;
90
+ }
91
+ async function aes256GcmEncryptDetached(params) {
92
+ const { key32, iv12, plaintext, aad } = params;
93
+ if (!(key32 instanceof Uint8Array) || key32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "AES-256-GCM key32 must be 32 bytes");
94
+ if (!(iv12 instanceof Uint8Array) || iv12.length !== 12) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "AES-256-GCM iv12 must be 12 bytes");
95
+ const subtle = getSubtleCrypto();
96
+ const cryptoKey = await subtle.importKey("raw", toArrayBuffer(key32), { name: "AES-GCM" }, false, ["encrypt"]);
97
+ const combinedBuf = await subtle.encrypt({
98
+ name: "AES-GCM",
99
+ iv: toArrayBuffer(iv12),
100
+ additionalData: toArrayBuffer(aad),
101
+ tagLength: 128
102
+ }, cryptoKey, toArrayBuffer(plaintext));
103
+ const combined = new Uint8Array(combinedBuf);
104
+ return {
105
+ ciphertext: combined.slice(0, plaintext.length),
106
+ tag16: combined.slice(plaintext.length, plaintext.length + 16)
107
+ };
108
+ }
109
+ async function aes256GcmDecryptDetached(params) {
110
+ const { key32, iv12, ciphertext, tag16, aad, authFailureCode = "PERSONAL_ENVELOPE_AUTH_FAILED" } = params;
111
+ if (!(key32 instanceof Uint8Array) || key32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "AES-256-GCM key32 must be 32 bytes");
112
+ if (!(iv12 instanceof Uint8Array) || iv12.length !== 12 || !(tag16 instanceof Uint8Array) || tag16.length !== 16) throw new require_constants.MpcProtocolError(authFailureCode, "Invalid AES-256-GCM IV or authentication tag length");
113
+ const subtle = getSubtleCrypto();
114
+ const cryptoKey = await subtle.importKey("raw", toArrayBuffer(key32), { name: "AES-GCM" }, false, ["decrypt"]);
115
+ const combined = require_secp256k1_scalar.concatBytes(ciphertext, tag16);
116
+ try {
117
+ const plainBuf = await subtle.decrypt({
118
+ name: "AES-GCM",
119
+ iv: toArrayBuffer(iv12),
120
+ additionalData: toArrayBuffer(aad),
121
+ tagLength: 128
122
+ }, cryptoKey, toArrayBuffer(combined));
123
+ return new Uint8Array(plainBuf);
124
+ } catch {
125
+ throw new require_constants.MpcProtocolError(authFailureCode, "AES-256-GCM authentication failed");
126
+ } finally {
127
+ require_secp256k1_scalar.zeroizeBytes(combined);
128
+ }
129
+ }
130
+ function readU16BE(bytes, offset) {
131
+ return (bytes[offset] << 8 | bytes[offset + 1]) >>> 0;
132
+ }
133
+ function readU64BE(bytes, offset) {
134
+ let acc = 0n;
135
+ for (let i = 0; i < 8; i++) acc = acc << 8n | BigInt(bytes[offset + i]);
136
+ return acc;
137
+ }
138
+ const MAX_UINT64 = (1n << 64n) - 1n;
139
+ const MAX_UINT128 = (1n << 128n) - 1n;
140
+ const MAX_UINT256 = (1n << 256n) - 1n;
141
+ const PERSONAL_MAX_VELOCITY_UINT128 = MAX_UINT128;
142
+ const UNLIMITED_APPROVE_THRESHOLD = 1n << 255n;
143
+ function assertPrintableIdentifierAscii(id, maxBytes, label, errorCode = "PERSONAL_BLOB_MALFORMED") {
144
+ if (typeof id !== "string" || id.length === 0 || id.length > maxBytes) throw new require_constants.MpcProtocolError(errorCode, `${label} must be 1..${maxBytes} printable ASCII characters`);
145
+ for (let i = 0; i < id.length; i++) {
146
+ const code = id.charCodeAt(i);
147
+ if (code < 33 || code > 126) throw new require_constants.MpcProtocolError(errorCode, `${label} contains non-printable or whitespace ASCII character`);
148
+ }
149
+ return require_secp256k1_scalar.utf8Bytes(id);
150
+ }
151
+ function decodeZeroPaddedIdentifierAscii(blob, lenOffset, maxLen, label) {
152
+ const declaredLen = blob[lenOffset];
153
+ if (declaredLen < 1 || declaredLen > maxLen) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Invalid ${label} length ${declaredLen} in blob header`);
154
+ const fieldStart = lenOffset + 1;
155
+ const fieldEnd = fieldStart + maxLen;
156
+ for (let i = fieldStart; i < fieldStart + declaredLen; i++) {
157
+ const b = blob[i];
158
+ if (b < 33 || b > 126) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Invalid ASCII byte 0x${b.toString(16)} in ${label}`);
159
+ }
160
+ for (let i = fieldStart + declaredLen; i < fieldEnd; i++) if (blob[i] !== 0) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Non-zero trailing padding in ${label}`);
161
+ return utf8DecodeStrict(blob.subarray(fieldStart, fieldStart + declaredLen), "PERSONAL_BLOB_MALFORMED");
162
+ }
163
+ const ACTOR_KIND_AND_ALG_BYTE = {
164
+ "human-p256": 1,
165
+ "agent-ed25519": 2,
166
+ "agent-p256": 3
167
+ };
168
+ const HSM_SEALED_BLOB_VERSION = 1;
169
+ const HSM_SEALED_BLOB_HEADER_BYTES = 319;
170
+ const HSM_SEALED_BLOB_HEADER_MAC_OFFSET = 319;
171
+ const HSM_SEALED_BLOB_HEADER_WITH_MAC_BYTES = 351;
172
+ const HSM_SEALED_BLOB_IV_OFFSET = 351;
173
+ const HSM_SEALED_BLOB_TAG_OFFSET = 363;
174
+ const HSM_SEALED_BLOB_CIPHERTEXT_OFFSET = 379;
175
+ const HSM_SEALED_BLOB_CIPHERTEXT_BYTES = 3717;
176
+ const HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES = 3642;
177
+ const HSM_BLOB_MAGIC_BYTES_8 = require_secp256k1_scalar.utf8Bytes(require_constants.DST_PERSONAL_BLOB_MAGIC);
178
+ function actorKindAndAlgToByte(kind) {
179
+ const b = ACTOR_KIND_AND_ALG_BYTE[kind];
180
+ if (b === void 0) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Unsupported actorKindAndAlg: ${String(kind)}`);
181
+ return b;
182
+ }
183
+ function byteToActorKindAndAlg(byte) {
184
+ if (byte === 1) return "human-p256";
185
+ if (byte === 2) return "agent-ed25519";
186
+ if (byte === 3) return "agent-p256";
187
+ throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Unknown actorKindAndAlg byte: 0x${byte.toString(16)}`);
188
+ }
189
+ function isAgentActorKind(kind) {
190
+ return kind === "agent-ed25519" || kind === "agent-p256";
191
+ }
192
+ function validateEd25519PublicKeyNonTorsion32(pubKey32, errorCode = "PERSONAL_BLOB_MALFORMED") {
193
+ if (!(pubKey32 instanceof Uint8Array) || pubKey32.length !== 32) throw new require_constants.MpcProtocolError(errorCode, "Ed25519 public key must be 32 bytes");
194
+ let pt;
195
+ try {
196
+ pt = _noble_curves_ed25519_js.ed25519.Point.fromBytes(pubKey32, false);
197
+ pt.assertValidity();
198
+ } catch {
199
+ throw new require_constants.MpcProtocolError(errorCode, "Invalid Ed25519 public key encoding");
200
+ }
201
+ if (pt.is0() || pt.clearCofactor().is0()) throw new require_constants.MpcProtocolError(errorCode, "Low-order torsion or identity Ed25519 public key rejected");
202
+ }
203
+ function validateP256UncompressedPublicKey65(pubKey65, errorCode = "PERSONAL_BLOB_MALFORMED") {
204
+ if (!(pubKey65 instanceof Uint8Array) || pubKey65.length !== 65 || pubKey65[0] !== 4) throw new require_constants.MpcProtocolError(errorCode, "Expected 65-byte uncompressed (0x04) P-256 public key");
205
+ try {
206
+ const pt = _noble_curves_nist_js.p256.Point.fromBytes(pubKey65);
207
+ pt.assertValidity();
208
+ if (pt.is0()) throw new Error("P-256 infinity");
209
+ } catch {
210
+ throw new require_constants.MpcProtocolError(errorCode, "Invalid off-curve P-256 public key");
211
+ }
212
+ }
213
+ /**
214
+ * Normalizes an actor public key (`33B` compressed or `65B` uncompressed P-256 for `0x01`/`0x03`,
215
+ * or `32B` Ed25519 / `65B` zero-padded Ed25519 for `0x02`) into canonical `65`-byte padded format.
216
+ */
217
+ function normalizeActorPublicKeyToPadded65(actorKindAndAlg, pubKeyInput, errorCode = "PERSONAL_BLOB_MALFORMED") {
218
+ actorKindAndAlgToByte(actorKindAndAlg);
219
+ const raw = require_secp256k1_scalar.normalizeHexBytes(pubKeyInput);
220
+ if (actorKindAndAlg === "human-p256" || actorKindAndAlg === "agent-p256") {
221
+ if (raw.length !== 33 && raw.length !== 65) throw new require_constants.MpcProtocolError(errorCode, "P-256 public key must be 33 (compressed) or 65 (uncompressed) bytes");
222
+ try {
223
+ const pt = _noble_curves_nist_js.p256.Point.fromBytes(raw);
224
+ pt.assertValidity();
225
+ if (pt.is0()) throw new Error("P-256 infinity");
226
+ return pt.toBytes(false);
227
+ } catch {
228
+ throw new require_constants.MpcProtocolError(errorCode, "Invalid P-256 actor public key");
229
+ }
230
+ }
231
+ if (raw.length === 32) {
232
+ validateEd25519PublicKeyNonTorsion32(raw, errorCode);
233
+ const out = new Uint8Array(65);
234
+ out.set(raw, 0);
235
+ return out;
236
+ }
237
+ if (raw.length === 65) {
238
+ for (let i = 32; i < 65; i++) if (raw[i] !== 0) throw new require_constants.MpcProtocolError(errorCode, "Non-zero trailing padding in 65-byte Ed25519 actor public key");
239
+ validateEd25519PublicKeyNonTorsion32(raw.subarray(0, 32), errorCode);
240
+ return new Uint8Array(raw);
241
+ }
242
+ throw new require_constants.MpcProtocolError(errorCode, "Ed25519 public key must be 32 bytes (or 65 zero-padded bytes)");
243
+ }
244
+ function validateActorPublicKeyPadded65(actorKindAndAlg, actorPubKeyPadded65, errorCode = "PERSONAL_BLOB_MALFORMED") {
245
+ if (!(actorPubKeyPadded65 instanceof Uint8Array) || actorPubKeyPadded65.length !== 65) throw new require_constants.MpcProtocolError(errorCode, "actorPubKeyPadded65 must be exactly 65 bytes");
246
+ if (actorKindAndAlg === "human-p256" || actorKindAndAlg === "agent-p256") {
247
+ validateP256UncompressedPublicKey65(actorPubKeyPadded65, errorCode);
248
+ return;
249
+ }
250
+ for (let i = 32; i < 65; i++) if (actorPubKeyPadded65[i] !== 0) throw new require_constants.MpcProtocolError(errorCode, "Non-zero trailing padding in Ed25519 actorPubKeyPadded65[32..64]");
251
+ validateEd25519PublicKeyNonTorsion32(actorPubKeyPadded65.subarray(0, 32), errorCode);
252
+ }
253
+ function canonicalizePersonalBlobAadBytes(aad) {
254
+ if (aad === void 0) return require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_BLOB_AAD_V1, [require_secp256k1_scalar.u8(0)]);
255
+ if (aad instanceof Uint8Array) return require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_BLOB_AAD_V1, [require_secp256k1_scalar.u8(1), aad]);
256
+ if (typeof aad === "string") return require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_BLOB_AAD_V1, [require_secp256k1_scalar.u8(2), require_secp256k1_scalar.utf8Bytes(aad)]);
257
+ if (typeof aad === "object" && aad !== null && !Array.isArray(aad)) {
258
+ const sortedKeys = Object.keys(aad).sort();
259
+ const parts = [require_secp256k1_scalar.u8(3), require_secp256k1_scalar.u32be(sortedKeys.length)];
260
+ for (const k of sortedKeys) {
261
+ const val = aad[k];
262
+ if (typeof val !== "string") throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `AAD map key "${k}" must have a string value`);
263
+ parts.push(require_secp256k1_scalar.utf8Bytes(k), require_secp256k1_scalar.utf8Bytes(val));
264
+ }
265
+ return require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_BLOB_AAD_V1, parts);
266
+ }
267
+ throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Unsupported PersonalBlobAadInput type");
268
+ }
269
+ /**
270
+ * Encodes the canonical `319`-byte `HsmSealedBlob` header (`[0..318]`, `design.md` §4.1).
271
+ */
272
+ function encodeHsmSealedBlobHeader319(params) {
273
+ const kidBytes = assertPrintableIdentifierAscii(params.kid, 32, "kid");
274
+ const vaultIdBytes = assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId");
275
+ const slotIdBytes = assertPrintableIdentifierAscii(params.slotId, 64, "slotId");
276
+ let pRootComp33;
277
+ try {
278
+ pRootComp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.rootPublicKeyComp33, 33), false));
279
+ } catch {
280
+ throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Invalid secp256k1 rootPublicKeyComp33 in header");
281
+ }
282
+ if (typeof params.policyEpoch !== "bigint" || params.policyEpoch < 1n || params.policyEpoch > MAX_UINT64) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "policyEpoch must satisfy 1 <= policyEpoch <= 2^64-1");
283
+ const actorKindByte = actorKindAndAlgToByte(params.actorKindAndAlg);
284
+ const actorPubKey65 = normalizeActorPublicKeyToPadded65(params.actorKindAndAlg, params.actorPublicKey, "PERSONAL_BLOB_MALFORMED");
285
+ if (typeof params.slotExpiresAtSec !== "bigint" || params.slotExpiresAtSec < 0n || params.slotExpiresAtSec > MAX_UINT64) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Invalid slotExpiresAtSec uint64");
286
+ if (isAgentActorKind(params.actorKindAndAlg) && params.slotExpiresAtSec <= 0n) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Agent actor slot (${params.actorKindAndAlg}) requires mandatory slotExpiresAtSec > 0n`);
287
+ let policyHashBytes32;
288
+ try {
289
+ policyHashBytes32 = require_secp256k1_scalar.normalizeHexBytes(params.policyHash32, 32);
290
+ } catch {
291
+ throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "policyHash32 must be 32 bytes");
292
+ }
293
+ const header = new Uint8Array(HSM_SEALED_BLOB_HEADER_BYTES);
294
+ header.set(HSM_BLOB_MAGIC_BYTES_8, 0);
295
+ header[8] = HSM_SEALED_BLOB_VERSION;
296
+ header[9] = kidBytes.length;
297
+ header.set(kidBytes, 10);
298
+ header[42] = vaultIdBytes.length;
299
+ header.set(vaultIdBytes, 43);
300
+ header[107] = slotIdBytes.length;
301
+ header.set(slotIdBytes, 108);
302
+ header.set(pRootComp33, 172);
303
+ header.set(require_secp256k1_scalar.u64be(params.policyEpoch), 205);
304
+ header[213] = actorKindByte;
305
+ header.set(actorPubKey65, 214);
306
+ header.set(require_secp256k1_scalar.u64be(params.slotExpiresAtSec), 279);
307
+ header.set(policyHashBytes32, 287);
308
+ return header;
309
+ }
310
+ function decodeHsmSealedBlobHeader319(headerBytes) {
311
+ if (!(headerBytes instanceof Uint8Array) || headerBytes.length !== HSM_SEALED_BLOB_HEADER_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Expected ${HSM_SEALED_BLOB_HEADER_BYTES}-byte header, got ${headerBytes?.length}`);
312
+ if (!require_secp256k1_scalar.constantTimeEqual(headerBytes.subarray(0, 8), HSM_BLOB_MAGIC_BYTES_8)) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Invalid HsmSealedBlob magic bytes");
313
+ const version = headerBytes[8];
314
+ if (version !== HSM_SEALED_BLOB_VERSION) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Unsupported HsmSealedBlob version: ${version}`);
315
+ const kid = decodeZeroPaddedIdentifierAscii(headerBytes, 9, 32, "kid");
316
+ const vaultId = decodeZeroPaddedIdentifierAscii(headerBytes, 42, 64, "vaultId");
317
+ const slotId = decodeZeroPaddedIdentifierAscii(headerBytes, 107, 64, "slotId");
318
+ const rootPublicKeyComp33 = headerBytes.slice(172, 205);
319
+ try {
320
+ require_secp256k1_scalar.decodePointCompressed(rootPublicKeyComp33, false);
321
+ } catch {
322
+ throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Invalid secp256k1 rootPublicKeyComp33 in blob header");
323
+ }
324
+ const policyEpoch = readU64BE(headerBytes, 205);
325
+ if (policyEpoch < 1n) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "policyEpoch in blob header must be >= 1n");
326
+ const actorKindAndAlg = byteToActorKindAndAlg(headerBytes[213]);
327
+ const actorPubKeyPadded65 = headerBytes.slice(214, 279);
328
+ validateActorPublicKeyPadded65(actorKindAndAlg, actorPubKeyPadded65, "PERSONAL_BLOB_MALFORMED");
329
+ const slotExpiresAtSec = readU64BE(headerBytes, 279);
330
+ if (isAgentActorKind(actorKindAndAlg) && slotExpiresAtSec <= 0n) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Agent slot header missing mandatory slotExpiresAtSec > 0n");
331
+ return {
332
+ version: 1,
333
+ kid,
334
+ vaultId,
335
+ slotId,
336
+ rootPublicKeyComp33,
337
+ policyEpoch,
338
+ actorKindAndAlg,
339
+ actorPubKeyPadded65,
340
+ slotExpiresAtSec,
341
+ policyHash32: headerBytes.slice(287, 319)
342
+ };
343
+ }
344
+ /**
345
+ * Parses and validates a fixed `4,096`-byte `HsmSealedBlob` (`design.md` §4.1).
346
+ */
347
+ function parseHsmSealedBlobHeader(blobBytes) {
348
+ if (!(blobBytes instanceof Uint8Array) || blobBytes.length !== require_constants.HSM_SEALED_BLOB_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `HsmSealedBlob must be exactly ${require_constants.HSM_SEALED_BLOB_BYTES} bytes, got ${blobBytes?.length}`);
349
+ const header319 = blobBytes.slice(0, HSM_SEALED_BLOB_HEADER_BYTES);
350
+ return {
351
+ header: decodeHsmSealedBlobHeader319(header319),
352
+ header319,
353
+ headerMac32: blobBytes.slice(HSM_SEALED_BLOB_HEADER_MAC_OFFSET, HSM_SEALED_BLOB_HEADER_WITH_MAC_BYTES),
354
+ authenticatedPrefix351: blobBytes.slice(0, HSM_SEALED_BLOB_HEADER_WITH_MAC_BYTES),
355
+ aesGcmIv12: blobBytes.slice(HSM_SEALED_BLOB_IV_OFFSET, HSM_SEALED_BLOB_TAG_OFFSET),
356
+ aesGcmTag16: blobBytes.slice(HSM_SEALED_BLOB_TAG_OFFSET, HSM_SEALED_BLOB_CIPHERTEXT_OFFSET),
357
+ ciphertext3717: blobBytes.slice(HSM_SEALED_BLOB_CIPHERTEXT_OFFSET, require_constants.HSM_SEALED_BLOB_BYTES)
358
+ };
359
+ }
360
+ function assertPersonalSlotNotExpired(header, nowSec) {
361
+ if (isAgentActorKind(header.actorKindAndAlg) && header.slotExpiresAtSec <= 0n) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Agent slot requires slotExpiresAtSec > 0n");
362
+ if (header.slotExpiresAtSec > 0n && nowSec >= header.slotExpiresAtSec) throw new require_constants.MpcProtocolError("PERSONAL_SLOT_EXPIRED", "Actor slot has expired");
363
+ }
364
+ function computeHsmSealedBlobHeaderMac32(params) {
365
+ if (!(params.headerMacKey32 instanceof Uint8Array) || params.headerMacKey32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "headerMacKey32 must be 32 bytes");
366
+ if (!(params.header319 instanceof Uint8Array) || params.header319.length !== HSM_SEALED_BLOB_HEADER_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "header319 must be 319 bytes");
367
+ const canonicalAad = canonicalizePersonalBlobAadBytes(params.aad);
368
+ return (0, _noble_hashes_hmac_js.hmac)(_noble_hashes_sha2_js.sha256, params.headerMacKey32, require_secp256k1_scalar.concatBytes(params.header319, canonicalAad));
369
+ }
370
+ function deriveHsmPersonalSealKey32(params) {
371
+ if (params.hsmWrappingKey32.length !== 32 || params.kUnsealSecret32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "hsmWrappingKey32 and kUnsealSecret32 must be 32 bytes");
372
+ const ikm64 = require_secp256k1_scalar.concatBytes(params.hsmWrappingKey32, params.kUnsealSecret32);
373
+ const salt32 = (0, _noble_hashes_sha2_js.sha256)(require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_SEAL_SALT_V1, [require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId)]));
374
+ try {
375
+ return (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, ikm64, salt32, require_secp256k1_scalar.utf8Bytes(require_constants.DST_PERSONAL_SEAL_KEY_V1), 32);
376
+ } finally {
377
+ require_secp256k1_scalar.zeroizeBytes(ikm64, salt32);
378
+ }
379
+ }
380
+ function encodeHsmSealedBlobInnerPlaintext3717(params) {
381
+ const sHsm = require_secp256k1_scalar.bytes32ToScalarNonZero(params.sHsmBytes32);
382
+ const pRoot = require_secp256k1_scalar.decodePointCompressed(params.rootPublicKeyComp33, false);
383
+ const xActor = require_secp256k1_scalar.decodePointCompressed(params.xActorComp33, false);
384
+ if (xActor.equals(pRoot)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate X_actor == P_root forbidden");
385
+ if (!xActor.add(require_secp256k1_scalar.mulBaseG(sHsm)).equals(pRoot)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "X_actor + s_hsm * G != P_root");
386
+ if (params.canonicalPolicyUtf8.length < 1 || params.canonicalPolicyUtf8.length > HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Policy UTF-8 length must be 1..${HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES}`);
387
+ if (!require_secp256k1_scalar.constantTimeEqual((0, _noble_hashes_sha2_js.sha256)(require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_POLICY_V1, [params.canonicalPolicyUtf8])), params.expectedPolicyHash32)) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_TAMPERED", "Policy hash mismatch against header");
388
+ const out = new Uint8Array(HSM_SEALED_BLOB_CIPHERTEXT_BYTES);
389
+ out.set(params.sHsmBytes32, 0);
390
+ out.set(require_secp256k1_scalar.encodePointCompressed(xActor), 32);
391
+ out.set(require_secp256k1_scalar.u64be(params.sealedAtSec), 65);
392
+ out.set(require_secp256k1_scalar.u16be(params.canonicalPolicyUtf8.length), 73);
393
+ out.set(params.canonicalPolicyUtf8, 75);
394
+ return out;
395
+ }
396
+ function decodeHsmSealedBlobInnerPlaintext3717(params) {
397
+ const { plaintext3717, rootPublicKeyComp33, expectedPolicyHash32 } = params;
398
+ if (!(plaintext3717 instanceof Uint8Array) || plaintext3717.length !== HSM_SEALED_BLOB_CIPHERTEXT_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Inner plaintext must be 3717 bytes");
399
+ const sHsmBytes32 = plaintext3717.slice(0, 32);
400
+ const xActorComp33 = plaintext3717.slice(32, 65);
401
+ try {
402
+ const sHsm = require_secp256k1_scalar.bytes32ToScalarNonZero(sHsmBytes32);
403
+ const pRoot = require_secp256k1_scalar.decodePointCompressed(rootPublicKeyComp33, false);
404
+ const xActor = require_secp256k1_scalar.decodePointCompressed(xActorComp33, false);
405
+ if (xActor.equals(pRoot) || !xActor.add(require_secp256k1_scalar.mulBaseG(sHsm)).equals(pRoot)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Invalid unsealed additive split against P_root");
406
+ const sealedAtSec = readU64BE(plaintext3717, 65);
407
+ const policyJsonLen = readU16BE(plaintext3717, 73);
408
+ if (policyJsonLen < 1 || policyJsonLen > HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_TAMPERED", `Invalid policyJsonLen ${policyJsonLen} in unsealed blob`);
409
+ const padStart = 75 + policyJsonLen;
410
+ for (let i = padStart; i < HSM_SEALED_BLOB_CIPHERTEXT_BYTES; i++) if (plaintext3717[i] !== 0) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_TAMPERED", "Non-zero padding byte detected in unsealed blob");
411
+ const canonicalPolicyUtf8 = plaintext3717.slice(75, padStart);
412
+ if (!require_secp256k1_scalar.constantTimeEqual((0, _noble_hashes_sha2_js.sha256)(require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_POLICY_V1, [canonicalPolicyUtf8])), expectedPolicyHash32)) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_TAMPERED", "Unsealed policy hash mismatch");
413
+ return {
414
+ sHsmBytes32,
415
+ xActorComp33,
416
+ sealedAtSec,
417
+ canonicalPolicyUtf8,
418
+ canonicalPolicyJson: utf8DecodeStrict(canonicalPolicyUtf8, "PERSONAL_BLOB_TAMPERED")
419
+ };
420
+ } catch (err) {
421
+ require_secp256k1_scalar.zeroizeBytes(sHsmBytes32);
422
+ throw err;
423
+ }
424
+ }
425
+ function deriveBlindVaultTag32(blindTagKey32, vaultId, rootPublicKeyComp33) {
426
+ if (blindTagKey32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "blindTagKey32 must be 32 bytes");
427
+ const pRoot = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.decodePointCompressed(rootPublicKeyComp33, false));
428
+ return (0, _noble_hashes_hmac_js.hmac)(_noble_hashes_sha2_js.sha256, blindTagKey32, require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_BLIND_VAULT_TAG_V1, [require_secp256k1_scalar.utf8Bytes(vaultId), pRoot]));
429
+ }
430
+ function deriveBlindSlotTag32(blindTagKey32, vaultId, slotId, rootPublicKeyComp33) {
431
+ if (blindTagKey32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "blindTagKey32 must be 32 bytes");
432
+ const pRoot = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.decodePointCompressed(rootPublicKeyComp33, false));
433
+ return (0, _noble_hashes_hmac_js.hmac)(_noble_hashes_sha2_js.sha256, blindTagKey32, require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_BLIND_SLOT_TAG_V1, [
434
+ require_secp256k1_scalar.utf8Bytes(vaultId),
435
+ require_secp256k1_scalar.utf8Bytes(slotId),
436
+ pRoot
437
+ ]));
438
+ }
439
+ function deriveBlindVelocityTag32(blindTagKey32, vaultId, rootPublicKeyComp33, chainId, assetKeyLower) {
440
+ if (blindTagKey32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "blindTagKey32 must be 32 bytes");
441
+ const pRoot = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.decodePointCompressed(rootPublicKeyComp33, false));
442
+ return (0, _noble_hashes_hmac_js.hmac)(_noble_hashes_sha2_js.sha256, blindTagKey32, require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_BLIND_VELOCITY_TAG_V1, [
443
+ require_secp256k1_scalar.utf8Bytes(vaultId),
444
+ pRoot,
445
+ require_secp256k1_scalar.u64be(chainId),
446
+ require_secp256k1_scalar.utf8Bytes(assetKeyLower.toLowerCase())
447
+ ]));
448
+ }
449
+ function deriveBlindOcapVelocityTag32(blindTagKey32, vaultId, rootPublicKeyComp33, ocapChainId, assetIdentifier) {
450
+ if (blindTagKey32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "blindTagKey32 must be 32 bytes");
451
+ const chainBytes = assertPrintableIdentifierAscii(ocapChainId, 64, "ocapChainId", "INVALID_PARAMETER");
452
+ const assetBytes = assertPrintableIdentifierAscii(assetIdentifier, 64, "assetIdentifier", "INVALID_PARAMETER");
453
+ const pRoot = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.decodePointCompressed(rootPublicKeyComp33, false));
454
+ return (0, _noble_hashes_hmac_js.hmac)(_noble_hashes_sha2_js.sha256, blindTagKey32, require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_BLIND_OCAP_VELOCITY_TAG_V1, [
455
+ require_secp256k1_scalar.utf8Bytes(vaultId),
456
+ pRoot,
457
+ chainBytes,
458
+ assetBytes
459
+ ]));
460
+ }
461
+ const INV_TWO_MOD_N = require_secp256k1_scalar.invModN(2n);
462
+ function additiveToShamirSlot1Share(sActor32) {
463
+ return require_secp256k1_scalar.scalarToBytes32(require_secp256k1_scalar.mulModN(INV_TWO_MOD_N, require_secp256k1_scalar.bytes32ToScalarNonZero(sActor32)));
464
+ }
465
+ function additiveToShamirSlot2Share(sHsm32) {
466
+ return require_secp256k1_scalar.scalarToBytes32(require_secp256k1_scalar.negModN(require_secp256k1_scalar.bytes32ToScalarNonZero(sHsm32)));
467
+ }
468
+ function verifyPersonalAdditiveSplitMatchesRoot(params) {
469
+ const sActor = require_secp256k1_scalar.bytes32ToScalarNonZero(params.sActor32);
470
+ const sHsm = require_secp256k1_scalar.bytes32ToScalarNonZero(params.sHsm32);
471
+ if (require_secp256k1_scalar.addModN(sActor, sHsm) === 0n) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "s_actor + s_hsm collapsed to 0 mod n");
472
+ const pRoot = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.rootPublicKeyComp33, 33), false);
473
+ const xActor = require_secp256k1_scalar.mulBaseG(sActor);
474
+ const xHsm = require_secp256k1_scalar.mulBaseG(sHsm);
475
+ if (xActor.is0() || xHsm.is0() || xActor.equals(pRoot)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate additive split point");
476
+ if (!xActor.add(xHsm).equals(pRoot)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "s_actor * G + s_hsm * G != P_root");
477
+ const xActorEncoded = require_secp256k1_scalar.encodePointCompressed(xActor);
478
+ if (params.xActorComp33 !== void 0) {
479
+ if (!require_secp256k1_scalar.constantTimeEqual(xActorEncoded, require_secp256k1_scalar.normalizeHexBytes(params.xActorComp33, 33))) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "X_actor mismatch against s_actor * G");
480
+ }
481
+ return {
482
+ xActorComp33: xActorEncoded,
483
+ xHsmComp33: require_secp256k1_scalar.encodePointCompressed(xHsm)
484
+ };
485
+ }
486
+ function buildPersonalVaultClusterInfo(params) {
487
+ assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
488
+ assertPrintableIdentifierAscii(params.slotId, 64, "slotId", "INVALID_PARAMETER");
489
+ if (typeof params.policyEpoch !== "bigint" || params.policyEpoch < 1n || params.policyEpoch > MAX_UINT64) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "policyEpoch must satisfy 1 <= policyEpoch <= 2^64-1");
490
+ const pRoot = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.rootPublicKeyComp33, 33), false);
491
+ const xActor = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.xActorComp33, 33), false);
492
+ if (xActor.equals(pRoot)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "X_actor cannot equal P_root (s_hsm == 0)");
493
+ const x1Point = require_secp256k1_scalar.mulPoint(xActor, INV_TWO_MOD_N);
494
+ const x2Point = xActor.subtract(pRoot);
495
+ if (x1Point.is0() || x2Point.is0()) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate Shamir public share derived from X_actor");
496
+ const pRootComp33 = require_secp256k1_scalar.encodePointCompressed(pRoot);
497
+ const xActorEncoded = require_secp256k1_scalar.encodePointCompressed(xActor);
498
+ const hDkg32 = require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CLUSTER_HDKG_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId), require_secp256k1_scalar.u64be(params.policyEpoch), pRootComp33, xActorEncoded);
499
+ return {
500
+ rootId: params.vaultId,
501
+ keyEpoch: params.policyEpoch,
502
+ t: 2,
503
+ nParties: 2,
504
+ hDkg32,
505
+ rootPublicKeyComp33: pRootComp33,
506
+ publicSharesComp33BySlot: new Map([[1, require_secp256k1_scalar.encodePointCompressed(x1Point)], [2, require_secp256k1_scalar.encodePointCompressed(x2Point)]])
507
+ };
508
+ }
509
+ function derivePersonalWakePasswordKeys(params) {
510
+ if (typeof params.password !== "string") throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Wake password must be a string");
511
+ const normalized = params.password.normalize("NFKC");
512
+ if (normalized.length === 0 || normalized.length > 512) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Wake password must be 1..512 characters after NFKC");
513
+ const salt32 = require_secp256k1_scalar.normalizeHexBytes(params.vaultSalt32, 32);
514
+ const pwdBytes = require_secp256k1_scalar.utf8Bytes(normalized);
515
+ const kdfMode = params.kdf ?? "pbkdf2-sha256";
516
+ let masterKey64 = null;
517
+ try {
518
+ if (kdfMode === "pbkdf2-sha256") {
519
+ const iterations = params.pbkdf2Iterations ?? 21e4;
520
+ if (!Number.isInteger(iterations) || iterations < 1e3 || iterations > 5e6) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "pbkdf2Iterations must be in [1000, 5000000]");
521
+ masterKey64 = (0, _noble_hashes_pbkdf2_js.pbkdf2)(_noble_hashes_sha2_js.sha256, pwdBytes, salt32, {
522
+ c: iterations,
523
+ dkLen: 64
524
+ });
525
+ } else if (kdfMode === "scrypt") {
526
+ const opts = params.scryptOpts ?? {
527
+ N: 16384,
528
+ r: 8,
529
+ p: 1
530
+ };
531
+ if (!Number.isInteger(opts.N) || opts.N < 1024 || (opts.N & opts.N - 1) !== 0) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "scrypt N must be a power of 2 >= 1024");
532
+ masterKey64 = (0, _noble_hashes_scrypt_js.scrypt)(pwdBytes, salt32, {
533
+ N: opts.N,
534
+ r: opts.r,
535
+ p: opts.p,
536
+ dkLen: 64
537
+ });
538
+ } else throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `Unsupported KDF mode: ${String(kdfMode)}`);
539
+ return {
540
+ kPwdClient32: (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, masterKey64, salt32, require_secp256k1_scalar.utf8Bytes(require_constants.DST_PERSONAL_PWD_CLIENT_HKDF_V1), 32),
541
+ kPwdHsm32: (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, masterKey64, salt32, require_secp256k1_scalar.utf8Bytes(require_constants.DST_PERSONAL_PWD_HSM_HKDF_V1), 32)
542
+ };
543
+ } finally {
544
+ require_secp256k1_scalar.zeroizeBytes(pwdBytes, masterKey64);
545
+ }
546
+ }
547
+ function buildDeviceEnvelopeAad(vaultId, slotId, rootPublicKeyComp33, xActorComp33) {
548
+ return require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_DEVICE_AAD_V1, [
549
+ require_secp256k1_scalar.utf8Bytes(vaultId),
550
+ require_secp256k1_scalar.utf8Bytes(slotId),
551
+ rootPublicKeyComp33,
552
+ xActorComp33
553
+ ]);
554
+ }
555
+ function deriveDeviceEnvelopeKey32(kHw32, kPwdClient32, deviceSalt32) {
556
+ if (kHw32.length !== 32 || kPwdClient32.length !== 32 || deviceSalt32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "kHw32, kPwdClient32, and deviceSalt32 must each be 32 bytes");
557
+ const ikm64 = require_secp256k1_scalar.concatBytes(kHw32, kPwdClient32);
558
+ try {
559
+ return (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, ikm64, deviceSalt32, require_secp256k1_scalar.utf8Bytes(require_constants.DST_PERSONAL_DEVICE_ENV_V1), 32);
560
+ } finally {
561
+ require_secp256k1_scalar.zeroizeBytes(ikm64);
562
+ }
563
+ }
564
+ async function sealDeviceShareEnvelope(params) {
565
+ const rng = params.rng ?? require_secp256k1_scalar.defaultRandomBytes;
566
+ assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
567
+ assertPrintableIdentifierAscii(params.slotId, 64, "slotId", "INVALID_PARAMETER");
568
+ const sActor = require_secp256k1_scalar.bytes32ToScalarNonZero(params.sActorBytes32);
569
+ const pRoot = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.rootPublicKeyComp33, 33), false);
570
+ const xActor = require_secp256k1_scalar.mulBaseG(sActor);
571
+ if (xActor.is0() || xActor.equals(pRoot)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate s_actor share in sealDeviceShareEnvelope");
572
+ const pRootComp33 = require_secp256k1_scalar.encodePointCompressed(pRoot);
573
+ const xActorComp33 = require_secp256k1_scalar.encodePointCompressed(xActor);
574
+ const deviceSalt32 = params.deviceSalt32 ? require_secp256k1_scalar.normalizeHexBytes(params.deviceSalt32, 32) : rng(32);
575
+ const iv12 = rng(12);
576
+ const envKey32 = deriveDeviceEnvelopeKey32(params.kHw32, params.kPwdClient32, deviceSalt32);
577
+ const aad = buildDeviceEnvelopeAad(params.vaultId, params.slotId, pRootComp33, xActorComp33);
578
+ try {
579
+ const { ciphertext, tag16 } = await aes256GcmEncryptDetached({
580
+ key32: envKey32,
581
+ iv12,
582
+ plaintext: params.sActorBytes32,
583
+ aad
584
+ });
585
+ return {
586
+ version: 1,
587
+ vaultId: params.vaultId,
588
+ slotId: params.slotId,
589
+ rootPublicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(pRootComp33)}`,
590
+ xActorPublicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(xActorComp33)}`,
591
+ deviceSaltHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(deviceSalt32)}`,
592
+ ivHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(iv12)}`,
593
+ tagHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(tag16)}`,
594
+ ciphertextHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(ciphertext)}`
595
+ };
596
+ } finally {
597
+ require_secp256k1_scalar.zeroizeBytes(envKey32);
598
+ }
599
+ }
600
+ async function unsealDeviceShareEnvelope(params) {
601
+ const { envelope } = params;
602
+ if (!envelope || envelope.version !== 1) throw new require_constants.MpcProtocolError("PERSONAL_ENVELOPE_AUTH_FAILED", "Invalid DeviceShareEnvelope version");
603
+ let pRootComp33;
604
+ let xActorComp33;
605
+ let deviceSalt32;
606
+ let iv12;
607
+ let tag16;
608
+ let ciphertext;
609
+ try {
610
+ pRootComp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(envelope.rootPublicKeyHex, 33), false));
611
+ xActorComp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(envelope.xActorPublicKeyHex, 33), false));
612
+ deviceSalt32 = require_secp256k1_scalar.normalizeHexBytes(envelope.deviceSaltHex, 32);
613
+ iv12 = require_secp256k1_scalar.normalizeHexBytes(envelope.ivHex, 12);
614
+ tag16 = require_secp256k1_scalar.normalizeHexBytes(envelope.tagHex, 16);
615
+ ciphertext = require_secp256k1_scalar.normalizeHexBytes(envelope.ciphertextHex, 32);
616
+ } catch {
617
+ throw new require_constants.MpcProtocolError("PERSONAL_ENVELOPE_AUTH_FAILED", "Malformed DeviceShareEnvelope fields");
618
+ }
619
+ const envKey32 = deriveDeviceEnvelopeKey32(params.kHw32, params.kPwdClient32, deviceSalt32);
620
+ const aad = buildDeviceEnvelopeAad(envelope.vaultId, envelope.slotId, pRootComp33, xActorComp33);
621
+ try {
622
+ const sActorBytes32 = await aes256GcmDecryptDetached({
623
+ key32: envKey32,
624
+ iv12,
625
+ ciphertext,
626
+ tag16,
627
+ aad,
628
+ authFailureCode: "PERSONAL_ENVELOPE_AUTH_FAILED"
629
+ });
630
+ const derivedX = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.mulBaseG(require_secp256k1_scalar.bytes32ToScalarNonZero(sActorBytes32)));
631
+ if (!require_secp256k1_scalar.constantTimeEqual(derivedX, xActorComp33) || require_secp256k1_scalar.constantTimeEqual(derivedX, pRootComp33)) {
632
+ require_secp256k1_scalar.zeroizeBytes(sActorBytes32);
633
+ throw new require_constants.MpcProtocolError("PERSONAL_ENVELOPE_AUTH_FAILED", "Unsealed s_actor does not match X_actor");
634
+ }
635
+ return {
636
+ sActorBytes32,
637
+ xActorComp33,
638
+ rootPublicKeyComp33: pRootComp33
639
+ };
640
+ } finally {
641
+ require_secp256k1_scalar.zeroizeBytes(envKey32);
642
+ }
643
+ }
644
+ /**
645
+ * Double-wraps a `4,096B` `HsmSealedBlob` into a `4,140B` `CloudSyncBlob` (`design.md` §4.4):
646
+ * `syncSalt16 [0..15] || iv12 [16..27] || tag16 [28..43] || ciphertext [44..4139]`.
647
+ */
648
+ async function wrapSealedBlobForCloudSync(params) {
649
+ const rng = params.rng ?? require_secp256k1_scalar.defaultRandomBytes;
650
+ parseHsmSealedBlobHeader(params.sealedBlob4096);
651
+ if (!(params.syncSecret32 instanceof Uint8Array) || params.syncSecret32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "syncSecret32 must be 32 bytes");
652
+ if (typeof params.recordId !== "string" || params.recordId.length === 0 || params.recordId.length > 256) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "recordId must be 1..256 characters");
653
+ const syncSalt16 = rng(16);
654
+ const iv12 = rng(12);
655
+ const kSync32 = (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, params.syncSecret32, syncSalt16, require_secp256k1_scalar.utf8Bytes(require_constants.DST_PERSONAL_CLOUD_SYNC_V1), 32);
656
+ const aad = require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_CLOUD_BLOB_V1, [require_secp256k1_scalar.utf8Bytes(params.recordId)]);
657
+ try {
658
+ const { ciphertext, tag16 } = await aes256GcmEncryptDetached({
659
+ key32: kSync32,
660
+ iv12,
661
+ plaintext: params.sealedBlob4096,
662
+ aad
663
+ });
664
+ const out = require_secp256k1_scalar.concatBytes(syncSalt16, iv12, tag16, ciphertext);
665
+ if (out.length !== require_constants.CLOUD_SYNC_SEALED_BLOB_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "CloudSyncBlob output length invariant failed");
666
+ return out;
667
+ } finally {
668
+ require_secp256k1_scalar.zeroizeBytes(kSync32);
669
+ }
670
+ }
671
+ async function unwrapSealedBlobFromCloudSync(params) {
672
+ const { cloudBlob4140, syncSecret32, recordId } = params;
673
+ if (!(cloudBlob4140 instanceof Uint8Array) || cloudBlob4140.length !== require_constants.CLOUD_SYNC_SEALED_BLOB_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `CloudSyncBlob must be exactly ${require_constants.CLOUD_SYNC_SEALED_BLOB_BYTES} bytes`);
674
+ if (!(syncSecret32 instanceof Uint8Array) || syncSecret32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "syncSecret32 must be 32 bytes");
675
+ if (typeof recordId !== "string" || recordId.length === 0 || recordId.length > 256) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "recordId must be 1..256 characters");
676
+ const syncSalt16 = cloudBlob4140.subarray(0, 16);
677
+ const iv12 = cloudBlob4140.subarray(16, 28);
678
+ const tag16 = cloudBlob4140.subarray(28, 44);
679
+ const ciphertext4096 = cloudBlob4140.subarray(44, require_constants.CLOUD_SYNC_SEALED_BLOB_BYTES);
680
+ const kSync32 = (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, syncSecret32, syncSalt16, require_secp256k1_scalar.utf8Bytes(require_constants.DST_PERSONAL_CLOUD_SYNC_V1), 32);
681
+ const aad = require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_CLOUD_BLOB_V1, [require_secp256k1_scalar.utf8Bytes(recordId)]);
682
+ try {
683
+ const plainBlob = await aes256GcmDecryptDetached({
684
+ key32: kSync32,
685
+ iv12,
686
+ ciphertext: ciphertext4096,
687
+ tag16,
688
+ aad,
689
+ authFailureCode: "PERSONAL_BLOB_TAMPERED"
690
+ });
691
+ parseHsmSealedBlobHeader(plainBlob);
692
+ return plainBlob;
693
+ } finally {
694
+ require_secp256k1_scalar.zeroizeBytes(kSync32);
695
+ }
696
+ }
697
+ function buildTransportBoxAad(vaultId, slotId, challengeNonce32, headerMac32) {
698
+ return require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_TRANSPORT_AAD_V1, [
699
+ require_secp256k1_scalar.utf8Bytes(vaultId),
700
+ require_secp256k1_scalar.utf8Bytes(slotId),
701
+ challengeNonce32,
702
+ headerMac32
703
+ ]);
704
+ }
705
+ /**
706
+ * Seals inbound sensitive material (`kUnsealSecret32`, `sHsm1`, or resplit `delta`) to the HSM's
707
+ * X25519 transport public key (`epkX25519_32 || iv12 || tag16 || ciphertext`, `design.md` §4.4).
708
+ */
709
+ async function sealHsmInboundTransportBox(params) {
710
+ const rng = params.rng ?? require_secp256k1_scalar.defaultRandomBytes;
711
+ assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
712
+ assertPrintableIdentifierAscii(params.slotId, 64, "slotId", "INVALID_PARAMETER");
713
+ const hsmPub32 = require_secp256k1_scalar.normalizeHexBytes(params.hsmTransportPub32, 32);
714
+ require_secp256k1_scalar.assertValidX25519PublicKey(hsmPub32, "INVALID_POINT");
715
+ const challengeNonce32 = require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32);
716
+ const headerMac32 = require_secp256k1_scalar.normalizeHexBytes(params.headerMac32, 32);
717
+ const esk32 = rng(32);
718
+ let shared32 = null;
719
+ let boxKey32 = null;
720
+ try {
721
+ const epk32 = _noble_curves_ed25519_js.x25519.getPublicKey(esk32);
722
+ shared32 = require_secp256k1_scalar.computeX25519SharedSecret(esk32, hsmPub32, "INVALID_POINT");
723
+ boxKey32 = (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, shared32, require_secp256k1_scalar.concatBytes(epk32, hsmPub32), require_secp256k1_scalar.utf8Bytes(require_constants.DST_PERSONAL_TRANSPORT_BOX_V1), 32);
724
+ const iv12 = rng(12);
725
+ const aad = buildTransportBoxAad(params.vaultId, params.slotId, challengeNonce32, headerMac32);
726
+ const { ciphertext, tag16 } = await aes256GcmEncryptDetached({
727
+ key32: boxKey32,
728
+ iv12,
729
+ plaintext: params.plaintext,
730
+ aad
731
+ });
732
+ return require_secp256k1_scalar.concatBytes(epk32, iv12, tag16, ciphertext);
733
+ } finally {
734
+ require_secp256k1_scalar.zeroizeBytes(esk32, shared32, boxKey32);
735
+ }
736
+ }
737
+ async function openHsmInboundTransportBox(params) {
738
+ if (!(params.hsmTransportSecretKey32 instanceof Uint8Array) || params.hsmTransportSecretKey32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "hsmTransportSecretKey32 must be 32 bytes");
739
+ const box = require_secp256k1_scalar.normalizeHexBytes(params.boxBytes);
740
+ if (box.length < 60) throw new require_constants.MpcProtocolError("PERSONAL_ENVELOPE_AUTH_FAILED", "HsmInboundTransportBox truncated (< 60 bytes)");
741
+ const challengeNonce32 = require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32);
742
+ const headerMac32 = require_secp256k1_scalar.normalizeHexBytes(params.headerMac32, 32);
743
+ const epk32 = box.subarray(0, 32);
744
+ const iv12 = box.subarray(32, 44);
745
+ const tag16 = box.subarray(44, 60);
746
+ const ciphertext = box.subarray(60);
747
+ require_secp256k1_scalar.assertValidX25519PublicKey(epk32, "PERSONAL_ENVELOPE_AUTH_FAILED");
748
+ const hsmPub32 = _noble_curves_ed25519_js.x25519.getPublicKey(params.hsmTransportSecretKey32);
749
+ let shared32 = null;
750
+ let boxKey32 = null;
751
+ try {
752
+ shared32 = require_secp256k1_scalar.computeX25519SharedSecret(params.hsmTransportSecretKey32, epk32, "PERSONAL_ENVELOPE_AUTH_FAILED");
753
+ boxKey32 = (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, shared32, require_secp256k1_scalar.concatBytes(epk32, hsmPub32), require_secp256k1_scalar.utf8Bytes(require_constants.DST_PERSONAL_TRANSPORT_BOX_V1), 32);
754
+ const aad = buildTransportBoxAad(params.vaultId, params.slotId, challengeNonce32, headerMac32);
755
+ return await aes256GcmDecryptDetached({
756
+ key32: boxKey32,
757
+ iv12,
758
+ ciphertext,
759
+ tag16,
760
+ aad,
761
+ authFailureCode: "PERSONAL_ENVELOPE_AUTH_FAILED"
762
+ });
763
+ } finally {
764
+ require_secp256k1_scalar.zeroizeBytes(shared32, boxKey32);
765
+ }
766
+ }
767
+ function signPersonalActorChallenge(params) {
768
+ if (!(params.actorSecretKey32 instanceof Uint8Array) || params.actorSecretKey32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "actorSecretKey32 must be 32 bytes");
769
+ const digest32 = require_secp256k1_scalar.normalizeHexBytes(params.challengeDigest32, 32);
770
+ if (params.mode === "raw-p256") {
771
+ const format = params.p256Format ?? "compact";
772
+ return {
773
+ mode: "raw-p256",
774
+ signatureBytes: _noble_curves_nist_js.p256.sign(digest32, params.actorSecretKey32, {
775
+ prehash: true,
776
+ lowS: true,
777
+ format
778
+ })
779
+ };
780
+ }
781
+ if (params.mode === "ed25519") return {
782
+ mode: "ed25519",
783
+ signatureBytes: _noble_curves_ed25519_js.ed25519.sign(digest32, params.actorSecretKey32)
784
+ };
785
+ throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `Unsupported sign mode: ${String(params.mode)}`);
786
+ }
787
+ function verifyP256Sha256SignatureFlexible(sigBytes, messageBytes, pubKey65) {
788
+ if (sigBytes.length >= 8 && sigBytes.length <= 73 && sigBytes[0] === 48 && sigBytes[1] === sigBytes.length - 2 && sigBytes[2] === 2) try {
789
+ if (_noble_curves_nist_js.p256.verify(sigBytes, messageBytes, pubKey65, {
790
+ prehash: true,
791
+ lowS: false,
792
+ format: "der"
793
+ })) return true;
794
+ } catch {}
795
+ if (sigBytes.length === 64) try {
796
+ return _noble_curves_nist_js.p256.verify(sigBytes, messageBytes, pubKey65, {
797
+ prehash: true,
798
+ lowS: false,
799
+ format: "compact"
800
+ });
801
+ } catch {
802
+ return false;
803
+ }
804
+ return false;
805
+ }
806
+ const WEBAUTHN_FLAG_UP = 1;
807
+ const WEBAUTHN_FLAG_UV = 4;
808
+ const WEBAUTHN_FLAG_BE = 8;
809
+ const WEBAUTHN_FLAG_BS = 16;
810
+ function verifyPersonalActorSignature(params) {
811
+ const digest32 = require_secp256k1_scalar.normalizeHexBytes(params.challengeDigest32, 32);
812
+ const padded65 = normalizeActorPublicKeyToPadded65(params.actorKindAndAlg, params.actorPublicKey, "PERSONAL_ACTOR_SIGNATURE_INVALID");
813
+ const { signature } = params;
814
+ if (!signature || typeof signature !== "object") throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Missing actor signature");
815
+ if (signature.mode === "ed25519") {
816
+ if (params.actorKindAndAlg !== "agent-ed25519") throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Ed25519 signature rejected for P-256 slot");
817
+ let sig64;
818
+ try {
819
+ sig64 = require_secp256k1_scalar.normalizeHexBytes(signature.signatureBytes, 64);
820
+ } catch {
821
+ throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Ed25519 signature must be 64 bytes");
822
+ }
823
+ const pub32 = padded65.subarray(0, 32);
824
+ let ok = false;
825
+ try {
826
+ ok = _noble_curves_ed25519_js.ed25519.verify(sig64, digest32, pub32, { zip215: false });
827
+ } catch {
828
+ ok = false;
829
+ }
830
+ if (!ok) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid Ed25519 actor signature");
831
+ return;
832
+ }
833
+ if (params.actorKindAndAlg !== "human-p256" && params.actorKindAndAlg !== "agent-p256") throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "P-256 signature rejected for Ed25519 slot");
834
+ if (signature.mode === "raw-p256") {
835
+ let sigBytes;
836
+ try {
837
+ sigBytes = require_secp256k1_scalar.normalizeHexBytes(signature.signatureBytes);
838
+ } catch {
839
+ throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Malformed raw P-256 signature bytes");
840
+ }
841
+ if (!verifyP256Sha256SignatureFlexible(sigBytes, digest32, padded65)) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid raw P-256 actor signature");
842
+ return;
843
+ }
844
+ if (signature.mode === "webauthn-p256") {
845
+ if (!params.webauthnPolicy || !params.webauthnPolicy.expectedRpId) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn verification requires expectedRpId and expectedOrigin policy");
846
+ let authData;
847
+ let sigBytes;
848
+ try {
849
+ authData = require_secp256k1_scalar.normalizeHexBytes(signature.authenticatorData);
850
+ sigBytes = require_secp256k1_scalar.normalizeHexBytes(signature.signatureBytes);
851
+ } catch {
852
+ throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Malformed WebAuthn binary fields");
853
+ }
854
+ if (authData.length < 37 || authData.length > 2048) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn authenticatorData must be 37..2048 bytes");
855
+ const expectedRpIdHash32 = (0, _noble_hashes_sha2_js.sha256)(require_secp256k1_scalar.utf8Bytes(params.webauthnPolicy.expectedRpId));
856
+ if (!require_secp256k1_scalar.constantTimeEqual(authData.subarray(0, 32), expectedRpIdHash32)) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn rpIdHash mismatch");
857
+ const flags = authData[32];
858
+ if ((flags & WEBAUTHN_FLAG_UP) === 0 || (flags & WEBAUTHN_FLAG_UV) === 0) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn UP (0x01) and UV (0x04) flags required");
859
+ if ((flags & WEBAUTHN_FLAG_BE) === 0 && (flags & WEBAUTHN_FLAG_BS) !== 0) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid WebAuthn BE=0 / BS=1 flag state");
860
+ const clientDataBytes = typeof signature.clientDataJSON === "string" ? require_secp256k1_scalar.utf8Bytes(signature.clientDataJSON) : signature.clientDataJSON instanceof Uint8Array ? signature.clientDataJSON : null;
861
+ if (!clientDataBytes || clientDataBytes.length < 20 || clientDataBytes.length > 4096) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid WebAuthn clientDataJSON length");
862
+ const clientDataStr = utf8DecodeStrict(clientDataBytes, "PERSONAL_ACTOR_SIGNATURE_INVALID");
863
+ let parsedClientData;
864
+ try {
865
+ const rawJson = JSON.parse(clientDataStr);
866
+ if (!rawJson || typeof rawJson !== "object" || Array.isArray(rawJson)) throw new Error("not object");
867
+ parsedClientData = rawJson;
868
+ } catch {
869
+ throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Malformed WebAuthn clientDataJSON");
870
+ }
871
+ if (parsedClientData.type !== "webauthn.get") throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn type must be \"webauthn.get\"");
872
+ if (parsedClientData.crossOrigin === true || parsedClientData.crossOrigin !== void 0 && parsedClientData.crossOrigin !== false) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Cross-origin WebAuthn assertions are forbidden");
873
+ const allowedOrigins = Array.isArray(params.webauthnPolicy.expectedOrigin) ? params.webauthnPolicy.expectedOrigin : [params.webauthnPolicy.expectedOrigin];
874
+ if (typeof parsedClientData.origin !== "string" || !allowedOrigins.includes(parsedClientData.origin)) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn origin mismatch");
875
+ if (typeof parsedClientData.challenge !== "string") throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Missing WebAuthn challenge");
876
+ if (!require_secp256k1_scalar.constantTimeEqual(base64UrlDecodeBytes(parsedClientData.challenge, "PERSONAL_ACTOR_SIGNATURE_INVALID"), digest32) || base64UrlEncodeBytes(digest32) !== parsedClientData.challenge) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn challenge mismatch");
877
+ const signedData = require_secp256k1_scalar.concatBytes(authData, (0, _noble_hashes_sha2_js.sha256)(clientDataBytes));
878
+ if (!verifyP256Sha256SignatureFlexible(sigBytes, signedData, padded65)) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid WebAuthn P-256 signature");
879
+ return;
880
+ }
881
+ throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Unsupported PersonalActorSignature mode");
882
+ }
883
+ /**
884
+ * Generates a Schnorr Proof of Knowledge of `s_actor` for `X_actor = s_actor * G` bound to
885
+ * `(vaultId, slotId, challengeNonce32)` (`LOW-2` rogue-key defense on `seal-enroll`).
886
+ */
887
+ function createPersonalSealEnrollActorPok(params) {
888
+ assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
889
+ assertPrintableIdentifierAscii(params.slotId, 64, "slotId", "INVALID_PARAMETER");
890
+ const challengeNonce32 = require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32);
891
+ let sActorScalar = 0n;
892
+ try {
893
+ sActorScalar = require_secp256k1_scalar.bytes32ToScalarNonZero(params.sActorBytes32);
894
+ const derivedXActor = require_secp256k1_scalar.mulBaseG(sActorScalar);
895
+ if (params.xActorComp33 !== void 0) {
896
+ const expectedX = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.xActorComp33, 33), false);
897
+ if (!derivedXActor.equals(expectedX)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "sActorBytes32 * G does not match xActorComp33");
898
+ }
899
+ return require_secp256k1_scalar.createSchnorrPokInBase({
900
+ dst: require_constants.DST_PERSONAL_SEAL_ENROLL_ACTOR_POK_V1,
901
+ basePoint: require_secp256k1_scalar.SECP256K1_G,
902
+ statementPoint: derivedXActor,
903
+ secretScalar: sActorScalar,
904
+ contextParts: [
905
+ require_secp256k1_scalar.utf8Bytes(params.vaultId),
906
+ require_secp256k1_scalar.utf8Bytes(params.slotId),
907
+ challengeNonce32
908
+ ],
909
+ rng: params.rng
910
+ });
911
+ } finally {
912
+ sActorScalar = 0n;
913
+ }
914
+ }
915
+ function verifyPersonalSealEnrollActorPok(params) {
916
+ if (!params.actorSharePok || typeof params.actorSharePok !== "object" || Array.isArray(params.actorSharePok)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Missing seal-enroll actorSharePok Schnorr PoK");
917
+ let noncePointComp33;
918
+ let responseBytes32;
919
+ let statementPoint;
920
+ let challengeNonce32;
921
+ try {
922
+ noncePointComp33 = require_secp256k1_scalar.normalizeHexBytes(params.actorSharePok.noncePointComp33, 33);
923
+ responseBytes32 = require_secp256k1_scalar.normalizeHexBytes(params.actorSharePok.responseBytes32, 32);
924
+ statementPoint = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.xActorComp33, 33), false);
925
+ challengeNonce32 = require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32);
926
+ } catch {
927
+ throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Malformed seal-enroll actorSharePok fields");
928
+ }
929
+ if (!require_secp256k1_scalar.verifySchnorrPokInBase({
930
+ dst: require_constants.DST_PERSONAL_SEAL_ENROLL_ACTOR_POK_V1,
931
+ basePoint: require_secp256k1_scalar.SECP256K1_G,
932
+ statementPoint,
933
+ proof: {
934
+ noncePointComp33,
935
+ responseBytes32
936
+ },
937
+ contextParts: [
938
+ require_secp256k1_scalar.utf8Bytes(params.vaultId),
939
+ require_secp256k1_scalar.utf8Bytes(params.slotId),
940
+ challengeNonce32
941
+ ]
942
+ })) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Invalid Schnorr PoK for X_actor = s_actor * G on seal-enroll");
943
+ }
944
+ function buildPersonalSealEnrollChallengeDigest32(params) {
945
+ decodeHsmSealedBlobHeader319(params.header319);
946
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CHALLENGE_SEAL_ENROLL_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId), require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32), params.header319);
947
+ }
948
+ function buildPersonalPresignInitChallengeDigest32(params) {
949
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CHALLENGE_PRESIGN_INIT_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId), require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32), require_secp256k1_scalar.normalizeHexBytes(params.headerMac32, 32), require_secp256k1_scalar.normalizeHexBytes(params.sessionNonce32, 32));
950
+ }
951
+ function buildPersonalSignChallengeDigest32(params) {
952
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CHALLENGE_SIGN_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId), require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32), require_secp256k1_scalar.normalizeHexBytes(params.headerMac32, 32), require_secp256k1_scalar.normalizeHexBytes(params.presigId32, 32), require_secp256k1_scalar.normalizeHexBytes(params.clearSigningPreviewHash32, 32), require_secp256k1_scalar.normalizeHexBytes(params.signingDigest32, 32));
953
+ }
954
+ function buildPersonalPairResplitChallengeDigest32(params) {
955
+ validateActorPublicKeyPadded65(params.targetActorKindAndAlg, params.targetActorPubKeyPadded65);
956
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CHALLENGE_PAIR_RESPLIT_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.sourceSlotId), require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32), require_secp256k1_scalar.normalizeHexBytes(params.sourceHeaderMac32, 32), require_secp256k1_scalar.utf8Bytes(params.targetSlotId), require_secp256k1_scalar.u8(actorKindAndAlgToByte(params.targetActorKindAndAlg)), params.targetActorPubKeyPadded65, require_secp256k1_scalar.normalizeHexBytes(params.xActor2Comp33, 33), require_secp256k1_scalar.u64be(params.targetSlotExpiresAtSec), require_secp256k1_scalar.normalizeHexBytes(params.targetPairNonce32, 32));
957
+ }
958
+ function buildPersonalAnnounceChallengeDigest32(params) {
959
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CHALLENGE_ANNOUNCE_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId), require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32), require_secp256k1_scalar.normalizeHexBytes(params.headerMac32, 32), require_secp256k1_scalar.normalizeHexBytes(params.clearSigningPreviewHash32, 32), require_secp256k1_scalar.normalizeHexBytes(params.signingDigest32, 32));
960
+ }
961
+ function buildPersonalVetoChallengeDigest32(params) {
962
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CHALLENGE_VETO_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId), require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32), require_secp256k1_scalar.normalizeHexBytes(params.headerMac32, 32), require_secp256k1_scalar.utf8Bytes(params.reason));
963
+ }
964
+ function buildPersonalRevokeSlotChallengeDigest32(params) {
965
+ assertPrintableIdentifierAscii(params.targetSlotId, 64, "targetSlotId", "INVALID_PARAMETER");
966
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CHALLENGE_REVOKE_SLOT_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId), require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32), require_secp256k1_scalar.normalizeHexBytes(params.headerMac32, 32), require_secp256k1_scalar.utf8Bytes(params.targetSlotId));
967
+ }
968
+ function buildPersonalSessionOpenChallengeDigest32(params) {
969
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CHALLENGE_SESSION_OPEN_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId), require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32), require_secp256k1_scalar.normalizeHexBytes(params.headerMac32, 32), require_secp256k1_scalar.u32be(params.ttlSeconds));
970
+ }
971
+ function buildPersonalSessionLockChallengeDigest32(params) {
972
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CHALLENGE_SESSION_LOCK_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId), require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32), require_secp256k1_scalar.normalizeHexBytes(params.headerMac32, 32), require_secp256k1_scalar.utf8Bytes(params.sessionLeaseId));
973
+ }
974
+ function buildPersonalResealKidChallengeDigest32(params) {
975
+ assertPrintableIdentifierAscii(params.targetKid, 32, "targetKid", "INVALID_PARAMETER");
976
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CHALLENGE_RESEAL_KID_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId), require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32), require_secp256k1_scalar.normalizeHexBytes(params.oldHeaderMac32, 32), require_secp256k1_scalar.utf8Bytes(params.targetKid));
977
+ }
978
+ function buildPersonalEntitlementApplyChallengeDigest32(params) {
979
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_CHALLENGE_ENTITLEMENT_APPLY_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.slotId), require_secp256k1_scalar.normalizeHexBytes(params.challengeNonce32, 32), require_secp256k1_scalar.normalizeHexBytes(params.headerMac32, 32), require_secp256k1_scalar.normalizeHexBytes(params.entitlementTicketHash32, 32));
980
+ }
981
+ function computePersonalActorChallengeDigest32(payload) {
982
+ switch (payload.action) {
983
+ case "seal-enroll": return buildPersonalSealEnrollChallengeDigest32(payload);
984
+ case "presign-init": return buildPersonalPresignInitChallengeDigest32(payload);
985
+ case "sign": return buildPersonalSignChallengeDigest32(payload);
986
+ case "pair-resplit": return buildPersonalPairResplitChallengeDigest32(payload);
987
+ case "announce": return buildPersonalAnnounceChallengeDigest32(payload);
988
+ case "veto": return buildPersonalVetoChallengeDigest32(payload);
989
+ case "revoke-slot": return buildPersonalRevokeSlotChallengeDigest32(payload);
990
+ case "session-open": return buildPersonalSessionOpenChallengeDigest32(payload);
991
+ case "session-lock": return buildPersonalSessionLockChallengeDigest32(payload);
992
+ case "reseal-kid": return buildPersonalResealKidChallengeDigest32(payload);
993
+ case "entitlement-apply": return buildPersonalEntitlementApplyChallengeDigest32(payload);
994
+ default: throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Unsupported personal challenge action");
995
+ }
996
+ }
997
+ const ERC20_APPROVE_SELECTOR_HEX = "095ea7b3";
998
+ const EIP7702_SET_CODE_TX_TYPE = 4;
999
+ const EIP7702_AUTH_MAGIC = 5;
1000
+ function selectorHexFromSignature(sig) {
1001
+ return `0x${(0, _noble_hashes_utils_js.bytesToHex)((0, _noble_hashes_sha3_js.keccak_256)(require_secp256k1_scalar.utf8Bytes(sig)).subarray(0, 4))}`;
1002
+ }
1003
+ const HARD_BANNED_PERSONAL_EVM_SELECTORS = new Set([
1004
+ selectorHexFromSignature("transferFrom(address,address,uint256)"),
1005
+ selectorHexFromSignature("safeTransferFrom(address,address,uint256)"),
1006
+ selectorHexFromSignature("safeTransferFrom(address,address,uint256,bytes)"),
1007
+ selectorHexFromSignature("multicall(bytes[])"),
1008
+ selectorHexFromSignature("multicall(uint256,bytes[])"),
1009
+ selectorHexFromSignature("multicall(bytes32,bytes[])"),
1010
+ selectorHexFromSignature("execute(address,uint256,bytes)")
1011
+ ]);
1012
+ function encodeErc20ApproveCalldata(spenderAddress, allowanceAmount) {
1013
+ const parsedSpender = require_tweak.parseStrictEthAddress(spenderAddress);
1014
+ if (typeof allowanceAmount !== "bigint" || allowanceAmount < 0n || allowanceAmount > MAX_UINT256) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "ERC-20 approve allowanceAmount must satisfy 0 <= amount <= 2^256 - 1");
1015
+ const out = new Uint8Array(68);
1016
+ out.set(require_secp256k1_scalar.normalizeHexBytes(ERC20_APPROVE_SELECTOR_HEX, 4), 0);
1017
+ out.set(parsedSpender.addressBytes20, 16);
1018
+ let rem = allowanceAmount;
1019
+ for (let i = 67; i >= 36; i--) {
1020
+ out[i] = Number(rem & 255n);
1021
+ rem >>= 8n;
1022
+ }
1023
+ return out;
1024
+ }
1025
+ function decodeErc20ApproveCalldata(calldata) {
1026
+ const bytes = require_secp256k1_scalar.normalizeHexBytes(calldata);
1027
+ if (bytes.length !== 68 || (0, _noble_hashes_utils_js.bytesToHex)(bytes.subarray(0, 4)) !== ERC20_APPROVE_SELECTOR_HEX) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Expected 68-byte ERC-20 approve(address,uint256) calldata");
1028
+ for (let i = 4; i < 16; i++) if (bytes[i] !== 0) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Non-zero padding in ABI-encoded ERC-20 spender word");
1029
+ const addrLower = (0, _noble_hashes_utils_js.bytesToHex)(bytes.subarray(16, 36));
1030
+ if (/^0+$/.test(addrLower)) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Zero spender in ERC-20 approve calldata");
1031
+ const allowanceAmount = require_secp256k1_scalar.bytesToBigIntBE(bytes.subarray(36, 68));
1032
+ return {
1033
+ spenderChecksumAddress: require_tweak.toEip55ChecksumAddress(addrLower),
1034
+ allowanceAmount,
1035
+ isUnlimitedApprove: allowanceAmount >= UNLIMITED_APPROVE_THRESHOLD
1036
+ };
1037
+ }
1038
+ /**
1039
+ * Hard-bans `0x04` EIP-7702 `SetCode` transactions, `0x05` EIP-7702 authorization magic payloads,
1040
+ * and raw `32`-byte blind message digests (`design.md` §2 Lens 4).
1041
+ */
1042
+ function assertNoEip7702Bytes(rawPayload) {
1043
+ const bytes = require_secp256k1_scalar.normalizeHexBytes(rawPayload);
1044
+ if (bytes.length === 0) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Empty transaction payload");
1045
+ const firstByte = bytes[0];
1046
+ if (firstByte === EIP7702_SET_CODE_TX_TYPE || firstByte === EIP7702_AUTH_MAGIC) throw new require_constants.MpcProtocolError("PERSONAL_EIP7702_FORBIDDEN", `EIP-7702 envelope byte 0x0${firstByte.toString(16)} is strictly forbidden on MPC-secured EOAs`);
1047
+ if (firstByte !== require_rlp_eip1559.EIP1559_TX_TYPE_BYTE) {
1048
+ if (bytes.length === 32) throw new require_constants.MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Opaque 32-byte blind digest signing is strictly forbidden");
1049
+ throw new require_constants.MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", `Only EIP-1559 Type 0x02 clear-signed transactions are permitted (got prefix 0x${firstByte.toString(16).padStart(2, "0")})`);
1050
+ }
1051
+ return bytes;
1052
+ }
1053
+ function parseStrictNonNegativeBigInt(val, max, label, errorCode = "PERSONAL_POLICY_VIOLATION") {
1054
+ let out;
1055
+ if (typeof val === "bigint") out = val;
1056
+ else if (typeof val === "number") {
1057
+ if (!Number.isSafeInteger(val) || val < 0) throw new require_constants.MpcProtocolError(errorCode, `${label} must be a non-negative safe integer`);
1058
+ out = BigInt(val);
1059
+ } else if (typeof val === "string" && /^(?:0|[1-9][0-9]*)$/.test(val)) out = BigInt(val);
1060
+ else throw new require_constants.MpcProtocolError(errorCode, `Invalid canonical integer for ${label}: ${String(val)}`);
1061
+ if (out < 0n || out > max) throw new require_constants.MpcProtocolError(errorCode, `${label} exceeds range [0, ${max}]`);
1062
+ return out;
1063
+ }
1064
+ function normalizeSelector4Lower(sel) {
1065
+ if (typeof sel !== "string" || !/^0x[0-9a-fA-F]{8}$/.test(sel)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid 4-byte selector: ${String(sel)}`);
1066
+ const lower = sel.toLowerCase();
1067
+ if (HARD_BANNED_PERSONAL_EVM_SELECTORS.has(lower)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Selector ${lower} is hard-banned and cannot be allowlisted`);
1068
+ return lower;
1069
+ }
1070
+ function validateAndNormalizeQuorumMember(member) {
1071
+ assertPrintableIdentifierAscii(member.memberId, 64, "memberId", "PERSONAL_POLICY_VIOLATION");
1072
+ const rawPub = require_secp256k1_scalar.normalizeHexBytes(member.publicKeyHex);
1073
+ if (member.alg === "p256") {
1074
+ if (rawPub.length !== 33 && rawPub.length !== 65) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Quorum p256 publicKey must be 33 or 65 bytes");
1075
+ const pt = _noble_curves_nist_js.p256.Point.fromBytes(rawPub);
1076
+ pt.assertValidity();
1077
+ if (pt.is0()) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Degenerate p256 quorum public key");
1078
+ return {
1079
+ memberId: member.memberId,
1080
+ alg: "p256",
1081
+ publicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(pt.toBytes(false))}`
1082
+ };
1083
+ }
1084
+ if (member.alg === "ed25519") {
1085
+ validateEd25519PublicKeyNonTorsion32(rawPub, "PERSONAL_POLICY_VIOLATION");
1086
+ return {
1087
+ memberId: member.memberId,
1088
+ alg: "ed25519",
1089
+ publicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(rawPub)}`
1090
+ };
1091
+ }
1092
+ if (member.alg === "secp256k1") {
1093
+ const pt = require_secp256k1_scalar.decodePointCompressed(rawPub, false);
1094
+ return {
1095
+ memberId: member.memberId,
1096
+ alg: "secp256k1",
1097
+ publicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(require_secp256k1_scalar.encodePointCompressed(pt))}`
1098
+ };
1099
+ }
1100
+ throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Unsupported quorum alg: ${String(member.alg)}`);
1101
+ }
1102
+ function normalizeRosterMembers(threshold, members, label) {
1103
+ if (!Array.isArray(members) || members.length === 0 || members.length > 32) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} must have 1..32 members`);
1104
+ if (!Number.isInteger(threshold) || threshold < 1 || threshold > members.length) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid threshold ${threshold} for ${label}`);
1105
+ const normalized = members.map((m) => validateAndNormalizeQuorumMember(m));
1106
+ normalized.sort((a, b) => a.memberId.localeCompare(b.memberId));
1107
+ const seenIds = /* @__PURE__ */ new Set();
1108
+ const seenKeys = /* @__PURE__ */ new Set();
1109
+ for (const m of normalized) {
1110
+ if (seenIds.has(m.memberId) || seenKeys.has(`${m.alg}:${m.publicKeyHex}`)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Duplicate memberId or publicKey in ${label}`);
1111
+ seenIds.add(m.memberId);
1112
+ seenKeys.add(`${m.alg}:${m.publicKeyHex}`);
1113
+ }
1114
+ return normalized;
1115
+ }
1116
+ function deterministicJsonStringify(value) {
1117
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1118
+ if (Array.isArray(value)) return `[${value.map((v) => deterministicJsonStringify(v)).join(",")}]`;
1119
+ const obj = value;
1120
+ return `{${Object.keys(obj).filter((k) => obj[k] !== void 0).sort().map((k) => `${JSON.stringify(k)}:${deterministicJsonStringify(obj[k])}`).join(",")}}`;
1121
+ }
1122
+ const OCAP_BASE58_BODY_RE = /^z[1-9A-HJ-NP-Za-km-z]{24,60}$/;
1123
+ const OCAP_TX_TYPE_RE = /^fg:t:[a-z0-9_]{1,64}$/;
1124
+ function normalizeOcapAddressOrEth(raw, label, errorCode = "PERSONAL_POLICY_VIOLATION") {
1125
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > 96) throw new require_constants.MpcProtocolError(errorCode, `Invalid ${label} address`);
1126
+ const stripped = raw.replace(/^did:[a-z0-9]+:/, "");
1127
+ if (stripped.startsWith("0x") || stripped.startsWith("0X")) return require_tweak.parseStrictEthAddress(stripped).checksumAddress;
1128
+ if (!OCAP_BASE58_BODY_RE.test(stripped)) throw new require_constants.MpcProtocolError(errorCode, `Invalid OCAP base58btc or EIP-55 address for ${label}`);
1129
+ return stripped;
1130
+ }
1131
+ function normalizeCanonicalOcapTokenKey(raw, label, errorCode = "PERSONAL_POLICY_VIOLATION") {
1132
+ const norm = normalizeOcapAddressOrEth(raw, label, errorCode);
1133
+ return norm.startsWith("0x") || norm.startsWith("0X") ? norm.toLowerCase() : norm;
1134
+ }
1135
+ function canonicalizePersonalVaultPolicy(policy) {
1136
+ if (!policy || policy.version !== 1) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "PersonalVaultPolicy version must be 1");
1137
+ assertPrintableIdentifierAscii(policy.vaultId, 64, "vaultId", "PERSONAL_POLICY_VIOLATION");
1138
+ if (!Array.isArray(policy.allowedChainIds)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "allowedChainIds must be an array");
1139
+ const ocapChainSet = /* @__PURE__ */ new Set();
1140
+ for (const rawOcapChain of policy.allowedOcapChainIds ?? []) {
1141
+ assertPrintableIdentifierAscii(rawOcapChain, 64, "allowedOcapChainIds[]", "PERSONAL_POLICY_VIOLATION");
1142
+ ocapChainSet.add(rawOcapChain);
1143
+ }
1144
+ const allowedOcapChainIds = [...ocapChainSet].sort();
1145
+ if (policy.allowedChainIds.length === 0 && allowedOcapChainIds.length === 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "allowedChainIds or allowedOcapChainIds must be non-empty");
1146
+ const chainSet = /* @__PURE__ */ new Set();
1147
+ for (const rawChain of policy.allowedChainIds) {
1148
+ const cid = parseStrictNonNegativeBigInt(rawChain, MAX_UINT64, "chainId");
1149
+ if (cid < 1n) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "chainId must be >= 1");
1150
+ chainSet.add(cid.toString(10));
1151
+ }
1152
+ const allowedChainIds = [...chainSet].sort((a, b) => BigInt(a) < BigInt(b) ? -1 : BigInt(a) > BigInt(b) ? 1 : 0);
1153
+ const ocapTxTypeSet = /* @__PURE__ */ new Set();
1154
+ for (const txType of policy.allowedOcapTxTypes ?? []) {
1155
+ if (typeof txType !== "string" || !OCAP_TX_TYPE_RE.test(txType)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid allowedOcapTxTypes entry: ${String(txType)}`);
1156
+ ocapTxTypeSet.add(txType);
1157
+ }
1158
+ const allowedOcapTxTypes = [...ocapTxTypeSet].sort();
1159
+ const payeeSet = /* @__PURE__ */ new Set();
1160
+ for (const p of policy.allowedPayees ?? []) payeeSet.add(require_tweak.parseStrictEthAddress(p).checksumAddress);
1161
+ const allowedPayees = [...payeeSet].sort();
1162
+ const ocapPayeeSet = /* @__PURE__ */ new Set();
1163
+ for (const p of policy.allowedOcapPayees ?? []) ocapPayeeSet.add(normalizeOcapAddressOrEth(p, "allowedOcapPayees[]"));
1164
+ const allowedOcapPayees = [...ocapPayeeSet].sort();
1165
+ const allowedContracts = (policy.allowedContracts ?? []).map((rule) => {
1166
+ const cid = parseStrictNonNegativeBigInt(rule.chainId, MAX_UINT64, "contract.chainId");
1167
+ if (cid < 1n) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "contract.chainId must be >= 1");
1168
+ const checksumAddr = require_tweak.parseStrictEthAddress(rule.address).checksumAddress;
1169
+ const selSet = /* @__PURE__ */ new Set();
1170
+ for (const s of rule.selectors) selSet.add(normalizeSelector4Lower(s));
1171
+ if (selSet.size === 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "allowedContracts selectors must be non-empty");
1172
+ const maxVal = rule.maxValueWei === void 0 ? 0n : parseStrictNonNegativeBigInt(rule.maxValueWei, MAX_UINT128, "maxValueWei");
1173
+ return {
1174
+ chainId: cid.toString(10),
1175
+ address: checksumAddr,
1176
+ selectors: [...selSet].sort(),
1177
+ maxValueWei: maxVal.toString(10)
1178
+ };
1179
+ }).sort((a, b) => `${a.chainId}:${a.address}`.localeCompare(`${b.chainId}:${b.address}`));
1180
+ const seenAssetKeys = /* @__PURE__ */ new Set();
1181
+ const assetLimits = (policy.assetLimits ?? []).map((lim) => {
1182
+ const cid = parseStrictNonNegativeBigInt(lim.chainId, MAX_UINT64, "assetLimit.chainId");
1183
+ if (cid < 1n) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "assetLimit.chainId must be >= 1");
1184
+ const normalizedAsset = lim.asset === "native" ? "native" : require_tweak.parseStrictEthAddress(lim.asset).lowercaseAddress;
1185
+ const key = `${cid.toString(10)}:${normalizedAsset}`;
1186
+ if (seenAssetKeys.has(key)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Duplicate assetLimit entry for ${key}`);
1187
+ seenAssetKeys.add(key);
1188
+ const l0PerTx = parseStrictNonNegativeBigInt(lim.l0MaxPerTxAmount, MAX_UINT128, "l0MaxPerTxAmount");
1189
+ const l0Roll = parseStrictNonNegativeBigInt(lim.l0MaxRolling24hAmount, MAX_UINT128, "l0MaxRolling24hAmount");
1190
+ if (l0Roll < l0PerTx) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l0MaxRolling24hAmount must be >= l0MaxPerTxAmount");
1191
+ const l1Max = lim.l1MaxPerTxAmount !== void 0 ? parseStrictNonNegativeBigInt(lim.l1MaxPerTxAmount, MAX_UINT128, "l1MaxPerTxAmount") : void 0;
1192
+ const l2Max = lim.l2MaxPerTxAmount !== void 0 ? parseStrictNonNegativeBigInt(lim.l2MaxPerTxAmount, MAX_UINT128, "l2MaxPerTxAmount") : void 0;
1193
+ if (l1Max !== void 0 && l1Max < l0PerTx) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l1MaxPerTxAmount must be >= l0MaxPerTxAmount");
1194
+ if (l2Max !== void 0 && l1Max !== void 0 && l2Max < l1Max) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l2MaxPerTxAmount must be >= l1MaxPerTxAmount");
1195
+ if (l2Max !== void 0 && l1Max === void 0 && l2Max < l0PerTx) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l2MaxPerTxAmount must be >= l0MaxPerTxAmount");
1196
+ return {
1197
+ chainId: cid.toString(10),
1198
+ asset: normalizedAsset,
1199
+ l0MaxPerTxAmount: l0PerTx.toString(10),
1200
+ l0MaxRolling24hAmount: l0Roll.toString(10),
1201
+ ...l1Max !== void 0 ? { l1MaxPerTxAmount: l1Max.toString(10) } : {},
1202
+ ...l2Max !== void 0 ? { l2MaxPerTxAmount: l2Max.toString(10) } : {}
1203
+ };
1204
+ }).sort((a, b) => `${a.chainId}:${a.asset}`.localeCompare(`${b.chainId}:${b.asset}`));
1205
+ if (!Number.isInteger(policy.timelockDelaySec) || policy.timelockDelaySec < 1 || policy.timelockDelaySec > 2592e3) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "timelockDelaySec must be 1..2592000");
1206
+ const roleRosters = {};
1207
+ if (policy.roleRosters) for (const roleKey of Object.keys(policy.roleRosters).sort()) {
1208
+ const r = policy.roleRosters[roleKey];
1209
+ assertPrintableIdentifierAscii(r.role, 64, "roleRoster.role", "PERSONAL_POLICY_VIOLATION");
1210
+ if (r.role !== roleKey) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `roleRosters key "${roleKey}" != role "${r.role}"`);
1211
+ roleRosters[roleKey] = {
1212
+ role: r.role,
1213
+ threshold: r.threshold,
1214
+ members: normalizeRosterMembers(r.threshold, r.members, `roleRosters[${roleKey}]`)
1215
+ };
1216
+ }
1217
+ if (policy.defaultRoleForL2 !== void 0 && !roleRosters[policy.defaultRoleForL2]) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "defaultRoleForL2 must reference a defined roleRoster");
1218
+ if (policy.defaultRoleForL3 !== void 0 && !roleRosters[policy.defaultRoleForL3]) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "defaultRoleForL3 must reference a defined roleRoster");
1219
+ if (Object.keys(roleRosters).length > 1 && policy.defaultRoleForL2 === void 0 && policy.defaultRoleForL3 === void 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "defaultRoleForL2 must be explicitly specified when roleRosters defines multiple roles");
1220
+ const guardianRoster = policy.guardianRoster ? {
1221
+ threshold: policy.guardianRoster.threshold,
1222
+ members: normalizeRosterMembers(policy.guardianRoster.threshold, policy.guardianRoster.members, "guardianRoster")
1223
+ } : void 0;
1224
+ const emergencyExitAddress = policy.emergencyExitAddress !== void 0 ? require_tweak.parseStrictEthAddress(policy.emergencyExitAddress).checksumAddress : void 0;
1225
+ const emergencyExitOcapAddress = policy.emergencyExitOcapAddress !== void 0 ? normalizeOcapAddressOrEth(policy.emergencyExitOcapAddress, "emergencyExitOcapAddress") : void 0;
1226
+ const seenOcapAssetKeys = /* @__PURE__ */ new Set();
1227
+ const ocapAssetLimits = (policy.ocapAssetLimits ?? []).map((lim) => {
1228
+ assertPrintableIdentifierAscii(lim.chainId, 64, "ocapAssetLimit.chainId", "PERSONAL_POLICY_VIOLATION");
1229
+ const normalizedAsset = lim.asset === "native" ? "native" : normalizeCanonicalOcapTokenKey(lim.asset, "ocapAssetLimit.asset");
1230
+ const key = `${lim.chainId}:${normalizedAsset}`;
1231
+ if (seenOcapAssetKeys.has(key)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Duplicate ocapAssetLimit entry for ${key}`);
1232
+ seenOcapAssetKeys.add(key);
1233
+ const l0PerTx = parseStrictNonNegativeBigInt(lim.l0MaxPerTxAmount, MAX_UINT128, "ocap.l0MaxPerTxAmount");
1234
+ const l0Roll = parseStrictNonNegativeBigInt(lim.l0MaxRolling24hAmount, MAX_UINT128, "ocap.l0MaxRolling24hAmount");
1235
+ if (l0Roll < l0PerTx) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l0MaxRolling24hAmount must be >= l0MaxPerTxAmount");
1236
+ const l1Max = lim.l1MaxPerTxAmount !== void 0 ? parseStrictNonNegativeBigInt(lim.l1MaxPerTxAmount, MAX_UINT128, "ocap.l1MaxPerTxAmount") : void 0;
1237
+ const l2Max = lim.l2MaxPerTxAmount !== void 0 ? parseStrictNonNegativeBigInt(lim.l2MaxPerTxAmount, MAX_UINT128, "ocap.l2MaxPerTxAmount") : void 0;
1238
+ if (l1Max !== void 0 && l1Max < l0PerTx) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l1MaxPerTxAmount must be >= l0MaxPerTxAmount");
1239
+ if (l2Max !== void 0 && l1Max !== void 0 && l2Max < l1Max) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l2MaxPerTxAmount must be >= l1MaxPerTxAmount");
1240
+ if (l2Max !== void 0 && l1Max === void 0 && l2Max < l0PerTx) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l2MaxPerTxAmount must be >= l0MaxPerTxAmount");
1241
+ return {
1242
+ chainId: lim.chainId,
1243
+ asset: normalizedAsset,
1244
+ l0MaxPerTxAmount: l0PerTx.toString(10),
1245
+ l0MaxRolling24hAmount: l0Roll.toString(10),
1246
+ ...l1Max !== void 0 ? { l1MaxPerTxAmount: l1Max.toString(10) } : {},
1247
+ ...l2Max !== void 0 ? { l2MaxPerTxAmount: l2Max.toString(10) } : {}
1248
+ };
1249
+ }).sort((a, b) => `${a.chainId}:${a.asset}`.localeCompare(`${b.chainId}:${b.asset}`));
1250
+ const ocapPrimaryTokenByChainId = {};
1251
+ if (policy.ocapPrimaryTokenByChainId) {
1252
+ assertPlainSimulationRecord(policy.ocapPrimaryTokenByChainId, "ocapPrimaryTokenByChainId");
1253
+ for (const chainKey of Object.keys(policy.ocapPrimaryTokenByChainId).sort()) {
1254
+ assertPrintableIdentifierAscii(chainKey, 64, "ocapPrimaryTokenByChainId.key", "PERSONAL_POLICY_VIOLATION");
1255
+ const rawTok = policy.ocapPrimaryTokenByChainId[chainKey];
1256
+ ocapPrimaryTokenByChainId[chainKey] = normalizeCanonicalOcapTokenKey(rawTok, `ocapPrimaryTokenByChainId[${chainKey}]`);
1257
+ }
1258
+ }
1259
+ const ocapGasConfigByChainId = {};
1260
+ if (policy.ocapGasConfigByChainId !== void 0) {
1261
+ assertPlainSimulationRecord(policy.ocapGasConfigByChainId, "ocapGasConfigByChainId");
1262
+ for (const chainKey of Object.keys(policy.ocapGasConfigByChainId).sort()) {
1263
+ assertPrintableIdentifierAscii(chainKey, 64, "ocapGasConfigByChainId.key", "PERSONAL_POLICY_VIOLATION");
1264
+ const rawCfg = policy.ocapGasConfigByChainId[chainKey];
1265
+ assertPlainSimulationRecord(rawCfg, `ocapGasConfigByChainId[${chainKey}]`);
1266
+ const price = parseStrictNonNegativeBigInt(rawCfg.price, MAX_UINT128, `ocapGasConfig[${chainKey}].price`);
1267
+ const dataStorage = rawCfg.dataStorage !== void 0 ? parseStrictNonNegativeBigInt(rawCfg.dataStorage, MAX_UINT64, `ocapGasConfig[${chainKey}].dataStorage`) : price > 0n ? 0n : 1n;
1268
+ const createState = rawCfg.createState !== void 0 ? parseStrictNonNegativeBigInt(rawCfg.createState, MAX_UINT64, `ocapGasConfig[${chainKey}].createState`) : price > 0n ? 0n : 1n;
1269
+ const updateState = rawCfg.updateState !== void 0 ? parseStrictNonNegativeBigInt(rawCfg.updateState, MAX_UINT64, `ocapGasConfig[${chainKey}].updateState`) : price > 0n ? 0n : 1n;
1270
+ if (price > 0n && (dataStorage < 1n || createState < 1n || updateState < 1n)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `ocapGasConfigByChainId[${chainKey}] with price > 0 requires positive dataStorage, createState, and updateState`);
1271
+ let txFeeBaseUnitsByType;
1272
+ if (rawCfg.txFeeBaseUnitsByType !== void 0) {
1273
+ assertPlainSimulationRecord(rawCfg.txFeeBaseUnitsByType, `ocapGasConfig[${chainKey}].txFeeBaseUnitsByType`);
1274
+ txFeeBaseUnitsByType = {};
1275
+ for (const feeKey of Object.keys(rawCfg.txFeeBaseUnitsByType).sort()) {
1276
+ assertPrintableIdentifierAscii(feeKey, 64, "txFeeBaseUnitsByType.key", "PERSONAL_POLICY_VIOLATION");
1277
+ const feeVal = parseStrictNonNegativeBigInt(rawCfg.txFeeBaseUnitsByType[feeKey], MAX_UINT128, `txFeeBaseUnitsByType[${feeKey}]`);
1278
+ txFeeBaseUnitsByType[feeKey] = feeVal.toString(10);
1279
+ }
1280
+ }
1281
+ let signedEnvelopeOverheadBytes;
1282
+ if (rawCfg.signedEnvelopeOverheadBytes !== void 0) {
1283
+ if (!Number.isSafeInteger(rawCfg.signedEnvelopeOverheadBytes) || rawCfg.signedEnvelopeOverheadBytes < 72 || rawCfg.signedEnvelopeOverheadBytes > 4096) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `ocapGasConfig[${chainKey}].signedEnvelopeOverheadBytes must be an integer in 72..4096`);
1284
+ signedEnvelopeOverheadBytes = rawCfg.signedEnvelopeOverheadBytes;
1285
+ }
1286
+ ocapGasConfigByChainId[chainKey] = {
1287
+ price: price.toString(10),
1288
+ dataStorage: dataStorage.toString(10),
1289
+ createState: createState.toString(10),
1290
+ updateState: updateState.toString(10),
1291
+ ...txFeeBaseUnitsByType && Object.keys(txFeeBaseUnitsByType).length > 0 ? { txFeeBaseUnitsByType } : {},
1292
+ ...signedEnvelopeOverheadBytes !== void 0 ? { signedEnvelopeOverheadBytes } : {}
1293
+ };
1294
+ }
1295
+ }
1296
+ for (const allowedChain of allowedOcapChainIds) if (!ocapGasConfigByChainId[allowedChain]) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `allowedOcapChainIds entry "${allowedChain}" requires an explicit trusted ocapGasConfigByChainId["${allowedChain}"] bound`);
1297
+ const issuerSet = /* @__PURE__ */ new Set();
1298
+ for (const hexKey of policy.entitlementIssuerPublicKeysHex ?? []) {
1299
+ const pub32 = require_secp256k1_scalar.normalizeHexBytes(hexKey, 32);
1300
+ validateEd25519PublicKeyNonTorsion32(pub32, "PERSONAL_POLICY_VIOLATION");
1301
+ issuerSet.add(`0x${(0, _noble_hashes_utils_js.bytesToHex)(pub32)}`);
1302
+ }
1303
+ const entitlementIssuerPublicKeysHex = [...issuerSet].sort();
1304
+ if (policy.requireEntitlement && entitlementIssuerPublicKeysHex.length === 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "requireEntitlement=true requires at least one entitlementIssuerPublicKeysHex");
1305
+ const firewallVerifierSet = /* @__PURE__ */ new Set();
1306
+ for (const hexKey of policy.firewallVerifierPublicKeysHex ?? []) {
1307
+ const pub32 = require_secp256k1_scalar.normalizeHexBytes(hexKey, 32);
1308
+ validateEd25519PublicKeyNonTorsion32(pub32, "PERSONAL_POLICY_VIOLATION");
1309
+ firewallVerifierSet.add(`0x${(0, _noble_hashes_utils_js.bytesToHex)(pub32)}`);
1310
+ }
1311
+ const firewallVerifierPublicKeysHex = [...firewallVerifierSet].sort();
1312
+ if (policy.requireFirewallAttestation && firewallVerifierPublicKeysHex.length === 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "requireFirewallAttestation=true requires at least one firewallVerifierPublicKeysHex");
1313
+ const canonicalPolicy = {
1314
+ version: 1,
1315
+ vaultId: policy.vaultId,
1316
+ allowedChainIds,
1317
+ ...allowedOcapChainIds.length > 0 ? { allowedOcapChainIds } : {},
1318
+ ...allowedOcapTxTypes.length > 0 ? { allowedOcapTxTypes } : {},
1319
+ allowedPayees,
1320
+ ...allowedOcapPayees.length > 0 ? { allowedOcapPayees } : {},
1321
+ enforcePayeeAllowlistInL0: Boolean(policy.enforcePayeeAllowlistInL0),
1322
+ allowedContracts,
1323
+ assetLimits,
1324
+ ...ocapAssetLimits.length > 0 ? { ocapAssetLimits } : {},
1325
+ ...Object.keys(ocapPrimaryTokenByChainId).length > 0 ? { ocapPrimaryTokenByChainId } : {},
1326
+ ...Object.keys(ocapGasConfigByChainId).length > 0 ? { ocapGasConfigByChainId } : {},
1327
+ timelockDelaySec: policy.timelockDelaySec,
1328
+ allowUnlimitedApproveByQuorum: Boolean(policy.allowUnlimitedApproveByQuorum),
1329
+ ...policy.allowArcblockJwt ? { allowArcblockJwt: true } : {},
1330
+ ...policy.allowDelegationTokenByQuorum ? { allowDelegationTokenByQuorum: true } : {},
1331
+ ...policy.defaultRoleForL2 !== void 0 ? { defaultRoleForL2: policy.defaultRoleForL2 } : {},
1332
+ ...policy.defaultRoleForL3 !== void 0 ? { defaultRoleForL3: policy.defaultRoleForL3 } : {},
1333
+ roleRosters,
1334
+ ...guardianRoster !== void 0 ? { guardianRoster } : {},
1335
+ ...emergencyExitAddress !== void 0 ? { emergencyExitAddress } : {},
1336
+ ...emergencyExitOcapAddress !== void 0 ? { emergencyExitOcapAddress } : {},
1337
+ requireEntitlement: Boolean(policy.requireEntitlement),
1338
+ entitlementIssuerPublicKeysHex,
1339
+ ...policy.requireFirewallAttestation ? { requireFirewallAttestation: true } : {},
1340
+ ...firewallVerifierPublicKeysHex.length > 0 ? { firewallVerifierPublicKeysHex } : {}
1341
+ };
1342
+ const canonicalPolicyJson = deterministicJsonStringify(canonicalPolicy);
1343
+ const canonicalPolicyUtf8 = require_secp256k1_scalar.utf8Bytes(canonicalPolicyJson);
1344
+ if (canonicalPolicyUtf8.length > HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Canonical PersonalVaultPolicy (${canonicalPolicyUtf8.length}B) exceeds ${HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES}B limit`);
1345
+ return {
1346
+ canonicalPolicy,
1347
+ canonicalPolicyJson,
1348
+ canonicalPolicyUtf8,
1349
+ policyHash32: (0, _noble_hashes_sha2_js.sha256)(require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_POLICY_V1, [canonicalPolicyUtf8]))
1350
+ };
1351
+ }
1352
+ function computePersonalPolicyHash32(policy) {
1353
+ if (typeof policy === "string") return canonicalizePersonalVaultPolicy(JSON.parse(policy)).policyHash32;
1354
+ return canonicalizePersonalVaultPolicy(policy).policyHash32;
1355
+ }
1356
+ function decodeRawUnsignedEip1559Bytes(rawBytes) {
1357
+ assertNoEip7702Bytes(rawBytes);
1358
+ const decoded = require_rlp_eip1559.rlpDecode(rawBytes.subarray(1));
1359
+ if (!Array.isArray(decoded) || decoded.length !== 9) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Unsigned EIP-1559 RLP list must have 9 elements");
1360
+ for (let i = 0; i < 9; i++) if (i === 8) {
1361
+ if (!Array.isArray(decoded[8])) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "accessList must be an RLP list");
1362
+ } else if (!(decoded[i] instanceof Uint8Array)) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", `Field ${i} must be an RLP byte string`);
1363
+ const parseCanonicalUint = (b, label) => {
1364
+ if (b.length > 32 || b.length > 0 && b[0] === 0) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", `Non-canonical RLP integer in ${label}`);
1365
+ return require_secp256k1_scalar.bytesToBigIntBE(b);
1366
+ };
1367
+ const toBytes = decoded[5];
1368
+ if (toBytes.length === 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Contract creation transactions are forbidden");
1369
+ if (toBytes.length !== 20) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Destination address must be 20 bytes");
1370
+ const toHex = (0, _noble_hashes_utils_js.bytesToHex)(toBytes);
1371
+ if (/^0+$/.test(toHex)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Zero destination address is forbidden");
1372
+ const accessList = decoded[8].map((entry) => {
1373
+ if (!Array.isArray(entry) || entry.length !== 2 || !(entry[0] instanceof Uint8Array) || !Array.isArray(entry[1])) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid accessList item");
1374
+ if (entry[0].length !== 20) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid accessList address length");
1375
+ return {
1376
+ address: require_tweak.toEip55ChecksumAddress((0, _noble_hashes_utils_js.bytesToHex)(entry[0])),
1377
+ storageKeys: entry[1].map((sk) => {
1378
+ if (!(sk instanceof Uint8Array) || sk.length !== 32) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid accessList storageKey");
1379
+ return new Uint8Array(sk);
1380
+ })
1381
+ };
1382
+ });
1383
+ const fields = {
1384
+ chainId: parseCanonicalUint(decoded[0], "chainId"),
1385
+ nonce: parseCanonicalUint(decoded[1], "nonce"),
1386
+ maxPriorityFeePerGasWei: parseCanonicalUint(decoded[2], "maxPriorityFeePerGasWei"),
1387
+ maxFeePerGasWei: parseCanonicalUint(decoded[3], "maxFeePerGasWei"),
1388
+ gasLimit: parseCanonicalUint(decoded[4], "gasLimit"),
1389
+ to: require_tweak.toEip55ChecksumAddress(toHex),
1390
+ valueWei: parseCanonicalUint(decoded[6], "valueWei"),
1391
+ data: new Uint8Array(decoded[7]),
1392
+ accessList
1393
+ };
1394
+ if (!require_secp256k1_scalar.constantTimeEqual(rawBytes, require_rlp_eip1559.encodeUnsignedEip1559Tx(fields).unsignedPayloadBytes)) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Non-canonical unsigned EIP-1559 RLP encoding");
1395
+ return fields;
1396
+ }
1397
+ function decodeAndVerifyPersonalEip1559Tx(params) {
1398
+ let txFields;
1399
+ if (params.txOrRawBytes instanceof Uint8Array || typeof params.txOrRawBytes === "string") txFields = decodeRawUnsignedEip1559Bytes(assertNoEip7702Bytes(params.txOrRawBytes));
1400
+ else {
1401
+ txFields = params.txOrRawBytes;
1402
+ if (!txFields || typeof txFields !== "object") throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing EIP-1559 transaction fields");
1403
+ if (typeof txFields.to !== "string" || txFields.to.trim() === "" || txFields.to === "0x") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Contract creation transactions are forbidden");
1404
+ }
1405
+ const encoded = require_rlp_eip1559.encodeUnsignedEip1559Tx(txFields);
1406
+ const dataBytes = txFields.data === void 0 || txFields.data === "0x" || txFields.data === "" ? new Uint8Array(0) : require_secp256k1_scalar.normalizeHexBytes(txFields.data);
1407
+ if (dataBytes.length > require_constants.MAX_PERSONAL_TX_DATA_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Transaction calldata (${dataBytes.length}B) exceeds MAX_PERSONAL_TX_DATA_BYTES (${require_constants.MAX_PERSONAL_TX_DATA_BYTES}B)`);
1408
+ if (dataBytes.length > 0 && dataBytes.length < 4) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Truncated 1..3 byte EVM function selector is forbidden");
1409
+ const canonicalPolicy = params.policy ? "enforcePayeeAllowlistInL0" in params.policy && Array.isArray(params.policy.allowedChainIds) && params.policy.allowedChainIds.every((c) => typeof c === "string") ? params.policy : canonicalizePersonalVaultPolicy(params.policy).canonicalPolicy : void 0;
1410
+ if (canonicalPolicy && !canonicalPolicy.allowedChainIds.includes(txFields.chainId.toString(10))) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `ChainId ${txFields.chainId} is not allowlisted by policy`);
1411
+ const maxGasFeeWei = txFields.gasLimit * txFields.maxFeePerGasWei;
1412
+ if (maxGasFeeWei > MAX_UINT256) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "maxGasFeeWei (gasLimit * maxFeePerGasWei) overflows uint256");
1413
+ if (dataBytes.length === 0) {
1414
+ if (txFields.valueWei + maxGasFeeWei > MAX_UINT256) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "valueWei + maxGasFeeWei overflows uint256");
1415
+ return {
1416
+ txFields,
1417
+ unsignedPayloadBytes: encoded.unsignedPayloadBytes,
1418
+ signingDigest32: encoded.signingDigest32,
1419
+ signingDigestHex: encoded.signingDigestHex,
1420
+ toChecksumAddress: encoded.toChecksumAddress,
1421
+ callKind: "native-transfer",
1422
+ selector4Lower: "0x",
1423
+ velocityAssetKey: "native",
1424
+ velocityAmount: txFields.valueWei,
1425
+ maxGasFeeWei,
1426
+ payeeOrSpenderChecksumAddress: encoded.toChecksumAddress,
1427
+ isUnlimitedApprove: false,
1428
+ callDepth: require_constants.MAX_PERSONAL_CALL_DEPTH
1429
+ };
1430
+ }
1431
+ const selector4Hex = (0, _noble_hashes_utils_js.bytesToHex)(dataBytes.subarray(0, 4)).toLowerCase();
1432
+ const selector4Lower = `0x${selector4Hex}`;
1433
+ if (HARD_BANNED_PERSONAL_EVM_SELECTORS.has(selector4Lower)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Dangerous EVM selector ${selector4Lower} is hard-banned on MPC-secured EOAs`);
1434
+ if (selector4Hex === require_rlp_eip1559.ERC20_TRANSFER_SELECTOR_HEX) {
1435
+ if (txFields.valueWei !== 0n) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "ERC-20 transfer must have valueWei === 0n");
1436
+ const decodedTransfer = require_rlp_eip1559.decodeErc20TransferCalldata(dataBytes);
1437
+ return {
1438
+ txFields,
1439
+ unsignedPayloadBytes: encoded.unsignedPayloadBytes,
1440
+ signingDigest32: encoded.signingDigest32,
1441
+ signingDigestHex: encoded.signingDigestHex,
1442
+ toChecksumAddress: encoded.toChecksumAddress,
1443
+ callKind: "erc20-transfer",
1444
+ selector4Lower,
1445
+ velocityAssetKey: encoded.toChecksumAddress.toLowerCase(),
1446
+ velocityAmount: decodedTransfer.tokenAmount,
1447
+ maxGasFeeWei,
1448
+ payeeOrSpenderChecksumAddress: decodedTransfer.recipientChecksumAddress,
1449
+ isUnlimitedApprove: false,
1450
+ callDepth: require_constants.MAX_PERSONAL_CALL_DEPTH
1451
+ };
1452
+ }
1453
+ if (selector4Hex === ERC20_APPROVE_SELECTOR_HEX) {
1454
+ if (txFields.valueWei !== 0n) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "ERC-20 approve must have valueWei === 0n");
1455
+ const decodedApprove = decodeErc20ApproveCalldata(dataBytes);
1456
+ if (decodedApprove.isUnlimitedApprove && (!params.allowPolicyBlindCustomCalldata || canonicalPolicy)) {
1457
+ if (!(Boolean(canonicalPolicy?.allowUnlimitedApproveByQuorum) && Boolean(params.hasL2OrL3QuorumProof))) throw new require_constants.MpcProtocolError("PERSONAL_UNLIMITED_APPROVE_FORBIDDEN", "ERC-20 approve >= 2^255 is forbidden without allowUnlimitedApproveByQuorum + L2/L3 quorum proof");
1458
+ }
1459
+ return {
1460
+ txFields,
1461
+ unsignedPayloadBytes: encoded.unsignedPayloadBytes,
1462
+ signingDigest32: encoded.signingDigest32,
1463
+ signingDigestHex: encoded.signingDigestHex,
1464
+ toChecksumAddress: encoded.toChecksumAddress,
1465
+ callKind: "erc20-approve",
1466
+ selector4Lower,
1467
+ velocityAssetKey: encoded.toChecksumAddress.toLowerCase(),
1468
+ velocityAmount: decodedApprove.allowanceAmount,
1469
+ maxGasFeeWei,
1470
+ payeeOrSpenderChecksumAddress: decodedApprove.spenderChecksumAddress,
1471
+ isUnlimitedApprove: decodedApprove.isUnlimitedApprove,
1472
+ callDepth: require_constants.MAX_PERSONAL_CALL_DEPTH
1473
+ };
1474
+ }
1475
+ if (canonicalPolicy) {
1476
+ const matchingContract = canonicalPolicy.allowedContracts.find((c) => c.chainId === txFields.chainId.toString(10) && c.address === encoded.toChecksumAddress && c.selectors.includes(selector4Lower));
1477
+ if (!matchingContract) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Contract call (${txFields.chainId}, ${encoded.toChecksumAddress}, ${selector4Lower}) is not allowlisted`);
1478
+ if (txFields.valueWei > BigInt(matchingContract.maxValueWei)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Contract call valueWei (${txFields.valueWei}) exceeds rule maxValueWei (${matchingContract.maxValueWei})`);
1479
+ } else if (!params.allowPolicyBlindCustomCalldata) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Custom calldata selector ${selector4Lower} requires an explicit PersonalVaultPolicy allowlist`);
1480
+ if (txFields.valueWei + maxGasFeeWei > MAX_UINT256) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "valueWei + maxGasFeeWei overflows uint256");
1481
+ return {
1482
+ txFields,
1483
+ unsignedPayloadBytes: encoded.unsignedPayloadBytes,
1484
+ signingDigest32: encoded.signingDigest32,
1485
+ signingDigestHex: encoded.signingDigestHex,
1486
+ toChecksumAddress: encoded.toChecksumAddress,
1487
+ callKind: "allowlisted-contract-call",
1488
+ selector4Lower,
1489
+ velocityAssetKey: "native",
1490
+ velocityAmount: txFields.valueWei,
1491
+ maxGasFeeWei,
1492
+ payeeOrSpenderChecksumAddress: encoded.toChecksumAddress,
1493
+ isUnlimitedApprove: false,
1494
+ callDepth: require_constants.MAX_PERSONAL_CALL_DEPTH
1495
+ };
1496
+ }
1497
+ function buildPersonalClearSigningPreview(params) {
1498
+ const fromChecksum = require_tweak.parseStrictEthAddress(params.fromAddress).checksumAddress;
1499
+ const { verifiedTx } = params;
1500
+ const { txFields } = verifiedTx;
1501
+ const maxGasFeeWei = txFields.gasLimit * txFields.maxFeePerGasWei;
1502
+ let summaryText;
1503
+ if (verifiedTx.callKind === "native-transfer") summaryText = `Pay ${verifiedTx.velocityAmount.toString(10)} wei native on chain ${txFields.chainId.toString(10)} to ${verifiedTx.payeeOrSpenderChecksumAddress}`;
1504
+ else if (verifiedTx.callKind === "erc20-transfer") summaryText = `Transfer ${verifiedTx.velocityAmount.toString(10)} units of token ${verifiedTx.toChecksumAddress} on chain ${txFields.chainId.toString(10)} to ${verifiedTx.payeeOrSpenderChecksumAddress}`;
1505
+ else if (verifiedTx.callKind === "erc20-approve") summaryText = `Approve spender ${verifiedTx.payeeOrSpenderChecksumAddress} for ${verifiedTx.velocityAmount.toString(10)} units of token ${verifiedTx.toChecksumAddress} on chain ${txFields.chainId.toString(10)}`;
1506
+ else summaryText = `Call ${verifiedTx.selector4Lower} on ${verifiedTx.toChecksumAddress} (value ${txFields.valueWei.toString(10)} wei) on chain ${txFields.chainId.toString(10)}`;
1507
+ return {
1508
+ version: 1,
1509
+ chainId: txFields.chainId.toString(10),
1510
+ fromAddress: fromChecksum,
1511
+ toAddress: verifiedTx.toChecksumAddress,
1512
+ callKind: verifiedTx.callKind,
1513
+ selector: verifiedTx.selector4Lower,
1514
+ payeeOrSpenderAddress: verifiedTx.payeeOrSpenderChecksumAddress,
1515
+ assetIdentifier: verifiedTx.velocityAssetKey,
1516
+ outflowAmount: verifiedTx.velocityAmount.toString(10),
1517
+ maxGasFeeWei: maxGasFeeWei.toString(10),
1518
+ nonce: txFields.nonce.toString(10),
1519
+ signingDigestHex: verifiedTx.signingDigestHex,
1520
+ summaryText
1521
+ };
1522
+ }
1523
+ function computePersonalClearSigningPreviewHash32(preview) {
1524
+ return (0, _noble_hashes_sha2_js.sha256)(require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_CLEAR_PREVIEW_V1, [require_secp256k1_scalar.utf8Bytes(deterministicJsonStringify(preview))]));
1525
+ }
1526
+ const FORBIDDEN_SIMULATION_KEYS = new Set([
1527
+ "__proto__",
1528
+ "constructor",
1529
+ "prototype"
1530
+ ]);
1531
+ function assertPlainSimulationRecord(value, label) {
1532
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label} must be a plain object`);
1533
+ const proto = Object.getPrototypeOf(value);
1534
+ if (proto !== null && proto !== Object.prototype) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label} must be a plain object`);
1535
+ for (const key of Object.getOwnPropertyNames(value)) if (FORBIDDEN_SIMULATION_KEYS.has(key)) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Forbidden property "${key}" in ${label}`);
1536
+ return value;
1537
+ }
1538
+ function assertNonNegativeSimulationBigInt(value, label) {
1539
+ if (typeof value !== "bigint" || value < 0n || value > MAX_UINT256) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label} must be a non-negative bigint within uint256`);
1540
+ return value;
1541
+ }
1542
+ function assertSignedSimulationBigInt(value, label) {
1543
+ if (typeof value !== "bigint" || value < -MAX_UINT256 || value > MAX_UINT256) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label} must be a signed bigint within [-2^256+1, 2^256-1]`);
1544
+ return value;
1545
+ }
1546
+ function assertOptionalSimulationStringArray(value, label) {
1547
+ if (value === void 0) return void 0;
1548
+ if (!Array.isArray(value)) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label} must be an array of strings`);
1549
+ for (let i = 0; i < value.length; i++) if (typeof value[i] !== "string" || value[i].length === 0) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label}[${i}] must be a non-empty string`);
1550
+ return value;
1551
+ }
1552
+ function normalizeSimulationTokenAddress(tokenAddr, label) {
1553
+ if (typeof tokenAddr !== "string" || tokenAddr.length === 0 || tokenAddr.length > 128) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Invalid token address in ${label}`);
1554
+ const stripped = tokenAddr.replace(/^did:[a-z0-9]+:/, "");
1555
+ if (stripped.startsWith("0x") || stripped.startsWith("0X")) {
1556
+ const colonIdx = stripped.indexOf(":");
1557
+ if (colonIdx !== -1) {
1558
+ const addrPart = stripped.slice(0, colonIdx);
1559
+ const idPart = stripped.slice(colonIdx + 1);
1560
+ if (!/^(?:0|[1-9][0-9]{0,77}|batch)$/.test(idPart)) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Invalid ERC-1155 tokenId in ${label}`);
1561
+ try {
1562
+ return `${require_tweak.parseStrictEthAddress(addrPart).lowercaseAddress}:${idPart}`;
1563
+ } catch {
1564
+ throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Invalid EVM ERC-1155 contract in ${label}`);
1565
+ }
1566
+ }
1567
+ try {
1568
+ return require_tweak.parseStrictEthAddress(stripped).lowercaseAddress;
1569
+ } catch {
1570
+ throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Invalid EVM token address in ${label}`);
1571
+ }
1572
+ }
1573
+ if (!OCAP_BASE58_BODY_RE.test(stripped)) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Invalid token address in ${label}`);
1574
+ return stripped;
1575
+ }
1576
+ function normalizeMaxTokenOutflowsCaps(maxTokenOutflows) {
1577
+ const allowedTokenMax = /* @__PURE__ */ new Map();
1578
+ if (maxTokenOutflows === void 0) return allowedTokenMax;
1579
+ const rawMaxMap = assertPlainSimulationRecord(maxTokenOutflows, "postConditions.maxTokenOutflows");
1580
+ for (const tokenAddr of Object.keys(rawMaxMap)) {
1581
+ const cap = assertNonNegativeSimulationBigInt(rawMaxMap[tokenAddr], `maxTokenOutflows[${tokenAddr}]`);
1582
+ const tokenLower = normalizeSimulationTokenAddress(tokenAddr, "postConditions.maxTokenOutflows");
1583
+ const existingCap = allowedTokenMax.get(tokenLower);
1584
+ if (existingCap !== void 0 && existingCap !== cap) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Conflicting duplicate token entry in maxTokenOutflows for ${tokenLower}`);
1585
+ allowedTokenMax.set(tokenLower, cap);
1586
+ }
1587
+ return allowedTokenMax;
1588
+ }
1589
+ function verifyPersonalSimulationBalanceDelta(params) {
1590
+ if (!params || typeof params !== "object") throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", "Missing postConditions or simulatedDelta");
1591
+ const { postConditions, simulatedDelta } = params;
1592
+ assertPlainSimulationRecord(postConditions, "postConditions");
1593
+ assertPlainSimulationRecord(simulatedDelta, "simulatedDelta");
1594
+ if (typeof postConditions.strictZeroUnlistedOutflow !== "boolean") throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", "postConditions.strictZeroUnlistedOutflow must be a boolean");
1595
+ if (simulatedDelta.simulationReverted !== void 0 && typeof simulatedDelta.simulationReverted !== "boolean") throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", "simulatedDelta.simulationReverted must be a boolean when provided");
1596
+ if (simulatedDelta.simulationReverted) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", "Dry-run transaction simulation reverted");
1597
+ const maxNativeOutflowWei = assertNonNegativeSimulationBigInt(postConditions.maxNativeOutflowWei, "postConditions.maxNativeOutflowWei");
1598
+ const minNativeInflowWei = postConditions.minNativeInflowWei !== void 0 ? assertNonNegativeSimulationBigInt(postConditions.minNativeInflowWei, "postConditions.minNativeInflowWei") : void 0;
1599
+ const nativeDeltaWei = assertSignedSimulationBigInt(simulatedDelta.nativeDeltaWei, "simulatedDelta.nativeDeltaWei");
1600
+ const nativeOutflow = nativeDeltaWei < 0n ? -nativeDeltaWei : 0n;
1601
+ const nativeInflow = nativeDeltaWei > 0n ? nativeDeltaWei : 0n;
1602
+ if (nativeOutflow > maxNativeOutflowWei) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Simulated native outflow (${nativeOutflow}) exceeds maxNativeOutflowWei (${maxNativeOutflowWei})`);
1603
+ if (minNativeInflowWei !== void 0 && nativeInflow < minNativeInflowWei) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Simulated native inflow (${nativeInflow}) below minNativeInflowWei (${minNativeInflowWei})`);
1604
+ const allowedTokenMax = /* @__PURE__ */ new Map();
1605
+ if (postConditions.maxTokenOutflows !== void 0) {
1606
+ const rawMaxMap = assertPlainSimulationRecord(postConditions.maxTokenOutflows, "postConditions.maxTokenOutflows");
1607
+ for (const tokenAddr of Object.keys(rawMaxMap)) {
1608
+ const cap = assertNonNegativeSimulationBigInt(rawMaxMap[tokenAddr], `maxTokenOutflows[${tokenAddr}]`);
1609
+ const tokenLower = normalizeSimulationTokenAddress(tokenAddr, "postConditions.maxTokenOutflows");
1610
+ const existingCap = allowedTokenMax.get(tokenLower);
1611
+ if (existingCap !== void 0 && existingCap !== cap) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Conflicting duplicate token entry in maxTokenOutflows for ${tokenLower}`);
1612
+ allowedTokenMax.set(tokenLower, cap);
1613
+ }
1614
+ }
1615
+ const normalizedSimTokens = /* @__PURE__ */ new Map();
1616
+ if (simulatedDelta.tokenDeltas !== void 0) {
1617
+ const rawDeltaMap = assertPlainSimulationRecord(simulatedDelta.tokenDeltas, "simulatedDelta.tokenDeltas");
1618
+ for (const tokenAddr of Object.keys(rawDeltaMap)) {
1619
+ const delta = assertSignedSimulationBigInt(rawDeltaMap[tokenAddr], `tokenDeltas[${tokenAddr}]`);
1620
+ const key = normalizeSimulationTokenAddress(tokenAddr, "simulatedDelta.tokenDeltas");
1621
+ normalizedSimTokens.set(key, (normalizedSimTokens.get(key) ?? 0n) + delta);
1622
+ }
1623
+ }
1624
+ for (const [tokenLower, delta] of normalizedSimTokens) if (delta < 0n) {
1625
+ const outflow = -delta;
1626
+ const cap = allowedTokenMax.get(tokenLower);
1627
+ if (cap === void 0) {
1628
+ if (postConditions.strictZeroUnlistedOutflow) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Unlisted token outflow (${outflow}) detected on ${tokenLower}`);
1629
+ } else if (outflow > cap) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Token ${tokenLower} outflow (${outflow}) exceeds maxTokenOutflows (${cap})`);
1630
+ }
1631
+ if (postConditions.minTokenInflows !== void 0) {
1632
+ const rawMinInMap = assertPlainSimulationRecord(postConditions.minTokenInflows, "postConditions.minTokenInflows");
1633
+ for (const tokenAddr of Object.keys(rawMinInMap)) {
1634
+ const minIn = assertNonNegativeSimulationBigInt(rawMinInMap[tokenAddr], `minTokenInflows[${tokenAddr}]`);
1635
+ const key = normalizeSimulationTokenAddress(tokenAddr, "postConditions.minTokenInflows");
1636
+ const actualDelta = normalizedSimTokens.get(key) ?? 0n;
1637
+ const actualInflow = actualDelta > 0n ? actualDelta : 0n;
1638
+ if (actualInflow < minIn) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Token ${key} inflow (${actualInflow}) below minTokenInflows (${minIn})`);
1639
+ }
1640
+ }
1641
+ const allowedOutgoing = assertOptionalSimulationStringArray(postConditions.allowedOutgoingAssets, "postConditions.allowedOutgoingAssets");
1642
+ const outgoingIds = assertOptionalSimulationStringArray(simulatedDelta.outgoingAssetIds, "simulatedDelta.outgoingAssetIds");
1643
+ const normalizeAssetEntry = (rawAsset) => {
1644
+ if ((rawAsset.startsWith("0x") || rawAsset.startsWith("0X")) && rawAsset.includes(":")) return normalizeSimulationTokenAddress(rawAsset, "assetId");
1645
+ return rawAsset;
1646
+ };
1647
+ const allowedOutgoingSet = new Set((allowedOutgoing ?? []).map(normalizeAssetEntry));
1648
+ for (const rawAssetId of outgoingIds ?? []) {
1649
+ const assetId = normalizeAssetEntry(rawAssetId);
1650
+ const coveredByAllowedMax = allowedOutgoing === void 0 && (allowedTokenMax.get(assetId) ?? 0n) > 0n;
1651
+ if (!allowedOutgoingSet.has(assetId) && !coveredByAllowedMax) {
1652
+ if (postConditions.strictZeroUnlistedOutflow || allowedOutgoing !== void 0) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Forbidden outgoing asset "${rawAssetId}" in simulation`);
1653
+ }
1654
+ }
1655
+ const mustOwnAfter = assertOptionalSimulationStringArray(postConditions.mustOwnAssetsAfter, "postConditions.mustOwnAssetsAfter");
1656
+ const ownedAfterList = assertOptionalSimulationStringArray(simulatedDelta.ownedAssetIdsAfter, "simulatedDelta.ownedAssetIdsAfter");
1657
+ if (mustOwnAfter && mustOwnAfter.length > 0) {
1658
+ const ownedAfter = new Set(ownedAfterList ?? []);
1659
+ for (const requiredAsset of mustOwnAfter) if (!ownedAfter.has(requiredAsset)) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Required post-tx asset "${requiredAsset}" missing after simulation`);
1660
+ }
1661
+ }
1662
+ function joinRequiredPolicyTiers(a, b) {
1663
+ if (a === b) return a;
1664
+ if (a === "L0") return b;
1665
+ if (b === "L0") return a;
1666
+ return "L3";
1667
+ }
1668
+ function evaluateSingleAssetTier(params) {
1669
+ const { canonical, chainStr, assetKey, txAmount, currentRolling, payeeAllowedInL0 } = params;
1670
+ if (txAmount > MAX_UINT128 || currentRolling > MAX_UINT128 || currentRolling + txAmount > MAX_UINT128) {
1671
+ if (!params.hasL2OrL3QuorumForOverflow) throw new require_constants.MpcProtocolError("PERSONAL_AMOUNT_OVERFLOW", "Transaction amount or rolling 24h sum exceeds u128 velocity envelope without L2/L3 quorum proof");
1672
+ return {
1673
+ requiredTier: canonical.guardianRoster ? "L3" : "L2",
1674
+ projectedRolling: null
1675
+ };
1676
+ }
1677
+ const projectedRolling = currentRolling + txAmount;
1678
+ const assetRule = canonical.assetLimits.find((r) => r.chainId === chainStr && r.asset === assetKey);
1679
+ if (!assetRule) {
1680
+ if (Object.keys(canonical.roleRosters).length > 0 || canonical.guardianRoster) return {
1681
+ requiredTier: canonical.guardianRoster && Object.keys(canonical.roleRosters).length === 0 ? "L3" : "L2",
1682
+ projectedRolling
1683
+ };
1684
+ throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Asset ${assetKey} on chain ${chainStr} has no configured assetLimits`);
1685
+ }
1686
+ const l0PerTx = BigInt(assetRule.l0MaxPerTxAmount);
1687
+ const l0Roll = BigInt(assetRule.l0MaxRolling24hAmount);
1688
+ if (payeeAllowedInL0 && txAmount <= l0PerTx && projectedRolling <= l0Roll) return {
1689
+ requiredTier: "L0",
1690
+ projectedRolling
1691
+ };
1692
+ if (assetRule.l1MaxPerTxAmount !== void 0 && txAmount <= BigInt(assetRule.l1MaxPerTxAmount)) return {
1693
+ requiredTier: "L1",
1694
+ projectedRolling
1695
+ };
1696
+ if (assetRule.l2MaxPerTxAmount !== void 0 && txAmount <= BigInt(assetRule.l2MaxPerTxAmount)) return {
1697
+ requiredTier: "L2",
1698
+ projectedRolling
1699
+ };
1700
+ return {
1701
+ requiredTier: "L3",
1702
+ projectedRolling
1703
+ };
1704
+ }
1705
+ function resolveRequiredPolicyTier(params) {
1706
+ const canonical = "enforcePayeeAllowlistInL0" in params.policy && Array.isArray(params.policy.allowedChainIds) && params.policy.allowedChainIds.every((c) => typeof c === "string") ? params.policy : canonicalizePersonalVaultPolicy(params.policy).canonicalPolicy;
1707
+ const { verifiedTx } = params;
1708
+ const chainStr = verifiedTx.txFields.chainId.toString(10);
1709
+ if (!canonical.allowedChainIds.includes(chainStr)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Chain ${chainStr} is not allowlisted`);
1710
+ const currentRolling = params.currentRolling24hSpendAmount ?? 0n;
1711
+ if (currentRolling < 0n) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "currentRolling24hSpendAmount cannot be negative");
1712
+ const currentNativeRolling = verifiedTx.velocityAssetKey === "native" ? params.currentNativeRolling24hSpendAmount ?? currentRolling : params.currentNativeRolling24hSpendAmount ?? 0n;
1713
+ if (currentNativeRolling < 0n) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "currentNativeRolling24hSpendAmount cannot be negative");
1714
+ const maxGasFeeWei = verifiedTx.maxGasFeeWei ?? verifiedTx.txFields.gasLimit * verifiedTx.txFields.maxFeePerGasWei;
1715
+ if (maxGasFeeWei < 0n || maxGasFeeWei > MAX_UINT256) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid maxGasFeeWei");
1716
+ const payeeAllowedInL0 = !canonical.enforcePayeeAllowlistInL0 || canonical.allowedPayees.includes(verifiedTx.payeeOrSpenderChecksumAddress);
1717
+ if (verifiedTx.velocityAssetKey === "native") {
1718
+ const evalNative = evaluateSingleAssetTier({
1719
+ canonical,
1720
+ chainStr,
1721
+ assetKey: "native",
1722
+ txAmount: verifiedTx.velocityAmount + maxGasFeeWei,
1723
+ currentRolling: currentNativeRolling,
1724
+ payeeAllowedInL0,
1725
+ hasL2OrL3QuorumForOverflow: params.hasL2OrL3QuorumForOverflow
1726
+ });
1727
+ return {
1728
+ requiredTier: evalNative.requiredTier,
1729
+ projectedRolling24hSpendAmount: evalNative.projectedRolling,
1730
+ projectedNativeRolling24hSpendAmount: evalNative.projectedRolling
1731
+ };
1732
+ }
1733
+ let tokenTier;
1734
+ let projectedTokenRolling;
1735
+ if (verifiedTx.isUnlimitedApprove) {
1736
+ if (!canonical.allowUnlimitedApproveByQuorum) throw new require_constants.MpcProtocolError("PERSONAL_UNLIMITED_APPROVE_FORBIDDEN", "Unlimited ERC-20 approve is forbidden by policy");
1737
+ tokenTier = canonical.guardianRoster ? "L3" : "L2";
1738
+ projectedTokenRolling = null;
1739
+ } else {
1740
+ const evalToken = evaluateSingleAssetTier({
1741
+ canonical,
1742
+ chainStr,
1743
+ assetKey: verifiedTx.velocityAssetKey,
1744
+ txAmount: verifiedTx.velocityAmount,
1745
+ currentRolling,
1746
+ payeeAllowedInL0,
1747
+ hasL2OrL3QuorumForOverflow: params.hasL2OrL3QuorumForOverflow
1748
+ });
1749
+ tokenTier = evalToken.requiredTier;
1750
+ projectedTokenRolling = evalToken.projectedRolling;
1751
+ }
1752
+ if (maxGasFeeWei === 0n) return {
1753
+ requiredTier: tokenTier,
1754
+ projectedRolling24hSpendAmount: projectedTokenRolling,
1755
+ projectedNativeRolling24hSpendAmount: currentNativeRolling
1756
+ };
1757
+ const evalGas = evaluateSingleAssetTier({
1758
+ canonical,
1759
+ chainStr,
1760
+ assetKey: "native",
1761
+ txAmount: maxGasFeeWei,
1762
+ currentRolling: currentNativeRolling,
1763
+ payeeAllowedInL0: true,
1764
+ hasL2OrL3QuorumForOverflow: params.hasL2OrL3QuorumForOverflow
1765
+ });
1766
+ return {
1767
+ requiredTier: joinRequiredPolicyTiers(tokenTier, evalGas.requiredTier),
1768
+ projectedRolling24hSpendAmount: projectedTokenRolling,
1769
+ projectedNativeRolling24hSpendAmount: evalGas.projectedRolling
1770
+ };
1771
+ }
1772
+ function buildQuorumApprovalDigest32(params) {
1773
+ return require_secp256k1_scalar.hashTranscriptSha256(params.dst, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.u64be(params.policyEpoch), params.policyHash32, require_secp256k1_scalar.utf8Bytes(params.roleOrGuardianTag), params.clearSigningPreviewHash32, params.signingDigest32, require_secp256k1_scalar.u64be(params.expiresAtSec));
1774
+ }
1775
+ function signQuorumDigestWithMemberKey(params) {
1776
+ if (params.secretKey32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Approver secretKey32 must be 32 bytes");
1777
+ if (params.alg === "p256") {
1778
+ const pub65 = _noble_curves_nist_js.p256.getPublicKey(params.secretKey32, false);
1779
+ const sig = _noble_curves_nist_js.p256.sign(params.digest32, params.secretKey32, {
1780
+ prehash: true,
1781
+ lowS: true,
1782
+ format: "compact"
1783
+ });
1784
+ return {
1785
+ memberId: params.memberId,
1786
+ alg: "p256",
1787
+ publicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(pub65)}`,
1788
+ signatureHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(sig)}`
1789
+ };
1790
+ }
1791
+ if (params.alg === "ed25519") {
1792
+ const pub32 = _noble_curves_ed25519_js.ed25519.getPublicKey(params.secretKey32);
1793
+ const sig = _noble_curves_ed25519_js.ed25519.sign(params.digest32, params.secretKey32);
1794
+ return {
1795
+ memberId: params.memberId,
1796
+ alg: "ed25519",
1797
+ publicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(pub32)}`,
1798
+ signatureHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(sig)}`
1799
+ };
1800
+ }
1801
+ if (params.alg === "secp256k1") {
1802
+ const pub33 = _noble_curves_secp256k1_js.secp256k1.getPublicKey(params.secretKey32, true);
1803
+ const sig = _noble_curves_secp256k1_js.secp256k1.sign(params.digest32, params.secretKey32, {
1804
+ prehash: false,
1805
+ lowS: true,
1806
+ format: "compact"
1807
+ });
1808
+ return {
1809
+ memberId: params.memberId,
1810
+ alg: "secp256k1",
1811
+ publicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(pub33)}`,
1812
+ signatureHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(sig)}`
1813
+ };
1814
+ }
1815
+ throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `Unsupported quorum alg: ${String(params.alg)}`);
1816
+ }
1817
+ function verifySingleQuorumMemberApproval(entry, rosterMember, digest32) {
1818
+ if (entry.alg !== rosterMember.alg) return false;
1819
+ let normalizedEntryMember;
1820
+ let sigBytes;
1821
+ try {
1822
+ normalizedEntryMember = validateAndNormalizeQuorumMember({
1823
+ memberId: entry.memberId,
1824
+ alg: entry.alg,
1825
+ publicKeyHex: entry.publicKeyHex
1826
+ });
1827
+ sigBytes = require_secp256k1_scalar.normalizeHexBytes(entry.signatureHex);
1828
+ } catch {
1829
+ return false;
1830
+ }
1831
+ if (normalizedEntryMember.publicKeyHex !== rosterMember.publicKeyHex) return false;
1832
+ const pubBytes = require_secp256k1_scalar.normalizeHexBytes(rosterMember.publicKeyHex);
1833
+ if (entry.alg === "p256") return verifyP256Sha256SignatureFlexible(sigBytes, digest32, pubBytes);
1834
+ if (entry.alg === "ed25519") {
1835
+ if (sigBytes.length !== 64) return false;
1836
+ try {
1837
+ return _noble_curves_ed25519_js.ed25519.verify(sigBytes, digest32, pubBytes, { zip215: false });
1838
+ } catch {
1839
+ return false;
1840
+ }
1841
+ }
1842
+ if (entry.alg === "secp256k1") {
1843
+ if (sigBytes.length !== 64) return false;
1844
+ try {
1845
+ return _noble_curves_secp256k1_js.secp256k1.verify(sigBytes, digest32, pubBytes, {
1846
+ prehash: false,
1847
+ lowS: true,
1848
+ format: "compact"
1849
+ });
1850
+ } catch {
1851
+ return false;
1852
+ }
1853
+ }
1854
+ return false;
1855
+ }
1856
+ function signRoleQuorumApproval(params) {
1857
+ const digest32 = buildQuorumApprovalDigest32({
1858
+ dst: require_constants.DST_PERSONAL_ROLE_QUORUM_V1,
1859
+ vaultId: params.vaultId,
1860
+ policyEpoch: params.policyEpoch,
1861
+ policyHash32: require_secp256k1_scalar.normalizeHexBytes(params.policyHash32, 32),
1862
+ roleOrGuardianTag: params.role,
1863
+ clearSigningPreviewHash32: require_secp256k1_scalar.normalizeHexBytes(params.clearSigningPreviewHash32, 32),
1864
+ signingDigest32: require_secp256k1_scalar.normalizeHexBytes(params.signingDigest32, 32),
1865
+ expiresAtSec: params.expiresAtSec
1866
+ });
1867
+ return signQuorumDigestWithMemberKey({
1868
+ memberId: params.memberId,
1869
+ alg: params.alg,
1870
+ secretKey32: params.secretKey32,
1871
+ digest32
1872
+ });
1873
+ }
1874
+ function verifyRoleQuorumProof(params) {
1875
+ const canonical = "enforcePayeeAllowlistInL0" in params.policy && Array.isArray(params.policy.allowedChainIds) && params.policy.allowedChainIds.every((c) => typeof c === "string") ? params.policy : canonicalizePersonalVaultPolicy(params.policy).canonicalPolicy;
1876
+ const { proof } = params;
1877
+ if (!proof || proof.kind !== "role-quorum" || proof.vaultId !== params.vaultId) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "RoleQuorumProof vaultId or kind mismatch");
1878
+ const expectedPolicyHash32 = require_secp256k1_scalar.normalizeHexBytes(params.policyHash32, 32);
1879
+ const expectedPreviewHash32 = require_secp256k1_scalar.normalizeHexBytes(params.clearSigningPreviewHash32, 32);
1880
+ const expectedSigningDigest32 = require_secp256k1_scalar.normalizeHexBytes(params.signingDigest32, 32);
1881
+ let proofEpoch;
1882
+ let expiresAtSec;
1883
+ let proofPolicyHash32;
1884
+ let proofPreviewHash32;
1885
+ let proofSigningDigest32;
1886
+ try {
1887
+ proofEpoch = parseStrictNonNegativeBigInt(proof.policyEpoch, MAX_UINT64, "policyEpoch", "PERSONAL_PROOF_INVALID");
1888
+ expiresAtSec = parseStrictNonNegativeBigInt(proof.expiresAtSec, MAX_UINT64, "expiresAtSec", "PERSONAL_PROOF_INVALID");
1889
+ proofPolicyHash32 = require_secp256k1_scalar.normalizeHexBytes(proof.policyHashHex, 32);
1890
+ proofPreviewHash32 = require_secp256k1_scalar.normalizeHexBytes(proof.clearSigningPreviewHashHex, 32);
1891
+ proofSigningDigest32 = require_secp256k1_scalar.normalizeHexBytes(proof.signingDigestHex, 32);
1892
+ } catch {
1893
+ throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Malformed RoleQuorumProof header fields");
1894
+ }
1895
+ if (proofEpoch !== params.policyEpoch || !require_secp256k1_scalar.constantTimeEqual(proofPolicyHash32, expectedPolicyHash32) || !require_secp256k1_scalar.constantTimeEqual(proofPreviewHash32, expectedPreviewHash32) || !require_secp256k1_scalar.constantTimeEqual(proofSigningDigest32, expectedSigningDigest32)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "RoleQuorumProof binding mismatch");
1896
+ if (params.nowSec > expiresAtSec) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "RoleQuorumProof has expired");
1897
+ const roster = canonical.roleRosters[proof.role];
1898
+ if (!roster) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", `Unknown role "${proof.role}" in RoleQuorumProof`);
1899
+ if (!Array.isArray(proof.approvals) || proof.approvals.length < roster.threshold) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", `Insufficient role quorum approvals (${proof.approvals?.length ?? 0} < ${roster.threshold})`);
1900
+ const digest32 = buildQuorumApprovalDigest32({
1901
+ dst: require_constants.DST_PERSONAL_ROLE_QUORUM_V1,
1902
+ vaultId: params.vaultId,
1903
+ policyEpoch: params.policyEpoch,
1904
+ policyHash32: expectedPolicyHash32,
1905
+ roleOrGuardianTag: proof.role,
1906
+ clearSigningPreviewHash32: expectedPreviewHash32,
1907
+ signingDigest32: expectedSigningDigest32,
1908
+ expiresAtSec
1909
+ });
1910
+ const rosterById = new Map(roster.members.map((m) => [m.memberId, m]));
1911
+ const seenMemberIds = /* @__PURE__ */ new Set();
1912
+ const seenPubKeys = /* @__PURE__ */ new Set();
1913
+ let validCount = 0;
1914
+ for (const entry of proof.approvals) {
1915
+ if (!entry || seenMemberIds.has(entry.memberId)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Duplicate memberId in RoleQuorumProof");
1916
+ const rosterMember = rosterById.get(entry.memberId);
1917
+ if (!rosterMember) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", `Unknown roster member "${entry.memberId}"`);
1918
+ const pubKeyId = `${rosterMember.alg}:${rosterMember.publicKeyHex}`;
1919
+ if (seenPubKeys.has(pubKeyId)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Duplicate approver publicKey in RoleQuorumProof");
1920
+ if (!verifySingleQuorumMemberApproval(entry, rosterMember, digest32)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", `Invalid quorum signature from "${entry.memberId}"`);
1921
+ seenMemberIds.add(entry.memberId);
1922
+ seenPubKeys.add(pubKeyId);
1923
+ validCount += 1;
1924
+ }
1925
+ if (validCount < roster.threshold) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "RoleQuorumProof threshold not met");
1926
+ }
1927
+ function signGuardianQuorumApproval(params) {
1928
+ const digest32 = buildQuorumApprovalDigest32({
1929
+ dst: require_constants.DST_PERSONAL_GUARDIAN_QUORUM_V1,
1930
+ vaultId: params.vaultId,
1931
+ policyEpoch: params.policyEpoch,
1932
+ policyHash32: require_secp256k1_scalar.normalizeHexBytes(params.policyHash32, 32),
1933
+ roleOrGuardianTag: "guardian",
1934
+ clearSigningPreviewHash32: require_secp256k1_scalar.normalizeHexBytes(params.clearSigningPreviewHash32, 32),
1935
+ signingDigest32: require_secp256k1_scalar.normalizeHexBytes(params.signingDigest32, 32),
1936
+ expiresAtSec: params.expiresAtSec
1937
+ });
1938
+ return signQuorumDigestWithMemberKey({
1939
+ memberId: params.memberId,
1940
+ alg: params.alg,
1941
+ secretKey32: params.secretKey32,
1942
+ digest32
1943
+ });
1944
+ }
1945
+ function verifyGuardianQuorumProof(params) {
1946
+ const canonical = "enforcePayeeAllowlistInL0" in params.policy && Array.isArray(params.policy.allowedChainIds) && params.policy.allowedChainIds.every((c) => typeof c === "string") ? params.policy : canonicalizePersonalVaultPolicy(params.policy).canonicalPolicy;
1947
+ const { proof } = params;
1948
+ if (!proof || proof.kind !== "guardian-quorum" || proof.vaultId !== params.vaultId) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "GuardianQuorumProof vaultId or kind mismatch");
1949
+ if (!canonical.guardianRoster) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Policy has no guardianRoster configured");
1950
+ const expectedPolicyHash32 = require_secp256k1_scalar.normalizeHexBytes(params.policyHash32, 32);
1951
+ const expectedPreviewHash32 = require_secp256k1_scalar.normalizeHexBytes(params.clearSigningPreviewHash32, 32);
1952
+ const expectedSigningDigest32 = require_secp256k1_scalar.normalizeHexBytes(params.signingDigest32, 32);
1953
+ let proofEpoch;
1954
+ let expiresAtSec;
1955
+ let proofPolicyHash32;
1956
+ let proofPreviewHash32;
1957
+ let proofSigningDigest32;
1958
+ try {
1959
+ proofEpoch = parseStrictNonNegativeBigInt(proof.policyEpoch, MAX_UINT64, "policyEpoch", "PERSONAL_PROOF_INVALID");
1960
+ expiresAtSec = parseStrictNonNegativeBigInt(proof.expiresAtSec, MAX_UINT64, "expiresAtSec", "PERSONAL_PROOF_INVALID");
1961
+ proofPolicyHash32 = require_secp256k1_scalar.normalizeHexBytes(proof.policyHashHex, 32);
1962
+ proofPreviewHash32 = require_secp256k1_scalar.normalizeHexBytes(proof.clearSigningPreviewHashHex, 32);
1963
+ proofSigningDigest32 = require_secp256k1_scalar.normalizeHexBytes(proof.signingDigestHex, 32);
1964
+ } catch {
1965
+ throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Malformed GuardianQuorumProof header fields");
1966
+ }
1967
+ if (proofEpoch !== params.policyEpoch || !require_secp256k1_scalar.constantTimeEqual(proofPolicyHash32, expectedPolicyHash32) || !require_secp256k1_scalar.constantTimeEqual(proofPreviewHash32, expectedPreviewHash32) || !require_secp256k1_scalar.constantTimeEqual(proofSigningDigest32, expectedSigningDigest32)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "GuardianQuorumProof binding mismatch");
1968
+ if (params.nowSec > expiresAtSec) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "GuardianQuorumProof has expired");
1969
+ const roster = canonical.guardianRoster;
1970
+ if (!Array.isArray(proof.approvals) || proof.approvals.length < roster.threshold) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Insufficient guardian quorum approvals");
1971
+ const digest32 = buildQuorumApprovalDigest32({
1972
+ dst: require_constants.DST_PERSONAL_GUARDIAN_QUORUM_V1,
1973
+ vaultId: params.vaultId,
1974
+ policyEpoch: params.policyEpoch,
1975
+ policyHash32: expectedPolicyHash32,
1976
+ roleOrGuardianTag: "guardian",
1977
+ clearSigningPreviewHash32: expectedPreviewHash32,
1978
+ signingDigest32: expectedSigningDigest32,
1979
+ expiresAtSec
1980
+ });
1981
+ const rosterById = new Map(roster.members.map((m) => [m.memberId, m]));
1982
+ const seenIds = /* @__PURE__ */ new Set();
1983
+ const seenKeys = /* @__PURE__ */ new Set();
1984
+ let validCount = 0;
1985
+ for (const entry of proof.approvals) {
1986
+ if (!entry || seenIds.has(entry.memberId)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Duplicate guardian memberId");
1987
+ const rosterMember = rosterById.get(entry.memberId);
1988
+ if (!rosterMember) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", `Unknown guardian member "${entry.memberId}"`);
1989
+ const pubKeyId = `${rosterMember.alg}:${rosterMember.publicKeyHex}`;
1990
+ if (seenKeys.has(pubKeyId)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Duplicate guardian publicKey");
1991
+ if (!verifySingleQuorumMemberApproval(entry, rosterMember, digest32)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", `Invalid guardian signature from "${entry.memberId}"`);
1992
+ seenIds.add(entry.memberId);
1993
+ seenKeys.add(pubKeyId);
1994
+ validCount += 1;
1995
+ }
1996
+ if (validCount < roster.threshold) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "GuardianQuorumProof threshold not met");
1997
+ }
1998
+ function computeAnnounceTicketMac32(params) {
1999
+ return (0, _noble_hashes_hmac_js.hmac)(_noble_hashes_sha2_js.sha256, params.ticketMacKey32, require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_ANNOUNCE_TICKET_V1, [
2000
+ require_secp256k1_scalar.utf8Bytes(params.ticketKid),
2001
+ require_secp256k1_scalar.utf8Bytes(params.vaultId),
2002
+ require_secp256k1_scalar.u64be(params.policyEpoch),
2003
+ require_secp256k1_scalar.u64be(params.vetoEpoch),
2004
+ params.clearSigningPreviewHash32,
2005
+ params.signingDigest32,
2006
+ require_secp256k1_scalar.u64be(params.announcedAtSec),
2007
+ require_secp256k1_scalar.u64be(params.executableAfterSec),
2008
+ require_secp256k1_scalar.u64be(params.expiresAtSec)
2009
+ ]));
2010
+ }
2011
+ const MIN_ANNOUNCE_VALIDITY_WINDOW_SEC = 60;
2012
+ const MAX_ANNOUNCE_VALIDITY_WINDOW_SEC = 604800;
2013
+ function signAnnounceTicket(params) {
2014
+ if (params.ticketMacKey32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "ticketMacKey32 must be 32 bytes");
2015
+ assertPrintableIdentifierAscii(params.ticketKid, 32, "ticketKid", "INVALID_PARAMETER");
2016
+ if (!Number.isInteger(params.timelockDelaySec) || params.timelockDelaySec < 1) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "timelockDelaySec must be >= 1");
2017
+ const windowSec = params.validityWindowSec ?? 3600;
2018
+ if (!Number.isInteger(windowSec) || windowSec < MIN_ANNOUNCE_VALIDITY_WINDOW_SEC || windowSec > MAX_ANNOUNCE_VALIDITY_WINDOW_SEC) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `validityWindowSec must be an integer within ${MIN_ANNOUNCE_VALIDITY_WINDOW_SEC}..${MAX_ANNOUNCE_VALIDITY_WINDOW_SEC}`);
2019
+ const previewHash32 = require_secp256k1_scalar.normalizeHexBytes(params.clearSigningPreviewHash32, 32);
2020
+ const sigDigest32 = require_secp256k1_scalar.normalizeHexBytes(params.signingDigest32, 32);
2021
+ const executableAfterSec = params.announcedAtSec + BigInt(params.timelockDelaySec);
2022
+ const expiresAtSec = executableAfterSec + BigInt(windowSec);
2023
+ const mac32 = computeAnnounceTicketMac32({
2024
+ ticketMacKey32: params.ticketMacKey32,
2025
+ ticketKid: params.ticketKid,
2026
+ vaultId: params.vaultId,
2027
+ policyEpoch: params.policyEpoch,
2028
+ vetoEpoch: params.vetoEpoch,
2029
+ clearSigningPreviewHash32: previewHash32,
2030
+ signingDigest32: sigDigest32,
2031
+ announcedAtSec: params.announcedAtSec,
2032
+ executableAfterSec,
2033
+ expiresAtSec
2034
+ });
2035
+ return {
2036
+ kind: "announce-ticket",
2037
+ vaultId: params.vaultId,
2038
+ policyEpoch: params.policyEpoch.toString(10),
2039
+ vetoEpoch: params.vetoEpoch.toString(10),
2040
+ clearSigningPreviewHashHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(previewHash32)}`,
2041
+ signingDigestHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(sigDigest32)}`,
2042
+ announcedAtSec: params.announcedAtSec.toString(10),
2043
+ executableAfterSec: executableAfterSec.toString(10),
2044
+ expiresAtSec: expiresAtSec.toString(10),
2045
+ ticketKid: params.ticketKid,
2046
+ macHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(mac32)}`
2047
+ };
2048
+ }
2049
+ function verifySignedAnnounceTicket(params) {
2050
+ const { ticket } = params;
2051
+ if (!ticket || ticket.kind !== "announce-ticket" || ticket.vaultId !== params.vaultId) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Invalid SignedAnnounceTicket");
2052
+ const expectedPreview32 = require_secp256k1_scalar.normalizeHexBytes(params.clearSigningPreviewHash32, 32);
2053
+ const expectedDigest32 = require_secp256k1_scalar.normalizeHexBytes(params.signingDigest32, 32);
2054
+ let policyEpoch;
2055
+ let vetoEpoch;
2056
+ let announcedAtSec;
2057
+ let executableAfterSec;
2058
+ let expiresAtSec;
2059
+ let mac32;
2060
+ let ticketPreview32;
2061
+ let ticketDigest32;
2062
+ try {
2063
+ policyEpoch = parseStrictNonNegativeBigInt(ticket.policyEpoch, MAX_UINT64, "policyEpoch", "PERSONAL_PROOF_INVALID");
2064
+ vetoEpoch = parseStrictNonNegativeBigInt(ticket.vetoEpoch, MAX_UINT64, "vetoEpoch", "PERSONAL_PROOF_INVALID");
2065
+ announcedAtSec = parseStrictNonNegativeBigInt(ticket.announcedAtSec, MAX_UINT64, "announcedAtSec", "PERSONAL_PROOF_INVALID");
2066
+ executableAfterSec = parseStrictNonNegativeBigInt(ticket.executableAfterSec, MAX_UINT64, "executableAfterSec", "PERSONAL_PROOF_INVALID");
2067
+ expiresAtSec = parseStrictNonNegativeBigInt(ticket.expiresAtSec, MAX_UINT64, "expiresAtSec", "PERSONAL_PROOF_INVALID");
2068
+ mac32 = require_secp256k1_scalar.normalizeHexBytes(ticket.macHex, 32);
2069
+ ticketPreview32 = require_secp256k1_scalar.normalizeHexBytes(ticket.clearSigningPreviewHashHex, 32);
2070
+ ticketDigest32 = require_secp256k1_scalar.normalizeHexBytes(ticket.signingDigestHex, 32);
2071
+ } catch {
2072
+ throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Malformed SignedAnnounceTicket fields");
2073
+ }
2074
+ const expectedMac32 = computeAnnounceTicketMac32({
2075
+ ticketMacKey32: params.ticketMacKey32,
2076
+ ticketKid: ticket.ticketKid,
2077
+ vaultId: ticket.vaultId,
2078
+ policyEpoch,
2079
+ vetoEpoch,
2080
+ clearSigningPreviewHash32: ticketPreview32,
2081
+ signingDigest32: ticketDigest32,
2082
+ announcedAtSec,
2083
+ executableAfterSec,
2084
+ expiresAtSec
2085
+ });
2086
+ if (!require_secp256k1_scalar.constantTimeEqual(mac32, expectedMac32)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket HMAC verification failed");
2087
+ if (policyEpoch !== params.policyEpoch || !require_secp256k1_scalar.constantTimeEqual(ticketPreview32, expectedPreview32) || !require_secp256k1_scalar.constantTimeEqual(ticketDigest32, expectedDigest32)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket transaction binding mismatch");
2088
+ if (vetoEpoch !== params.currentVetoEpoch) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket invalidated by emergency vetoEpoch bump");
2089
+ if (executableAfterSec - announcedAtSec < BigInt(params.minTimelockDelaySec)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket delay shorter than policy timelockDelaySec");
2090
+ if (params.nowSec < executableAfterSec) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket timelock has not matured yet");
2091
+ if (params.nowSec > expiresAtSec) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket has expired");
2092
+ }
2093
+ const TIER_RANK = {
2094
+ L0: 0,
2095
+ L1: 1,
2096
+ L2: 2,
2097
+ L3: 3
2098
+ };
2099
+ function verifyPersonalPolicyProofBundle(params) {
2100
+ const canonical = "enforcePayeeAllowlistInL0" in params.policy && Array.isArray(params.policy.allowedChainIds) && params.policy.allowedChainIds.every((c) => typeof c === "string") ? params.policy : canonicalizePersonalVaultPolicy(params.policy).canonicalPolicy;
2101
+ const { requiredTier, proofBundle } = params;
2102
+ if (!proofBundle || TIER_RANK[proofBundle.tier] < TIER_RANK[requiredTier]) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Transaction requires policy tier ${requiredTier}, got ${proofBundle?.tier ?? "none"}`);
2103
+ if (requiredTier === "L1" && proofBundle.tier === "L2") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "L1 timelock requirement can only be satisfied by L1 announceTicket or L3 quorum-and-timelock");
2104
+ if (proofBundle.tier === "L0") return;
2105
+ if (proofBundle.tier === "L1") {
2106
+ if (!params.ticketMacKey32) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Missing ticketMacKey32 for L1 timelock verification");
2107
+ verifySignedAnnounceTicket({
2108
+ ticket: proofBundle.announceTicket,
2109
+ ticketMacKey32: params.ticketMacKey32,
2110
+ vaultId: params.vaultId,
2111
+ policyEpoch: params.policyEpoch,
2112
+ currentVetoEpoch: params.currentVetoEpoch,
2113
+ minTimelockDelaySec: canonical.timelockDelaySec,
2114
+ clearSigningPreviewHash32: params.clearSigningPreviewHash32,
2115
+ signingDigest32: params.signingDigest32,
2116
+ nowSec: params.nowSec
2117
+ });
2118
+ return;
2119
+ }
2120
+ if (proofBundle.tier === "L2") {
2121
+ if (!proofBundle.quorumProof || proofBundle.quorumProof.kind !== "role-quorum") throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "L2 requires a role-quorum proof");
2122
+ if (params.allowedL2Roles && params.allowedL2Roles.length > 0) {
2123
+ if (!params.allowedL2Roles.includes(proofBundle.quorumProof.role)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", `RoleQuorumProof role "${proofBundle.quorumProof.role}" is not permitted for this L2 action`);
2124
+ } else {
2125
+ const requiredL2Role = canonical.defaultRoleForL2 ?? canonical.defaultRoleForL3;
2126
+ if (requiredL2Role !== void 0 && proofBundle.quorumProof.role !== requiredL2Role) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", `L2 RoleQuorumProof role "${proofBundle.quorumProof.role}" does not match required role "${requiredL2Role}"`);
2127
+ }
2128
+ verifyRoleQuorumProof({
2129
+ proof: proofBundle.quorumProof,
2130
+ policy: canonical,
2131
+ vaultId: params.vaultId,
2132
+ policyEpoch: params.policyEpoch,
2133
+ policyHash32: params.policyHash32,
2134
+ clearSigningPreviewHash32: params.clearSigningPreviewHash32,
2135
+ signingDigest32: params.signingDigest32,
2136
+ nowSec: params.nowSec
2137
+ });
2138
+ return;
2139
+ }
2140
+ if (proofBundle.tier === "L3") {
2141
+ if (!params.ticketMacKey32) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Missing ticketMacKey32 for L3 timelock verification");
2142
+ verifySignedAnnounceTicket({
2143
+ ticket: proofBundle.announceTicket,
2144
+ ticketMacKey32: params.ticketMacKey32,
2145
+ vaultId: params.vaultId,
2146
+ policyEpoch: params.policyEpoch,
2147
+ currentVetoEpoch: params.currentVetoEpoch,
2148
+ minTimelockDelaySec: canonical.timelockDelaySec,
2149
+ clearSigningPreviewHash32: params.clearSigningPreviewHash32,
2150
+ signingDigest32: params.signingDigest32,
2151
+ nowSec: params.nowSec
2152
+ });
2153
+ if (canonical.guardianRoster !== void 0) {
2154
+ if (!proofBundle.quorumProof || proofBundle.quorumProof.kind !== "guardian-quorum") throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "L3 strictly requires guardian-quorum when guardianRoster is configured in policy");
2155
+ verifyGuardianQuorumProof({
2156
+ proof: proofBundle.quorumProof,
2157
+ policy: canonical,
2158
+ vaultId: params.vaultId,
2159
+ policyEpoch: params.policyEpoch,
2160
+ policyHash32: params.policyHash32,
2161
+ clearSigningPreviewHash32: params.clearSigningPreviewHash32,
2162
+ signingDigest32: params.signingDigest32,
2163
+ nowSec: params.nowSec
2164
+ });
2165
+ } else {
2166
+ if (!proofBundle.quorumProof || proofBundle.quorumProof.kind !== "role-quorum") throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "L3 requires role-quorum when policy has no guardianRoster");
2167
+ const requiredL3Role = canonical.defaultRoleForL3 ?? canonical.defaultRoleForL2;
2168
+ if (requiredL3Role !== void 0 && proofBundle.quorumProof.role !== requiredL3Role) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", `L3 RoleQuorumProof role "${proofBundle.quorumProof.role}" does not match required role "${requiredL3Role}"`);
2169
+ verifyRoleQuorumProof({
2170
+ proof: proofBundle.quorumProof,
2171
+ policy: canonical,
2172
+ vaultId: params.vaultId,
2173
+ policyEpoch: params.policyEpoch,
2174
+ policyHash32: params.policyHash32,
2175
+ clearSigningPreviewHash32: params.clearSigningPreviewHash32,
2176
+ signingDigest32: params.signingDigest32,
2177
+ nowSec: params.nowSec
2178
+ });
2179
+ }
2180
+ return;
2181
+ }
2182
+ throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Unsupported PersonalPolicyProofBundle");
2183
+ }
2184
+ const ENTITLEMENT_TIER_CODE = {
2185
+ "free-trial": 0,
2186
+ "staked-quota": 1,
2187
+ "metered-credits": 2,
2188
+ "enterprise-sponsored": 3
2189
+ };
2190
+ function computeVaultEntitlementTicketDigest32(ticket) {
2191
+ const blindTag32 = require_secp256k1_scalar.normalizeHexBytes(ticket.blindVaultTagHex, 32);
2192
+ const tierCode = ENTITLEMENT_TIER_CODE[ticket.entitlementTier];
2193
+ if (tierCode === void 0) throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Invalid VaultEntitlementTier");
2194
+ const epoch = parseStrictNonNegativeBigInt(ticket.entitlementEpoch, MAX_UINT64, "entitlementEpoch", "PERSONAL_ENTITLEMENT_REQUIRED");
2195
+ if (epoch < 1n) throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "entitlementEpoch must be >= 1n");
2196
+ const validUntilSec = parseStrictNonNegativeBigInt(ticket.validUntilSec, MAX_UINT64, "validUntilSec", "PERSONAL_ENTITLEMENT_REQUIRED");
2197
+ if (!Number.isInteger(ticket.grantedCredits) || ticket.grantedCredits < 0 || ticket.grantedCredits > 4294967295) throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Invalid grantedCredits u32");
2198
+ if (!Number.isInteger(ticket.maxActorSlots) || ticket.maxActorSlots < 1 || ticket.maxActorSlots > 255) throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Invalid maxActorSlots u8");
2199
+ const stakeRef32 = ticket.stakeRefHashHex ? require_secp256k1_scalar.normalizeHexBytes(ticket.stakeRefHashHex, 32) : new Uint8Array(0);
2200
+ const issuerPub32 = require_secp256k1_scalar.normalizeHexBytes(ticket.issuerPublicKeyHex, 32);
2201
+ validateEd25519PublicKeyNonTorsion32(issuerPub32, "PERSONAL_ENTITLEMENT_REQUIRED");
2202
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_ENTITLEMENT_TICKET_V1, blindTag32, require_secp256k1_scalar.u8(tierCode), require_secp256k1_scalar.u64be(epoch), require_secp256k1_scalar.u64be(validUntilSec), require_secp256k1_scalar.u32be(ticket.grantedCredits), require_secp256k1_scalar.u8(ticket.maxActorSlots), stakeRef32, issuerPub32);
2203
+ }
2204
+ function signVaultEntitlementTicket(params) {
2205
+ if (params.issuerEd25519SecretKey32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "issuerEd25519SecretKey32 must be 32 bytes");
2206
+ const issuerPub32 = _noble_curves_ed25519_js.ed25519.getPublicKey(params.issuerEd25519SecretKey32);
2207
+ const blindTag32 = require_secp256k1_scalar.normalizeHexBytes(params.blindVaultTag32, 32);
2208
+ const stakeRef32 = params.stakeRefHash32 !== void 0 ? require_secp256k1_scalar.normalizeHexBytes(params.stakeRefHash32, 32) : void 0;
2209
+ const unsigned = {
2210
+ version: 1,
2211
+ blindVaultTagHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(blindTag32)}`,
2212
+ entitlementTier: params.entitlementTier,
2213
+ entitlementEpoch: params.entitlementEpoch.toString(10),
2214
+ validUntilSec: params.validUntilSec.toString(10),
2215
+ grantedCredits: params.grantedCredits,
2216
+ maxActorSlots: params.maxActorSlots,
2217
+ ...stakeRef32 ? { stakeRefHashHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(stakeRef32)}` } : {},
2218
+ issuerPublicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(issuerPub32)}`
2219
+ };
2220
+ const digest32 = computeVaultEntitlementTicketDigest32(unsigned);
2221
+ const sig64 = _noble_curves_ed25519_js.ed25519.sign(digest32, params.issuerEd25519SecretKey32);
2222
+ return {
2223
+ ...unsigned,
2224
+ signatureHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(sig64)}`
2225
+ };
2226
+ }
2227
+ function verifyVaultEntitlementTicket(params) {
2228
+ const { ticket } = params;
2229
+ if (!ticket || ticket.version !== 1) throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Missing or invalid VaultEntitlementTicket");
2230
+ const expectedTag32 = require_secp256k1_scalar.normalizeHexBytes(params.expectedBlindVaultTag32, 32);
2231
+ let ticketTag32;
2232
+ let issuerPub32;
2233
+ let sig64;
2234
+ try {
2235
+ ticketTag32 = require_secp256k1_scalar.normalizeHexBytes(ticket.blindVaultTagHex, 32);
2236
+ issuerPub32 = require_secp256k1_scalar.normalizeHexBytes(ticket.issuerPublicKeyHex, 32);
2237
+ sig64 = require_secp256k1_scalar.normalizeHexBytes(ticket.signatureHex, 64);
2238
+ validateEd25519PublicKeyNonTorsion32(issuerPub32, "PERSONAL_ENTITLEMENT_REQUIRED");
2239
+ } catch {
2240
+ throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Malformed VaultEntitlementTicket binary fields");
2241
+ }
2242
+ if (!require_secp256k1_scalar.constantTimeEqual(ticketTag32, expectedTag32)) throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "VaultEntitlementTicket blindVaultTag32 mismatch");
2243
+ if (!params.trustedIssuerPublicKeys.some((k) => {
2244
+ try {
2245
+ return require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.normalizeHexBytes(k, 32), issuerPub32);
2246
+ } catch {
2247
+ return false;
2248
+ }
2249
+ })) throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Untrusted VaultEntitlementTicket issuer");
2250
+ const digest32 = computeVaultEntitlementTicketDigest32(ticket);
2251
+ let sigOk = false;
2252
+ try {
2253
+ sigOk = _noble_curves_ed25519_js.ed25519.verify(sig64, digest32, issuerPub32, { zip215: false });
2254
+ } catch {
2255
+ sigOk = false;
2256
+ }
2257
+ if (!sigOk) throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Invalid VaultEntitlementTicket Ed25519 signature");
2258
+ const epoch = BigInt(ticket.entitlementEpoch);
2259
+ const validUntilSec = BigInt(ticket.validUntilSec);
2260
+ if (params.minEntitlementEpochExclusive !== void 0 && epoch <= params.minEntitlementEpochExclusive) throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", `Stale entitlementEpoch ${epoch} <= ${params.minEntitlementEpochExclusive}`);
2261
+ if (params.nowSec >= validUntilSec) throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "VaultEntitlementTicket has expired");
2262
+ if (ticket.entitlementTier === "metered-credits" && ticket.grantedCredits < 1) throw new require_constants.MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "metered-credits ticket requires grantedCredits >= 1");
2263
+ return {
2264
+ entitlementTier: ticket.entitlementTier,
2265
+ entitlementEpoch: epoch,
2266
+ validUntilSec,
2267
+ grantedCredits: ticket.grantedCredits,
2268
+ maxActorSlots: ticket.maxActorSlots,
2269
+ ticketHash32: digest32
2270
+ };
2271
+ }
2272
+ function computePairingPopDigest32(params) {
2273
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_PAIR_POP_V1, require_secp256k1_scalar.utf8Bytes(params.vaultId), require_secp256k1_scalar.utf8Bytes(params.targetSlotId), require_secp256k1_scalar.u8(actorKindAndAlgToByte(params.actorKindAndAlg)), params.actorPubKeyPadded65, params.ephemeralX25519PublicKey32, require_secp256k1_scalar.u64be(params.slotExpiresAtSec), params.pairNonce32);
2274
+ }
2275
+ async function createActorSlotPairingBootstrap(params) {
2276
+ const rng = params.rng ?? require_secp256k1_scalar.defaultRandomBytes;
2277
+ assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
2278
+ assertPrintableIdentifierAscii(params.targetSlotId, 64, "targetSlotId", "INVALID_PARAMETER");
2279
+ const slotExpiresAtSec = params.slotExpiresAtSec ?? 0n;
2280
+ if (isAgentActorKind(params.actorKindAndAlg) && slotExpiresAtSec <= 0n) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Agent actor slot (${params.actorKindAndAlg}) requires slotExpiresAtSec > 0n`);
2281
+ const actorPubKeyPadded65 = normalizeActorPublicKeyToPadded65(params.actorKindAndAlg, params.actorPublicKey);
2282
+ const ephemeralX25519SecretKey32 = rng(32);
2283
+ const ephemeralX25519PublicKey32 = _noble_curves_ed25519_js.x25519.getPublicKey(ephemeralX25519SecretKey32);
2284
+ const pairNonce32 = rng(32);
2285
+ const popDigest32 = computePairingPopDigest32({
2286
+ vaultId: params.vaultId,
2287
+ targetSlotId: params.targetSlotId,
2288
+ actorKindAndAlg: params.actorKindAndAlg,
2289
+ actorPubKeyPadded65,
2290
+ ephemeralX25519PublicKey32,
2291
+ slotExpiresAtSec,
2292
+ pairNonce32
2293
+ });
2294
+ let popSignature;
2295
+ if (params.signPopDigest) popSignature = await params.signPopDigest(popDigest32);
2296
+ else if (params.actorSecretKey32) popSignature = signPersonalActorChallenge({
2297
+ mode: params.actorKindAndAlg === "agent-ed25519" ? "ed25519" : "raw-p256",
2298
+ actorSecretKey32: params.actorSecretKey32,
2299
+ challengeDigest32: popDigest32
2300
+ });
2301
+ else {
2302
+ require_secp256k1_scalar.zeroizeBytes(ephemeralX25519SecretKey32);
2303
+ throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Provide actorSecretKey32 or signPopDigest");
2304
+ }
2305
+ return {
2306
+ bootstrapPackage: {
2307
+ version: 1,
2308
+ vaultId: params.vaultId,
2309
+ targetSlotId: params.targetSlotId,
2310
+ actorKindAndAlg: params.actorKindAndAlg,
2311
+ actorPubKeyPadded65Hex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(actorPubKeyPadded65)}`,
2312
+ slotExpiresAtSec: slotExpiresAtSec.toString(10),
2313
+ ephemeralX25519PublicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(ephemeralX25519PublicKey32)}`,
2314
+ pairNonceHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(pairNonce32)}`,
2315
+ popSignature
2316
+ },
2317
+ ephemeralX25519SecretKey32
2318
+ };
2319
+ }
2320
+ function verifyActorSlotPairingBootstrap(bootstrap, webauthnPolicy) {
2321
+ if (!bootstrap || bootstrap.version !== 1) throw new require_constants.MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid ActorSlotPairingBootstrapPackage");
2322
+ assertPrintableIdentifierAscii(bootstrap.vaultId, 64, "vaultId", "PERSONAL_BLOB_MALFORMED");
2323
+ assertPrintableIdentifierAscii(bootstrap.targetSlotId, 64, "targetSlotId", "PERSONAL_BLOB_MALFORMED");
2324
+ const actorPubKeyPadded65 = require_secp256k1_scalar.normalizeHexBytes(bootstrap.actorPubKeyPadded65Hex, 65);
2325
+ validateActorPublicKeyPadded65(bootstrap.actorKindAndAlg, actorPubKeyPadded65, "PERSONAL_BLOB_MALFORMED");
2326
+ const slotExpiresAtSec = parseStrictNonNegativeBigInt(bootstrap.slotExpiresAtSec, MAX_UINT64, "slotExpiresAtSec", "PERSONAL_BLOB_MALFORMED");
2327
+ if (isAgentActorKind(bootstrap.actorKindAndAlg) && slotExpiresAtSec <= 0n) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Agent pairing bootstrap requires slotExpiresAtSec > 0n");
2328
+ const epk32 = require_secp256k1_scalar.normalizeHexBytes(bootstrap.ephemeralX25519PublicKeyHex, 32);
2329
+ require_secp256k1_scalar.assertValidX25519PublicKey(epk32, "PERSONAL_ACTOR_SIGNATURE_INVALID");
2330
+ const pairNonce32 = require_secp256k1_scalar.normalizeHexBytes(bootstrap.pairNonceHex, 32);
2331
+ const popDigest32 = computePairingPopDigest32({
2332
+ vaultId: bootstrap.vaultId,
2333
+ targetSlotId: bootstrap.targetSlotId,
2334
+ actorKindAndAlg: bootstrap.actorKindAndAlg,
2335
+ actorPubKeyPadded65,
2336
+ ephemeralX25519PublicKey32: epk32,
2337
+ slotExpiresAtSec,
2338
+ pairNonce32
2339
+ });
2340
+ verifyPersonalActorSignature({
2341
+ actorKindAndAlg: bootstrap.actorKindAndAlg,
2342
+ actorPublicKey: actorPubKeyPadded65,
2343
+ challengeDigest32: popDigest32,
2344
+ signature: bootstrap.popSignature,
2345
+ webauthnPolicy
2346
+ });
2347
+ return {
2348
+ actorPubKeyPadded65,
2349
+ ephemeralX25519PublicKey32: epk32,
2350
+ pairNonce32,
2351
+ slotExpiresAtSec
2352
+ };
2353
+ }
2354
+ /**
2355
+ * Validates and computes `s_actor_2 = (s_actor_1 - delta) mod n`, rejecting ALL degenerate cases:
2356
+ * `delta == 0`, `delta >= n`, `s_actor_2 == 0`, `X_actor_2 == O`, `X_actor_2 == P_root` (`s_hsm_2 == 0`),
2357
+ * and `X_actor_2 == X_actor_1`.
2358
+ */
2359
+ function computeNonDegenerateActorResplitShare(params) {
2360
+ let sActor1;
2361
+ let delta;
2362
+ try {
2363
+ sActor1 = require_secp256k1_scalar.bytes32ToScalarNonZero(params.sActor1Bytes32);
2364
+ delta = require_secp256k1_scalar.bytes32ToScalarNonZero(params.deltaBytes32);
2365
+ } catch {
2366
+ throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Resplit scalars must satisfy 1 <= scalar < n");
2367
+ }
2368
+ const pRoot = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.rootPublicKeyComp33, 33), false);
2369
+ const xActor1 = require_secp256k1_scalar.mulBaseG(sActor1);
2370
+ if (xActor1.is0() || xActor1.equals(pRoot)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate source X_actor_1");
2371
+ const sActor2 = require_secp256k1_scalar.subModN(sActor1, delta);
2372
+ if (sActor2 === 0n) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate resplit: s_actor_2 == 0");
2373
+ const xActor2 = require_secp256k1_scalar.mulBaseG(sActor2);
2374
+ if (xActor2.is0() || xActor2.equals(pRoot) || xActor2.equals(xActor1)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate resplit: X_actor_2 hit O, P_root (s_hsm_2 == 0), or X_actor_1");
2375
+ return {
2376
+ sActor2Bytes32: require_secp256k1_scalar.scalarToBytes32(sActor2),
2377
+ xActor1Comp33: require_secp256k1_scalar.encodePointCompressed(xActor1),
2378
+ xActor2Comp33: require_secp256k1_scalar.encodePointCompressed(xActor2)
2379
+ };
2380
+ }
2381
+ /**
2382
+ * HSM-side zero-reconstruction re-split helper (`s_hsm_2 = (s_hsm_1 + delta) mod n`, `design.md` §4.2(2)).
2383
+ * Shared with Phase 2's `StatelessSealedHsmService.pairActorSlot`.
2384
+ */
2385
+ function applyHsmSlotResplitDelta(params) {
2386
+ let sHsm1;
2387
+ let delta;
2388
+ try {
2389
+ sHsm1 = require_secp256k1_scalar.bytes32ToScalarNonZero(params.sHsm1Bytes32);
2390
+ delta = require_secp256k1_scalar.bytes32ToScalarNonZero(params.deltaBytes32);
2391
+ } catch {
2392
+ throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "HSM resplit scalars must satisfy 1 <= scalar < n");
2393
+ }
2394
+ const pRoot = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.rootPublicKeyComp33, 33), false);
2395
+ const xActor1 = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.xActor1Comp33, 33), false);
2396
+ const xActor2 = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.xActor2Comp33, 33), false);
2397
+ if (!xActor1.add(require_secp256k1_scalar.mulBaseG(sHsm1)).equals(pRoot)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Source slot share does not match P_root");
2398
+ const sHsm2 = require_secp256k1_scalar.addModN(sHsm1, delta);
2399
+ if (sHsm2 === 0n) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate HSM resplit: s_hsm_2 == 0");
2400
+ if (xActor2.is0() || xActor2.equals(pRoot) || xActor2.equals(xActor1)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate target X_actor_2");
2401
+ if (!xActor2.add(require_secp256k1_scalar.mulBaseG(sHsm2)).equals(pRoot)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "X_actor_2 + s_hsm_2 * G != P_root");
2402
+ return require_secp256k1_scalar.scalarToBytes32(sHsm2);
2403
+ }
2404
+ function buildTargetShareBoxAad(vaultId, sourceSlotId, targetSlotId, xActor2Comp33, pairNonce32) {
2405
+ return require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_PAIR_SHARE_AAD_V1, [
2406
+ require_secp256k1_scalar.utf8Bytes(vaultId),
2407
+ require_secp256k1_scalar.utf8Bytes(sourceSlotId),
2408
+ require_secp256k1_scalar.utf8Bytes(targetSlotId),
2409
+ xActor2Comp33,
2410
+ pairNonce32
2411
+ ]);
2412
+ }
2413
+ async function initiateActorSlotResplit(params) {
2414
+ const rng = params.rng ?? require_secp256k1_scalar.defaultRandomBytes;
2415
+ if (params.targetBootstrap.vaultId !== params.vaultId) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Target pairing bootstrap vaultId mismatch");
2416
+ if (params.targetBootstrap.targetSlotId === params.sourceSlotId) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "targetSlotId must differ from sourceSlotId");
2417
+ if (params.kUnsealSecret1_32.length !== 32 || params.kUnsealSecret2_32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "kUnsealSecret1_32 and kUnsealSecret2_32 must be 32 bytes");
2418
+ const verifiedBoot = verifyActorSlotPairingBootstrap(params.targetBootstrap, params.webauthnPolicy);
2419
+ const pRootComp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.rootPublicKeyComp33, 33), false));
2420
+ const { canonicalPolicyUtf8 } = canonicalizePersonalVaultPolicy(params.policy);
2421
+ let deltaBytes32 = null;
2422
+ let sActor2Bytes32 = null;
2423
+ let xActor2Comp33 = null;
2424
+ const senderEsk32 = rng(32);
2425
+ let sharedTarget32 = null;
2426
+ let targetBoxKey32 = null;
2427
+ let targetPlaintext = null;
2428
+ let hsmPlaintext96 = null;
2429
+ try {
2430
+ for (let attempt = 0; attempt < 64; attempt++) {
2431
+ const candidateDelta = require_secp256k1_scalar.scalarToBytes32(require_secp256k1_scalar.sampleScalarNonZero(rng));
2432
+ try {
2433
+ const res = computeNonDegenerateActorResplitShare({
2434
+ sActor1Bytes32: params.sActor1Bytes32,
2435
+ deltaBytes32: candidateDelta,
2436
+ rootPublicKeyComp33: pRootComp33
2437
+ });
2438
+ deltaBytes32 = candidateDelta;
2439
+ sActor2Bytes32 = res.sActor2Bytes32;
2440
+ xActor2Comp33 = res.xActor2Comp33;
2441
+ break;
2442
+ } catch {
2443
+ require_secp256k1_scalar.zeroizeBytes(candidateDelta);
2444
+ }
2445
+ }
2446
+ if (!deltaBytes32 || !sActor2Bytes32 || !xActor2Comp33) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Failed to sample non-degenerate resplit delta");
2447
+ const senderEpk32 = _noble_curves_ed25519_js.x25519.getPublicKey(senderEsk32);
2448
+ sharedTarget32 = require_secp256k1_scalar.computeX25519SharedSecret(senderEsk32, verifiedBoot.ephemeralX25519PublicKey32, "PERSONAL_ACTOR_SIGNATURE_INVALID");
2449
+ targetBoxKey32 = (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, sharedTarget32, require_secp256k1_scalar.concatBytes(senderEpk32, verifiedBoot.ephemeralX25519PublicKey32), require_secp256k1_scalar.utf8Bytes(require_constants.DST_PERSONAL_PAIR_SHARE_BOX_V1), 32);
2450
+ targetPlaintext = require_secp256k1_scalar.concatBytes(sActor2Bytes32, pRootComp33, require_secp256k1_scalar.u64be(params.policyEpoch), canonicalPolicyUtf8);
2451
+ const targetIv12 = rng(12);
2452
+ const targetAad = buildTargetShareBoxAad(params.vaultId, params.sourceSlotId, params.targetBootstrap.targetSlotId, xActor2Comp33, verifiedBoot.pairNonce32);
2453
+ const { ciphertext: targetCt, tag16: targetTag16 } = await aes256GcmEncryptDetached({
2454
+ key32: targetBoxKey32,
2455
+ iv12: targetIv12,
2456
+ plaintext: targetPlaintext,
2457
+ aad: targetAad
2458
+ });
2459
+ hsmPlaintext96 = require_secp256k1_scalar.concatBytes(params.kUnsealSecret1_32, params.kUnsealSecret2_32, deltaBytes32);
2460
+ const hsmInboundTransportBox = await sealHsmInboundTransportBox({
2461
+ hsmTransportPub32: params.hsmTransportPub32,
2462
+ vaultId: params.vaultId,
2463
+ slotId: params.sourceSlotId,
2464
+ challengeNonce32: params.challengeNonce32,
2465
+ headerMac32: params.sourceHeaderMac32,
2466
+ plaintext: hsmPlaintext96,
2467
+ rng
2468
+ });
2469
+ const pairResplitChallengeDigest32 = buildPersonalPairResplitChallengeDigest32({
2470
+ vaultId: params.vaultId,
2471
+ sourceSlotId: params.sourceSlotId,
2472
+ challengeNonce32: params.challengeNonce32,
2473
+ sourceHeaderMac32: params.sourceHeaderMac32,
2474
+ targetSlotId: params.targetBootstrap.targetSlotId,
2475
+ targetActorKindAndAlg: params.targetBootstrap.actorKindAndAlg,
2476
+ targetActorPubKeyPadded65: verifiedBoot.actorPubKeyPadded65,
2477
+ xActor2Comp33,
2478
+ targetSlotExpiresAtSec: verifiedBoot.slotExpiresAtSec,
2479
+ targetPairNonce32: verifiedBoot.pairNonce32
2480
+ });
2481
+ return {
2482
+ xActor2Comp33,
2483
+ encryptedTargetShareBox: {
2484
+ epkX25519Hex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(senderEpk32)}`,
2485
+ ivHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(targetIv12)}`,
2486
+ tagHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(targetTag16)}`,
2487
+ ciphertextHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(targetCt)}`,
2488
+ xActor2PublicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(xActor2Comp33)}`
2489
+ },
2490
+ hsmInboundTransportBox,
2491
+ pairResplitChallengeDigest32
2492
+ };
2493
+ } finally {
2494
+ require_secp256k1_scalar.zeroizeBytes(deltaBytes32, sActor2Bytes32, senderEsk32, sharedTarget32, targetBoxKey32, targetPlaintext, hsmPlaintext96);
2495
+ }
2496
+ }
2497
+ async function completeActorSlotPairingOnTarget(params) {
2498
+ if (params.ephemeralX25519SecretKey32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "ephemeralX25519SecretKey32 must be 32 bytes");
2499
+ const parsedBlob2 = parseHsmSealedBlobHeader(params.hsmSealedBlob2);
2500
+ if (parsedBlob2.header.vaultId !== params.vaultId || parsedBlob2.header.slotId !== params.targetBootstrap.targetSlotId || parsedBlob2.header.actorKindAndAlg !== params.targetBootstrap.actorKindAndAlg) {
2501
+ require_secp256k1_scalar.zeroizeBytes(params.ephemeralX25519SecretKey32);
2502
+ throw new require_constants.MpcProtocolError("PERSONAL_BLOB_TAMPERED", "HsmSealedBlob_2 header does not match target slot bootstrap");
2503
+ }
2504
+ const expectedPub65 = require_secp256k1_scalar.normalizeHexBytes(params.targetBootstrap.actorPubKeyPadded65Hex, 65);
2505
+ if (!require_secp256k1_scalar.constantTimeEqual(parsedBlob2.header.actorPubKeyPadded65, expectedPub65)) {
2506
+ require_secp256k1_scalar.zeroizeBytes(params.ephemeralX25519SecretKey32);
2507
+ throw new require_constants.MpcProtocolError("PERSONAL_BLOB_TAMPERED", "HsmSealedBlob_2 actor public key mismatch");
2508
+ }
2509
+ let shared32 = null;
2510
+ let boxKey32 = null;
2511
+ let plaintext = null;
2512
+ let sActor2Bytes32 = null;
2513
+ try {
2514
+ const senderEpk32 = require_secp256k1_scalar.normalizeHexBytes(params.encryptedTargetShareBox.epkX25519Hex, 32);
2515
+ require_secp256k1_scalar.assertValidX25519PublicKey(senderEpk32, "PERSONAL_ENVELOPE_AUTH_FAILED");
2516
+ const targetEpk32 = _noble_curves_ed25519_js.x25519.getPublicKey(params.ephemeralX25519SecretKey32);
2517
+ const pairNonce32 = require_secp256k1_scalar.normalizeHexBytes(params.targetBootstrap.pairNonceHex, 32);
2518
+ const xActor2Comp33 = require_secp256k1_scalar.normalizeHexBytes(params.encryptedTargetShareBox.xActor2PublicKeyHex, 33);
2519
+ const iv12 = require_secp256k1_scalar.normalizeHexBytes(params.encryptedTargetShareBox.ivHex, 12);
2520
+ const tag16 = require_secp256k1_scalar.normalizeHexBytes(params.encryptedTargetShareBox.tagHex, 16);
2521
+ const ciphertext = require_secp256k1_scalar.normalizeHexBytes(params.encryptedTargetShareBox.ciphertextHex);
2522
+ shared32 = require_secp256k1_scalar.computeX25519SharedSecret(params.ephemeralX25519SecretKey32, senderEpk32, "PERSONAL_ENVELOPE_AUTH_FAILED");
2523
+ boxKey32 = (0, _noble_hashes_hkdf_js.hkdf)(_noble_hashes_sha2_js.sha256, shared32, require_secp256k1_scalar.concatBytes(senderEpk32, targetEpk32), require_secp256k1_scalar.utf8Bytes(require_constants.DST_PERSONAL_PAIR_SHARE_BOX_V1), 32);
2524
+ const aad = buildTargetShareBoxAad(params.vaultId, params.sourceSlotId, params.targetBootstrap.targetSlotId, xActor2Comp33, pairNonce32);
2525
+ plaintext = await aes256GcmDecryptDetached({
2526
+ key32: boxKey32,
2527
+ iv12,
2528
+ ciphertext,
2529
+ tag16,
2530
+ aad,
2531
+ authFailureCode: "PERSONAL_ENVELOPE_AUTH_FAILED"
2532
+ });
2533
+ if (plaintext.length < 75) throw new require_constants.MpcProtocolError("PERSONAL_ENVELOPE_AUTH_FAILED", "Decrypted target share payload truncated");
2534
+ sActor2Bytes32 = plaintext.slice(0, 32);
2535
+ const pRootComp33 = plaintext.slice(32, 65);
2536
+ const policyEpoch = readU64BE(plaintext, 65);
2537
+ const policyJson = utf8DecodeStrict(plaintext.subarray(73), "PERSONAL_ENVELOPE_AUTH_FAILED");
2538
+ const sActor2 = require_secp256k1_scalar.bytes32ToScalarNonZero(sActor2Bytes32);
2539
+ const pRoot = require_secp256k1_scalar.decodePointCompressed(pRootComp33, false);
2540
+ const derivedXActor2 = require_secp256k1_scalar.mulBaseG(sActor2);
2541
+ if (derivedXActor2.is0() || derivedXActor2.equals(pRoot) || !require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.encodePointCompressed(derivedXActor2), xActor2Comp33)) throw new require_constants.MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Target share X_actor_2 verification failed");
2542
+ const { canonicalPolicy, policyHash32 } = canonicalizePersonalVaultPolicy(JSON.parse(policyJson));
2543
+ if (!require_secp256k1_scalar.constantTimeEqual(parsedBlob2.header.rootPublicKeyComp33, pRootComp33) || parsedBlob2.header.policyEpoch !== policyEpoch || !require_secp256k1_scalar.constantTimeEqual(parsedBlob2.header.policyHash32, policyHash32)) throw new require_constants.MpcProtocolError("PERSONAL_BLOB_TAMPERED", "HsmSealedBlob_2 policy/root mismatch against Slot 1 box");
2544
+ return {
2545
+ deviceEnvelope: await sealDeviceShareEnvelope({
2546
+ vaultId: params.vaultId,
2547
+ slotId: params.targetBootstrap.targetSlotId,
2548
+ rootPublicKeyComp33: pRootComp33,
2549
+ sActorBytes32: sActor2Bytes32,
2550
+ kHw32: params.kHw32,
2551
+ kPwdClient32: params.kPwdClient32,
2552
+ rng: params.rng
2553
+ }),
2554
+ rootPublicKeyComp33: pRootComp33,
2555
+ xActor2Comp33,
2556
+ policyEpoch,
2557
+ policy: canonicalPolicy
2558
+ };
2559
+ } finally {
2560
+ require_secp256k1_scalar.zeroizeBytes(params.ephemeralX25519SecretKey32, shared32, boxKey32, plaintext, sActor2Bytes32);
2561
+ }
2562
+ }
2563
+ function computeColdManifestHash32(manifest) {
2564
+ const parts = [
2565
+ require_secp256k1_scalar.utf8Bytes(manifest.vaultId),
2566
+ require_secp256k1_scalar.normalizeHexBytes(manifest.rootPublicKeyHex, 33),
2567
+ require_secp256k1_scalar.utf8Bytes(manifest.rootEthAddress),
2568
+ require_secp256k1_scalar.u8(manifest.tCold),
2569
+ require_secp256k1_scalar.u8(manifest.nCold),
2570
+ require_secp256k1_scalar.u8(manifest.coldFeldmanCommitmentsHex.length),
2571
+ ...manifest.coldFeldmanCommitmentsHex.map((c) => require_secp256k1_scalar.normalizeHexBytes(c, 33)),
2572
+ require_secp256k1_scalar.u8(manifest.plates.length)
2573
+ ];
2574
+ for (const plate of manifest.plates) parts.push(require_secp256k1_scalar.u8(plate.guardianIndex), require_secp256k1_scalar.utf8Bytes(plate.plateLabel), require_secp256k1_scalar.normalizeHexBytes(plate.coldPublicShareHex, 33), require_secp256k1_scalar.utf8Bytes(plate.decoyEthAddress));
2575
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_COLD_MANIFEST_V1, ...parts);
2576
+ }
2577
+ function verifyPersonalColdRecoveryKitManifest(manifest) {
2578
+ if (!manifest || manifest.version !== 1) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", "Invalid PersonalColdRecoveryKitManifest version");
2579
+ if (manifest.tCold !== 2 || manifest.nCold !== 2 && manifest.nCold !== 3) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", "Personal cold recovery kit requires 2-of-2 or 2-of-3");
2580
+ if (manifest.coldFeldmanCommitmentsHex.length !== manifest.tCold || manifest.plates.length !== manifest.nCold) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", "Malformed Feldman commitments or plate count in manifest");
2581
+ const rootPubComp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(manifest.rootPublicKeyHex, 33), false));
2582
+ if (!require_secp256k1_scalar.constantTimeEqual(rootPubComp33, require_secp256k1_scalar.normalizeHexBytes(manifest.coldFeldmanCommitmentsHex[0], 33))) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", "Cold Feldman C_0 does not match rootPublicKeyHex");
2583
+ const derivedAddr = require_tweak.pointToEthAddress(rootPubComp33).checksumAddress;
2584
+ if (manifest.rootEthAddress !== derivedAddr) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", "Manifest rootEthAddress mismatch against P_root");
2585
+ for (const cHex of manifest.coldFeldmanCommitmentsHex) require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(cHex, 33), false);
2586
+ for (let i = 0; i < manifest.plates.length; i++) {
2587
+ const p = manifest.plates[i];
2588
+ if (p.guardianIndex !== i + 1) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", "Non-sequential plate guardianIndex in manifest");
2589
+ require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(p.coldPublicShareHex, 33), false);
2590
+ require_tweak.parseStrictEthAddress(p.decoyEthAddress);
2591
+ }
2592
+ if (!require_secp256k1_scalar.constantTimeEqual(computeColdManifestHash32(manifest), require_secp256k1_scalar.normalizeHexBytes(manifest.manifestHashHex, 32))) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", "Cold recovery manifest integrity hash mismatch");
2593
+ return {
2594
+ rootPublicKeyComp33: rootPubComp33,
2595
+ rootEthAddress: derivedAddr
2596
+ };
2597
+ }
2598
+ async function bootstrapPersonalVaultClient(params) {
2599
+ const rng = params.rng ?? require_secp256k1_scalar.defaultRandomBytes;
2600
+ const tCold = params.tCold ?? 2;
2601
+ const nCold = params.nCold ?? 3;
2602
+ if (tCold !== 2 || nCold !== 2 && nCold !== 3) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Personal cold recovery supports 2-of-2 or 2-of-3");
2603
+ if (params.policy.vaultId !== params.vaultId) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "policy.vaultId must match vaultId");
2604
+ const policyEpoch = params.policyEpoch ?? 1n;
2605
+ const slotExpiresAtSec = params.slotExpiresAtSec ?? 0n;
2606
+ const { canonicalPolicyJson, policyHash32 } = canonicalizePersonalVaultPolicy(params.policy);
2607
+ let sk = 0n;
2608
+ let skBytes32 = null;
2609
+ let sActor1Bytes32 = null;
2610
+ let kPwdClient32 = null;
2611
+ const polyCoeffs = [];
2612
+ try {
2613
+ sk = require_secp256k1_scalar.sampleScalarNonZero(rng);
2614
+ skBytes32 = require_secp256k1_scalar.scalarToBytes32(sk);
2615
+ const pRoot = require_secp256k1_scalar.mulBaseG(sk);
2616
+ const rootPublicKeyComp33 = require_secp256k1_scalar.encodePointCompressed(pRoot);
2617
+ const rootEthAddress = require_tweak.pointToEthAddress(pRoot).checksumAddress;
2618
+ let sActor1 = 0n;
2619
+ let sHsm1 = 0n;
2620
+ for (;;) {
2621
+ const cand = require_secp256k1_scalar.sampleScalarNonZero(rng);
2622
+ const rem = require_secp256k1_scalar.subModN(sk, cand);
2623
+ if (rem >= 1n && rem < require_constants.SECP256K1_N) {
2624
+ const xA = require_secp256k1_scalar.mulBaseG(cand);
2625
+ if (!xA.is0() && !xA.equals(pRoot)) {
2626
+ sActor1 = cand;
2627
+ sHsm1 = rem;
2628
+ break;
2629
+ }
2630
+ }
2631
+ }
2632
+ sActor1Bytes32 = require_secp256k1_scalar.scalarToBytes32(sActor1);
2633
+ const sHsm1Bytes32 = require_secp256k1_scalar.scalarToBytes32(sHsm1);
2634
+ const xActor1Comp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.mulBaseG(sActor1));
2635
+ const header319 = encodeHsmSealedBlobHeader319({
2636
+ kid: params.kid,
2637
+ vaultId: params.vaultId,
2638
+ slotId: params.initialSlotId,
2639
+ rootPublicKeyComp33,
2640
+ policyEpoch,
2641
+ actorKindAndAlg: params.actorKindAndAlg,
2642
+ actorPublicKey: params.actorPublicKey,
2643
+ slotExpiresAtSec,
2644
+ policyHash32
2645
+ });
2646
+ let coldSharesScalars = [];
2647
+ for (;;) {
2648
+ polyCoeffs.length = 0;
2649
+ polyCoeffs.push(sk);
2650
+ for (let l = 1; l < tCold; l++) polyCoeffs.push(require_secp256k1_scalar.sampleScalarNonZero(rng));
2651
+ let allNonZero = true;
2652
+ coldSharesScalars = [];
2653
+ for (let k = 1; k <= nCold; k++) {
2654
+ const yk = require_secp256k1_scalar.evaluatePolynomialModN(polyCoeffs, BigInt(k));
2655
+ if (yk === 0n) {
2656
+ allNonZero = false;
2657
+ break;
2658
+ }
2659
+ coldSharesScalars.push(yk);
2660
+ }
2661
+ if (allNonZero) break;
2662
+ }
2663
+ const coldFeldmanCommitmentsComp33 = polyCoeffs.map((c) => require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.mulBaseG(c)));
2664
+ const coldFeldmanCommitmentsHex = coldFeldmanCommitmentsComp33.map((c) => `0x${(0, _noble_hashes_utils_js.bytesToHex)(c)}`);
2665
+ const platesPublic = [];
2666
+ const platesWords24 = [];
2667
+ for (let idx = 0; idx < nCold; idx++) {
2668
+ const guardianIndex = idx + 1;
2669
+ const shareBytes32 = require_secp256k1_scalar.scalarToBytes32(coldSharesScalars[idx]);
2670
+ coldSharesScalars[idx] = 0n;
2671
+ try {
2672
+ const words24 = require_steel_mnemonic.encodeColdShareToBip39Words24(shareBytes32);
2673
+ const identified = require_steel_mnemonic.identifyColdShareIndexViaFeldman(shareBytes32, coldFeldmanCommitmentsComp33, nCold);
2674
+ if (identified.guardianIndex !== guardianIndex) throw new require_constants.MpcProtocolError("COLD_SHARE_UNKNOWN_INDEX", "Feldman self-check failed during bootstrap");
2675
+ const decoyEthAddress = require_steel_mnemonic.deriveBip44EthAddressFromWords24(words24);
2676
+ const plateLabel = require_steel_mnemonic.guardianIndexToPlateLabel(guardianIndex);
2677
+ platesPublic.push({
2678
+ guardianIndex,
2679
+ plateLabel,
2680
+ coldPublicShareHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(identified.coldPublicShareComp33)}`,
2681
+ decoyEthAddress
2682
+ });
2683
+ platesWords24.push({
2684
+ guardianIndex,
2685
+ plateLabel,
2686
+ words24
2687
+ });
2688
+ } finally {
2689
+ require_secp256k1_scalar.zeroizeBytes(shareBytes32);
2690
+ }
2691
+ }
2692
+ const unsignedManifest = {
2693
+ version: 1,
2694
+ vaultId: params.vaultId,
2695
+ rootPublicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(rootPublicKeyComp33)}`,
2696
+ rootEthAddress,
2697
+ tCold,
2698
+ nCold,
2699
+ coldFeldmanCommitmentsHex,
2700
+ plates: platesPublic
2701
+ };
2702
+ const manifest = {
2703
+ ...unsignedManifest,
2704
+ manifestHashHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(computeColdManifestHash32(unsignedManifest))}`
2705
+ };
2706
+ const vaultSalt32 = rng(32);
2707
+ const derivedPwd = derivePersonalWakePasswordKeys({
2708
+ password: params.wakePassword,
2709
+ vaultSalt32,
2710
+ kdf: params.kdf,
2711
+ pbkdf2Iterations: params.pbkdf2Iterations,
2712
+ scryptOpts: params.scryptOpts
2713
+ });
2714
+ kPwdClient32 = derivedPwd.kPwdClient32;
2715
+ const deviceEnvelope = await sealDeviceShareEnvelope({
2716
+ vaultId: params.vaultId,
2717
+ slotId: params.initialSlotId,
2718
+ rootPublicKeyComp33,
2719
+ sActorBytes32: sActor1Bytes32,
2720
+ kHw32: params.kHw32,
2721
+ kPwdClient32,
2722
+ rng
2723
+ });
2724
+ return {
2725
+ vaultId: params.vaultId,
2726
+ initialSlotId: params.initialSlotId,
2727
+ rootPublicKeyComp33,
2728
+ rootEthAddress,
2729
+ xActor1Comp33,
2730
+ header319,
2731
+ sHsm1Bytes32,
2732
+ kPwdHsm32: derivedPwd.kPwdHsm32,
2733
+ vaultSalt32,
2734
+ deviceEnvelope,
2735
+ policyEpoch,
2736
+ canonicalPolicyJson,
2737
+ policyHash32,
2738
+ coldRecoveryKit: {
2739
+ manifest,
2740
+ platesWords24
2741
+ }
2742
+ };
2743
+ } finally {
2744
+ sk = 0n;
2745
+ polyCoeffs.fill(0n);
2746
+ require_secp256k1_scalar.zeroizeBytes(skBytes32, sActor1Bytes32, kPwdClient32);
2747
+ }
2748
+ }
2749
+ function recoverPersonalVaultRootOffline(params) {
2750
+ const { rootPublicKeyComp33, rootEthAddress } = verifyPersonalColdRecoveryKitManifest(params.manifest);
2751
+ if (!Array.isArray(params.platesWords24) || params.platesWords24.length < params.manifest.tCold) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", `Need at least ${params.manifest.tCold} 24-word plates, got ${params.platesWords24?.length ?? 0}`);
2752
+ const decodedShares = [];
2753
+ try {
2754
+ const seenIndices = /* @__PURE__ */ new Set();
2755
+ for (const mnemonic of params.platesWords24) {
2756
+ const shareBytes32 = require_steel_mnemonic.decodeBip39Words24ToColdShare(mnemonic);
2757
+ let identified;
2758
+ try {
2759
+ identified = require_steel_mnemonic.identifyColdShareIndexViaFeldman(shareBytes32, params.manifest.coldFeldmanCommitmentsHex, params.manifest.nCold);
2760
+ } catch (err) {
2761
+ require_secp256k1_scalar.zeroizeBytes(shareBytes32);
2762
+ throw err;
2763
+ }
2764
+ if (seenIndices.has(identified.guardianIndex)) {
2765
+ require_secp256k1_scalar.zeroizeBytes(shareBytes32);
2766
+ throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", `Duplicate cold recovery plate index ${identified.guardianIndex}`);
2767
+ }
2768
+ seenIndices.add(identified.guardianIndex);
2769
+ decodedShares.push({
2770
+ index: identified.guardianIndex,
2771
+ bytes32: shareBytes32
2772
+ });
2773
+ if (decodedShares.length === params.manifest.tCold) break;
2774
+ }
2775
+ const subset = decodedShares.map((s) => s.index);
2776
+ let sk = 0n;
2777
+ for (const item of decodedShares) {
2778
+ const yk = require_secp256k1_scalar.bytes32ToScalarNonZero(item.bytes32);
2779
+ const lambdaK = require_secp256k1_scalar.lagrangeCoefficientAtZero(item.index, subset);
2780
+ sk = require_secp256k1_scalar.addModN(sk, require_secp256k1_scalar.mulModN(lambdaK, yk));
2781
+ }
2782
+ require_secp256k1_scalar.assertScalarNonZero(sk, "recoveredRootScalar");
2783
+ if (!require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.mulBaseG(sk)), rootPublicKeyComp33)) {
2784
+ sk = 0n;
2785
+ throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", "Interpolated cold shares do not match P_root");
2786
+ }
2787
+ const rootScalarBytes32 = require_secp256k1_scalar.scalarToBytes32(sk);
2788
+ sk = 0n;
2789
+ return {
2790
+ rootScalarBytes32,
2791
+ rootPublicKeyComp33,
2792
+ rootEthAddress,
2793
+ usedGuardianIndices: subset
2794
+ };
2795
+ } finally {
2796
+ for (const item of decodedShares) require_secp256k1_scalar.zeroizeBytes(item.bytes32);
2797
+ }
2798
+ }
2799
+ function derivePersonalVaultChildKey(params) {
2800
+ const pRootComp33 = require_secp256k1_scalar.normalizeHexBytes(params.rootPublicKeyComp33, 33);
2801
+ const spec = params.derivation ?? { tweakMode: "untweaked" };
2802
+ if (spec.tweakMode === "untweaked") return require_tweak.deriveUntweakedChild(pRootComp33);
2803
+ if (spec.tweakMode === "role-bound") return require_tweak.deriveRoleBoundChild({
2804
+ rootPublicKey: pRootComp33,
2805
+ rootId: params.vaultId,
2806
+ role: spec.role,
2807
+ ethChainId: spec.ethChainId,
2808
+ tweakLabel: spec.tweakLabel
2809
+ });
2810
+ if (spec.tweakMode === "rule-bound") return require_tweak.deriveRuleBoundChild({
2811
+ rootPublicKey: pRootComp33,
2812
+ rootId: params.vaultId,
2813
+ controllerDid: spec.controllerDid,
2814
+ ethChainId: spec.ethChainId,
2815
+ ruleHash: spec.ruleHash
2816
+ });
2817
+ throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Unsupported PersonalChildDerivationInput");
2818
+ }
2819
+ function signPersonalVaultRecoverySweepOffline(params) {
2820
+ const parsedDest = require_tweak.parseStrictEthAddress(params.destinationAddress);
2821
+ if (!Array.isArray(params.sweeps) || params.sweeps.length === 0) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "sweeps list must be non-empty");
2822
+ const recovered = recoverPersonalVaultRootOffline({
2823
+ manifest: params.manifest,
2824
+ platesWords24: params.platesWords24
2825
+ });
2826
+ let skRoot = 0n;
2827
+ let childSkBytes32 = null;
2828
+ try {
2829
+ skRoot = require_secp256k1_scalar.bytes32ToScalarNonZero(recovered.rootScalarBytes32);
2830
+ const results = [];
2831
+ for (const item of params.sweeps) {
2832
+ const derivedChild = derivePersonalVaultChildKey({
2833
+ vaultId: params.manifest.vaultId,
2834
+ rootPublicKeyComp33: recovered.rootPublicKeyComp33,
2835
+ derivation: item.derivation
2836
+ });
2837
+ const skChild = require_secp256k1_scalar.addModN(skRoot, derivedChild.tweakScalar);
2838
+ require_secp256k1_scalar.assertScalarNonZero(skChild, "skChild");
2839
+ childSkBytes32 = require_secp256k1_scalar.scalarToBytes32(skChild);
2840
+ try {
2841
+ let txFields;
2842
+ if (item.asset.kind === "native-eth") {
2843
+ if (item.asset.valueWei <= 0n) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Native ETH sweep valueWei must be > 0");
2844
+ txFields = {
2845
+ chainId: item.chainId,
2846
+ nonce: item.nonce,
2847
+ maxPriorityFeePerGasWei: item.maxPriorityFeePerGasWei,
2848
+ maxFeePerGasWei: item.maxFeePerGasWei,
2849
+ gasLimit: item.gasLimit ?? 21000n,
2850
+ to: parsedDest.checksumAddress,
2851
+ valueWei: item.asset.valueWei,
2852
+ data: "0x",
2853
+ accessList: item.accessList
2854
+ };
2855
+ } else {
2856
+ const tokenAddr = require_tweak.parseStrictEthAddress(item.asset.tokenContract).checksumAddress;
2857
+ const calldata = require_rlp_eip1559.encodeErc20TransferCalldata(parsedDest.checksumAddress, item.asset.tokenAmount);
2858
+ txFields = {
2859
+ chainId: item.chainId,
2860
+ nonce: item.nonce,
2861
+ maxPriorityFeePerGasWei: item.maxPriorityFeePerGasWei,
2862
+ maxFeePerGasWei: item.maxFeePerGasWei,
2863
+ gasLimit: item.gasLimit ?? 65000n,
2864
+ to: tokenAddr,
2865
+ valueWei: 0n,
2866
+ data: calldata,
2867
+ accessList: item.accessList
2868
+ };
2869
+ }
2870
+ const unsigned = require_rlp_eip1559.encodeUnsignedEip1559Tx(txFields);
2871
+ const sigRecovered65 = _noble_curves_secp256k1_js.secp256k1.sign(unsigned.signingDigest32, childSkBytes32, {
2872
+ prehash: false,
2873
+ lowS: true,
2874
+ format: "recovered"
2875
+ });
2876
+ const yParity = sigRecovered65[0];
2877
+ const r = require_secp256k1_scalar.bytesToBigIntBE(sigRecovered65.subarray(1, 33));
2878
+ const s = require_secp256k1_scalar.bytesToBigIntBE(sigRecovered65.subarray(33, 65));
2879
+ if (s > require_constants.SECP256K1_HALF_N) throw new require_constants.MpcProtocolError("SIGN_AGGREGATION_FAILED", "Unexpected high-S offline sweep signature");
2880
+ const encodedSigned = require_rlp_eip1559.encodeSignedEip1559Tx({
2881
+ tx: txFields,
2882
+ yParity,
2883
+ r,
2884
+ s
2885
+ });
2886
+ if (require_rlp_eip1559.decodeAndRecoverSignedEip1559Tx(encodedSigned.rawSignedTxBytes).senderChecksumAddress !== derivedChild.ethAddress) throw new require_constants.MpcProtocolError("SIGN_AGGREGATION_FAILED", "Offline sweep ecrecover sender mismatch");
2887
+ results.push({
2888
+ senderAddress: derivedChild.ethAddress,
2889
+ destinationAddress: parsedDest.checksumAddress,
2890
+ rawSignedTxBytes: encodedSigned.rawSignedTxBytes,
2891
+ rawSignedTxHex: encodedSigned.rawSignedTxHex,
2892
+ txHashHex: encodedSigned.txHashHex
2893
+ });
2894
+ } finally {
2895
+ require_secp256k1_scalar.zeroizeBytes(childSkBytes32);
2896
+ childSkBytes32 = null;
2897
+ }
2898
+ }
2899
+ return results;
2900
+ } finally {
2901
+ skRoot = 0n;
2902
+ require_secp256k1_scalar.zeroizeBytes(recovered.rootScalarBytes32, childSkBytes32);
2903
+ }
2904
+ }
2905
+ function derivePersonalBaseOtContext(cluster, sessionNonce32, senderSlotB, receiverSlotA) {
2906
+ return require_secp256k1_scalar.hashTranscriptSha256(require_constants.DST_PERSONAL_BASEOT_CTX_V1, require_secp256k1_scalar.utf8Bytes(cluster.rootId), require_secp256k1_scalar.u64be(cluster.keyEpoch), cluster.hDkg32, sessionNonce32, require_secp256k1_scalar.u16be(senderSlotB), require_secp256k1_scalar.u16be(receiverSlotA));
2907
+ }
2908
+ /**
2909
+ * Stateful `Slot 2` (HSM Cosigner) 2-party presignature responder session.
2910
+ * Consumes `sHsmBytes32` once at construction (wiping it immediately after converting to Shamir Slot 2)
2911
+ * and stores the completed `PresignatureShareRecord` into the HSM's `VolatilePresignaturePool`.
2912
+ */
2913
+ var PersonalCosignerResponderSession = class {
2914
+ constructor(params) {
2915
+ this.baseOtReceiverA2 = null;
2916
+ this.baseOtPendingB2 = null;
2917
+ this.baseOtSenderB2 = null;
2918
+ this.partySession = null;
2919
+ this.hsmR1Commitment = null;
2920
+ this.hsmR1Reveal = null;
2921
+ this.clientR3 = null;
2922
+ this.hsmR3 = null;
2923
+ this.hsmR4 = null;
2924
+ this.closed = false;
2925
+ this.presignSessionId = params.presignSessionId;
2926
+ this.rng = params.rng ?? require_secp256k1_scalar.defaultRandomBytes;
2927
+ this.sessionNonce32 = require_secp256k1_scalar.normalizeHexBytes(params.sessionNonce32, 32);
2928
+ try {
2929
+ this.cluster = buildPersonalVaultClusterInfo({
2930
+ vaultId: params.vaultId,
2931
+ slotId: params.slotId,
2932
+ policyEpoch: params.policyEpoch,
2933
+ rootPublicKeyComp33: params.rootPublicKeyComp33,
2934
+ xActorComp33: params.xActorComp33
2935
+ });
2936
+ this.shamirSlot2Share32 = additiveToShamirSlot2Share(params.sHsmBytes32);
2937
+ } finally {
2938
+ require_secp256k1_scalar.zeroizeBytes(params.sHsmBytes32);
2939
+ }
2940
+ }
2941
+ get isClosed() {
2942
+ return this.closed;
2943
+ }
2944
+ abort() {
2945
+ this.closed = true;
2946
+ require_secp256k1_scalar.zeroizeBytes(this.shamirSlot2Share32, this.baseOtPendingB2?.yScalarBytes32);
2947
+ this.shamirSlot2Share32 = null;
2948
+ if (this.baseOtReceiverA2) {
2949
+ require_ot.wipeBaseOtReceiverState(this.baseOtReceiverA2);
2950
+ this.baseOtReceiverA2 = null;
2951
+ }
2952
+ if (this.baseOtSenderB2) {
2953
+ require_ot.wipeBaseOtSenderState(this.baseOtSenderB2);
2954
+ this.baseOtSenderB2 = null;
2955
+ }
2956
+ if (this.partySession) {
2957
+ this.partySession.abort();
2958
+ this.partySession = null;
2959
+ }
2960
+ }
2961
+ handleInit(req) {
2962
+ if (this.closed || this.baseOtReceiverA2 !== null) {
2963
+ this.abort();
2964
+ throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "Cosigner responder init already executed");
2965
+ }
2966
+ try {
2967
+ if (!require_secp256k1_scalar.constantTimeEqual(req.sessionNonce32, this.sessionNonce32)) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "sessionNonce32 mismatch");
2968
+ const ctxB1A2 = derivePersonalBaseOtContext(this.cluster, this.sessionNonce32, 1, 2);
2969
+ const ctxB2A1 = derivePersonalBaseOtContext(this.cluster, this.sessionNonce32, 2, 1);
2970
+ const step2Res = require_ot.baseOtReceiverStep2({
2971
+ ctxBaseOt: ctxB1A2,
2972
+ senderSlotB: 1,
2973
+ receiverSlotA: 2,
2974
+ step1Message: req.baseOtB1A2Step1,
2975
+ rng: this.rng
2976
+ });
2977
+ this.baseOtReceiverA2 = step2Res.receiverState;
2978
+ const step1Res = require_ot.baseOtSenderStep1({
2979
+ ctxBaseOt: ctxB2A1,
2980
+ senderSlotB: 2,
2981
+ receiverSlotA: 1,
2982
+ rng: this.rng
2983
+ });
2984
+ this.baseOtPendingB2 = step1Res.pending;
2985
+ return {
2986
+ presignSessionId: this.presignSessionId,
2987
+ baseOtB1A2Step2: step2Res.message,
2988
+ baseOtB2A1Step1: step1Res.message
2989
+ };
2990
+ } catch (err) {
2991
+ this.abort();
2992
+ throw err;
2993
+ }
2994
+ }
2995
+ handleStep(req, targetPool) {
2996
+ if (this.closed || req.presignSessionId !== this.presignSessionId) {
2997
+ this.abort();
2998
+ throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "Invalid or closed presignSessionId");
2999
+ }
3000
+ try {
3001
+ if (req.step === "r1-commit") {
3002
+ if (!this.baseOtPendingB2 || !this.baseOtReceiverA2 || !this.shamirSlot2Share32 || this.partySession) throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "Unexpected r1-commit step");
3003
+ this.baseOtSenderB2 = require_ot.baseOtSenderStep3({
3004
+ pending: this.baseOtPendingB2,
3005
+ step2Message: req.baseOtB2A1Step2
3006
+ });
3007
+ this.baseOtPendingB2 = null;
3008
+ const channels = {
3009
+ ownerSlot: 2,
3010
+ asExtendedSenderA: new Map([[1, this.baseOtReceiverA2]]),
3011
+ asExtendedReceiverB: new Map([[1, this.baseOtSenderB2]])
3012
+ };
3013
+ try {
3014
+ this.partySession = new require_presign.PresignPartySession({
3015
+ slot: 2,
3016
+ nodeSecretShareBytes32: this.shamirSlot2Share32,
3017
+ cluster: this.cluster,
3018
+ subset: [1, 2],
3019
+ sessionNonce32: this.sessionNonce32,
3020
+ baseOtChannels: channels,
3021
+ rng: this.rng
3022
+ });
3023
+ } finally {
3024
+ require_secp256k1_scalar.zeroizeBytes(this.shamirSlot2Share32);
3025
+ this.shamirSlot2Share32 = null;
3026
+ }
3027
+ const c2 = this.partySession.round1CreateCommitment();
3028
+ const rev2 = this.partySession.round1ReceiveCommitmentsAndReveal([req.clientR1Commitment, c2]);
3029
+ this.hsmR1Commitment = c2;
3030
+ this.hsmR1Reveal = rev2.reveal;
3031
+ return {
3032
+ step: "r1-commit-ack",
3033
+ presigId32: rev2.presigId32,
3034
+ hsmR1Commitment: c2,
3035
+ hsmR1Reveal: rev2.reveal
3036
+ };
3037
+ }
3038
+ if (!this.partySession) throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "PresignPartySession not initialized");
3039
+ if (req.step === "r1-reveal-and-ot1") {
3040
+ if (!this.hsmR1Commitment || !this.hsmR1Reveal) throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "Missing Round-1 HSM state");
3041
+ this.partySession.round1VerifyAllReveals([req.clientR1Reveal, this.hsmR1Reveal]);
3042
+ return {
3043
+ step: "ot1-and-ot2",
3044
+ hsmOt1: this.partySession.round2CreateOtStep1Messages(),
3045
+ hsmOt2: this.partySession.round2ProcessOtStep1AndCreateStep2(req.clientOt1)
3046
+ };
3047
+ }
3048
+ if (req.step === "ot2-and-ot3") return {
3049
+ step: "ot3-and-mta",
3050
+ hsmOt3: this.partySession.round2ProcessOtStep2AndCreateStep3(req.clientOt2),
3051
+ hsmMta: this.partySession.round2VerifyKos15AndCreateMtaPayloads(req.clientOt3)
3052
+ };
3053
+ if (req.step === "mta-and-r3") {
3054
+ this.partySession.round2VerifyMtaPayloads(req.clientMta);
3055
+ const hsmR3 = this.partySession.round3CreateBroadcast();
3056
+ const hsmR4 = this.partySession.round3VerifyAndCreateRound4Broadcast([req.clientR3, hsmR3]);
3057
+ this.clientR3 = req.clientR3;
3058
+ this.hsmR3 = hsmR3;
3059
+ this.hsmR4 = hsmR4;
3060
+ return {
3061
+ step: "r3-and-r4",
3062
+ hsmR3,
3063
+ hsmR4
3064
+ };
3065
+ }
3066
+ if (req.step === "r4-finalize") {
3067
+ if (!this.clientR3 || !this.hsmR3 || !this.hsmR4) throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "Missing Round-3/4 HSM state");
3068
+ const record = this.partySession.round4VerifyAndFinalize([req.clientR4, this.hsmR4]);
3069
+ targetPool.store(record);
3070
+ const presigIdHex = record.publicVerification.presigIdHex;
3071
+ this.abort();
3072
+ return {
3073
+ step: "finalized",
3074
+ presigIdHex
3075
+ };
3076
+ }
3077
+ throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "Unknown presign step");
3078
+ } catch (err) {
3079
+ this.abort();
3080
+ throw err;
3081
+ }
3082
+ }
3083
+ };
3084
+ function computeSimulatedDeltaCommitment32(delta, extra) {
3085
+ assertPlainSimulationRecord(delta, "simulatedDelta");
3086
+ const nativeDeltaWei = assertSignedSimulationBigInt(delta.nativeDeltaWei, "simulatedDelta.nativeDeltaWei");
3087
+ const tokenMap = /* @__PURE__ */ new Map();
3088
+ if (delta.tokenDeltas !== void 0) {
3089
+ const rawDeltaMap = assertPlainSimulationRecord(delta.tokenDeltas, "simulatedDelta.tokenDeltas");
3090
+ for (const tokenAddr of Object.keys(rawDeltaMap)) {
3091
+ const val = assertSignedSimulationBigInt(rawDeltaMap[tokenAddr], `tokenDeltas[${tokenAddr}]`);
3092
+ const key = normalizeSimulationTokenAddress(tokenAddr, "simulatedDelta.tokenDeltas");
3093
+ tokenMap.set(key, (tokenMap.get(key) ?? 0n) + val);
3094
+ }
3095
+ }
3096
+ const sortedTokens = [...tokenMap.entries()].filter(([, v]) => v !== 0n).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v.toString(10)}`);
3097
+ const outgoing = [...assertOptionalSimulationStringArray(delta.outgoingAssetIds, "outgoingAssetIds") ?? []].sort();
3098
+ const ownedAfter = [...assertOptionalSimulationStringArray(delta.ownedAssetIdsAfter, "ownedAssetIdsAfter") ?? []].sort();
3099
+ const proxyImplNorm = extra?.proxyImplementationAddress && extra.proxyImplementationAddress !== "0x" ? require_tweak.parseStrictEthAddress(extra.proxyImplementationAddress).lowercaseAddress : "";
3100
+ return (0, _noble_hashes_sha2_js.sha256)(require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_SIMULATED_DELTA_V1, [require_secp256k1_scalar.utf8Bytes(deterministicJsonStringify({
3101
+ version: 1,
3102
+ simulationReverted: Boolean(delta.simulationReverted),
3103
+ nativeDeltaWei: nativeDeltaWei.toString(10),
3104
+ tokenDeltas: sortedTokens,
3105
+ outgoingAssetIds: outgoing,
3106
+ ownedAssetIdsAfter: ownedAfter,
3107
+ proxyImplementationAddress: proxyImplNorm
3108
+ }))]));
3109
+ }
3110
+ function buildFirewallAttestationSigningDigest32(params) {
3111
+ return (0, _noble_hashes_sha2_js.sha256)(require_secp256k1_scalar.lengthPrefixedEncode(require_constants.DST_PERSONAL_FIREWALL_ATTESTATION_V1, [
3112
+ require_secp256k1_scalar.u8(1),
3113
+ require_secp256k1_scalar.utf8Bytes(params.attestationId),
3114
+ require_secp256k1_scalar.utf8Bytes(params.vaultId),
3115
+ require_secp256k1_scalar.u64be(params.policyEpoch),
3116
+ require_secp256k1_scalar.utf8Bytes(params.chainNamespace),
3117
+ require_secp256k1_scalar.utf8Bytes(params.chainId),
3118
+ require_secp256k1_scalar.utf8Bytes(params.fromAddress),
3119
+ require_secp256k1_scalar.utf8Bytes(params.toAddress),
3120
+ params.signingDigest32,
3121
+ params.clearSigningPreviewHash32,
3122
+ require_secp256k1_scalar.u64be(params.simulatedBlockNumber),
3123
+ params.simulatedDeltaHash32,
3124
+ require_secp256k1_scalar.utf8Bytes(params.tier),
3125
+ require_secp256k1_scalar.utf8Bytes(params.verdict),
3126
+ require_secp256k1_scalar.utf8Bytes(params.riskCodes.join(",")),
3127
+ require_secp256k1_scalar.u64be(params.issuedAtSec),
3128
+ require_secp256k1_scalar.u64be(params.expiresAtSec),
3129
+ params.verifierPublicKey32
3130
+ ]));
3131
+ }
3132
+ function signPersonalFirewallAttestation(params) {
3133
+ const sk32 = require_secp256k1_scalar.normalizeHexBytes(params.verifierSecretKey32, 32);
3134
+ try {
3135
+ assertPrintableIdentifierAscii(params.attestationId, 64, "attestationId", "INVALID_PARAMETER");
3136
+ assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
3137
+ assertPrintableIdentifierAscii(params.chainId, 64, "chainId", "INVALID_PARAMETER");
3138
+ const normalizedFrom = normalizeOcapAddressOrEth(params.fromAddress, "fromAddress", "INVALID_PARAMETER");
3139
+ const normalizedTo = normalizeOcapAddressOrEth(params.toAddress, "toAddress", "INVALID_PARAMETER");
3140
+ const signingDigest32 = require_secp256k1_scalar.normalizeHexBytes(params.signingDigest32, 32);
3141
+ const previewHash32 = require_secp256k1_scalar.normalizeHexBytes(params.clearSigningPreviewHash32, 32);
3142
+ const simDeltaHash32 = require_secp256k1_scalar.normalizeHexBytes(params.simulatedDeltaHash32, 32);
3143
+ const ttl = params.ttlSeconds ?? 120;
3144
+ if (!Number.isInteger(ttl) || ttl < 1 || ttl > require_constants.MAX_PERSONAL_FIREWALL_ATTESTATION_TTL_SECONDS) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `Firewall attestation ttlSeconds must be 1..${require_constants.MAX_PERSONAL_FIREWALL_ATTESTATION_TTL_SECONDS}`);
3145
+ const expiresAtSec = params.issuedAtSec + BigInt(ttl);
3146
+ const riskCodes = (params.riskCodes ?? []).map((code) => {
3147
+ assertPrintableIdentifierAscii(code, 64, "riskCode", "INVALID_PARAMETER");
3148
+ if (code.includes(",")) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "riskCode must not contain commas");
3149
+ return code;
3150
+ });
3151
+ if (riskCodes.length > 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "riskCodes exceeds maximum length 32");
3152
+ const verifierPub32 = _noble_curves_ed25519_js.ed25519.getPublicKey(sk32);
3153
+ validateEd25519PublicKeyNonTorsion32(verifierPub32, "INVALID_PARAMETER");
3154
+ const digest32 = buildFirewallAttestationSigningDigest32({
3155
+ attestationId: params.attestationId,
3156
+ vaultId: params.vaultId,
3157
+ policyEpoch: params.policyEpoch,
3158
+ chainNamespace: params.chainNamespace,
3159
+ chainId: params.chainId,
3160
+ fromAddress: normalizedFrom,
3161
+ toAddress: normalizedTo,
3162
+ signingDigest32,
3163
+ clearSigningPreviewHash32: previewHash32,
3164
+ simulatedBlockNumber: params.simulatedBlockNumber,
3165
+ simulatedDeltaHash32: simDeltaHash32,
3166
+ tier: params.tier,
3167
+ verdict: params.verdict,
3168
+ riskCodes,
3169
+ issuedAtSec: params.issuedAtSec,
3170
+ expiresAtSec,
3171
+ verifierPublicKey32: verifierPub32
3172
+ });
3173
+ const sig64 = _noble_curves_ed25519_js.ed25519.sign(digest32, sk32);
3174
+ return {
3175
+ version: 1,
3176
+ attestationId: params.attestationId,
3177
+ vaultId: params.vaultId,
3178
+ policyEpoch: params.policyEpoch.toString(10),
3179
+ chainNamespace: params.chainNamespace,
3180
+ chainId: params.chainId,
3181
+ fromAddress: normalizedFrom,
3182
+ toAddress: normalizedTo,
3183
+ signingDigestHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(signingDigest32)}`,
3184
+ clearSigningPreviewHashHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(previewHash32)}`,
3185
+ simulatedBlockNumber: params.simulatedBlockNumber.toString(10),
3186
+ simulatedDeltaHashHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(simDeltaHash32)}`,
3187
+ tier: params.tier,
3188
+ verdict: params.verdict,
3189
+ riskCodes,
3190
+ issuedAtSec: params.issuedAtSec.toString(10),
3191
+ expiresAtSec: expiresAtSec.toString(10),
3192
+ verifierPublicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(verifierPub32)}`,
3193
+ signatureHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(sig64)}`
3194
+ };
3195
+ } finally {
3196
+ require_secp256k1_scalar.zeroizeBytes(sk32);
3197
+ }
3198
+ }
3199
+ function verifyPersonalFirewallAttestation(params) {
3200
+ const { attestation } = params;
3201
+ if (!attestation || typeof attestation !== "object" || attestation.version !== 1) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Invalid SignedFirewallAttestation version");
3202
+ if (!Array.isArray(params.trustedVerifierPublicKeys) || params.trustedVerifierPublicKeys.length === 0) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_REQUIRED", "No trusted firewall verifier public keys available");
3203
+ let policyEpoch;
3204
+ let simulatedBlockNumber;
3205
+ let issuedAtSec;
3206
+ let expiresAtSec;
3207
+ let signingDigest32;
3208
+ let previewHash32;
3209
+ let simDeltaHash32;
3210
+ let verifierPub32;
3211
+ let sig64;
3212
+ let normalizedFrom;
3213
+ let normalizedTo;
3214
+ try {
3215
+ assertPrintableIdentifierAscii(attestation.attestationId, 64, "attestationId", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3216
+ assertPrintableIdentifierAscii(attestation.vaultId, 64, "vaultId", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3217
+ assertPrintableIdentifierAscii(attestation.chainId, 64, "chainId", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3218
+ if (attestation.chainNamespace !== "evm" && attestation.chainNamespace !== "ocap") throw new Error("bad namespace");
3219
+ if (attestation.tier !== "free-local" && attestation.tier !== "pro-shield" && attestation.tier !== "vault-enforced") throw new Error("bad tier");
3220
+ if (attestation.verdict !== "allow" && attestation.verdict !== "warn" && attestation.verdict !== "block") throw new Error("bad verdict");
3221
+ if (!Array.isArray(attestation.riskCodes) || attestation.riskCodes.length > 32) throw new Error("bad riskCodes");
3222
+ for (const rc of attestation.riskCodes) {
3223
+ assertPrintableIdentifierAscii(rc, 64, "riskCode", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3224
+ if (rc.includes(",")) throw new Error("comma in riskCode");
3225
+ }
3226
+ normalizedFrom = normalizeOcapAddressOrEth(attestation.fromAddress, "fromAddress", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3227
+ normalizedTo = normalizeOcapAddressOrEth(attestation.toAddress, "toAddress", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3228
+ policyEpoch = parseStrictNonNegativeBigInt(attestation.policyEpoch, MAX_UINT64, "policyEpoch", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3229
+ simulatedBlockNumber = parseStrictNonNegativeBigInt(attestation.simulatedBlockNumber, MAX_UINT64, "simulatedBlockNumber", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3230
+ issuedAtSec = parseStrictNonNegativeBigInt(attestation.issuedAtSec, MAX_UINT64, "issuedAtSec", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3231
+ expiresAtSec = parseStrictNonNegativeBigInt(attestation.expiresAtSec, MAX_UINT64, "expiresAtSec", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3232
+ signingDigest32 = require_secp256k1_scalar.normalizeHexBytes(attestation.signingDigestHex, 32);
3233
+ previewHash32 = require_secp256k1_scalar.normalizeHexBytes(attestation.clearSigningPreviewHashHex, 32);
3234
+ simDeltaHash32 = require_secp256k1_scalar.normalizeHexBytes(attestation.simulatedDeltaHashHex, 32);
3235
+ verifierPub32 = require_secp256k1_scalar.normalizeHexBytes(attestation.verifierPublicKeyHex, 32);
3236
+ validateEd25519PublicKeyNonTorsion32(verifierPub32, "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3237
+ sig64 = require_secp256k1_scalar.normalizeHexBytes(attestation.signatureHex, 64);
3238
+ } catch (err) {
3239
+ if (err instanceof require_constants.MpcProtocolError) throw err;
3240
+ throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Malformed SignedFirewallAttestation fields");
3241
+ }
3242
+ if (!params.trustedVerifierPublicKeys.some((rawKey) => {
3243
+ try {
3244
+ return require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.normalizeHexBytes(rawKey, 32), verifierPub32);
3245
+ } catch {
3246
+ return false;
3247
+ }
3248
+ })) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "SignedFirewallAttestation verifier key is not in trusted intersection");
3249
+ const digest32 = buildFirewallAttestationSigningDigest32({
3250
+ attestationId: attestation.attestationId,
3251
+ vaultId: attestation.vaultId,
3252
+ policyEpoch,
3253
+ chainNamespace: attestation.chainNamespace,
3254
+ chainId: attestation.chainId,
3255
+ fromAddress: normalizedFrom,
3256
+ toAddress: normalizedTo,
3257
+ signingDigest32,
3258
+ clearSigningPreviewHash32: previewHash32,
3259
+ simulatedBlockNumber,
3260
+ simulatedDeltaHash32: simDeltaHash32,
3261
+ tier: attestation.tier,
3262
+ verdict: attestation.verdict,
3263
+ riskCodes: attestation.riskCodes,
3264
+ issuedAtSec,
3265
+ expiresAtSec,
3266
+ verifierPublicKey32: verifierPub32
3267
+ });
3268
+ let sigOk = false;
3269
+ try {
3270
+ sigOk = _noble_curves_ed25519_js.ed25519.verify(sig64, digest32, verifierPub32, { zip215: false });
3271
+ } catch {
3272
+ sigOk = false;
3273
+ }
3274
+ if (!sigOk) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Invalid Ed25519 signature on SignedFirewallAttestation");
3275
+ if (attestation.verdict !== "allow") throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", `Firewall attestation verdict is "${attestation.verdict}", expected "allow"`);
3276
+ if (params.requirePaidTier && attestation.tier === "free-local") throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Paid pro-shield or vault-enforced firewall attestation is required");
3277
+ if (expiresAtSec <= issuedAtSec || expiresAtSec - issuedAtSec > BigInt(require_constants.MAX_PERSONAL_FIREWALL_ATTESTATION_TTL_SECONDS)) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", `Firewall attestation TTL exceeds ${require_constants.MAX_PERSONAL_FIREWALL_ATTESTATION_TTL_SECONDS}s maximum`);
3278
+ if (params.nowSec + 30n < issuedAtSec || params.nowSec >= expiresAtSec) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "SignedFirewallAttestation is expired or not yet valid");
3279
+ if (params.expectedVaultId !== void 0 && attestation.vaultId !== params.expectedVaultId) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation vaultId mismatch");
3280
+ if (params.expectedPolicyEpoch !== void 0 && policyEpoch !== params.expectedPolicyEpoch) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation policyEpoch mismatch");
3281
+ if (params.expectedChainNamespace !== void 0 && attestation.chainNamespace !== params.expectedChainNamespace) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation chainNamespace mismatch");
3282
+ if (params.expectedChainId !== void 0 && attestation.chainId !== params.expectedChainId) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation chainId mismatch");
3283
+ if (params.expectedFromAddress !== void 0) {
3284
+ const expFrom = normalizeOcapAddressOrEth(params.expectedFromAddress, "expectedFromAddress", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3285
+ if (normalizedFrom !== expFrom) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation fromAddress mismatch");
3286
+ }
3287
+ if (params.expectedToAddress !== void 0) {
3288
+ const expTo = normalizeOcapAddressOrEth(params.expectedToAddress, "expectedToAddress", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
3289
+ if (normalizedTo !== expTo) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation toAddress mismatch");
3290
+ }
3291
+ if (params.expectedSigningDigest32 !== void 0) {
3292
+ const expDigest32 = require_secp256k1_scalar.normalizeHexBytes(params.expectedSigningDigest32, 32);
3293
+ if (!require_secp256k1_scalar.constantTimeEqual(signingDigest32, expDigest32)) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation signingDigest32 mismatch");
3294
+ }
3295
+ if (params.expectedClearSigningPreviewHash32 !== void 0) {
3296
+ const expPreview32 = require_secp256k1_scalar.normalizeHexBytes(params.expectedClearSigningPreviewHash32, 32);
3297
+ if (!require_secp256k1_scalar.constantTimeEqual(previewHash32, expPreview32)) throw new require_constants.MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation clearSigningPreviewHash32 mismatch");
3298
+ }
3299
+ return {
3300
+ simulatedBlockNumber,
3301
+ simulatedDeltaHash32: simDeltaHash32,
3302
+ issuedAtSec,
3303
+ expiresAtSec,
3304
+ tier: attestation.tier
3305
+ };
3306
+ }
3307
+ async function runPersonalClientPresignWithTransport(params) {
3308
+ const rng = params.rng ?? require_secp256k1_scalar.defaultRandomBytes;
3309
+ const sessionNonce32 = rng(32);
3310
+ const shamirSlot1Share32 = additiveToShamirSlot1Share(params.sActorBytes32);
3311
+ let pendingB1 = null;
3312
+ let senderB1 = null;
3313
+ let receiverA1 = null;
3314
+ let clientSession = null;
3315
+ try {
3316
+ const ctxB1A2 = derivePersonalBaseOtContext(params.cluster, sessionNonce32, 1, 2);
3317
+ const ctxB2A1 = derivePersonalBaseOtContext(params.cluster, sessionNonce32, 2, 1);
3318
+ const b1Step1 = require_ot.baseOtSenderStep1({
3319
+ ctxBaseOt: ctxB1A2,
3320
+ senderSlotB: 1,
3321
+ receiverSlotA: 2,
3322
+ rng
3323
+ });
3324
+ pendingB1 = b1Step1.pending;
3325
+ const initReply = await params.transport.initPresign({
3326
+ sessionNonce32,
3327
+ baseOtB1A2Step1: b1Step1.message
3328
+ });
3329
+ senderB1 = require_ot.baseOtSenderStep3({
3330
+ pending: pendingB1,
3331
+ step2Message: initReply.baseOtB1A2Step2
3332
+ });
3333
+ pendingB1 = null;
3334
+ const a1Step2 = require_ot.baseOtReceiverStep2({
3335
+ ctxBaseOt: ctxB2A1,
3336
+ senderSlotB: 2,
3337
+ receiverSlotA: 1,
3338
+ step1Message: initReply.baseOtB2A1Step1,
3339
+ rng
3340
+ });
3341
+ receiverA1 = a1Step2.receiverState;
3342
+ const channels = {
3343
+ ownerSlot: 1,
3344
+ asExtendedSenderA: new Map([[2, receiverA1]]),
3345
+ asExtendedReceiverB: new Map([[2, senderB1]])
3346
+ };
3347
+ clientSession = new require_presign.PresignPartySession({
3348
+ slot: 1,
3349
+ nodeSecretShareBytes32: shamirSlot1Share32,
3350
+ cluster: params.cluster,
3351
+ subset: [1, 2],
3352
+ sessionNonce32,
3353
+ baseOtChannels: channels,
3354
+ rng
3355
+ });
3356
+ require_secp256k1_scalar.zeroizeBytes(shamirSlot1Share32);
3357
+ const c1 = clientSession.round1CreateCommitment();
3358
+ const ack1 = await params.transport.stepPresign({
3359
+ presignSessionId: initReply.presignSessionId,
3360
+ step: "r1-commit",
3361
+ baseOtB2A1Step2: a1Step2.message,
3362
+ clientR1Commitment: c1
3363
+ });
3364
+ if (ack1.step !== "r1-commit-ack") throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "Unexpected step 1 response");
3365
+ const rev1 = clientSession.round1ReceiveCommitmentsAndReveal([c1, ack1.hsmR1Commitment]);
3366
+ clientSession.round1VerifyAllReveals([rev1.reveal, ack1.hsmR1Reveal]);
3367
+ const ot1Client = clientSession.round2CreateOtStep1Messages();
3368
+ const ack2 = await params.transport.stepPresign({
3369
+ presignSessionId: initReply.presignSessionId,
3370
+ step: "r1-reveal-and-ot1",
3371
+ clientR1Reveal: rev1.reveal,
3372
+ clientOt1: ot1Client
3373
+ });
3374
+ if (ack2.step !== "ot1-and-ot2") throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "Unexpected step 2 response");
3375
+ const ot2Client = clientSession.round2ProcessOtStep1AndCreateStep2(ack2.hsmOt1);
3376
+ const ot3Client = clientSession.round2ProcessOtStep2AndCreateStep3(ack2.hsmOt2);
3377
+ const ack3 = await params.transport.stepPresign({
3378
+ presignSessionId: initReply.presignSessionId,
3379
+ step: "ot2-and-ot3",
3380
+ clientOt2: ot2Client,
3381
+ clientOt3: ot3Client
3382
+ });
3383
+ if (ack3.step !== "ot3-and-mta") throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "Unexpected step 3 response");
3384
+ const mtaClient = clientSession.round2VerifyKos15AndCreateMtaPayloads(ack3.hsmOt3);
3385
+ clientSession.round2VerifyMtaPayloads(ack3.hsmMta);
3386
+ const r3Client = clientSession.round3CreateBroadcast();
3387
+ const ack4 = await params.transport.stepPresign({
3388
+ presignSessionId: initReply.presignSessionId,
3389
+ step: "mta-and-r3",
3390
+ clientMta: mtaClient,
3391
+ clientR3: r3Client
3392
+ });
3393
+ if (ack4.step !== "r3-and-r4") throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "Unexpected step 4 response");
3394
+ const r4Client = clientSession.round3VerifyAndCreateRound4Broadcast([r3Client, ack4.hsmR3]);
3395
+ const record = clientSession.round4VerifyAndFinalize([r4Client, ack4.hsmR4]);
3396
+ const ack5 = await params.transport.stepPresign({
3397
+ presignSessionId: initReply.presignSessionId,
3398
+ step: "r4-finalize",
3399
+ clientR4: r4Client
3400
+ });
3401
+ if (ack5.step !== "finalized" || ack5.presigIdHex !== record.publicVerification.presigIdHex) {
3402
+ require_secp256k1_scalar.zeroizeBytes(record.kShareBytes32, record.chiShareBytes32);
3403
+ throw new require_constants.MpcProtocolError("PRESIG_STATE_VIOLATION", "Cosigner finalize presigId mismatch");
3404
+ }
3405
+ return record;
3406
+ } catch (err) {
3407
+ clientSession?.abort();
3408
+ throw err;
3409
+ } finally {
3410
+ require_secp256k1_scalar.zeroizeBytes(shamirSlot1Share32, pendingB1?.yScalarBytes32);
3411
+ if (senderB1) require_ot.wipeBaseOtSenderState(senderB1);
3412
+ if (receiverA1) require_ot.wipeBaseOtReceiverState(receiverA1);
3413
+ }
3414
+ }
3415
+ function parseHexOrDecimalBigInt(raw, label) {
3416
+ if (typeof raw === "bigint") return raw;
3417
+ if (typeof raw === "number") {
3418
+ if (!Number.isSafeInteger(raw) || raw < 0) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", `Invalid ${label}`);
3419
+ return BigInt(raw);
3420
+ }
3421
+ if (typeof raw === "string") {
3422
+ if (/^0x[0-9a-fA-F]+$/.test(raw)) return BigInt(raw);
3423
+ if (/^(?:0|[1-9][0-9]*)$/.test(raw)) return BigInt(raw);
3424
+ }
3425
+ throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", `Invalid ${label}: ${String(raw)}`);
3426
+ }
3427
+ function parseEip1193TxObject(raw) {
3428
+ if (raw instanceof Uint8Array || typeof raw === "string") return decodeAndVerifyPersonalEip1559Tx({ txOrRawBytes: raw }).txFields;
3429
+ if (!raw || typeof raw !== "object") throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "Expected EIP-1559 transaction object");
3430
+ const obj = raw;
3431
+ if (obj.type !== void 0 && obj.type !== "0x2" && obj.type !== "0x02" && obj.type !== 2 && obj.type !== "eip1559") {
3432
+ if (obj.type === "0x4" || obj.type === "0x04" || obj.type === 4 || obj.authorizationList !== void 0) throw new require_constants.MpcProtocolError("PERSONAL_EIP7702_FORBIDDEN", "EIP-7702 transactions are forbidden");
3433
+ throw new require_constants.MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Only EIP-1559 Type-2 transactions are supported");
3434
+ }
3435
+ if (obj.authorizationList !== void 0) throw new require_constants.MpcProtocolError("PERSONAL_EIP7702_FORBIDDEN", "EIP-7702 authorizationList is forbidden");
3436
+ if (typeof obj.to !== "string" || obj.to.trim() === "" || obj.to === "0x") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Contract creation transactions are forbidden");
3437
+ return {
3438
+ chainId: parseHexOrDecimalBigInt(obj.chainId, "chainId"),
3439
+ nonce: parseHexOrDecimalBigInt(obj.nonce ?? 0, "nonce"),
3440
+ maxPriorityFeePerGasWei: parseHexOrDecimalBigInt(obj.maxPriorityFeePerGasWei ?? obj.maxPriorityFeePerGas, "maxPriorityFeePerGas"),
3441
+ maxFeePerGasWei: parseHexOrDecimalBigInt(obj.maxFeePerGasWei ?? obj.maxFeePerGas, "maxFeePerGas"),
3442
+ gasLimit: parseHexOrDecimalBigInt(obj.gasLimit ?? obj.gas, "gasLimit"),
3443
+ to: obj.to,
3444
+ valueWei: parseHexOrDecimalBigInt(obj.valueWei ?? obj.value ?? 0n, "value"),
3445
+ data: typeof obj.data === "string" || obj.data instanceof Uint8Array ? obj.data : "0x",
3446
+ accessList: Array.isArray(obj.accessList) ? obj.accessList : void 0
3447
+ };
3448
+ }
3449
+ /**
3450
+ * Creates an ergonomic `EIP-1193` & `viem`-compatible MPC EOA signer (`Slot 1` Client).
3451
+ * - Runs clear-signing & optional simulation post-condition verification locally BEFORE presign/sign.
3452
+ * - Executes 2-party `KOS15` + `GadgetMtA` presignature + Groth-Shoup online signing against `transport`.
3453
+ * - `s_1` (`MpcOnlineSignShare` for Slot 1) and `s_actor` NEVER leave the client!
3454
+ */
3455
+ function createPersonalMpcEoaSigner(params) {
3456
+ const pRootComp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(params.rootPublicKeyComp33, 33), false));
3457
+ const derivedChild = derivePersonalVaultChildKey({
3458
+ vaultId: params.vaultId,
3459
+ rootPublicKeyComp33: pRootComp33,
3460
+ derivation: params.childDerivation
3461
+ });
3462
+ let cachedCluster = params.xActorComp33 !== void 0 ? buildPersonalVaultClusterInfo({
3463
+ vaultId: params.vaultId,
3464
+ slotId: params.slotId,
3465
+ policyEpoch: params.policyEpoch,
3466
+ rootPublicKeyComp33: pRootComp33,
3467
+ xActorComp33: params.xActorComp33
3468
+ }) : null;
3469
+ const signTransaction = async (tx, options) => {
3470
+ const hasQuorum = options?.policyProof?.tier === "L2" || options?.policyProof?.tier === "L3";
3471
+ const verifiedTx = decodeAndVerifyPersonalEip1559Tx({
3472
+ txOrRawBytes: tx,
3473
+ policy: params.policy,
3474
+ hasL2OrL3QuorumProof: hasQuorum
3475
+ });
3476
+ if (options?.postConditions) {
3477
+ if (!options.simulatedDelta) throw new require_constants.MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", "simulatedDelta is required when postConditions are specified");
3478
+ verifyPersonalSimulationBalanceDelta({
3479
+ postConditions: options.postConditions,
3480
+ simulatedDelta: options.simulatedDelta
3481
+ });
3482
+ }
3483
+ const preview = buildPersonalClearSigningPreview({
3484
+ fromAddress: derivedChild.ethAddress,
3485
+ verifiedTx
3486
+ });
3487
+ const previewHash32 = computePersonalClearSigningPreviewHash32(preview);
3488
+ const callerSActor = await params.getActorShareBytes32();
3489
+ const sActorCopy32 = new Uint8Array(callerSActor);
3490
+ const localPool = new require_presign.VolatilePresignaturePool();
3491
+ let presigPub = null;
3492
+ try {
3493
+ const xActorComp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.mulBaseG(require_secp256k1_scalar.bytes32ToScalarNonZero(sActorCopy32)));
3494
+ if (!cachedCluster) cachedCluster = buildPersonalVaultClusterInfo({
3495
+ vaultId: params.vaultId,
3496
+ slotId: params.slotId,
3497
+ policyEpoch: params.policyEpoch,
3498
+ rootPublicKeyComp33: pRootComp33,
3499
+ xActorComp33
3500
+ });
3501
+ const clientPresigRecord = await runPersonalClientPresignWithTransport({
3502
+ cluster: cachedCluster,
3503
+ sActorBytes32: sActorCopy32,
3504
+ transport: params.transport,
3505
+ rng: params.rng
3506
+ });
3507
+ presigPub = clientPresigRecord.publicVerification;
3508
+ localPool.store(clientPresigRecord);
3509
+ const onlineReq = {
3510
+ rootId: params.vaultId,
3511
+ presigId: presigPub.presigId32,
3512
+ subset: [1, 2],
3513
+ msgDigest32: verifiedTx.signingDigest32,
3514
+ childDerivation: derivedChild.derivationSpec
3515
+ };
3516
+ const localShareRes = require_sign.createOnlineSignShare({
3517
+ pool: localPool,
3518
+ request: onlineReq
3519
+ });
3520
+ const cosignerRes = await params.transport.signOnline({
3521
+ vaultId: params.vaultId,
3522
+ slotId: params.slotId,
3523
+ presigIdHex: presigPub.presigIdHex,
3524
+ payloadKind: "eip1559",
3525
+ unsignedTx: verifiedTx.txFields,
3526
+ unsignedPayloadBytes: verifiedTx.unsignedPayloadBytes,
3527
+ signingDigest32: verifiedTx.signingDigest32,
3528
+ clearSigningPreview: preview,
3529
+ clearSigningPreviewHash32: previewHash32,
3530
+ childDerivation: derivedChild.derivationSpec,
3531
+ policyProof: options?.policyProof,
3532
+ entitlementTicket: options?.entitlementTicket,
3533
+ firewallAttestation: options?.firewallAttestation,
3534
+ attestedProxyImplementationAddress: options?.attestedProxyImplementationAddress,
3535
+ simulatedDelta: options?.simulatedDelta,
3536
+ postConditions: options?.postConditions
3537
+ });
3538
+ if (!cosignerRes?.share || cosignerRes.share.slot !== 2) throw new require_constants.MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", "Expected cosigner partial signature from slot 2", 2);
3539
+ const aggregated = require_sign.aggregateOnlineSignature({
3540
+ shares: [localShareRes.share, cosignerRes.share],
3541
+ publicVerification: presigPub,
3542
+ request: onlineReq
3543
+ });
3544
+ const signedTx = require_rlp_eip1559.encodeSignedEip1559Tx({
3545
+ tx: verifiedTx.txFields,
3546
+ yParity: aggregated.yParity,
3547
+ r: aggregated.r,
3548
+ s: aggregated.s
3549
+ });
3550
+ return {
3551
+ rawSignedTxBytes: signedTx.rawSignedTxBytes,
3552
+ rawSignedTxHex: signedTx.rawSignedTxHex,
3553
+ txHashHex: signedTx.txHashHex,
3554
+ signingDigest32: signedTx.signingDigest32,
3555
+ signerAddress: aggregated.signerAddress,
3556
+ signature: aggregated,
3557
+ clearSigningPreview: preview,
3558
+ clearSigningPreviewHash32: previewHash32
3559
+ };
3560
+ } finally {
3561
+ require_secp256k1_scalar.zeroizeBytes(sActorCopy32);
3562
+ localPool.wipeAll();
3563
+ }
3564
+ };
3565
+ const request = async (args) => {
3566
+ const method = args?.method;
3567
+ if (method === "eth_accounts" || method === "eth_requestAccounts") return [derivedChild.ethAddress];
3568
+ if (method === "eth_signTransaction") return (await signTransaction(parseEip1193TxObject(args.params?.[0]))).rawSignedTxHex;
3569
+ if (method === "eth_sendTransaction") {
3570
+ if (!params.transport.broadcastRawTransaction) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "PersonalCosignerTransport.broadcastRawTransaction is not configured for eth_sendTransaction");
3571
+ const signed = await signTransaction(parseEip1193TxObject(args.params?.[0]));
3572
+ return params.transport.broadcastRawTransaction(signed.rawSignedTxHex);
3573
+ }
3574
+ if (method === "eth_sign" || method === "personal_sign" || method === "eth_signTypedData" || method === "eth_signTypedData_v3" || method === "eth_signTypedData_v4") throw new require_constants.MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", `RPC method "${method}" is forbidden: MPC-secured EOA enforces EIP-1559 Clear-Signing`);
3575
+ throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `Unsupported EIP-1193 method: ${String(method)}`);
3576
+ };
3577
+ const placeholderCluster = cachedCluster ?? {
3578
+ rootId: params.vaultId,
3579
+ keyEpoch: params.policyEpoch,
3580
+ t: 2,
3581
+ nParties: 2,
3582
+ hDkg32: new Uint8Array(32),
3583
+ rootPublicKeyComp33: pRootComp33,
3584
+ publicSharesComp33BySlot: /* @__PURE__ */ new Map()
3585
+ };
3586
+ return {
3587
+ address: derivedChild.ethAddress,
3588
+ publicKeyComp33: derivedChild.childPublicKeyComp33,
3589
+ publicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(derivedChild.childPublicKeyComp33)}`,
3590
+ childDerivation: derivedChild.derivationSpec,
3591
+ get cluster() {
3592
+ return cachedCluster ?? placeholderCluster;
3593
+ },
3594
+ signTransaction,
3595
+ request,
3596
+ toViemLocalAccount() {
3597
+ return {
3598
+ address: derivedChild.ethAddress,
3599
+ publicKey: `0x${(0, _noble_hashes_utils_js.bytesToHex)(derivedChild.childPublicKeyComp33)}`,
3600
+ source: "mpc-personal-vault",
3601
+ type: "local",
3602
+ async signTransaction(tx, options) {
3603
+ return (await signTransaction(tx, options)).rawSignedTxHex;
3604
+ },
3605
+ async signMessage() {
3606
+ throw new require_constants.MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Blind personal_sign is forbidden");
3607
+ },
3608
+ async signTypedData() {
3609
+ throw new require_constants.MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Opaque signTypedData is forbidden");
3610
+ }
3611
+ };
3612
+ }
3613
+ };
3614
+ }
3615
+
3616
+ //#endregion
3617
+ exports.ACTOR_KIND_AND_ALG_BYTE = ACTOR_KIND_AND_ALG_BYTE;
3618
+ exports.ENTITLEMENT_TIER_CODE = ENTITLEMENT_TIER_CODE;
3619
+ exports.ERC20_APPROVE_SELECTOR_HEX = ERC20_APPROVE_SELECTOR_HEX;
3620
+ exports.HARD_BANNED_PERSONAL_EVM_SELECTORS = HARD_BANNED_PERSONAL_EVM_SELECTORS;
3621
+ exports.HSM_SEALED_BLOB_CIPHERTEXT_BYTES = HSM_SEALED_BLOB_CIPHERTEXT_BYTES;
3622
+ exports.HSM_SEALED_BLOB_CIPHERTEXT_OFFSET = HSM_SEALED_BLOB_CIPHERTEXT_OFFSET;
3623
+ exports.HSM_SEALED_BLOB_HEADER_BYTES = HSM_SEALED_BLOB_HEADER_BYTES;
3624
+ exports.HSM_SEALED_BLOB_HEADER_MAC_OFFSET = HSM_SEALED_BLOB_HEADER_MAC_OFFSET;
3625
+ exports.HSM_SEALED_BLOB_HEADER_WITH_MAC_BYTES = HSM_SEALED_BLOB_HEADER_WITH_MAC_BYTES;
3626
+ exports.HSM_SEALED_BLOB_IV_OFFSET = HSM_SEALED_BLOB_IV_OFFSET;
3627
+ exports.HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES = HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES;
3628
+ exports.HSM_SEALED_BLOB_TAG_OFFSET = HSM_SEALED_BLOB_TAG_OFFSET;
3629
+ exports.HSM_SEALED_BLOB_VERSION = HSM_SEALED_BLOB_VERSION;
3630
+ exports.MAX_ANNOUNCE_VALIDITY_WINDOW_SEC = MAX_ANNOUNCE_VALIDITY_WINDOW_SEC;
3631
+ exports.MIN_ANNOUNCE_VALIDITY_WINDOW_SEC = MIN_ANNOUNCE_VALIDITY_WINDOW_SEC;
3632
+ exports.PERSONAL_MAX_VELOCITY_UINT128 = PERSONAL_MAX_VELOCITY_UINT128;
3633
+ exports.PersonalCosignerResponderSession = PersonalCosignerResponderSession;
3634
+ exports.UNLIMITED_APPROVE_THRESHOLD = UNLIMITED_APPROVE_THRESHOLD;
3635
+ exports.actorKindAndAlgToByte = actorKindAndAlgToByte;
3636
+ exports.additiveToShamirSlot1Share = additiveToShamirSlot1Share;
3637
+ exports.additiveToShamirSlot2Share = additiveToShamirSlot2Share;
3638
+ exports.aes256GcmDecryptDetached = aes256GcmDecryptDetached;
3639
+ exports.aes256GcmEncryptDetached = aes256GcmEncryptDetached;
3640
+ exports.applyHsmSlotResplitDelta = applyHsmSlotResplitDelta;
3641
+ exports.assertNoEip7702Bytes = assertNoEip7702Bytes;
3642
+ exports.assertPersonalSlotNotExpired = assertPersonalSlotNotExpired;
3643
+ exports.base64UrlDecodeBytes = base64UrlDecodeBytes;
3644
+ exports.base64UrlEncodeBytes = base64UrlEncodeBytes;
3645
+ exports.bootstrapPersonalVaultClient = bootstrapPersonalVaultClient;
3646
+ exports.buildPersonalAnnounceChallengeDigest32 = buildPersonalAnnounceChallengeDigest32;
3647
+ exports.buildPersonalClearSigningPreview = buildPersonalClearSigningPreview;
3648
+ exports.buildPersonalEntitlementApplyChallengeDigest32 = buildPersonalEntitlementApplyChallengeDigest32;
3649
+ exports.buildPersonalPairResplitChallengeDigest32 = buildPersonalPairResplitChallengeDigest32;
3650
+ exports.buildPersonalPresignInitChallengeDigest32 = buildPersonalPresignInitChallengeDigest32;
3651
+ exports.buildPersonalResealKidChallengeDigest32 = buildPersonalResealKidChallengeDigest32;
3652
+ exports.buildPersonalRevokeSlotChallengeDigest32 = buildPersonalRevokeSlotChallengeDigest32;
3653
+ exports.buildPersonalSealEnrollChallengeDigest32 = buildPersonalSealEnrollChallengeDigest32;
3654
+ exports.buildPersonalSessionLockChallengeDigest32 = buildPersonalSessionLockChallengeDigest32;
3655
+ exports.buildPersonalSessionOpenChallengeDigest32 = buildPersonalSessionOpenChallengeDigest32;
3656
+ exports.buildPersonalSignChallengeDigest32 = buildPersonalSignChallengeDigest32;
3657
+ exports.buildPersonalVaultClusterInfo = buildPersonalVaultClusterInfo;
3658
+ exports.buildPersonalVetoChallengeDigest32 = buildPersonalVetoChallengeDigest32;
3659
+ exports.byteToActorKindAndAlg = byteToActorKindAndAlg;
3660
+ exports.bytesToHex = _noble_hashes_utils_js.bytesToHex;
3661
+ exports.canonicalizePersonalBlobAadBytes = canonicalizePersonalBlobAadBytes;
3662
+ exports.canonicalizePersonalVaultPolicy = canonicalizePersonalVaultPolicy;
3663
+ exports.completeActorSlotPairingOnTarget = completeActorSlotPairingOnTarget;
3664
+ exports.computeHsmSealedBlobHeaderMac32 = computeHsmSealedBlobHeaderMac32;
3665
+ exports.computeNonDegenerateActorResplitShare = computeNonDegenerateActorResplitShare;
3666
+ exports.computePersonalActorChallengeDigest32 = computePersonalActorChallengeDigest32;
3667
+ exports.computePersonalClearSigningPreviewHash32 = computePersonalClearSigningPreviewHash32;
3668
+ exports.computePersonalPolicyHash32 = computePersonalPolicyHash32;
3669
+ exports.computeSimulatedDeltaCommitment32 = computeSimulatedDeltaCommitment32;
3670
+ exports.computeVaultEntitlementTicketDigest32 = computeVaultEntitlementTicketDigest32;
3671
+ exports.createActorSlotPairingBootstrap = createActorSlotPairingBootstrap;
3672
+ exports.createPersonalMpcEoaSigner = createPersonalMpcEoaSigner;
3673
+ exports.createPersonalSealEnrollActorPok = createPersonalSealEnrollActorPok;
3674
+ exports.decodeAndVerifyPersonalEip1559Tx = decodeAndVerifyPersonalEip1559Tx;
3675
+ exports.decodeErc20ApproveCalldata = decodeErc20ApproveCalldata;
3676
+ exports.decodeHsmSealedBlobHeader319 = decodeHsmSealedBlobHeader319;
3677
+ exports.decodeHsmSealedBlobInnerPlaintext3717 = decodeHsmSealedBlobInnerPlaintext3717;
3678
+ exports.deriveBlindOcapVelocityTag32 = deriveBlindOcapVelocityTag32;
3679
+ exports.deriveBlindSlotTag32 = deriveBlindSlotTag32;
3680
+ exports.deriveBlindVaultTag32 = deriveBlindVaultTag32;
3681
+ exports.deriveBlindVelocityTag32 = deriveBlindVelocityTag32;
3682
+ exports.deriveHsmPersonalSealKey32 = deriveHsmPersonalSealKey32;
3683
+ exports.derivePersonalVaultChildKey = derivePersonalVaultChildKey;
3684
+ exports.derivePersonalWakePasswordKeys = derivePersonalWakePasswordKeys;
3685
+ exports.encodeErc20ApproveCalldata = encodeErc20ApproveCalldata;
3686
+ exports.encodeHsmSealedBlobHeader319 = encodeHsmSealedBlobHeader319;
3687
+ exports.encodeHsmSealedBlobInnerPlaintext3717 = encodeHsmSealedBlobInnerPlaintext3717;
3688
+ exports.hexToBytes = _noble_hashes_utils_js.hexToBytes;
3689
+ exports.initiateActorSlotResplit = initiateActorSlotResplit;
3690
+ exports.isAgentActorKind = isAgentActorKind;
3691
+ exports.normalizeActorPublicKeyToPadded65 = normalizeActorPublicKeyToPadded65;
3692
+ exports.normalizeCanonicalOcapTokenKey = normalizeCanonicalOcapTokenKey;
3693
+ exports.normalizeMaxTokenOutflowsCaps = normalizeMaxTokenOutflowsCaps;
3694
+ exports.normalizeOcapAddressOrEth = normalizeOcapAddressOrEth;
3695
+ exports.openHsmInboundTransportBox = openHsmInboundTransportBox;
3696
+ exports.parseHsmSealedBlobHeader = parseHsmSealedBlobHeader;
3697
+ exports.recoverPersonalVaultRootOffline = recoverPersonalVaultRootOffline;
3698
+ exports.resolveRequiredPolicyTier = resolveRequiredPolicyTier;
3699
+ exports.runPersonalClientPresignWithTransport = runPersonalClientPresignWithTransport;
3700
+ exports.sealDeviceShareEnvelope = sealDeviceShareEnvelope;
3701
+ exports.sealHsmInboundTransportBox = sealHsmInboundTransportBox;
3702
+ exports.signAnnounceTicket = signAnnounceTicket;
3703
+ exports.signGuardianQuorumApproval = signGuardianQuorumApproval;
3704
+ exports.signPersonalActorChallenge = signPersonalActorChallenge;
3705
+ exports.signPersonalFirewallAttestation = signPersonalFirewallAttestation;
3706
+ exports.signPersonalVaultRecoverySweepOffline = signPersonalVaultRecoverySweepOffline;
3707
+ exports.signRoleQuorumApproval = signRoleQuorumApproval;
3708
+ exports.signVaultEntitlementTicket = signVaultEntitlementTicket;
3709
+ exports.unsealDeviceShareEnvelope = unsealDeviceShareEnvelope;
3710
+ exports.unwrapSealedBlobFromCloudSync = unwrapSealedBlobFromCloudSync;
3711
+ exports.validateActorPublicKeyPadded65 = validateActorPublicKeyPadded65;
3712
+ exports.verifyActorSlotPairingBootstrap = verifyActorSlotPairingBootstrap;
3713
+ exports.verifyGuardianQuorumProof = verifyGuardianQuorumProof;
3714
+ exports.verifyPersonalActorSignature = verifyPersonalActorSignature;
3715
+ exports.verifyPersonalAdditiveSplitMatchesRoot = verifyPersonalAdditiveSplitMatchesRoot;
3716
+ exports.verifyPersonalColdRecoveryKitManifest = verifyPersonalColdRecoveryKitManifest;
3717
+ exports.verifyPersonalFirewallAttestation = verifyPersonalFirewallAttestation;
3718
+ exports.verifyPersonalPolicyProofBundle = verifyPersonalPolicyProofBundle;
3719
+ exports.verifyPersonalSealEnrollActorPok = verifyPersonalSealEnrollActorPok;
3720
+ exports.verifyPersonalSimulationBalanceDelta = verifyPersonalSimulationBalanceDelta;
3721
+ exports.verifyRoleQuorumProof = verifyRoleQuorumProof;
3722
+ exports.verifySignedAnnounceTicket = verifySignedAnnounceTicket;
3723
+ exports.verifyVaultEntitlementTicket = verifyVaultEntitlementTicket;
3724
+ exports.wrapSealedBlobForCloudSync = wrapSealedBlobForCloudSync;
3725
+ exports.zeroizeBytes = require_secp256k1_scalar.zeroizeBytes;