-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathinjectWalletGuard.tsx
461 lines (407 loc) · 15.9 KB
/
injectWalletGuard.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import { ethErrors } from 'eth-rpc-errors';
import logger from '../lib/logger';
import { RequestManager, Response } from '../lib/simulation/requests';
declare global {
interface Window {
ethereum?: any;
}
}
// this function standardizes all values sent to the API into strings to prevent type errors
export function convertObjectValuesToString(inputObj: any): any {
const keys = Object.keys(inputObj);
const output: any = {};
for (let x of keys) {
if (Array.isArray(inputObj[x])) {
const array: any[] = [];
for (let y in inputObj[x]) {
array.push(convertObjectValuesToString(inputObj[x][y]));
}
output[x] = array;
} else if (inputObj[x] === null) {
output[x] = null;
} else if (typeof inputObj[x] === 'object') {
output[x] = convertObjectValuesToString(inputObj[x]);
} else if (typeof inputObj[x] === 'number' || typeof inputObj[x] === 'bigint') {
output[x] = String(inputObj[x]);
} else {
output[x] = inputObj[x];
}
}
return output;
}
const log = logger.child({ component: 'Injected' });
// Handling all the request communication.
const REQUEST_MANAGER = new RequestManager();
let timer: NodeJS.Timer | undefined = undefined;
// Injector taken heavily taken from Pocket Universe and Revoke Cash
// Shoutout to both for innovating on this <3
// https://github.com/RevokeCash/browser-extension
// https://github.com/jqphu/PocketUniverse
const addWalletGuardProxy = (provider: any) => {
const sendHandler = {
apply: (target: any, thisArg: any, args: any[]) => {
const [payloadOrMethod, callbackOrParams] = args;
// ethereum.send has three overloads:
// ethereum.send(method: string, params?: Array<unknown>): Promise<JsonRpcResponse>;
// > gets handled like ethereum.request
if (typeof payloadOrMethod === 'string') {
return provider.request({
method: payloadOrMethod,
params: callbackOrParams,
});
}
// ethereum.send(payload: JsonRpcRequest): unknown;
// > cannot contain signature requests
if (!callbackOrParams) {
return Reflect.apply(target, thisArg, args);
}
// ethereum.send(payload: JsonRpcRequest, callback: JsonRpcCallback): void;
// > gets handled like ethereum.sendAsync
return provider.sendAsync(payloadOrMethod, callbackOrParams);
},
};
const requestHandler = {
apply: async (target: any, thisArg: any, args: any[]) => {
const [request] = args;
if (!request) {
return Reflect.apply(target, thisArg, args);
}
if (
request.method !== 'eth_signTypedData_v3' &&
request.method !== 'eth_signTypedData_v4' &&
request.method !== 'eth_sendTransaction' &&
request.method !== 'eth_sign' &&
request.method !== 'personal_sign'
) {
return Reflect.apply(target, thisArg, args);
}
log.info({ args }, 'Request type');
let response;
if (request.method === 'eth_sendTransaction') {
if (request.params.length !== 1) {
// Forward the request anyway.
log.warn('Unexpected argument length.');
return Reflect.apply(target, thisArg, args);
}
log.info(request, 'Request being sent');
// Sending response.
response = await REQUEST_MANAGER.request({
chainId: await provider.request({ method: 'eth_chainId' }),
signer: request.params[0].from,
transaction: request.params[0], // this is type safe
method: request.method,
});
if (response === Response.Reject) {
log.info('Reject');
// Based on EIP-1103
// eslint-disable-next-line no-throw-literal
throw ethErrors.provider.userRejectedRequest('Wallet Guard Tx Signature: User denied transaction signature.');
}
} else if (request.method === 'eth_signTypedData_v3' || request.method === 'eth_signTypedData_v4') {
if (request.params.length < 2) {
// Forward the request anyway.
log.warn('Unexpected argument length.');
return Reflect.apply(target, thisArg, args);
}
const params = JSON.parse(request.params[1]);
log.info({ params }, 'Request being sent');
let signer: string = params[0];
if (!signer) {
signer = request.params[0];
}
const domain = convertObjectValuesToString(params.domain);
const message = convertObjectValuesToString(params.message);
// Sending response.
response = await REQUEST_MANAGER.request({
chainId: await provider.request({ method: 'eth_chainId' }),
signer: signer,
domain: domain,
message: message,
primaryType: params['primaryType'],
method: request.method,
});
if (response === Response.Reject) {
log.info('Reject');
// NOTE: Be cautious when changing this name. 1inch behaves strangely when the error message diverges.
throw ethErrors.provider.userRejectedRequest(
'Wallet Guard Message Signature: User denied message signature.'
);
}
} else if (request.method === 'eth_sign') {
log.info('EthSign Request');
if (request.params.length < 2) {
// Forward the request anyway.
log.warn('Unexpected argument length.');
return Reflect.apply(target, thisArg, args);
}
// Sending response.
response = await REQUEST_MANAGER.request({
chainId: await provider.request({ method: 'eth_chainId' }),
signer: request.params[0],
hash: request.params[1],
method: request.method,
});
if (response === Response.Reject) {
log.info('Reject');
// NOTE: Be cautious when changing this name. 1inch behaves strangely when the error message diverges.
throw ethErrors.provider.userRejectedRequest(
'Wallet Guard Message Signature: User denied message signature.'
);
}
} else if (request.method === 'personal_sign') {
if (request.params.length < 2) {
// Forward the request anyway.
log.warn('Unexpected argument length.');
return Reflect.apply(target, thisArg, args);
}
const signer: string = request.params[1];
const signMessage: string = request.params[0];
// Sending response.
response = await REQUEST_MANAGER.request({
chainId: await provider.request({ method: 'eth_chainId' }),
signer,
signMessage,
method: request.method,
});
if (response === Response.Reject) {
log.info('Reject');
// NOTE: Be cautious when changing this name. 1inch behaves strangely when the error message diverges.
throw ethErrors.provider.userRejectedRequest(
'Wallet Guard Message Signature: User denied message signature.'
);
}
} else {
throw new Error('Show never reach here');
}
// For error, we just continue, to make sure we don't block the user!
// we should also implement auto continue on errors (server response isn't mapped properly)
if (response === Response.Continue || response === Response.Error) {
return Reflect.apply(target, thisArg, args);
}
},
};
const sendAsyncHandler = {
apply: async (target: any, thisArg: any, args: any[]) => {
const [request, callback] = args;
if (!request) {
return Reflect.apply(target, thisArg, args);
}
if (
request.method !== 'eth_signTypedData_v3' &&
request.method !== 'eth_signTypedData_v4' &&
request.method !== 'eth_sendTransaction' &&
request.method !== 'eth_sign' &&
request.method !== 'personal_sign'
) {
return Reflect.apply(target, thisArg, args);
}
if (request.method === 'eth_sendTransaction') {
if (request.params.length !== 1) {
// Forward the request anyway.
log.warn('Unexpected argument length.');
return Reflect.apply(target, thisArg, args);
}
log.info(request, 'Request being sent');
provider
.request({ method: 'eth_chainId' })
.then((chainId: any) => {
return REQUEST_MANAGER.request({
chainId,
signer: request.params[0].from,
transaction: request.params[0], // this is type safe
method: request.method,
});
})
.then((response: any) => {
if (response === Response.Reject) {
log.info('Reject');
// Based on EIP-1103
// eslint-disable-next-line no-throw-literal
const error = ethErrors.provider.userRejectedRequest(
'Wallet Guard Tx Signature: User denied transaction signature.'
);
const response = {
id: request?.id,
jsonrpc: '2.0',
error,
};
callback(error, response);
// For error, we just continue, to make sure we don't block the user!
} else if (response === Response.Continue || response === Response.Error) {
log.info(response, 'Continue | Error');
return Reflect.apply(target, thisArg, args);
}
});
} else if (request.method === 'eth_signTypedData_v3' || request.method === 'eth_signTypedData_v4') {
if (request.params.length < 2) {
// Forward the request anyway.
log.warn('Unexpected argument length.');
return Reflect.apply(target, thisArg, args);
}
const params = JSON.parse(request.params[1]);
log.info({ params }, 'Request being sent');
let signer: string = params[0];
if (!signer) {
signer = request.params[0];
}
const domain = convertObjectValuesToString(params.domain);
const message = convertObjectValuesToString(params.message);
provider
.request({ method: 'eth_chainId' })
.then((chainId: any) => {
return REQUEST_MANAGER.request({
chainId,
signer: signer,
domain: domain,
message: message,
primaryType: params['primaryType'],
method: request.method,
});
})
.then((response: any) => {
if (response === Response.Reject) {
log.info('Reject');
// Based on EIP-1103
// eslint-disable-next-line no-throw-literal
const error = ethErrors.provider.userRejectedRequest(
'Wallet Guard Message Signature: User denied message signature.'
);
const response = {
id: request?.id,
jsonrpc: '2.0',
error,
};
callback(error, response);
// For error, we just continue, to make sure we don't block the user!
} else if (response === Response.Continue || response === Response.Error) {
return Reflect.apply(target, thisArg, args);
}
});
} else if (request.method === 'eth_sign') {
log.info('EthSign Request');
if (request.params.length < 2) {
// Forward the request anyway.
log.warn('Unexpected argument length.');
return Reflect.apply(target, thisArg, args);
}
const signer: string = request.params[0];
const hash: string = request.params[1];
provider
.request({ method: 'eth_chainId' })
.then((chainId: any) => {
return REQUEST_MANAGER.request({
chainId,
signer,
hash,
method: request.method,
});
})
.then((response: any) => {
if (response === Response.Reject) {
log.info('Reject');
// Based on EIP-1103
// eslint-disable-next-line no-throw-literal
const error = ethErrors.provider.userRejectedRequest(
'Wallet Guard Message Signature: User denied message signature.'
);
const response = {
id: request?.id,
jsonrpc: '2.0',
error,
};
callback(error, response);
// For error, we just continue, to make sure we don't block the user!
} else if (response === Response.Continue || response === Response.Error) {
log.info(response, 'Continue | Error');
return Reflect.apply(target, thisArg, args);
}
});
} else if (request.method === 'personal_sign') {
log.info('Presonal Sign Request');
if (request.params.length === 0) {
// Forward the request anyway.
log.warn('Unexpected argument length.');
return Reflect.apply(target, thisArg, args);
}
const signer: string = request.params[1];
const signMessage: string = request.params[0];
provider
.request({ method: 'eth_chainId' })
.then((chainId: any) => {
return REQUEST_MANAGER.request({
chainId,
signer,
signMessage,
method: request.method,
});
})
.then((response: any) => {
if (response === Response.Reject) {
log.info('Reject');
// Based on EIP-1103
// eslint-disable-next-line no-throw-literal
const error = ethErrors.provider.userRejectedRequest(
'Wallet Guard Message Signature: User denied message signature.'
);
const response = {
id: request?.id,
jsonrpc: '2.0',
error,
};
callback(error, response);
// For error, we just continue, to make sure we don't block the user!
} else if (response === Response.Continue || response === Response.Error) {
return Reflect.apply(target, thisArg, args);
}
});
}
},
};
// if provider and wallet guard is not in provider
if (provider && !provider?.isWalletGuard) {
try {
Object.defineProperty(provider, 'request', {
value: new Proxy(provider.request, requestHandler),
});
Object.defineProperty(provider, 'send', {
value: new Proxy(provider.send, sendHandler),
});
Object.defineProperty(provider, 'sendAsync', {
value: new Proxy(provider.sendAsync, sendAsyncHandler),
});
provider.isWalletGuard = true;
console.log('Wallet Guard is running!');
} catch (error) {
// If we can't add ourselves to this provider, don't mess with other providers.
log.warn({ provider, error }, 'Could not attach to provider');
console.log('Wallet Guard could not start!');
}
}
};
// if window.ethereum is there and proxy is not already initizlised
// inject proxy too window.ethereum
// if there are new providers add proxy to all providers
const addProxy = () => {
// Protect against double initialization.
if (window.ethereum && !window.ethereum?.isWalletGuard) {
addWalletGuardProxy(window.ethereum);
if (window.ethereum.providers?.length) {
window.ethereum.providers.forEach(addWalletGuardProxy);
}
}
};
// If we detect window.ethereum
// Add proxy ( proxy server is a server application that acts as an intermediary between a client requesting a
// resource and the server providing that resource.)
// if we do not detect window.ethereum
// add an event listener to window to add proxy when ethereum is initalized
if (window.ethereum) {
addProxy();
} else {
window.addEventListener('ethereum#initialized', addProxy);
}
timer = setInterval(addProxy, 100);
setTimeout(() => {
window.removeEventListener('ethereum#initialized', addProxy);
clearTimeout(timer);
}, 5000);