@ocap/mpc-hsm 1.33.6 → 1.33.8

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 (56) 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 +66 -2
  4. package/esm/constants.mjs +65 -1
  5. package/esm/dkg.mjs +2 -2
  6. package/esm/index.d.mts +11 -3
  7. package/esm/index.mjs +11 -3
  8. package/esm/ocap-clear-signing.d.mts +125 -0
  9. package/esm/ocap-clear-signing.mjs +1170 -0
  10. package/esm/offline-ceremony.d.mts +127 -0
  11. package/esm/offline-ceremony.mjs +481 -0
  12. package/esm/ot.d.mts +7 -1
  13. package/esm/ot.mjs +149 -16
  14. package/esm/personal-vault.d.mts +1292 -0
  15. package/esm/personal-vault.mjs +3615 -0
  16. package/esm/personal.d.mts +10 -0
  17. package/esm/personal.mjs +11 -0
  18. package/esm/presign.mjs +1 -1
  19. package/esm/rlp-eip1559.d.mts +75 -0
  20. package/esm/rlp-eip1559.mjs +293 -0
  21. package/esm/secp256k1-scalar.d.mts +1 -1
  22. package/esm/secp256k1-scalar.mjs +14 -5
  23. package/esm/steel-mnemonic.d.mts +55 -0
  24. package/esm/steel-mnemonic.mjs +247 -0
  25. package/esm/ves-backup.d.mts +296 -0
  26. package/esm/ves-backup.mjs +1025 -0
  27. package/esm/x402-agent-guard.d.mts +111 -0
  28. package/esm/x402-agent-guard.mjs +780 -0
  29. package/lib/bip39-english-wordlist.cjs +33 -0
  30. package/lib/bip39-english-wordlist.d.cts +11 -0
  31. package/lib/constants.cjs +128 -0
  32. package/lib/constants.d.cts +66 -2
  33. package/lib/dkg.cjs +2 -2
  34. package/lib/index.cjs +249 -0
  35. package/lib/index.d.cts +11 -3
  36. package/lib/ocap-clear-signing.cjs +1176 -0
  37. package/lib/ocap-clear-signing.d.cts +125 -0
  38. package/lib/offline-ceremony.cjs +487 -0
  39. package/lib/offline-ceremony.d.cts +127 -0
  40. package/lib/ot.cjs +150 -15
  41. package/lib/ot.d.cts +7 -1
  42. package/lib/personal-vault.cjs +3725 -0
  43. package/lib/personal-vault.d.cts +1292 -0
  44. package/lib/personal.cjs +338 -0
  45. package/lib/personal.d.cts +10 -0
  46. package/lib/presign.cjs +1 -1
  47. package/lib/rlp-eip1559.cjs +303 -0
  48. package/lib/rlp-eip1559.d.cts +75 -0
  49. package/lib/secp256k1-scalar.cjs +14 -5
  50. package/lib/steel-mnemonic.cjs +253 -0
  51. package/lib/steel-mnemonic.d.cts +55 -0
  52. package/lib/ves-backup.cjs +1053 -0
  53. package/lib/ves-backup.d.cts +296 -0
  54. package/lib/x402-agent-guard.cjs +788 -0
  55. package/lib/x402-agent-guard.d.cts +111 -0
  56. package/package.json +6 -1
