@ocap/wallet-hsm 0.0.0-stage → 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.
@@ -0,0 +1,263 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_mpc_hsm_personal = require("@ocap/mpc-hsm/personal");
3
+
4
+ //#region src/broadcaster.ts
5
+ /**
6
+ * Isomorphic Multi-Chain Transaction Broadcasters (`@ocap/wallet-hsm`, #2333).
7
+ *
8
+ * - `createChainGatewayBroadcaster`: talks to Follower / `ocap-chain-edge` `/api/wallet-relay/v1/{prepare,broadcast}`
9
+ * to obtain Stage 1 `SignedFirewallAttestation` + `SimulatedBalanceDelta` and enforce Stage 2 TOCTOU state-drift
10
+ * verification. Security blocks (`400`/`401`/`403`/`409`/`429`) NEVER fall back to `DirectRpcBroadcaster`; only
11
+ * network/timeout errors or `5xx` gateway outages trigger optional sovereign fallback.
12
+ * - `createDirectRpcBroadcaster`: sovereign multi-RPC JSON-RPC fan-out (`eth_sendRawTransaction`) with local
13
+ * `decodeAndRecoverSignedEip1559Tx` pre-verification.
14
+ */
15
+ var WalletRelayError = class extends Error {
16
+ constructor(code, message, httpStatus, riskCodes = []) {
17
+ super(message);
18
+ this.name = "WalletRelayError";
19
+ this.code = code;
20
+ this.httpStatus = httpStatus;
21
+ this.riskCodes = riskCodes;
22
+ }
23
+ };
24
+ function serializeSimulatedDeltaWire(delta) {
25
+ const tokenDeltas = {};
26
+ if (delta.tokenDeltas) for (const [k, v] of Object.entries(delta.tokenDeltas)) tokenDeltas[k] = v.toString(10);
27
+ return {
28
+ ...delta.simulationReverted !== void 0 ? { simulationReverted: delta.simulationReverted } : {},
29
+ nativeDeltaWei: delta.nativeDeltaWei.toString(10),
30
+ ...Object.keys(tokenDeltas).length > 0 ? { tokenDeltas } : {},
31
+ ...delta.outgoingAssetIds ? { outgoingAssetIds: delta.outgoingAssetIds } : {},
32
+ ...delta.ownedAssetIdsAfter ? { ownedAssetIdsAfter: delta.ownedAssetIdsAfter } : {}
33
+ };
34
+ }
35
+ function deserializeSimulatedDeltaWire(raw) {
36
+ const tokenDeltas = {};
37
+ if (raw.tokenDeltas && typeof raw.tokenDeltas === "object" && !Array.isArray(raw.tokenDeltas)) for (const [k, v] of Object.entries(raw.tokenDeltas)) tokenDeltas[k] = BigInt(String(v));
38
+ return {
39
+ ...typeof raw.simulationReverted === "boolean" ? { simulationReverted: raw.simulationReverted } : {},
40
+ nativeDeltaWei: BigInt(String(raw.nativeDeltaWei ?? "0")),
41
+ ...Object.keys(tokenDeltas).length > 0 ? { tokenDeltas } : {},
42
+ ...Array.isArray(raw.outgoingAssetIds) ? { outgoingAssetIds: raw.outgoingAssetIds.map(String) } : {},
43
+ ...Array.isArray(raw.ownedAssetIdsAfter) ? { ownedAssetIdsAfter: raw.ownedAssetIdsAfter.map(String) } : {}
44
+ };
45
+ }
46
+ function serializePostConditionsWire(pc) {
47
+ const maxTokenOutflows = {};
48
+ if (pc.maxTokenOutflows) for (const [k, v] of Object.entries(pc.maxTokenOutflows)) maxTokenOutflows[k] = v.toString(10);
49
+ const minTokenInflows = {};
50
+ if (pc.minTokenInflows) for (const [k, v] of Object.entries(pc.minTokenInflows)) minTokenInflows[k] = v.toString(10);
51
+ return {
52
+ maxNativeOutflowWei: pc.maxNativeOutflowWei.toString(10),
53
+ ...pc.minNativeInflowWei !== void 0 ? { minNativeInflowWei: pc.minNativeInflowWei.toString(10) } : {},
54
+ ...Object.keys(maxTokenOutflows).length > 0 ? { maxTokenOutflows } : {},
55
+ ...Object.keys(minTokenInflows).length > 0 ? { minTokenInflows } : {},
56
+ ...pc.allowedOutgoingAssets ? { allowedOutgoingAssets: pc.allowedOutgoingAssets } : {},
57
+ ...pc.mustOwnAssetsAfter ? { mustOwnAssetsAfter: pc.mustOwnAssetsAfter } : {},
58
+ strictZeroUnlistedOutflow: pc.strictZeroUnlistedOutflow
59
+ };
60
+ }
61
+ async function fetchJsonWithTimeout(params) {
62
+ const controller = new AbortController();
63
+ const timer = setTimeout(() => controller.abort(), params.timeoutMs);
64
+ try {
65
+ const res = await params.fetchImpl(params.url, {
66
+ method: "POST",
67
+ headers: {
68
+ "Content-Type": "application/json",
69
+ Accept: "application/json",
70
+ ...params.headers ?? {}
71
+ },
72
+ body: JSON.stringify(params.body),
73
+ signal: controller.signal
74
+ });
75
+ const text = await res.text();
76
+ let parsed = {};
77
+ try {
78
+ const p = JSON.parse(text);
79
+ if (p && typeof p === "object" && !Array.isArray(p)) parsed = p;
80
+ } catch {
81
+ parsed = {
82
+ error: "NON_JSON_RESPONSE",
83
+ message: text.slice(0, 200)
84
+ };
85
+ }
86
+ return {
87
+ status: res.status,
88
+ json: parsed
89
+ };
90
+ } finally {
91
+ clearTimeout(timer);
92
+ }
93
+ }
94
+ function createDirectRpcBroadcaster(options) {
95
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
96
+ const timeoutMs = options.timeoutMs ?? 4e3;
97
+ return { async broadcastEip1559(input) {
98
+ const decoded = (0, _ocap_mpc_hsm_personal.decodeAndRecoverSignedEip1559Tx)(input.rawSignedTxHex);
99
+ const expectedChainId = BigInt(input.chainId);
100
+ if (decoded.chainId !== expectedChainId) throw new WalletRelayError("WALLET_RELAY_CHAIN_MISMATCH", `Signed tx chainId (${decoded.chainId}) != requested chainId (${expectedChainId})`, 400);
101
+ const urls = options.rpcUrlsByChainId[expectedChainId.toString(10)] ?? [];
102
+ if (urls.length === 0) throw new WalletRelayError("DIRECT_RPC_UNCONFIGURED", `No direct RPC URLs configured for chainId ${expectedChainId.toString(10)}`, 503);
103
+ const txHex = input.rawSignedTxHex.startsWith("0x") ? input.rawSignedTxHex : `0x${input.rawSignedTxHex}`;
104
+ const attempts = urls.map(async (rpcUrl) => {
105
+ const { status, json } = await fetchJsonWithTimeout({
106
+ url: rpcUrl,
107
+ body: {
108
+ jsonrpc: "2.0",
109
+ id: 1,
110
+ method: "eth_sendRawTransaction",
111
+ params: [txHex]
112
+ },
113
+ fetchImpl,
114
+ timeoutMs
115
+ });
116
+ if (status >= 200 && status < 300 && typeof json.result === "string" && /^0x[0-9a-fA-F]{64}$/.test(json.result)) return {
117
+ txHashHex: json.result,
118
+ via: "direct-rpc"
119
+ };
120
+ const rpcErr = json.error && typeof json.error === "object" ? String(json.error.message ?? "RPC error") : `HTTP ${status}`;
121
+ throw new Error(rpcErr);
122
+ });
123
+ const firstResolved = (promises) => new Promise((resolve, reject) => {
124
+ let pending = promises.length;
125
+ if (pending === 0) {
126
+ reject(/* @__PURE__ */ new Error("No promises"));
127
+ return;
128
+ }
129
+ for (const p of promises) p.then(resolve, () => {
130
+ pending -= 1;
131
+ if (pending === 0) reject(/* @__PURE__ */ new Error("All promises rejected"));
132
+ });
133
+ });
134
+ try {
135
+ return await firstResolved(attempts);
136
+ } catch {
137
+ throw new WalletRelayError("DIRECT_RPC_ALL_FAILED", "All configured direct RPC endpoints failed", 502);
138
+ }
139
+ } };
140
+ }
141
+ function createChainGatewayBroadcaster(options) {
142
+ const baseUrl = options.gatewayBaseUrl.replace(/\/+$/, "");
143
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
144
+ const timeoutMs = options.timeoutMs ?? 4e3;
145
+ return {
146
+ async prepareEip1559(input) {
147
+ const dataHex = input.tx.data instanceof Uint8Array ? `0x${(0, _ocap_mpc_hsm_personal.bytesToHex)(input.tx.data)}` : typeof input.tx.data === "string" && input.tx.data.length > 0 ? input.tx.data : "0x";
148
+ const { status, json } = await fetchJsonWithTimeout({
149
+ url: `${baseUrl}/api/wallet-relay/v1/prepare`,
150
+ fetchImpl,
151
+ timeoutMs,
152
+ headers: options.headers,
153
+ body: {
154
+ chainNamespace: "evm",
155
+ chainId: input.tx.chainId.toString(10),
156
+ ...input.vaultId ? { vaultId: input.vaultId } : {},
157
+ ...input.policyEpoch !== void 0 ? { policyEpoch: BigInt(input.policyEpoch).toString(10) } : {},
158
+ tier: input.tier ?? "pro-shield",
159
+ fromAddress: input.fromAddress,
160
+ tx: {
161
+ chainId: input.tx.chainId.toString(10),
162
+ nonce: input.tx.nonce.toString(10),
163
+ maxPriorityFeePerGasWei: input.tx.maxPriorityFeePerGasWei.toString(10),
164
+ maxFeePerGasWei: input.tx.maxFeePerGasWei.toString(10),
165
+ gasLimit: input.tx.gasLimit.toString(10),
166
+ to: input.tx.to,
167
+ valueWei: input.tx.valueWei.toString(10),
168
+ data: dataHex,
169
+ ...input.tx.accessList && input.tx.accessList.length > 0 ? { accessList: input.tx.accessList.map((entry) => ({
170
+ address: entry.address,
171
+ storageKeys: entry.storageKeys.map((k) => k instanceof Uint8Array ? `0x${(0, _ocap_mpc_hsm_personal.bytesToHex)(k)}` : String(k))
172
+ })) } : {}
173
+ },
174
+ ...input.signingDigestHex ? { signingDigestHex: input.signingDigestHex } : {},
175
+ ...input.clearSigningPreviewHashHex ? { clearSigningPreviewHashHex: input.clearSigningPreviewHashHex } : {},
176
+ ...input.knownCounterparties ? { knownCounterparties: input.knownCounterparties } : {},
177
+ ...input.postConditions ? { postConditions: serializePostConditionsWire(input.postConditions) } : {},
178
+ ...input.authProof ? { authProof: input.authProof } : {}
179
+ }
180
+ });
181
+ if (status < 200 || status >= 300 || json.ok !== true) throw new WalletRelayError(String(json.error ?? json.code ?? "WALLET_RELAY_PREPARE_FAILED"), String(json.message ?? "Wallet relay prepare failed"), status, Array.isArray(json.riskCodes) ? json.riskCodes.map(String) : []);
182
+ const simObj = json.simulation ?? {};
183
+ const feeObj = json.feeSuggestion ?? {};
184
+ return {
185
+ chainId: String(json.chainId ?? input.tx.chainId.toString(10)),
186
+ suggestedNonce: BigInt(String(json.suggestedNonce ?? input.tx.nonce.toString(10))),
187
+ maxFeePerGasWei: BigInt(String(feeObj.maxFeePerGasWei ?? input.tx.maxFeePerGasWei.toString(10))),
188
+ maxPriorityFeePerGasWei: BigInt(String(feeObj.maxPriorityFeePerGasWei ?? input.tx.maxPriorityFeePerGasWei.toString(10))),
189
+ gasLimit: BigInt(String(feeObj.gasLimit ?? input.tx.gasLimit.toString(10))),
190
+ simulatedBlockNumber: BigInt(String(simObj.simulatedBlockNumber ?? "0")),
191
+ simulatedDelta: deserializeSimulatedDeltaWire(simObj.simulatedDelta ?? { nativeDeltaWei: "0" }),
192
+ ...typeof simObj.attestedProxyImplementationAddress === "string" ? { attestedProxyImplementationAddress: simObj.attestedProxyImplementationAddress } : {},
193
+ verdict: json.verdict ?? "allow",
194
+ riskCodes: Array.isArray(json.riskCodes) ? json.riskCodes.map(String) : [],
195
+ ...json.firewallAttestation && typeof json.firewallAttestation === "object" ? { firewallAttestation: json.firewallAttestation } : {}
196
+ };
197
+ },
198
+ async broadcastEip1559(input) {
199
+ let gatewayNetworkOr5xxFailure = null;
200
+ try {
201
+ const { status, json } = await fetchJsonWithTimeout({
202
+ url: `${baseUrl}/api/wallet-relay/v1/broadcast`,
203
+ fetchImpl,
204
+ timeoutMs,
205
+ headers: options.headers,
206
+ body: {
207
+ chainNamespace: "evm",
208
+ chainId: BigInt(input.chainId).toString(10),
209
+ rawSignedTxHex: input.rawSignedTxHex,
210
+ tier: input.tier ?? (input.firewallAttestation ? input.firewallAttestation.tier : "pro-shield"),
211
+ ...input.firewallAttestation ? { firewallAttestation: input.firewallAttestation } : {},
212
+ ...input.stage1SimulatedDelta ? { stage1SimulatedDelta: serializeSimulatedDeltaWire(input.stage1SimulatedDelta) } : {},
213
+ ...input.attestedProxyImplementationAddress ? { attestedProxyImplementationAddress: input.attestedProxyImplementationAddress } : {},
214
+ ...input.postConditions ? { postConditions: serializePostConditionsWire(input.postConditions) } : {},
215
+ ...input.preferPrivateMevRpc !== void 0 ? { preferPrivateMevRpc: input.preferPrivateMevRpc } : {}
216
+ }
217
+ });
218
+ if (status >= 200 && status < 300 && json.ok === true && typeof json.txHashHex === "string") return {
219
+ txHashHex: json.txHashHex,
220
+ via: String(json.via ?? "chain-gateway")
221
+ };
222
+ if (status >= 400 && status < 500) throw new WalletRelayError(String(json.error ?? json.code ?? "WALLET_RELAY_BLOCKED"), String(json.message ?? "Transaction blocked by gateway"), status, Array.isArray(json.riskCodes) ? json.riskCodes.map(String) : []);
223
+ gatewayNetworkOr5xxFailure = new WalletRelayError(String(json.error ?? "WALLET_RELAY_UPSTREAM_UNAVAILABLE"), String(json.message ?? `Gateway returned HTTP ${status}`), status);
224
+ } catch (err) {
225
+ if (err instanceof WalletRelayError && err.httpStatus >= 400 && err.httpStatus < 500) throw err;
226
+ gatewayNetworkOr5xxFailure = err;
227
+ }
228
+ if (options.fallbackBroadcaster) {
229
+ if (input.tier === "vault-enforced" || input.firewallAttestation?.tier === "vault-enforced") throw gatewayNetworkOr5xxFailure instanceof Error ? gatewayNetworkOr5xxFailure : new WalletRelayError("WALLET_RELAY_VAULT_ENFORCED_UNAVAILABLE", "Gateway unavailable for vault-enforced tx", 503);
230
+ return options.fallbackBroadcaster.broadcastEip1559(input);
231
+ }
232
+ throw gatewayNetworkOr5xxFailure instanceof Error ? gatewayNetworkOr5xxFailure : new WalletRelayError("WALLET_RELAY_UNAVAILABLE", "Wallet relay gateway unreachable", 503);
233
+ },
234
+ async broadcastOcapTx(input) {
235
+ const { status, json } = await fetchJsonWithTimeout({
236
+ url: `${baseUrl}/api/wallet-relay/v1/broadcast`,
237
+ fetchImpl,
238
+ timeoutMs,
239
+ headers: options.headers,
240
+ body: {
241
+ chainNamespace: "ocap",
242
+ chainId: input.chainId,
243
+ rawSignedTxHex: input.rawSignedCborTxHex,
244
+ tier: input.tier ?? (input.firewallAttestation ? input.firewallAttestation.tier : "pro-shield"),
245
+ ...input.firewallAttestation ? { firewallAttestation: input.firewallAttestation } : {},
246
+ ...input.stage1SimulatedDelta ? { stage1SimulatedDelta: serializeSimulatedDeltaWire(input.stage1SimulatedDelta) } : {},
247
+ ...input.postConditions ? { postConditions: serializePostConditionsWire(input.postConditions) } : {}
248
+ }
249
+ });
250
+ if (status >= 200 && status < 300 && json.ok === true && typeof json.txHashHex === "string") return {
251
+ txHashHex: json.txHashHex,
252
+ via: String(json.via ?? "chain-gateway-ocap")
253
+ };
254
+ const riskCodes = Array.isArray(json.riskCodes) ? json.riskCodes.map(String) : [];
255
+ throw new WalletRelayError(String(json.error ?? json.code ?? "WALLET_RELAY_OCAP_BROADCAST_FAILED"), String(json.message ?? `OCAP relay broadcast failed (${status})`), status, riskCodes);
256
+ }
257
+ };
258
+ }
259
+
260
+ //#endregion
261
+ exports.WalletRelayError = WalletRelayError;
262
+ exports.createChainGatewayBroadcaster = createChainGatewayBroadcaster;
263
+ exports.createDirectRpcBroadcaster = createDirectRpcBroadcaster;
@@ -0,0 +1,88 @@
1
+ import { Eip1559UnsignedTxFields, FirewallCommercialTier, FirewallRiskVerdict, PersonalPostConditions, SignedFirewallAttestation, SimulatedBalanceDelta } from "@ocap/mpc-hsm/personal";
2
+
3
+ //#region src/broadcaster.d.ts
4
+
5
+ declare class WalletRelayError extends Error {
6
+ readonly code: string;
7
+ readonly httpStatus: number;
8
+ readonly riskCodes: ReadonlyArray<string>;
9
+ constructor(code: string, message: string, httpStatus: number, riskCodes?: ReadonlyArray<string>);
10
+ }
11
+ interface GatewayPrepareAuthProof {
12
+ readonly mode: 'ticket' | 'statedb-stake';
13
+ readonly ticket?: Record<string, unknown>;
14
+ readonly stakedDid?: string;
15
+ readonly callerPublicKeyHex: string;
16
+ readonly callerKeyType: 'ed25519' | 'secp256k1' | 'ethereum' | 'p256';
17
+ readonly timestampSec: string;
18
+ readonly authNonceHex: string;
19
+ readonly signatureHex: string;
20
+ }
21
+ interface GatewayPrepareEip1559Input {
22
+ readonly vaultId?: string;
23
+ readonly policyEpoch?: bigint | string;
24
+ readonly tier?: FirewallCommercialTier;
25
+ readonly fromAddress: string;
26
+ readonly tx: Eip1559UnsignedTxFields;
27
+ readonly signingDigestHex?: string;
28
+ readonly clearSigningPreviewHashHex?: string;
29
+ readonly knownCounterparties?: ReadonlyArray<string>;
30
+ readonly postConditions?: PersonalPostConditions;
31
+ readonly authProof?: GatewayPrepareAuthProof;
32
+ }
33
+ interface GatewayPrepareEip1559Result {
34
+ readonly chainId: string;
35
+ readonly suggestedNonce: bigint;
36
+ readonly maxFeePerGasWei: bigint;
37
+ readonly maxPriorityFeePerGasWei: bigint;
38
+ readonly gasLimit: bigint;
39
+ readonly simulatedBlockNumber: bigint;
40
+ readonly simulatedDelta: SimulatedBalanceDelta;
41
+ readonly attestedProxyImplementationAddress?: string;
42
+ readonly verdict: FirewallRiskVerdict;
43
+ readonly riskCodes: ReadonlyArray<string>;
44
+ readonly firewallAttestation?: SignedFirewallAttestation;
45
+ }
46
+ interface GatewayBroadcastEip1559Input {
47
+ readonly chainId: bigint | string;
48
+ readonly rawSignedTxHex: string;
49
+ readonly tier?: FirewallCommercialTier;
50
+ readonly firewallAttestation?: SignedFirewallAttestation;
51
+ readonly stage1SimulatedDelta?: SimulatedBalanceDelta;
52
+ readonly attestedProxyImplementationAddress?: string;
53
+ readonly postConditions?: PersonalPostConditions;
54
+ readonly preferPrivateMevRpc?: boolean;
55
+ }
56
+ interface GatewayBroadcastOcapInput {
57
+ readonly chainId: string;
58
+ readonly rawSignedCborTxHex: string;
59
+ readonly tier?: FirewallCommercialTier;
60
+ readonly firewallAttestation?: SignedFirewallAttestation;
61
+ readonly stage1SimulatedDelta?: SimulatedBalanceDelta;
62
+ readonly postConditions?: PersonalPostConditions;
63
+ }
64
+ interface TxBroadcaster {
65
+ prepareEip1559?(input: GatewayPrepareEip1559Input): Promise<GatewayPrepareEip1559Result>;
66
+ broadcastEip1559(input: GatewayBroadcastEip1559Input): Promise<{
67
+ readonly txHashHex: string;
68
+ readonly via: string;
69
+ }>;
70
+ broadcastOcapTx?(input: GatewayBroadcastOcapInput): Promise<{
71
+ readonly txHashHex: string;
72
+ readonly via: string;
73
+ }>;
74
+ }
75
+ declare function createDirectRpcBroadcaster(options: {
76
+ readonly rpcUrlsByChainId: Readonly<Record<string, ReadonlyArray<string>>>;
77
+ readonly fetchImpl?: typeof fetch;
78
+ readonly timeoutMs?: number;
79
+ }): TxBroadcaster;
80
+ declare function createChainGatewayBroadcaster(options: {
81
+ readonly gatewayBaseUrl: string;
82
+ readonly fallbackBroadcaster?: TxBroadcaster;
83
+ readonly fetchImpl?: typeof fetch;
84
+ readonly timeoutMs?: number;
85
+ readonly headers?: Readonly<Record<string, string>>;
86
+ }): TxBroadcaster;
87
+ //#endregion
88
+ export { GatewayBroadcastEip1559Input, GatewayBroadcastOcapInput, GatewayPrepareAuthProof, GatewayPrepareEip1559Input, GatewayPrepareEip1559Result, TxBroadcaster, WalletRelayError, createChainGatewayBroadcaster, createDirectRpcBroadcaster };
@@ -0,0 +1,217 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_mpc_hsm_personal = require("@ocap/mpc-hsm/personal");
3
+
4
+ //#region src/http-cosigner-transport.ts
5
+ /**
6
+ * Isomorphic HTTP Client Transport for `StatelessSealedHsmService` (`/v1/personal/*`, `@ocap/wallet-hsm`, #2333).
7
+ *
8
+ * Zero `node:*` imports and zero `Buffer` references — uses standard `fetch` + WebCrypto AES-GCM/X25519
9
+ * (`sealHsmInboundTransportBox`) and pure base64 wire encoding (`$b` / `__bigint`).
10
+ */
11
+ const STD_B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
12
+ function encodeStdBase64(bytes) {
13
+ let out = "";
14
+ let i = 0;
15
+ for (; i + 2 < bytes.length; i += 3) {
16
+ const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
17
+ out += STD_B64[n >>> 18 & 63] + STD_B64[n >>> 12 & 63] + STD_B64[n >>> 6 & 63] + STD_B64[n & 63];
18
+ }
19
+ const rem = bytes.length - i;
20
+ if (rem === 1) {
21
+ const n = bytes[i] << 4;
22
+ out += `${STD_B64[n >>> 6 & 63]}${STD_B64[n & 63]}==`;
23
+ } else if (rem === 2) {
24
+ const n = bytes[i] << 10 | bytes[i + 1] << 2;
25
+ out += `${STD_B64[n >>> 12 & 63]}${STD_B64[n >>> 6 & 63]}${STD_B64[n & 63]}=`;
26
+ }
27
+ return out;
28
+ }
29
+ function decodeStdBase64(b64) {
30
+ const clean = b64.replace(/[\r\n\s]/g, "");
31
+ if (clean.length === 0) return new Uint8Array(0);
32
+ const pad = clean.endsWith("==") ? 2 : clean.endsWith("=") ? 1 : 0;
33
+ const len = clean.length;
34
+ const out = new Uint8Array(Math.max(0, Math.floor(len * 3 / 4) - pad));
35
+ let outIdx = 0;
36
+ for (let i = 0; i < len; i += 4) {
37
+ const c0 = STD_B64.indexOf(clean[i] ?? "A");
38
+ const c1 = STD_B64.indexOf(clean[i + 1] ?? "A");
39
+ const c2 = clean[i + 2] === "=" || clean[i + 2] === void 0 ? 0 : STD_B64.indexOf(clean[i + 2]);
40
+ const c3 = clean[i + 3] === "=" || clean[i + 3] === void 0 ? 0 : STD_B64.indexOf(clean[i + 3]);
41
+ if (c0 < 0 || c1 < 0 || c2 < 0 || c3 < 0) throw new _ocap_mpc_hsm_personal.MpcProtocolError("INVALID_PARAMETER", "Malformed base64 wire bytes");
42
+ const n = c0 << 18 | c1 << 12 | c2 << 6 | c3;
43
+ if (outIdx < out.length) out[outIdx++] = n >>> 16 & 255;
44
+ if (outIdx < out.length) out[outIdx++] = n >>> 8 & 255;
45
+ if (outIdx < out.length) out[outIdx++] = n & 255;
46
+ }
47
+ return out;
48
+ }
49
+ function encodePersonalWireIsomorphic(value) {
50
+ if (value === null || value === void 0 || typeof value === "boolean" || typeof value === "number" || typeof value === "string") return value;
51
+ if (typeof value === "bigint") return { __bigint: value.toString(10) };
52
+ if (value instanceof Uint8Array) return { $b: encodeStdBase64(value) };
53
+ if (Array.isArray(value)) return value.map((item) => encodePersonalWireIsomorphic(item));
54
+ if (typeof value === "object") {
55
+ const out = {};
56
+ for (const [k, v] of Object.entries(value)) if (v !== void 0) out[k] = encodePersonalWireIsomorphic(v);
57
+ return out;
58
+ }
59
+ throw new _ocap_mpc_hsm_personal.MpcProtocolError("INVALID_PARAMETER", "Unsupported wire value");
60
+ }
61
+ function decodePersonalWireIsomorphic(raw) {
62
+ if (raw === null || raw === void 0 || typeof raw === "boolean" || typeof raw === "number" || typeof raw === "string") return raw;
63
+ if (Array.isArray(raw)) return raw.map((item) => decodePersonalWireIsomorphic(item));
64
+ if (typeof raw === "object") {
65
+ const obj = raw;
66
+ const keys = Object.keys(obj);
67
+ if (keys.length === 1 && typeof obj.$b === "string") return decodeStdBase64(obj.$b);
68
+ if (keys.length === 1 && typeof obj.__bigint === "string") {
69
+ if (!/^-?[0-9]{1,80}$/.test(obj.__bigint)) throw new _ocap_mpc_hsm_personal.MpcProtocolError("INVALID_PARAMETER", "Malformed __bigint wire value");
70
+ return BigInt(obj.__bigint);
71
+ }
72
+ const out = {};
73
+ for (const k of keys) {
74
+ if (k === "__proto__" || k === "constructor" || k === "prototype") throw new _ocap_mpc_hsm_personal.MpcProtocolError("INVALID_PARAMETER", `Forbidden prototype key "${k}" in wire response`);
75
+ out[k] = decodePersonalWireIsomorphic(obj[k]);
76
+ }
77
+ return out;
78
+ }
79
+ throw new _ocap_mpc_hsm_personal.MpcProtocolError("INVALID_PARAMETER", "Malformed wire response");
80
+ }
81
+ function createHttpPersonalCosignerTransport(options) {
82
+ const baseUrl = options.baseUrl.replace(/\/+$/, "");
83
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
84
+ const timeoutMs = options.timeoutMs ?? 8e3;
85
+ let cachedTransportPub32 = null;
86
+ const callJson = async (method, path, body) => {
87
+ const controller = new AbortController();
88
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
89
+ try {
90
+ const res = await fetchImpl(`${baseUrl}${path}`, {
91
+ method,
92
+ headers: {
93
+ Accept: "application/json",
94
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {}
95
+ },
96
+ ...body !== void 0 ? { body: JSON.stringify(encodePersonalWireIsomorphic(body)) } : {},
97
+ signal: controller.signal
98
+ });
99
+ const text = await res.text();
100
+ let parsed = {};
101
+ try {
102
+ parsed = JSON.parse(text);
103
+ } catch {
104
+ throw new _ocap_mpc_hsm_personal.MpcProtocolError("INVALID_PARAMETER", `Non-JSON response from personal HSM (${res.status})`);
105
+ }
106
+ if (!res.ok) {
107
+ const errObj = parsed.error && typeof parsed.error === "object" ? parsed.error : void 0;
108
+ throw new _ocap_mpc_hsm_personal.MpcProtocolError(typeof parsed.code === "string" ? parsed.code : typeof errObj?.code === "string" ? errObj.code : "PERSONAL_POLICY_VIOLATION", typeof errObj?.message === "string" ? errObj.message : typeof parsed.error === "string" ? parsed.error : String(parsed.message ?? `HSM HTTP ${res.status}`));
109
+ }
110
+ return parsed;
111
+ } finally {
112
+ clearTimeout(timer);
113
+ }
114
+ };
115
+ const getHsmTransportPub32 = async () => {
116
+ if (cachedTransportPub32) return cachedTransportPub32;
117
+ const info = await callJson("GET", "/v1/personal/transport-key");
118
+ cachedTransportPub32 = (0, _ocap_mpc_hsm_personal.normalizeHexBytes)(String(info.transportPublicKeyHex), 32);
119
+ return cachedTransportPub32;
120
+ };
121
+ const requestBoundChallenge32 = async (blobBytes4096) => {
122
+ const parsedHdr = (0, _ocap_mpc_hsm_personal.parseHsmSealedBlobHeader)(blobBytes4096);
123
+ const ch = await callJson("POST", "/v1/personal/challenge", {
124
+ header319: parsedHdr.header319,
125
+ headerMac32: parsedHdr.headerMac32,
126
+ ...options.aad ? { aad: options.aad } : {}
127
+ });
128
+ return (0, _ocap_mpc_hsm_personal.normalizeHexBytes)(String(ch.challengeNonceHex), 32);
129
+ };
130
+ return {
131
+ async initPresign(req) {
132
+ const blobBytes4096 = (0, _ocap_mpc_hsm_personal.normalizeHexBytes)(await options.getSealedBlob(), 4096);
133
+ const parsedHdr = (0, _ocap_mpc_hsm_personal.parseHsmSealedBlobHeader)(blobBytes4096);
134
+ const challengeNonce32 = await requestBoundChallenge32(blobBytes4096);
135
+ const action = {
136
+ action: "presign-init",
137
+ vaultId: parsedHdr.header.vaultId,
138
+ slotId: parsedHdr.header.slotId,
139
+ challengeNonce32,
140
+ headerMac32: parsedHdr.headerMac32,
141
+ sessionNonce32: req.sessionNonce32
142
+ };
143
+ const digest32 = (0, _ocap_mpc_hsm_personal.computePersonalActorChallengeDigest32)(action);
144
+ const actorSignature = await options.signActorChallenge({
145
+ challengeDigest32: digest32,
146
+ action
147
+ });
148
+ const hsmTransportPub32 = await getHsmTransportPub32();
149
+ const secretCopy = new Uint8Array(await options.getUnsealSecretBytes32());
150
+ let boxBytes;
151
+ try {
152
+ boxBytes = await (0, _ocap_mpc_hsm_personal.sealHsmInboundTransportBox)({
153
+ hsmTransportPub32,
154
+ plaintext: secretCopy,
155
+ vaultId: parsedHdr.header.vaultId,
156
+ slotId: parsedHdr.header.slotId,
157
+ challengeNonce32,
158
+ headerMac32: parsedHdr.headerMac32
159
+ });
160
+ } finally {
161
+ (0, _ocap_mpc_hsm_personal.zeroizeBytes)(secretCopy);
162
+ }
163
+ const rawResp = await callJson("POST", "/v1/personal/presign/init", {
164
+ sealedBlob: `0x${(0, _ocap_mpc_hsm_personal.bytesToHex)(blobBytes4096)}`,
165
+ initRequest: req,
166
+ challengeNonce32: `0x${(0, _ocap_mpc_hsm_personal.bytesToHex)(challengeNonce32)}`,
167
+ actorSignature,
168
+ hsmInboundTransportBox: `0x${(0, _ocap_mpc_hsm_personal.bytesToHex)(boxBytes)}`,
169
+ ...options.sessionLeaseId ? { sessionLeaseId: options.sessionLeaseId } : {},
170
+ ...options.aad ? { aad: options.aad } : {}
171
+ });
172
+ return decodePersonalWireIsomorphic(rawResp.response ?? rawResp);
173
+ },
174
+ async stepPresign(req) {
175
+ const rawResp = await callJson("POST", "/v1/personal/presign/step", { stepRequest: req });
176
+ return decodePersonalWireIsomorphic(rawResp.response ?? rawResp);
177
+ },
178
+ async signOnline(req) {
179
+ const blobBytes4096 = (0, _ocap_mpc_hsm_personal.normalizeHexBytes)(await options.getSealedBlob(), 4096);
180
+ const parsedHdr = (0, _ocap_mpc_hsm_personal.parseHsmSealedBlobHeader)(blobBytes4096);
181
+ const challengeNonce32 = await requestBoundChallenge32(blobBytes4096);
182
+ const action = {
183
+ action: "sign",
184
+ vaultId: parsedHdr.header.vaultId,
185
+ slotId: parsedHdr.header.slotId,
186
+ challengeNonce32,
187
+ headerMac32: parsedHdr.headerMac32,
188
+ presigId32: (0, _ocap_mpc_hsm_personal.normalizeHexBytes)(req.presigIdHex, 32),
189
+ clearSigningPreviewHash32: req.clearSigningPreviewHash32,
190
+ signingDigest32: req.signingDigest32
191
+ };
192
+ const digest32 = (0, _ocap_mpc_hsm_personal.computePersonalActorChallengeDigest32)(action);
193
+ const actorSignature = await options.signActorChallenge({
194
+ challengeDigest32: digest32,
195
+ action
196
+ });
197
+ const signExtras = options.getSignExtras?.();
198
+ const effectivePostConditions = req.postConditions ?? signExtras?.postConditions;
199
+ const effectiveSimulatedDelta = req.simulatedDelta ?? signExtras?.simulatedDelta;
200
+ return decodePersonalWireIsomorphic(await callJson("POST", "/v1/personal/sign/online", {
201
+ sealedBlob: `0x${(0, _ocap_mpc_hsm_personal.bytesToHex)(blobBytes4096)}`,
202
+ signRequest: req,
203
+ challengeNonce32: `0x${(0, _ocap_mpc_hsm_personal.bytesToHex)(challengeNonce32)}`,
204
+ actorSignature,
205
+ ...effectivePostConditions ? { postConditions: effectivePostConditions } : {},
206
+ ...effectiveSimulatedDelta ? { simulatedDelta: effectiveSimulatedDelta } : {},
207
+ ...options.aad ? { aad: options.aad } : {}
208
+ }));
209
+ },
210
+ ...options.broadcastRawTransaction ? { broadcastRawTransaction: options.broadcastRawTransaction } : {}
211
+ };
212
+ }
213
+
214
+ //#endregion
215
+ exports.createHttpPersonalCosignerTransport = createHttpPersonalCosignerTransport;
216
+ exports.decodePersonalWireIsomorphic = decodePersonalWireIsomorphic;
217
+ exports.encodePersonalWireIsomorphic = encodePersonalWireIsomorphic;
@@ -0,0 +1,28 @@
1
+ import { PersonalActorChallengeAction, PersonalActorSignature, PersonalBlobAadInput, PersonalCosignerTransport, PersonalPostConditions, SimulatedBalanceDelta } from "@ocap/mpc-hsm/personal";
2
+
3
+ //#region src/http-cosigner-transport.d.ts
4
+
5
+ declare function encodePersonalWireIsomorphic(value: unknown): unknown;
6
+ declare function decodePersonalWireIsomorphic<T>(raw: unknown): T;
7
+ interface HttpPersonalCosignerTransportOptions {
8
+ readonly baseUrl: string;
9
+ readonly getSealedBlob: () => Promise<Uint8Array | string> | Uint8Array | string;
10
+ /** Returns the 32B `kUnsealSecret32` (or masked secret when `sessionLeaseId` is active) */
11
+ readonly getUnsealSecretBytes32: () => Promise<Uint8Array> | Uint8Array;
12
+ readonly signActorChallenge: (params: {
13
+ readonly challengeDigest32: Uint8Array;
14
+ readonly action: PersonalActorChallengeAction;
15
+ }) => Promise<PersonalActorSignature> | PersonalActorSignature;
16
+ readonly sessionLeaseId?: string;
17
+ readonly aad?: PersonalBlobAadInput;
18
+ readonly getSignExtras?: () => {
19
+ readonly postConditions?: PersonalPostConditions;
20
+ readonly simulatedDelta?: SimulatedBalanceDelta;
21
+ };
22
+ readonly broadcastRawTransaction?: (rawSignedTxHex: string) => Promise<string>;
23
+ readonly fetchImpl?: typeof fetch;
24
+ readonly timeoutMs?: number;
25
+ }
26
+ declare function createHttpPersonalCosignerTransport(options: HttpPersonalCosignerTransportOptions): PersonalCosignerTransport;
27
+ //#endregion
28
+ export { HttpPersonalCosignerTransportOptions, createHttpPersonalCosignerTransport, decodePersonalWireIsomorphic, encodePersonalWireIsomorphic };
package/lib/index.cjs ADDED
@@ -0,0 +1,13 @@
1
+ const require_broadcaster = require('./broadcaster.cjs');
2
+ const require_http_cosigner_transport = require('./http-cosigner-transport.cjs');
3
+ const require_personal_hsm_wallet = require('./personal-hsm-wallet.cjs');
4
+ const require_logical_hsm_wallet = require('./logical-hsm-wallet.cjs');
5
+
6
+ exports.WalletRelayError = require_broadcaster.WalletRelayError;
7
+ exports.createChainGatewayBroadcaster = require_broadcaster.createChainGatewayBroadcaster;
8
+ exports.createDirectRpcBroadcaster = require_broadcaster.createDirectRpcBroadcaster;
9
+ exports.createHttpPersonalCosignerTransport = require_http_cosigner_transport.createHttpPersonalCosignerTransport;
10
+ exports.createLogicalHsmWallet = require_logical_hsm_wallet.createLogicalHsmWallet;
11
+ exports.createPersonalHsmWallet = require_personal_hsm_wallet.createPersonalHsmWallet;
12
+ exports.decodePersonalWireIsomorphic = require_http_cosigner_transport.decodePersonalWireIsomorphic;
13
+ exports.encodePersonalWireIsomorphic = require_http_cosigner_transport.encodePersonalWireIsomorphic;
@@ -0,0 +1,5 @@
1
+ import { GatewayBroadcastEip1559Input, GatewayBroadcastOcapInput, GatewayPrepareAuthProof, GatewayPrepareEip1559Input, GatewayPrepareEip1559Result, TxBroadcaster, WalletRelayError, createChainGatewayBroadcaster, createDirectRpcBroadcaster } from "./broadcaster.cjs";
2
+ import { HttpPersonalCosignerTransportOptions, createHttpPersonalCosignerTransport, decodePersonalWireIsomorphic, encodePersonalWireIsomorphic } from "./http-cosigner-transport.cjs";
3
+ import { PersonalHsmSendEip1559Options, PersonalHsmSignOptions, PersonalHsmWallet, PersonalSignedOcapResult, createPersonalHsmWallet } from "./personal-hsm-wallet.cjs";
4
+ import { CreateLogicalHsmWalletOptions, LogicalHsmSigningRequest, createLogicalHsmWallet } from "./logical-hsm-wallet.cjs";
5
+ export { CreateLogicalHsmWalletOptions, GatewayBroadcastEip1559Input, GatewayBroadcastOcapInput, GatewayPrepareAuthProof, GatewayPrepareEip1559Input, GatewayPrepareEip1559Result, HttpPersonalCosignerTransportOptions, LogicalHsmSigningRequest, PersonalHsmSendEip1559Options, PersonalHsmSignOptions, PersonalHsmWallet, PersonalSignedOcapResult, TxBroadcaster, WalletRelayError, createChainGatewayBroadcaster, createDirectRpcBroadcaster, createHttpPersonalCosignerTransport, createLogicalHsmWallet, createPersonalHsmWallet, decodePersonalWireIsomorphic, encodePersonalWireIsomorphic };
@@ -0,0 +1,35 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_mpc_hsm_personal = require("@ocap/mpc-hsm/personal");
3
+ let _ocap_util = require("@ocap/util");
4
+ let _ocap_wallet = require("@ocap/wallet");
5
+
6
+ //#region src/logical-hsm-wallet.ts
7
+ function createLogicalHsmWallet(options) {
8
+ if (!options || typeof options.signWithBox !== "function") throw new _ocap_mpc_hsm_personal.MpcProtocolError("INVALID_PARAMETER", "createLogicalHsmWallet requires a signWithBox callback");
9
+ return (0, _ocap_wallet.fromExternalSigner)({
10
+ publicKey: (0, _ocap_util.toHex)((0, _ocap_util.toUint8Array)(options.publicKey)),
11
+ address: options.address,
12
+ method: options.method,
13
+ async sign(_signingInput, context) {
14
+ if (!options.allowRawDigestSigning) {
15
+ if (context.kind === "raw") {
16
+ if (!context.hashBeforeSign || context.rawPayloadBytes.byteLength === 32) throw new _ocap_mpc_hsm_personal.MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Logical-HSM keyless wallet forbids raw 32-byte or unhashed blind digest signing");
17
+ }
18
+ if (context.kind === "jwt" && !context.hashBeforeSign) throw new _ocap_mpc_hsm_personal.MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Logical-HSM keyless wallet requires v1.1.0 prehashed JWT signing");
19
+ }
20
+ return options.signWithBox({
21
+ keyAlias: options.keyAlias,
22
+ kind: context.kind,
23
+ rawPayloadBytes: context.rawPayloadBytes,
24
+ signingDigestHex: context.digestHex,
25
+ hashBeforeSign: context.hashBeforeSign,
26
+ publicKeyHex: context.publicKey,
27
+ address: context.address,
28
+ extra: context.extra
29
+ });
30
+ }
31
+ }, options.didType ?? "default");
32
+ }
33
+
34
+ //#endregion
35
+ exports.createLogicalHsmWallet = createLogicalHsmWallet;