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