@@ -0,0 +1,125 @@
1
+ import { CanonicalPersonalOcapChainGasConfig, CanonicalPersonalVaultPolicy, PersonalClearSigningPreview, PersonalOcapChainGasConfig, PersonalPolicyTier, PersonalVaultPolicy } from "./personal-vault.cjs";
2
+
3
+ //#region src/ocap-clear-signing.d.ts
4
+
5
+ /**
6
+ * Derives the canonical OCAP `SECP256K1` (`ROLE_ACCOUNT = 0`, `KeyType.SECP256K1 = 1`, `HashType.SHA3 = 1`, `BASE58`)
7
+ * bare address (`z...`) and uncompressed 65-byte (`0x04 || X || Y`) + Ethereum 64-byte (`X || Y`) public keys
8
+ * from a compressed 33-byte secp256k1 child public key.
9
+ */
10
+ declare function deriveOcapIdentitiesFromChildPoint(childPublicKeyComp33: Uint8Array | string): {
11
+ readonly ethChecksumAddress: string;
12
+ readonly ethUncompressedPk64: Uint8Array;
13
+ readonly ethUncompressedPkHex: string;
14
+ readonly ocapSecp256k1Address: string;
15
+ readonly ocapSecp256k1Did: string;
16
+ readonly secp256k1UncompressedPk65: Uint8Array;
17
+ readonly secp256k1UncompressedPkHex: string;
18
+ };
19
+ declare class CborTagValue {
20
+ readonly tag: number;
21
+ readonly value: unknown;
22
+ constructor(tag: number, value: unknown);
23
+ }
24
+ interface VerifiedPersonalOcapTx {
25
+ readonly unsignedPayloadBytes: Uint8Array;
26
+ readonly signingDigest32: Uint8Array;
27
+ readonly signingDigestHex: string;
28
+ readonly signerAddress: string;
29
+ readonly signerScheme: 'ethereum' | 'secp256k1';
30
+ readonly fromAddress: string;
31
+ readonly delegatorAddress?: string;
32
+ readonly toAddress: string;
33
+ readonly chainId: string;
34
+ readonly nonce: bigint;
35
+ readonly itxTypeUrl: string;
36
+ /** Effective bounded execution gas + protocol txFee (>= declared `Transaction.gas` field 5). */
37
+ readonly gasFee: bigint;
38
+ /** Raw `Transaction.gas` field 5 declared in unsigned CBOR (`0n` when omitted). */
39
+ readonly declaredGasField: bigint;
40
+ readonly serviceFee: bigint;
41
+ readonly nativeValueOutflow: bigint;
42
+ readonly totalNativeOutflow: bigint;
43
+ readonly tokenOutflows: ReadonlyArray<{
44
+ readonly tokenAddress: string;
45
+ readonly amount: bigint;
46
+ }>;
47
+ readonly outgoingAssetIds: ReadonlyArray<string>;
48
+ readonly nativeInflowExpected: bigint;
49
+ readonly tokenInflowsExpected: ReadonlyArray<{
50
+ readonly tokenAddress: string;
51
+ readonly amount: bigint;
52
+ }>;
53
+ readonly incomingAssetIds: ReadonlyArray<string>;
54
+ readonly expiredAtIso?: string;
55
+ readonly delegatedOps: ReadonlyArray<string>;
56
+ readonly isTransferLike: boolean;
57
+ }
58
+ /**
59
+ * Computes a deterministic, fail-closed upper bound on the OCAP execution gas + protocol `txFee`
60
+ * charged by `CreateGasEnsureFn` (`ensure-gas.ts`) and `EnsureTxCost` (`ensure-cost.ts`), even when
61
+ * `Transaction.gas` (field 5) is absent or `0` and the sender lacks a valid gas stake.
62
+ */
63
+ declare function estimateOcapExecutionCostUpperBound(params: {
64
+ readonly unsignedPayloadByteLength: number;
65
+ readonly itxTypeUrl: string;
66
+ readonly outgoingAssetCount: number;
67
+ readonly incomingAssetCount: number;
68
+ readonly gasConfig: PersonalOcapChainGasConfig | CanonicalPersonalOcapChainGasConfig;
69
+ }): {
70
+ readonly estimatedExecutionGas: bigint;
71
+ readonly protocolTxFee: bigint;
72
+ readonly totalExecutionCostUpperBound: bigint;
73
+ };
74
+ declare function decodeAndVerifyPersonalOcapTx(params: {
75
+ readonly rawTxBytes: Uint8Array | string;
76
+ readonly childPublicKeyComp33: Uint8Array | string;
77
+ readonly policy?: PersonalVaultPolicy | CanonicalPersonalVaultPolicy;
78
+ readonly ocapGasConfig?: PersonalOcapChainGasConfig | CanonicalPersonalOcapChainGasConfig;
79
+ readonly requireExecutionGasBound?: boolean;
80
+ readonly ocapPrimaryTokenAddress?: string;
81
+ readonly nowSec?: bigint;
82
+ readonly hasL2OrL3QuorumProof?: boolean;
83
+ readonly hasL3GuardianQuorumProof?: boolean;
84
+ }): {
85
+ readonly verifiedOcapTx: VerifiedPersonalOcapTx;
86
+ readonly clearSigningPreview: PersonalClearSigningPreview;
87
+ readonly clearSigningPreviewHash32: Uint8Array;
88
+ /** Policy-independent preview hash computed solely from unsigned CBOR fields (`declaredGasField`), used by policy-blind Follower `SignedFirewallAttestation`. */
89
+ readonly intrinsicClearSigningPreviewHash32: Uint8Array;
90
+ };
91
+ declare function resolveRequiredOcapPolicyTier(params: {
92
+ readonly policy: PersonalVaultPolicy | CanonicalPersonalVaultPolicy;
93
+ readonly verifiedOcapTx: VerifiedPersonalOcapTx;
94
+ readonly currentRollingByAsset?: ReadonlyMap<string, bigint>;
95
+ readonly hasL2OrL3QuorumForOverflow?: boolean;
96
+ readonly attestedSimulatedNativeDeltaWei?: bigint;
97
+ }): {
98
+ readonly requiredTier: PersonalPolicyTier;
99
+ readonly projectedRollingByAsset: ReadonlyMap<string, bigint>;
100
+ };
101
+ interface VerifiedPersonalArcblockJwt {
102
+ readonly unsignedToken: string;
103
+ readonly unsignedPayloadBytes: Uint8Array;
104
+ readonly signingDigest32: Uint8Array;
105
+ readonly signingDigestHex: string;
106
+ readonly isDelegationToken: boolean;
107
+ readonly requiredTier: PersonalPolicyTier;
108
+ readonly issuerDid: string;
109
+ readonly subject: string;
110
+ readonly iatSec: bigint;
111
+ readonly expSec: bigint;
112
+ }
113
+ declare function decodeAndVerifyPersonalArcblockJwt(params: {
114
+ readonly unsignedTokenOrBytes: Uint8Array | string;
115
+ readonly childPublicKeyComp33: Uint8Array | string;
116
+ readonly nowSec: bigint;
117
+ readonly policy?: PersonalVaultPolicy | CanonicalPersonalVaultPolicy;
118
+ readonly hasL2OrL3QuorumProof?: boolean;
119
+ }): {
120
+ readonly verifiedJwt: VerifiedPersonalArcblockJwt;
121
+ readonly clearSigningPreview: PersonalClearSigningPreview;
122
+ readonly clearSigningPreviewHash32: Uint8Array;
123
+ };
124
+ //#endregion
125
+ export { CborTagValue, VerifiedPersonalArcblockJwt, VerifiedPersonalOcapTx, decodeAndVerifyPersonalArcblockJwt, decodeAndVerifyPersonalOcapTx, deriveOcapIdentitiesFromChildPoint, estimateOcapExecutionCostUpperBound, resolveRequiredOcapPolicyTier };
@@ -0,0 +1,487 @@
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_steel_mnemonic = require('./steel-mnemonic.cjs');
5
+ const require_ves_backup = require('./ves-backup.cjs');
6
+ const require_rlp_eip1559 = require('./rlp-eip1559.cjs');
7
+ let node_fs = require("node:fs");
8
+ let node_path = require("node:path");
9
+ let node_os = require("node:os");
10
+ let _noble_hashes_utils_js = require("@noble/hashes/utils.js");
11
+
12
+ //#region src/offline-ceremony.ts
13
+ /**
14
+ * Air-gapped 3-Custodian Cold Ceremony & Emergency Disaster Sweep (`design.md` §5.2):
15
+ * - `enforceSingleCustodianDecryptPerSession`: enforces single guardian index per air-gapped
16
+ * process AND live-boot session (`/dev/shm` + `/proc/sys/kernel/random/boot_id` on Linux,
17
+ * per-UID boot-persistent tmpdir lock on POSIX, plus unconditional process-wide RAM lock,
18
+ * symlink/ownership/mode verification, and `O_NOFOLLOW`), failing closed with
19
+ * `SINGLE_CUSTODIAN_SESSION_VIOLATION` on any attempt to decrypt a second index.
20
+ * - `proveColdShardFromSteelWords24`: accepts ONLY retranscribed 24 BIP-39 words + challenge bundle,
21
+ * verifies full `PrintableManifestCard` & `g(j)*G == Y_j` BEFORE PoK, and wipes all buffers.
22
+ * - `sweepEth` & `sweepErc20Transfer`: strictly destination-locked to `manifest.escapeColdWallet`
23
+ * with full `PrintableManifestCard` consistency verification, zeroizing all scalars in `finally`.
24
+ */
25
+ const SESSION_LOCK_SLEEP = new Int32Array(new SharedArrayBuffer(4));
26
+ const inProcessSessionLocks = /* @__PURE__ */ new Map();
27
+ let processWideLockedGuardianIndex = null;
28
+ function readLinuxKernelBootId() {
29
+ try {
30
+ if (!(0, node_fs.existsSync)("/proc/sys/kernel/random/boot_id")) return null;
31
+ const raw = (0, node_fs.readFileSync)("/proc/sys/kernel/random/boot_id", "utf8").trim();
32
+ if (/^[0-9a-fA-F-]{16,64}$/.test(raw)) return raw.toLowerCase();
33
+ return null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+ function resolveDefaultCustodianLockDir() {
39
+ const envDir = process.env.ARC_MPC_CUSTODIAN_LOCK_DIR?.trim();
40
+ if (envDir) return (0, node_path.resolve)(envDir);
41
+ const uid = typeof process.getuid === "function" ? process.getuid() : 0;
42
+ const bootId = readLinuxKernelBootId();
43
+ const suffix = bootId ? `arc-mpc-custodian-uid-${uid}-boot-${bootId}` : `arc-mpc-custodian-uid-${uid}-bootlock`;
44
+ if ((0, node_fs.existsSync)("/dev/shm")) return (0, node_path.join)("/dev/shm", suffix);
45
+ return (0, node_path.join)((0, node_os.tmpdir)(), suffix);
46
+ }
47
+ function assertOwnedPrivateDirectory(dirPath) {
48
+ const uid = typeof process.getuid === "function" ? process.getuid() : null;
49
+ let st;
50
+ try {
51
+ st = (0, node_fs.lstatSync)(dirPath);
52
+ } catch (err) {
53
+ throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Failed to stat custodian lock directory "${dirPath}": ${err.message}`);
54
+ }
55
+ if (st.isSymbolicLink() || !st.isDirectory()) throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Custodian lock directory "${dirPath}" must be a real directory (symlinks forbidden)`);
56
+ if (uid !== null && st.uid !== uid) throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Custodian lock directory "${dirPath}" is owned by UID ${st.uid}, expected ${uid}`);
57
+ if ((st.mode & 63) !== 0) throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Custodian lock directory "${dirPath}" has insecure permissions 0o${(st.mode & 511).toString(8)} (require 0700)`);
58
+ return (0, node_fs.realpathSync)(dirPath);
59
+ }
60
+ function readExistingLockFileNoFollow(filePath) {
61
+ const uid = typeof process.getuid === "function" ? process.getuid() : null;
62
+ const flags = node_fs.constants.O_RDONLY | (node_fs.constants.O_NOFOLLOW ?? 0);
63
+ let fd;
64
+ try {
65
+ const lst = (0, node_fs.lstatSync)(filePath);
66
+ if (lst.isSymbolicLink() || !lst.isFile()) throw new Error("Lock path is a symlink or non-regular file");
67
+ fd = (0, node_fs.openSync)(filePath, flags);
68
+ } catch (err) {
69
+ throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Unsafe or unreadable custodian session lock "${filePath}": ${err.message}`);
70
+ }
71
+ try {
72
+ const fst = (0, node_fs.fstatSync)(fd);
73
+ if (!fst.isFile() || uid !== null && fst.uid !== uid || (fst.mode & 63) !== 0) throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Custodian session lock "${filePath}" failed ownership or 0600 mode check`);
74
+ const raw = (0, node_fs.readFileSync)(fd, "utf8");
75
+ let parsed;
76
+ try {
77
+ parsed = JSON.parse(raw);
78
+ } catch {
79
+ throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Corrupted custodian session lock file "${filePath}" — failing closed`);
80
+ }
81
+ const existingIdx = parsed?.guardianIndex;
82
+ if (typeof existingIdx !== "number" || !Number.isInteger(existingIdx) || existingIdx < 1 || existingIdx > require_constants.MAX_MPC_CLUSTER_NODES) throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Malformed custodian session lock state in "${filePath}"`);
83
+ return existingIdx;
84
+ } finally {
85
+ try {
86
+ (0, node_fs.closeSync)(fd);
87
+ } catch {}
88
+ }
89
+ }
90
+ /**
91
+ * Enforces that an air-gapped custodian boot/process session can decrypt AT MOST ONE guardian index
92
+ * (`design.md` §5.2(1)). Refuses any second guardian index with `SINGLE_CUSTODIAN_SESSION_VIOLATION`
93
+ * across both process-wide memory AND boot-persistent `0700`/`0600` symlink-safe lock files.
94
+ */
95
+ function enforceSingleCustodianDecryptPerSession(params) {
96
+ const { guardianIndex } = params;
97
+ if (!Number.isInteger(guardianIndex) || guardianIndex < 1 || guardianIndex > require_constants.MAX_MPC_CLUSTER_NODES) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `Invalid guardianIndex: ${guardianIndex}`);
98
+ if (processWideLockedGuardianIndex !== null && processWideLockedGuardianIndex !== guardianIndex) throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Current process is already locked to guardian index ${processWideLockedGuardianIndex}; refusing index ${guardianIndex}`);
99
+ const requestedLockFile = params.lockFilePath ? (0, node_path.resolve)(params.lockFilePath) : (0, node_path.join)((0, node_path.resolve)(params.lockDir ?? resolveDefaultCustodianLockDir()), "custodian-decrypt-index.lock");
100
+ const rawParentDir = (0, node_path.dirname)(requestedLockFile);
101
+ try {
102
+ (0, node_fs.mkdirSync)(rawParentDir, {
103
+ recursive: true,
104
+ mode: 448
105
+ });
106
+ } catch (err) {
107
+ throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Failed to initialize custodian lock directory "${rawParentDir}": ${err.message}`);
108
+ }
109
+ let canonicalParentDir;
110
+ if (params.lockFilePath === void 0) canonicalParentDir = assertOwnedPrivateDirectory(rawParentDir);
111
+ else {
112
+ let pst;
113
+ try {
114
+ pst = (0, node_fs.lstatSync)(rawParentDir);
115
+ } catch (err) {
116
+ throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Unable to stat parent directory "${rawParentDir}": ${err.message}`);
117
+ }
118
+ if (pst.isSymbolicLink() || !pst.isDirectory()) throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Lock parent "${rawParentDir}" cannot be a symlink`);
119
+ canonicalParentDir = (0, node_fs.realpathSync)(rawParentDir);
120
+ }
121
+ const lockBasename = requestedLockFile.slice(rawParentDir.length + (rawParentDir.endsWith("/") ? 0 : 1));
122
+ const canonicalLockFile = (0, node_path.join)(canonicalParentDir, lockBasename);
123
+ const inMemExisting = inProcessSessionLocks.get(canonicalLockFile);
124
+ if (inMemExisting !== void 0 && inMemExisting !== guardianIndex) throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Custodian boot session is already locked to guardian index ${inMemExisting}; refusing index ${guardianIndex}`);
125
+ const createExclNoFollowFlags = node_fs.constants.O_CREAT | node_fs.constants.O_EXCL | node_fs.constants.O_WRONLY | (node_fs.constants.O_NOFOLLOW ?? 0);
126
+ const mutexPath = `${canonicalLockFile}.mutex`;
127
+ let mutexFd = null;
128
+ for (let attempt = 0; attempt < 100; attempt++) try {
129
+ mutexFd = (0, node_fs.openSync)(mutexPath, createExclNoFollowFlags, 384);
130
+ break;
131
+ } catch (err) {
132
+ if (err.code === "EEXIST" && attempt < 99) {
133
+ try {
134
+ if ((0, node_fs.lstatSync)(mutexPath).isSymbolicLink()) throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Symlink mutex detected at "${mutexPath}"`);
135
+ } catch (stErr) {
136
+ if (stErr instanceof require_constants.MpcProtocolError) throw stErr;
137
+ }
138
+ Atomics.wait(SESSION_LOCK_SLEEP, 0, 0, 5);
139
+ continue;
140
+ }
141
+ throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Unable to acquire custodian session lock mutex "${mutexPath}": ${err.message}`);
142
+ }
143
+ if (mutexFd === null) throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", "Timed out acquiring custodian session mutex");
144
+ try {
145
+ let lockAlreadyPresent = false;
146
+ try {
147
+ (0, node_fs.lstatSync)(canonicalLockFile);
148
+ lockAlreadyPresent = true;
149
+ } catch (err) {
150
+ if (err.code !== "ENOENT") throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Failed to inspect lock "${canonicalLockFile}": ${err.message}`);
151
+ }
152
+ if (lockAlreadyPresent) {
153
+ const existingIdx = readExistingLockFileNoFollow(canonicalLockFile);
154
+ inProcessSessionLocks.set(canonicalLockFile, existingIdx);
155
+ if (processWideLockedGuardianIndex === null) processWideLockedGuardianIndex = existingIdx;
156
+ if (existingIdx !== guardianIndex) throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Custodian boot session already decrypted guardian index ${existingIdx}; refusing second index ${guardianIndex}`);
157
+ return {
158
+ lockFilePath: canonicalLockFile,
159
+ lockedGuardianIndex: existingIdx
160
+ };
161
+ }
162
+ const recordJson = `${JSON.stringify({
163
+ version: 1,
164
+ guardianIndex,
165
+ pid: process.pid
166
+ })}\n`;
167
+ let fd;
168
+ try {
169
+ fd = (0, node_fs.openSync)(canonicalLockFile, createExclNoFollowFlags, 384);
170
+ } catch (err) {
171
+ throw new require_constants.MpcProtocolError("SINGLE_CUSTODIAN_SESSION_VIOLATION", `Failed to create exclusive custodian session lock "${canonicalLockFile}": ${err.message}`);
172
+ }
173
+ try {
174
+ (0, node_fs.fchmodSync)(fd, 384);
175
+ (0, node_fs.writeSync)(fd, recordJson, 0, "utf8");
176
+ (0, node_fs.fsyncSync)(fd);
177
+ } finally {
178
+ (0, node_fs.closeSync)(fd);
179
+ }
180
+ inProcessSessionLocks.set(canonicalLockFile, guardianIndex);
181
+ processWideLockedGuardianIndex = guardianIndex;
182
+ return {
183
+ lockFilePath: canonicalLockFile,
184
+ lockedGuardianIndex: guardianIndex
185
+ };
186
+ } finally {
187
+ try {
188
+ (0, node_fs.closeSync)(mutexFd);
189
+ } catch {}
190
+ try {
191
+ (0, node_fs.unlinkSync)(mutexPath);
192
+ } catch {}
193
+ }
194
+ }
195
+ function generateGuardianKeypair(rng = require_secp256k1_scalar.defaultRandomBytes) {
196
+ const sk = require_secp256k1_scalar.sampleScalarNonZero(rng);
197
+ const guardianSecretKeyBytes32 = require_secp256k1_scalar.scalarToBytes32(sk);
198
+ const guardianPublicKeyComp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.mulBaseG(sk));
199
+ return {
200
+ guardianSecretKeyBytes32,
201
+ guardianPublicKeyComp33,
202
+ guardianPublicKeyHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(guardianPublicKeyComp33)}`
203
+ };
204
+ }
205
+ /**
206
+ * Air-gapped Custodian Step 1 (`decrypt-to-steel`):
207
+ * 1. Enforces single-index per custodian boot AND process (`SINGLE_CUSTODIAN_SESSION_VIOLATION`).
208
+ * 2. Validates `PrintableManifestCard` (`printableText` + `escapeColdWallet` + `Y_k`) against `recoveryPackageBytes`.
209
+ * 3. Decrypts ONLY `g(guardianIndex)` via `BSGS_M = 680`, checks `g(k)*G == Y_k`, and wipes `guardianSecretKeyBytes32`.
210
+ * 4. Encodes `g(guardianIndex)` into 24 standard BIP-39 words (`0` passphrases), computes the `m/44'/60'/0'/0/0`
211
+ * honeypot bait address `0xDecoy_j`, and zeroizes `coldShareBytes32` before returning.
212
+ */
213
+ function decryptGuardianColdShareToSteelWords24(params) {
214
+ const { recoveryPackageBytes, guardianIndex, guardianSecretKeyBytes32, manifestCard, sessionLockDir, sessionLockFilePath } = params;
215
+ let decryptedShareBytes32 = null;
216
+ try {
217
+ const lockInfo = enforceSingleCustodianDecryptPerSession({
218
+ guardianIndex,
219
+ lockDir: sessionLockDir,
220
+ lockFilePath: sessionLockFilePath
221
+ });
222
+ if (manifestCard) {
223
+ if (!require_ves_backup.verifyManifestAgainstRecoveryPackage(manifestCard, recoveryPackageBytes)) throw new require_constants.MpcProtocolError("VES_PACKAGE_INVALID", "Recovery package failed verification against PrintableManifestCard");
224
+ }
225
+ const decrypted = require_ves_backup.decryptGuardianColdShareBsgs({
226
+ recoveryPackageBytes,
227
+ guardianIndex,
228
+ guardianSecretKeyBytes32,
229
+ expectedManifest: manifestCard ? {
230
+ ctxDkg32: require_secp256k1_scalar.normalizeHexBytes(manifestCard.ctxDkgHex, 32),
231
+ rootPublicKeyComp33: require_secp256k1_scalar.normalizeHexBytes(manifestCard.rootPublicKeyHex, 33),
232
+ aggColdCommitmentsComp33: manifestCard.coldFeldmanCommitmentsHex.map((h) => require_secp256k1_scalar.normalizeHexBytes(h, 33)),
233
+ guardianPublicKeysComp33: manifestCard.guardianPublicKeysHex.map((h) => require_secp256k1_scalar.normalizeHexBytes(h, 33))
234
+ } : void 0,
235
+ wipeSecretKeyInput: true
236
+ });
237
+ decryptedShareBytes32 = decrypted.coldShareBytes32;
238
+ const words24 = require_steel_mnemonic.encodeColdShareToBip39Words24(decryptedShareBytes32);
239
+ const decoyEthAddress = require_steel_mnemonic.deriveBip44EthAddressFromWords24(words24);
240
+ return {
241
+ guardianIndex,
242
+ plateLabel: require_steel_mnemonic.guardianIndexToPlateLabel(guardianIndex),
243
+ words24,
244
+ coldPublicShareHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(decrypted.coldPublicShareComp33)}`,
245
+ decoyEthAddress,
246
+ sessionLockFilePath: lockInfo.lockFilePath
247
+ };
248
+ } finally {
249
+ require_secp256k1_scalar.zeroizeBytes(guardianSecretKeyBytes32, decryptedShareBytes32);
250
+ }
251
+ }
252
+ /**
253
+ * Air-gapped Clean-Session Custodian Step 2 (`prove-cold-shard`):
254
+ * - Accepts ONLY the 24 BIP-39 words retranscribed from physical `Plate j` + `clusterChallengeBundle`
255
+ * (zero raw private-key file inputs, zero passphrases, zero reconstruction).
256
+ * - Validates full `PrintableManifestCard` consistency (including ALL `nCold` `guardianColdPublicSharesHex`
257
+ * entries!) when `manifestCard` is supplied.
258
+ * - Verifies 24-word SHA-256 checksum, matches `g(j)*G == Y_j` BEFORE creating the Schnorr PoK, and wipes
259
+ * the decoded share buffer in `finally`.
260
+ */
261
+ function proveColdShardFromSteelWords24(params) {
262
+ const { words24, challengeBundle, manifestCard, expectedGuardianIndex, rng } = params;
263
+ let coldShareBytes32 = null;
264
+ let shareScalar = 0n;
265
+ try {
266
+ if (!require_ves_backup.verifyCanaryChallengeBundle(challengeBundle)) throw new require_constants.MpcProtocolError("CANARY_CERT_INVALID", "Invalid or expired CanaryChallengeBundle");
267
+ if (manifestCard) require_ves_backup.assertChallengeBundleMatchesManifest(challengeBundle, manifestCard);
268
+ coldShareBytes32 = require_steel_mnemonic.decodeBip39Words24ToColdShare(words24);
269
+ shareScalar = require_secp256k1_scalar.bytes32ToScalarNonZero(coldShareBytes32);
270
+ const derivedYkComp33 = require_secp256k1_scalar.encodePointCompressed(require_secp256k1_scalar.mulBaseG(shareScalar));
271
+ let matchedGuardianIndex = null;
272
+ for (let k = 1; k <= challengeBundle.nCold; k++) if (require_secp256k1_scalar.constantTimeEqual(derivedYkComp33, require_secp256k1_scalar.normalizeHexBytes(challengeBundle.guardianColdPublicSharesHex[k - 1], 33))) {
273
+ matchedGuardianIndex = k;
274
+ break;
275
+ }
276
+ if (matchedGuardianIndex === null) throw new require_constants.MpcProtocolError("VES_SHARE_MISMATCH", "Retranscribed 24-word BIP-39 plate failed g(j)*G == Y_j check against cluster cold public shares");
277
+ if (expectedGuardianIndex !== void 0 && matchedGuardianIndex !== expectedGuardianIndex) throw new require_constants.MpcProtocolError("VES_SHARE_MISMATCH", `Retranscribed plate matched guardian ${matchedGuardianIndex}, expected guardian ${expectedGuardianIndex}`);
278
+ if (manifestCard) {
279
+ if (require_steel_mnemonic.identifyColdShareIndexViaFeldman(coldShareBytes32, manifestCard.coldFeldmanCommitmentsHex, manifestCard.nCold).guardianIndex !== matchedGuardianIndex) throw new require_constants.MpcProtocolError("VES_SHARE_MISMATCH", "Feldman commitment index mismatch on retranscribed plate");
280
+ }
281
+ const shardProof = require_ves_backup.createColdShardSchnorrPok({
282
+ ctxDkg: challengeBundle.ctxDkgHex,
283
+ guardianIndex: matchedGuardianIndex,
284
+ challengeNonce: challengeBundle.challengeNonceHex,
285
+ coldShareBytes32,
286
+ expectedColdPublicShare: challengeBundle.guardianColdPublicSharesHex[matchedGuardianIndex - 1],
287
+ rng,
288
+ wipeColdShareInput: true
289
+ });
290
+ return {
291
+ guardianIndex: matchedGuardianIndex,
292
+ plateLabel: require_steel_mnemonic.guardianIndexToPlateLabel(matchedGuardianIndex),
293
+ shardProof
294
+ };
295
+ } finally {
296
+ shareScalar = 0n;
297
+ require_secp256k1_scalar.zeroizeBytes(coldShareBytes32);
298
+ }
299
+ }
300
+ function signDigestDeterministicLowS(params) {
301
+ const { signingScalar, signingKeyBytes32, expectedSenderAddress, txDigest32 } = params;
302
+ const mScalar = require_secp256k1_scalar.modN(BigInt(`0x${(0, _noble_hashes_utils_js.bytesToHex)(txDigest32)}`));
303
+ for (let counter = 0; counter < 64; counter++) {
304
+ const kNonce = require_secp256k1_scalar.H_scalar(require_constants.DST_EMERGENCY_SWEEP_NONCE_V1, signingKeyBytes32, txDigest32, Uint8Array.of(counter & 255));
305
+ const rPoint = require_secp256k1_scalar.mulBaseG(kNonce);
306
+ if (rPoint.is0()) continue;
307
+ const affine = rPoint.toAffine();
308
+ if (affine.x >= require_constants.SECP256K1_N) continue;
309
+ const r = require_secp256k1_scalar.modN(affine.x);
310
+ if (r === 0n) continue;
311
+ let yParity = Number(affine.y & 1n);
312
+ const sRaw = require_secp256k1_scalar.mulModN(require_secp256k1_scalar.invModN(kNonce), require_secp256k1_scalar.addModN(mScalar, require_secp256k1_scalar.mulModN(r, signingScalar)));
313
+ if (sRaw === 0n) continue;
314
+ let s = sRaw;
315
+ if (s > require_constants.SECP256K1_HALF_N) {
316
+ s = require_secp256k1_scalar.subModN(0n, s);
317
+ yParity = yParity ^ 1;
318
+ }
319
+ if (require_tweak.ecrecoverEthAddress({
320
+ msgDigest32: txDigest32,
321
+ r,
322
+ s,
323
+ yParity
324
+ }).checksumAddress !== expectedSenderAddress) throw new require_constants.MpcProtocolError("SIGN_AGGREGATION_FAILED", "Emergency sweep signature failed self-ecrecover check");
325
+ return {
326
+ r,
327
+ s,
328
+ yParity
329
+ };
330
+ }
331
+ throw new require_constants.MpcProtocolError("SIGN_AGGREGATION_FAILED", "Unable to sample non-degenerate ECDSA nonce for sweep");
332
+ }
333
+ function executeEmergencySweepSign(params) {
334
+ const { manifest, steelPlatesWords24, childSpec = { tweakMode: "untweaked" }, buildUnsignedTx } = params;
335
+ require_ves_backup.validatePrintableManifestCard(manifest);
336
+ const escapeParsed = require_tweak.parseStrictEthAddress(manifest.escapeColdWallet);
337
+ if (manifest.tCold < 2) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", `Invalid cold quorum (${manifest.tCold}-of-${manifest.nCold})`);
338
+ const unsignedTx = buildUnsignedTx(escapeParsed.checksumAddress);
339
+ const { signingDigest32 } = require_rlp_eip1559.encodeUnsignedEip1559Tx(unsignedTx);
340
+ if (!Array.isArray(steelPlatesWords24) || steelPlatesWords24.length < manifest.tCold) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", `Emergency sweep requires at least ${manifest.tCold} physical 24-word steel plates, got ${steelPlatesWords24?.length}`);
341
+ const secretBuffersToZeroize = [];
342
+ let combinedColdScalar = 0n;
343
+ let signingScalar = 0n;
344
+ try {
345
+ const pRoot = require_secp256k1_scalar.decodePointCompressed(require_secp256k1_scalar.normalizeHexBytes(manifest.rootPublicKeyHex, 33), false);
346
+ const verifiedPlates = [];
347
+ const seenGuardians = /* @__PURE__ */ new Set();
348
+ for (const plateWords of steelPlatesWords24) {
349
+ const shareBytes32 = require_steel_mnemonic.decodeBip39Words24ToColdShare(plateWords);
350
+ secretBuffersToZeroize.push(shareBytes32);
351
+ const identified = require_steel_mnemonic.identifyColdShareIndexViaFeldman(shareBytes32, manifest.coldFeldmanCommitmentsHex, manifest.nCold);
352
+ if (seenGuardians.has(identified.guardianIndex)) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", `Duplicate steel plate supplied for guardian index ${identified.guardianIndex} (${identified.plateLabel})`);
353
+ const expectedYk33 = require_secp256k1_scalar.normalizeHexBytes(manifest.guardianColdPublicSharesHex[identified.guardianIndex - 1], 33);
354
+ if (!require_secp256k1_scalar.constantTimeEqual(identified.coldPublicShareComp33, expectedYk33)) throw new require_constants.MpcProtocolError("VES_SHARE_MISMATCH", "Plate public share mismatch against manifest Y_k");
355
+ seenGuardians.add(identified.guardianIndex);
356
+ verifiedPlates.push({
357
+ guardianIndex: identified.guardianIndex,
358
+ shareScalar: require_secp256k1_scalar.bytes32ToScalarNonZero(shareBytes32)
359
+ });
360
+ }
361
+ const activePlates = verifiedPlates.slice(0, manifest.tCold).sort((a, b) => a.guardianIndex - b.guardianIndex);
362
+ const coldSubset = activePlates.map((p) => p.guardianIndex);
363
+ for (const entry of activePlates) {
364
+ const lambda = require_secp256k1_scalar.lagrangeCoefficientAtZero(entry.guardianIndex, coldSubset);
365
+ combinedColdScalar = require_secp256k1_scalar.addModN(combinedColdScalar, require_secp256k1_scalar.mulModN(lambda, entry.shareScalar));
366
+ entry.shareScalar = 0n;
367
+ }
368
+ if (combinedColdScalar === 0n || !require_secp256k1_scalar.mulBaseG(combinedColdScalar).equals(pRoot)) throw new require_constants.MpcProtocolError("SWEEP_INVALID_QUORUM", "Lagrange interpolation of cold steel plates did not match manifest rootPublicKey");
369
+ let derivedChild;
370
+ if (childSpec.tweakMode === "untweaked") derivedChild = require_tweak.deriveUntweakedChild(pRoot);
371
+ else if (childSpec.tweakMode === "role-bound") {
372
+ if (childSpec.ethChainId !== unsignedTx.chainId) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "role-bound ethChainId must equal transaction chainId");
373
+ derivedChild = require_tweak.deriveRoleBoundChild({
374
+ rootPublicKey: pRoot,
375
+ rootId: manifest.rootId,
376
+ role: childSpec.role,
377
+ ethChainId: childSpec.ethChainId,
378
+ tweakLabel: childSpec.tweakLabel
379
+ });
380
+ } else {
381
+ if (childSpec.ethChainId !== unsignedTx.chainId) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "rule-bound ethChainId must equal transaction chainId");
382
+ derivedChild = require_tweak.deriveRuleBoundChild({
383
+ rootPublicKey: pRoot,
384
+ rootId: manifest.rootId,
385
+ controllerDid: childSpec.controllerDid,
386
+ ethChainId: childSpec.ethChainId,
387
+ ruleHash: childSpec.ruleHash
388
+ });
389
+ }
390
+ signingScalar = require_secp256k1_scalar.addModN(combinedColdScalar, derivedChild.tweakScalar);
391
+ if (signingScalar === 0n || !require_secp256k1_scalar.mulBaseG(signingScalar).equals(derivedChild.childPoint)) throw new require_constants.MpcProtocolError("DEGENERATE_TWEAK", "Derived sweep signing scalar mismatch");
392
+ const signingKeyBytes32 = require_secp256k1_scalar.scalarToBytes32(signingScalar);
393
+ secretBuffersToZeroize.push(signingKeyBytes32);
394
+ const { r, s, yParity } = signDigestDeterministicLowS({
395
+ signingScalar,
396
+ signingKeyBytes32,
397
+ expectedSenderAddress: derivedChild.ethAddress,
398
+ txDigest32: signingDigest32
399
+ });
400
+ const signed = require_rlp_eip1559.encodeSignedEip1559Tx({
401
+ tx: unsignedTx,
402
+ yParity,
403
+ r,
404
+ s
405
+ });
406
+ const rBytes32 = require_secp256k1_scalar.scalarToBytes32(r);
407
+ const sBytes32 = require_secp256k1_scalar.scalarToBytes32(s);
408
+ return {
409
+ senderEthAddress: derivedChild.ethAddress,
410
+ escapeColdWallet: escapeParsed.checksumAddress,
411
+ usedGuardianIndices: coldSubset,
412
+ rawSignedTxBytes: signed.rawSignedTxBytes,
413
+ rawSignedTxHex: signed.rawSignedTxHex,
414
+ txHashHex: signed.txHashHex,
415
+ yParity,
416
+ rHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(rBytes32)}`,
417
+ sHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(sBytes32)}`
418
+ };
419
+ } finally {
420
+ combinedColdScalar = 0n;
421
+ signingScalar = 0n;
422
+ require_secp256k1_scalar.zeroizeBytes(...secretBuffersToZeroize);
423
+ }
424
+ }
425
+ /**
426
+ * Signs an air-gapped EIP-1559 native ETH disaster-recovery sweep strictly locked to `manifest.escapeColdWallet`
427
+ * (`data = 0x` empty calldata enforced; refuses any `recipientAddress !== manifest.escapeColdWallet`).
428
+ */
429
+ function sweepEth(params) {
430
+ const { manifest, steelPlatesWords24, recipientAddress, amountWei, chainId, nonce, maxPriorityFeePerGasWei, maxFeePerGasWei, gasLimit = 21000n, childSpec } = params;
431
+ if (typeof amountWei !== "bigint" || amountWei <= 0n) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "ETH sweep amountWei must be > 0");
432
+ return executeEmergencySweepSign({
433
+ manifest,
434
+ steelPlatesWords24,
435
+ childSpec,
436
+ buildUnsignedTx: (escapeChecksumAddress) => {
437
+ const parsedRecipient = require_tweak.parseStrictEthAddress(recipientAddress);
438
+ if (parsedRecipient.checksumAddress !== escapeChecksumAddress) throw new require_constants.MpcProtocolError("SWEEP_DESTINATION_MISMATCH", `Emergency ETH sweep destination "${parsedRecipient.checksumAddress}" !== immutable escapeColdWallet "${escapeChecksumAddress}"`);
439
+ return {
440
+ chainId,
441
+ nonce,
442
+ maxPriorityFeePerGasWei,
443
+ maxFeePerGasWei,
444
+ gasLimit,
445
+ to: escapeChecksumAddress,
446
+ valueWei: amountWei,
447
+ data: new Uint8Array(0)
448
+ };
449
+ }
450
+ });
451
+ }
452
+ /**
453
+ * Signs an air-gapped EIP-1559 ERC-20 `transfer(escapeColdWallet, tokenAmount)` disaster-recovery sweep
454
+ * strictly locked to `manifest.escapeColdWallet` (`valueWei = 0n`; refuses any `recipientAddress !== manifest.escapeColdWallet`).
455
+ */
456
+ function sweepErc20Transfer(params) {
457
+ const { manifest, steelPlatesWords24, tokenContractAddress, recipientAddress, tokenAmount, chainId, nonce, maxPriorityFeePerGasWei, maxFeePerGasWei, gasLimit = 100000n, childSpec } = params;
458
+ return executeEmergencySweepSign({
459
+ manifest,
460
+ steelPlatesWords24,
461
+ childSpec,
462
+ buildUnsignedTx: (escapeChecksumAddress) => {
463
+ const parsedRecipient = require_tweak.parseStrictEthAddress(recipientAddress);
464
+ if (parsedRecipient.checksumAddress !== escapeChecksumAddress) throw new require_constants.MpcProtocolError("SWEEP_DESTINATION_MISMATCH", `Emergency ERC-20 sweep recipient "${parsedRecipient.checksumAddress}" !== immutable escapeColdWallet "${escapeChecksumAddress}"`);
465
+ const parsedToken = require_tweak.parseStrictEthAddress(tokenContractAddress);
466
+ const calldata = require_rlp_eip1559.encodeErc20TransferCalldata(escapeChecksumAddress, tokenAmount);
467
+ return {
468
+ chainId,
469
+ nonce,
470
+ maxPriorityFeePerGasWei,
471
+ maxFeePerGasWei,
472
+ gasLimit,
473
+ to: parsedToken.checksumAddress,
474
+ valueWei: 0n,
475
+ data: calldata
476
+ };
477
+ }
478
+ });
479
+ }
480
+
481
+ //#endregion
482
+ exports.decryptGuardianColdShareToSteelWords24 = decryptGuardianColdShareToSteelWords24;
483
+ exports.enforceSingleCustodianDecryptPerSession = enforceSingleCustodianDecryptPerSession;
484
+ exports.generateGuardianKeypair = generateGuardianKeypair;
485
+ exports.proveColdShardFromSteelWords24 = proveColdShardFromSteelWords24;
486
+ exports.sweepErc20Transfer = sweepErc20Transfer;
487
+ exports.sweepEth = sweepEth;