@crewhaus/wallet-engine 0.1.1 → 0.1.3
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.
- package/package.json +8 -13
- package/src/index.test.ts +128 -0
- package/src/index.ts +114 -11
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crewhaus/wallet-engine",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Wallet custody + sign-request flow. Routes every transaction through simulation, transaction-policy enforcement, approval gate, then broadcast. §47 slice 1.",
|
|
6
6
|
"main": "src/index.ts",
|
|
@@ -12,15 +12,15 @@
|
|
|
12
12
|
"test": "bun test src"
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"@crewhaus/boundary-classifier": "0.1.
|
|
16
|
-
"@crewhaus/chain-adapter-base": "0.1.
|
|
17
|
-
"@crewhaus/errors": "0.1.
|
|
15
|
+
"@crewhaus/boundary-classifier": "0.1.3",
|
|
16
|
+
"@crewhaus/chain-adapter-base": "0.1.3",
|
|
17
|
+
"@crewhaus/errors": "0.1.3"
|
|
18
18
|
},
|
|
19
19
|
"license": "Apache-2.0",
|
|
20
20
|
"author": {
|
|
21
21
|
"name": "Max Meier",
|
|
22
|
-
"email": "max@
|
|
23
|
-
"url": "https://
|
|
22
|
+
"email": "max@crewhaus.ai",
|
|
23
|
+
"url": "https://crewhaus.ai"
|
|
24
24
|
},
|
|
25
25
|
"repository": {
|
|
26
26
|
"type": "git",
|
|
@@ -32,12 +32,7 @@
|
|
|
32
32
|
"url": "https://github.com/crewhaus/factory/issues"
|
|
33
33
|
},
|
|
34
34
|
"publishConfig": {
|
|
35
|
-
"access": "
|
|
35
|
+
"access": "public"
|
|
36
36
|
},
|
|
37
|
-
"files": [
|
|
38
|
-
"src",
|
|
39
|
-
"README.md",
|
|
40
|
-
"LICENSE",
|
|
41
|
-
"NOTICE"
|
|
42
|
-
]
|
|
37
|
+
"files": ["src", "README.md", "LICENSE", "NOTICE"]
|
|
43
38
|
}
|
package/src/index.test.ts
CHANGED
|
@@ -85,6 +85,58 @@ describe("createWalletEngine — happy path", () => {
|
|
|
85
85
|
});
|
|
86
86
|
});
|
|
87
87
|
|
|
88
|
+
// SECURITY: simulationRequired must model the REAL signer, not address(0),
|
|
89
|
+
// or onlyOwner / msg.sender-dependent calls give false assurance (#415).
|
|
90
|
+
describe("createWalletEngine — simulation from-address", () => {
|
|
91
|
+
test("passes the wallet address as eth_call `from` when custody exposes getAddress", async () => {
|
|
92
|
+
let seenFrom: unknown = "UNSET";
|
|
93
|
+
const we = createWalletEngine({
|
|
94
|
+
resolveAdapter: () =>
|
|
95
|
+
fakeAdapter((method, params) => {
|
|
96
|
+
if (method === "eth_call") {
|
|
97
|
+
seenFrom = (params[0] as Record<string, unknown>)["from"];
|
|
98
|
+
return "0x";
|
|
99
|
+
}
|
|
100
|
+
if (method === "eth_estimateGas") return "0x5208";
|
|
101
|
+
if (method === "eth_getTransactionReceipt") return { blockNumber: "0x1", status: "0x1" };
|
|
102
|
+
return null;
|
|
103
|
+
}),
|
|
104
|
+
approve: async () => "allow",
|
|
105
|
+
});
|
|
106
|
+
we.registerCustody({
|
|
107
|
+
custody: "local",
|
|
108
|
+
async signAndBroadcast() {
|
|
109
|
+
return "0xhash";
|
|
110
|
+
},
|
|
111
|
+
async getAddress() {
|
|
112
|
+
return "0xWALLETADDR";
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
await we.requestSignAndBroadcast({ tx: TX_OK, policy: POLICY, wallet: WALLET });
|
|
116
|
+
expect(seenFrom).toBe("0xWALLETADDR");
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("omits `from` (back-compat) when custody does not expose getAddress", async () => {
|
|
120
|
+
let sawFromKey = true;
|
|
121
|
+
const we = createWalletEngine({
|
|
122
|
+
resolveAdapter: () =>
|
|
123
|
+
fakeAdapter((method, params) => {
|
|
124
|
+
if (method === "eth_call") {
|
|
125
|
+
sawFromKey = "from" in (params[0] as Record<string, unknown>);
|
|
126
|
+
return "0x";
|
|
127
|
+
}
|
|
128
|
+
if (method === "eth_estimateGas") return "0x5208";
|
|
129
|
+
if (method === "eth_getTransactionReceipt") return { blockNumber: "0x1", status: "0x1" };
|
|
130
|
+
return null;
|
|
131
|
+
}),
|
|
132
|
+
approve: async () => "allow",
|
|
133
|
+
});
|
|
134
|
+
we.registerCustody(createLocalSignerStub()); // no getAddress
|
|
135
|
+
await we.requestSignAndBroadcast({ tx: TX_OK, policy: POLICY, wallet: WALLET });
|
|
136
|
+
expect(sawFromKey).toBe(false);
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
88
140
|
describe("createWalletEngine — policy enforcement", () => {
|
|
89
141
|
test("rejects when contractId is missing and allowedContracts is non-empty", async () => {
|
|
90
142
|
const we = createWalletEngine({
|
|
@@ -110,6 +162,82 @@ describe("createWalletEngine — policy enforcement", () => {
|
|
|
110
162
|
).rejects.toThrow(/uniswap-router/);
|
|
111
163
|
});
|
|
112
164
|
|
|
165
|
+
// SECURITY: empty allowedContracts is now FAIL-CLOSED (was allow-all). The
|
|
166
|
+
// default onchain policy must not let a prompt-injected model send arbitrary
|
|
167
|
+
// calldata/value to any address.
|
|
168
|
+
test("fails closed when allowedContracts is empty (default policy)", async () => {
|
|
169
|
+
const we = createWalletEngine({
|
|
170
|
+
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
171
|
+
approve: async () => "allow",
|
|
172
|
+
});
|
|
173
|
+
we.registerCustody(createLocalSignerStub());
|
|
174
|
+
const emptyPolicy: TransactionPolicy = { ...POLICY, allowedContracts: [] };
|
|
175
|
+
await expect(
|
|
176
|
+
we.requestSignAndBroadcast({ tx: TX_OK, policy: emptyPolicy, wallet: WALLET }),
|
|
177
|
+
).rejects.toThrow(/allowedContracts is empty/);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
test("rejects when tx.to does not match the bound contract address (#151)", async () => {
|
|
181
|
+
const we = createWalletEngine({
|
|
182
|
+
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
183
|
+
approve: async () => "allow",
|
|
184
|
+
});
|
|
185
|
+
we.registerCustody(createLocalSignerStub());
|
|
186
|
+
const policy: TransactionPolicy = { ...POLICY, contractAddresses: { usdc: "0xusdc" } };
|
|
187
|
+
const tx: UnsignedTx = { ...TX_OK, to: "0xattacker" };
|
|
188
|
+
await expect(we.requestSignAndBroadcast({ tx, policy, wallet: WALLET })).rejects.toThrow(
|
|
189
|
+
/does not match the address/,
|
|
190
|
+
);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
test("rejects when tx value exceeds maxValueWei (#152)", async () => {
|
|
194
|
+
const we = createWalletEngine({
|
|
195
|
+
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
196
|
+
approve: async () => "allow",
|
|
197
|
+
});
|
|
198
|
+
we.registerCustody(createLocalSignerStub());
|
|
199
|
+
const policy: TransactionPolicy = { ...POLICY, maxValueWei: "0x10" };
|
|
200
|
+
const tx: UnsignedTx = { ...TX_OK, value: "0x20" };
|
|
201
|
+
await expect(we.requestSignAndBroadcast({ tx, policy, wallet: WALLET })).rejects.toThrow(
|
|
202
|
+
/exceeds transaction_policy\.maxValueWei/,
|
|
203
|
+
);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
test("fails closed when maxValueUsd is set without a price oracle (#152)", async () => {
|
|
207
|
+
const we = createWalletEngine({
|
|
208
|
+
resolveAdapter: () => fakeAdapter(() => "0x"),
|
|
209
|
+
approve: async () => "allow",
|
|
210
|
+
});
|
|
211
|
+
we.registerCustody(createLocalSignerStub());
|
|
212
|
+
const policy: TransactionPolicy = { ...POLICY, maxValueUsd: 100 };
|
|
213
|
+
await expect(we.requestSignAndBroadcast({ tx: TX_OK, policy, wallet: WALLET })).rejects.toThrow(
|
|
214
|
+
/price oracle/,
|
|
215
|
+
);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test("allows a case-insensitive address match with value under maxValueWei (#151, #152)", async () => {
|
|
219
|
+
const we = createWalletEngine({
|
|
220
|
+
resolveAdapter: () =>
|
|
221
|
+
fakeAdapter((method) => {
|
|
222
|
+
if (method === "eth_call") return "0x";
|
|
223
|
+
if (method === "eth_estimateGas") return "0x5208";
|
|
224
|
+
if (method === "eth_getTransactionReceipt")
|
|
225
|
+
return { blockNumber: "0x100", status: "0x1" };
|
|
226
|
+
return null;
|
|
227
|
+
}),
|
|
228
|
+
approve: async () => "allow",
|
|
229
|
+
});
|
|
230
|
+
we.registerCustody(createLocalSignerStub());
|
|
231
|
+
const policy: TransactionPolicy = {
|
|
232
|
+
...POLICY,
|
|
233
|
+
contractAddresses: { usdc: "0xUSDC" }, // checksum/case differs from TX_OK.to "0xusdc"
|
|
234
|
+
maxValueWei: "0x100",
|
|
235
|
+
};
|
|
236
|
+
const tx: UnsignedTx = { ...TX_OK, value: "0x10" };
|
|
237
|
+
const receipt = await we.requestSignAndBroadcast({ tx, policy, wallet: WALLET });
|
|
238
|
+
expect(receipt.status).toBe("0x1");
|
|
239
|
+
});
|
|
240
|
+
|
|
113
241
|
test("rejects approval='none' with non-automated wallet", async () => {
|
|
114
242
|
const we = createWalletEngine({
|
|
115
243
|
resolveAdapter: () => fakeAdapter(() => "0x"),
|
package/src/index.ts
CHANGED
|
@@ -66,7 +66,20 @@ export type WalletConfig = {
|
|
|
66
66
|
export type TransactionPolicy = {
|
|
67
67
|
readonly defaultWriteApproval: "required" | "policy" | "none";
|
|
68
68
|
readonly maxValueUsd?: number;
|
|
69
|
+
/**
|
|
70
|
+
* Native-token value ceiling in wei (decimal or 0x-hex). Oracle-free and
|
|
71
|
+
* enforced pre-broadcast (#152).
|
|
72
|
+
*/
|
|
73
|
+
readonly maxValueWei?: string;
|
|
69
74
|
readonly allowedContracts: readonly string[];
|
|
75
|
+
/**
|
|
76
|
+
* Resolved `contractId` → address map. When present, `tx.to` is bound to the
|
|
77
|
+
* address registered for `tx.contractId`, so a whitelisted id cannot be used
|
|
78
|
+
* to send to an arbitrary address (#151). The runtime should populate this
|
|
79
|
+
* from the spec's `contracts[]`; the stronger long-term fix is to drop `to`
|
|
80
|
+
* from the tool input entirely and resolve it from `contractId` here.
|
|
81
|
+
*/
|
|
82
|
+
readonly contractAddresses?: Readonly<Record<string, string>>;
|
|
70
83
|
readonly simulationRequired: boolean;
|
|
71
84
|
};
|
|
72
85
|
|
|
@@ -92,6 +105,21 @@ export type UnsignedTx = {
|
|
|
92
105
|
readonly gasLimit?: string;
|
|
93
106
|
};
|
|
94
107
|
|
|
108
|
+
/**
|
|
109
|
+
* Parse a wei amount expressed as a decimal or 0x-hex string. Throws a
|
|
110
|
+
* WalletEngineError (fail-closed) on a malformed value.
|
|
111
|
+
*/
|
|
112
|
+
function parseWei(walletId: string, label: string, v: string): bigint {
|
|
113
|
+
try {
|
|
114
|
+
return BigInt(v.trim());
|
|
115
|
+
} catch {
|
|
116
|
+
throw new WalletEngineError(
|
|
117
|
+
walletId,
|
|
118
|
+
`invalid ${label} "${v}" (expected wei as a decimal or 0x-hex string)`,
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
95
123
|
/**
|
|
96
124
|
* Simulation result. Conservatively typed — real adapters surface
|
|
97
125
|
* decoded balance deltas, permission deltas, etc. Slice 1 carries
|
|
@@ -159,6 +187,15 @@ export interface CustodyProvider {
|
|
|
159
187
|
readonly walletConfig: WalletConfig;
|
|
160
188
|
readonly adapter: ChainAdapter;
|
|
161
189
|
}): Promise<string>;
|
|
190
|
+
/**
|
|
191
|
+
* Optional: the wallet's on-chain address, used as `from` in pre-broadcast
|
|
192
|
+
* simulation so msg.sender-dependent / access-controlled calls (onlyOwner,
|
|
193
|
+
* etc.) are modeled as the REAL signer rather than address(0). When a
|
|
194
|
+
* provider can't (or won't) expose the address ahead of signing, simulation
|
|
195
|
+
* falls back to no `from` — accurate for stateless calls, best-effort
|
|
196
|
+
* otherwise.
|
|
197
|
+
*/
|
|
198
|
+
getAddress?(walletConfig: WalletConfig): Promise<string | undefined>;
|
|
162
199
|
}
|
|
163
200
|
|
|
164
201
|
/**
|
|
@@ -197,12 +234,16 @@ export function createWalletEngine(opts: WalletEngineOptions): WalletEngine {
|
|
|
197
234
|
return a;
|
|
198
235
|
}
|
|
199
236
|
|
|
200
|
-
async function simulate(args: { tx: UnsignedTx }): Promise<SimulationResult> {
|
|
237
|
+
async function simulate(args: { tx: UnsignedTx; from?: string }): Promise<SimulationResult> {
|
|
201
238
|
const adapter = requireAdapter(args.tx.chainId, args.tx.walletId);
|
|
202
239
|
const callParams: Record<string, unknown> = {
|
|
203
240
|
to: args.tx.to,
|
|
204
241
|
data: args.tx.data,
|
|
205
242
|
};
|
|
243
|
+
// Run the eth_call AS the signing wallet (not address(0)) so onlyOwner /
|
|
244
|
+
// msg.sender-dependent logic is modeled faithfully — otherwise a
|
|
245
|
+
// simulationRequired pre-flight gives false assurance.
|
|
246
|
+
if (args.from !== undefined) callParams["from"] = args.from;
|
|
206
247
|
if (args.tx.value !== undefined) callParams["value"] = args.tx.value;
|
|
207
248
|
// Prefer eth_call for state-read; fall back to estimateGas for revert detection.
|
|
208
249
|
let returnData: string | undefined;
|
|
@@ -238,24 +279,72 @@ export function createWalletEngine(opts: WalletEngineOptions): WalletEngine {
|
|
|
238
279
|
}
|
|
239
280
|
|
|
240
281
|
function enforceStaticPolicy(tx: UnsignedTx, policy: TransactionPolicy): void {
|
|
241
|
-
//
|
|
242
|
-
//
|
|
243
|
-
//
|
|
244
|
-
//
|
|
245
|
-
|
|
246
|
-
|
|
282
|
+
// Fail CLOSED on an empty `allowedContracts`. Previously empty meant "allow
|
|
283
|
+
// every contract", so an onchain agent on the default policy (allowedContracts
|
|
284
|
+
// defaults to []) let a prompt-injected model send arbitrary calldata/value
|
|
285
|
+
// to ANY address — a wallet-drain primitive. Operators must now declare the
|
|
286
|
+
// callable contract ids in transaction_policy.allowedContracts to permit sends.
|
|
287
|
+
if (policy.allowedContracts.length === 0) {
|
|
288
|
+
throw new WalletEngineError(
|
|
289
|
+
tx.walletId,
|
|
290
|
+
"transaction_policy.allowedContracts is empty — sends are denied (fail-closed). Declare the callable contract ids in transaction_policy.allowedContracts (bound to addresses via contracts[]).",
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
// Non-empty: contractId must be present and whitelisted. Raw-address calls
|
|
294
|
+
// (no contractId) are rejected — the spec author must declare every callable
|
|
295
|
+
// contract symbolically.
|
|
296
|
+
if (tx.contractId === undefined) {
|
|
297
|
+
throw new WalletEngineError(
|
|
298
|
+
tx.walletId,
|
|
299
|
+
`transaction_policy.allowedContracts is non-empty; raw-address calls forbidden (to=${tx.to}). Declare a contracts[] entry and pass its id.`,
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
if (!policy.allowedContracts.includes(tx.contractId)) {
|
|
303
|
+
throw new WalletEngineError(
|
|
304
|
+
tx.walletId,
|
|
305
|
+
`contract id "${tx.contractId}" not in transaction_policy.allowedContracts ${JSON.stringify(policy.allowedContracts)}`,
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// #151 — bind `to` to the claimed contractId. `allowedContracts` alone is a
|
|
310
|
+
// symbolic gate; without this an attacker can claim a whitelisted id and
|
|
311
|
+
// still send to an arbitrary address. When the resolved address map is
|
|
312
|
+
// present, `tx.to` MUST equal the address registered for `tx.contractId`.
|
|
313
|
+
if (tx.contractId !== undefined && policy.contractAddresses !== undefined) {
|
|
314
|
+
const expected = policy.contractAddresses[tx.contractId];
|
|
315
|
+
if (expected === undefined) {
|
|
316
|
+
throw new WalletEngineError(
|
|
317
|
+
tx.walletId,
|
|
318
|
+
`contract id "${tx.contractId}" has no resolved address in transaction_policy.contractAddresses`,
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
if (tx.to.toLowerCase() !== expected.toLowerCase()) {
|
|
247
322
|
throw new WalletEngineError(
|
|
248
323
|
tx.walletId,
|
|
249
|
-
`
|
|
324
|
+
`tx.to "${tx.to}" does not match the address ${expected} bound to contract id "${tx.contractId}"`,
|
|
250
325
|
);
|
|
251
326
|
}
|
|
252
|
-
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// #152 — value caps. maxValueWei is an oracle-free native ceiling enforced
|
|
330
|
+
// here. maxValueUsd cannot be enforced without a price oracle (none is
|
|
331
|
+
// wired in this build), so fail closed rather than give false assurance.
|
|
332
|
+
if (policy.maxValueWei !== undefined) {
|
|
333
|
+
const cap = parseWei(tx.walletId, "transaction_policy.maxValueWei", policy.maxValueWei);
|
|
334
|
+
const val = parseWei(tx.walletId, "tx.value", tx.value ?? "0x0");
|
|
335
|
+
if (val > cap) {
|
|
253
336
|
throw new WalletEngineError(
|
|
254
337
|
tx.walletId,
|
|
255
|
-
`
|
|
338
|
+
`tx value ${val} wei exceeds transaction_policy.maxValueWei (${cap} wei)`,
|
|
256
339
|
);
|
|
257
340
|
}
|
|
258
341
|
}
|
|
342
|
+
if (policy.maxValueUsd !== undefined) {
|
|
343
|
+
throw new WalletEngineError(
|
|
344
|
+
tx.walletId,
|
|
345
|
+
`transaction_policy.maxValueUsd (${policy.maxValueUsd}) cannot be enforced: USD value caps require a price oracle, which is not wired in this build. Use transaction_policy.maxValueWei for a native-token ceiling.`,
|
|
346
|
+
);
|
|
347
|
+
}
|
|
259
348
|
// `none` (defaultWriteApproval) is only valid under `automated` custody —
|
|
260
349
|
// documented invariant. The runtime layers that allow this combo perform
|
|
261
350
|
// a stronger check at boot; this layer just rejects the obvious misuse.
|
|
@@ -294,7 +383,21 @@ export function createWalletEngine(opts: WalletEngineOptions): WalletEngine {
|
|
|
294
383
|
|
|
295
384
|
let sim: SimulationResult | undefined;
|
|
296
385
|
if (args.policy.simulationRequired) {
|
|
297
|
-
|
|
386
|
+
// Resolve the signer address (best-effort) so simulation runs as the
|
|
387
|
+
// real wallet, not address(0).
|
|
388
|
+
let fromAddress: string | undefined;
|
|
389
|
+
const custody = custodies.get(args.wallet.custody);
|
|
390
|
+
if (custody?.getAddress !== undefined) {
|
|
391
|
+
try {
|
|
392
|
+
fromAddress = await custody.getAddress(args.wallet);
|
|
393
|
+
} catch {
|
|
394
|
+
fromAddress = undefined;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
sim = await simulate({
|
|
398
|
+
tx: args.tx,
|
|
399
|
+
...(fromAddress !== undefined ? { from: fromAddress } : {}),
|
|
400
|
+
});
|
|
298
401
|
if (!sim.success) {
|
|
299
402
|
throw new WalletEngineError(
|
|
300
403
|
args.wallet.id,
|