-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
contentscript.js
541 lines (465 loc) · 16.2 KB
/
contentscript.js
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
import { WindowPostMessageStream } from '@metamask/post-message-stream';
import PortStream from 'extension-port-stream';
import ObjectMultiplex from '@metamask/object-multiplex';
import { pipeline, Transform } from 'readable-stream';
import browser from 'webextension-polyfill';
import { EXTENSION_MESSAGES } from '../../shared/constants/app';
import {
checkForLastError,
getIsBrowserPrerenderBroken,
} from '../../shared/modules/browser-runtime.utils';
import shouldInjectProvider from '../../shared/modules/provider-injection';
// contexts
const CONTENT_SCRIPT = 'metamask-contentscript';
const INPAGE = 'metamask-inpage';
const PHISHING_WARNING_PAGE = 'metamask-phishing-warning-page';
// stream channels
const PHISHING_SAFELIST = 'metamask-phishing-safelist';
const PROVIDER = 'metamask-provider';
// For more information about these legacy streams, see here:
// https://github.com/MetaMask/metamask-extension/issues/15491
// TODO:LegacyProvider: Delete
const LEGACY_CONTENT_SCRIPT = 'contentscript';
const LEGACY_INPAGE = 'inpage';
const LEGACY_PROVIDER = 'provider';
const LEGACY_PUBLIC_CONFIG = 'publicConfig';
let legacyExtMux,
legacyExtChannel,
legacyExtPublicConfigChannel,
legacyPageMux,
legacyPageMuxLegacyProviderChannel,
legacyPagePublicConfigChannel,
notificationTransformStream;
const phishingPageUrl = new URL(process.env.PHISHING_WARNING_PAGE_URL);
let phishingExtChannel,
phishingExtMux,
phishingExtPort,
phishingExtStream,
phishingPageChannel,
phishingPageMux;
let extensionMux,
extensionChannel,
extensionPort,
extensionPhishingStream,
extensionStream,
pageMux,
pageChannel;
/**
* PHISHING STREAM LOGIC
*/
function setupPhishingPageStreams() {
// the transport-specific streams for communication between inpage and background
const phishingPageStream = new WindowPostMessageStream({
name: CONTENT_SCRIPT,
target: PHISHING_WARNING_PAGE,
});
// create and connect channel muxers
// so we can handle the channels individually
phishingPageMux = new ObjectMultiplex();
phishingPageMux.setMaxListeners(25);
pipeline(phishingPageMux, phishingPageStream, phishingPageMux, (err) =>
logStreamDisconnectWarning('MetaMask Inpage Multiplex', err),
);
phishingPageChannel = phishingPageMux.createStream(PHISHING_SAFELIST);
}
const setupPhishingExtStreams = () => {
phishingExtPort = browser.runtime.connect({
name: CONTENT_SCRIPT,
});
phishingExtStream = new PortStream(phishingExtPort);
// create and connect channel muxers
// so we can handle the channels individually
phishingExtMux = new ObjectMultiplex();
phishingExtMux.setMaxListeners(25);
pipeline(phishingExtMux, phishingExtStream, phishingExtMux, (err) => {
logStreamDisconnectWarning('MetaMask Background Multiplex', err);
window.postMessage(
{
target: PHISHING_WARNING_PAGE, // the post-message-stream "target"
data: {
// this object gets passed to @metamask/object-multiplex
name: PHISHING_SAFELIST, // the @metamask/object-multiplex channel name
data: {
jsonrpc: '2.0',
method: 'METAMASK_STREAM_FAILURE',
},
},
},
window.location.origin,
);
});
// forward communication across inpage-background for these channels only
phishingExtChannel = phishingExtMux.createStream(PHISHING_SAFELIST);
pipeline(
phishingPageChannel,
phishingExtChannel,
phishingPageChannel,
(error) =>
console.debug(
`MetaMask: Muxed traffic for channel "${PHISHING_SAFELIST}" failed.`,
error,
),
);
// eslint-disable-next-line no-use-before-define
phishingExtPort.onDisconnect.addListener(onDisconnectDestroyPhishingStreams);
};
/** Destroys all of the phishing extension streams */
const destroyPhishingExtStreams = () => {
phishingPageChannel.removeAllListeners();
phishingExtMux.removeAllListeners();
phishingExtMux.destroy();
phishingExtChannel.removeAllListeners();
phishingExtChannel.destroy();
phishingExtStream = null;
};
/**
* This listener destroys the phishing extension streams when the extension port is disconnected,
* so that streams may be re-established later the phishing extension port is reconnected.
*/
const onDisconnectDestroyPhishingStreams = () => {
const err = checkForLastError();
phishingExtPort.onDisconnect.removeListener(
onDisconnectDestroyPhishingStreams,
);
destroyPhishingExtStreams();
/**
* If an error is found, reset the streams. When running two or more dapps, resetting the service
* worker may cause the error, "Error: Could not establish connection. Receiving end does not
* exist.", due to a race-condition. The disconnect event may be called by runtime.connect which
* may cause issues. We suspect that this is a chromium bug as this event should only be called
* once the port and connections are ready. Delay time is arbitrary.
*/
if (err) {
console.warn(`${err} Resetting the phishing streams.`);
setTimeout(setupPhishingExtStreams, 1000);
}
};
/**
* When the extension background is loaded it sends the EXTENSION_MESSAGES.READY message to the browser tabs.
* This listener/callback receives the message to set up the streams after service worker in-activity.
*
* @param {object} msg
* @param {string} msg.name - custom property and name to identify the message received
* @returns {Promise|undefined}
*/
const onMessageSetUpPhishingStreams = (msg) => {
if (msg.name === EXTENSION_MESSAGES.READY) {
if (!phishingExtStream) {
setupPhishingExtStreams();
}
return Promise.resolve(
`MetaMask: handled "${EXTENSION_MESSAGES.READY}" for phishing streams`,
);
}
return undefined;
};
/**
* Initializes two-way communication streams between the browser extension and
* the phishing page context. This function also creates an event listener to
* reset the streams if the service worker resets.
*/
const initPhishingStreams = () => {
setupPhishingPageStreams();
setupPhishingExtStreams();
browser.runtime.onMessage.addListener(onMessageSetUpPhishingStreams);
};
/**
* INPAGE - EXTENSION STREAM LOGIC
*/
const setupPageStreams = () => {
// the transport-specific streams for communication between inpage and background
const pageStream = new WindowPostMessageStream({
name: CONTENT_SCRIPT,
target: INPAGE,
});
// create and connect channel muxers
// so we can handle the channels individually
pageMux = new ObjectMultiplex();
pageMux.setMaxListeners(25);
pipeline(pageMux, pageStream, pageMux, (err) =>
logStreamDisconnectWarning('MetaMask Inpage Multiplex', err),
);
pageChannel = pageMux.createStream(PROVIDER);
};
// The field below is used to ensure that replay is done only once for each restart.
let METAMASK_EXTENSION_CONNECT_SENT = false;
const setupExtensionStreams = () => {
METAMASK_EXTENSION_CONNECT_SENT = true;
extensionPort = browser.runtime.connect({ name: CONTENT_SCRIPT });
extensionStream = new PortStream(extensionPort);
extensionStream.on('data', extensionStreamMessageListener);
// create and connect channel muxers
// so we can handle the channels individually
extensionMux = new ObjectMultiplex();
extensionMux.setMaxListeners(25);
extensionMux.ignoreStream(LEGACY_PUBLIC_CONFIG); // TODO:LegacyProvider: Delete
pipeline(extensionMux, extensionStream, extensionMux, (err) => {
logStreamDisconnectWarning('MetaMask Background Multiplex', err);
notifyInpageOfStreamFailure();
});
// forward communication across inpage-background for these channels only
extensionChannel = extensionMux.createStream(PROVIDER);
pipeline(pageChannel, extensionChannel, pageChannel, (error) =>
console.debug(
`MetaMask: Muxed traffic for channel "${PROVIDER}" failed.`,
error,
),
);
// connect "phishing" channel to warning system
extensionPhishingStream = extensionMux.createStream('phishing');
extensionPhishingStream.once('data', redirectToPhishingWarning);
// eslint-disable-next-line no-use-before-define
extensionPort.onDisconnect.addListener(onDisconnectDestroyStreams);
};
/** Destroys all of the extension streams */
const destroyExtensionStreams = () => {
pageChannel.removeAllListeners();
extensionMux.removeAllListeners();
extensionMux.destroy();
extensionChannel.removeAllListeners();
extensionChannel.destroy();
extensionStream = null;
};
/**
* LEGACY STREAM LOGIC
* TODO:LegacyProvider: Delete
*/
// TODO:LegacyProvider: Delete
const setupLegacyPageStreams = () => {
const legacyPageStream = new WindowPostMessageStream({
name: LEGACY_CONTENT_SCRIPT,
target: LEGACY_INPAGE,
});
legacyPageMux = new ObjectMultiplex();
legacyPageMux.setMaxListeners(25);
pipeline(legacyPageMux, legacyPageStream, legacyPageMux, (err) =>
logStreamDisconnectWarning('MetaMask Legacy Inpage Multiplex', err),
);
legacyPageMuxLegacyProviderChannel =
legacyPageMux.createStream(LEGACY_PROVIDER);
legacyPagePublicConfigChannel =
legacyPageMux.createStream(LEGACY_PUBLIC_CONFIG);
};
// TODO:LegacyProvider: Delete
const setupLegacyExtensionStreams = () => {
legacyExtMux = new ObjectMultiplex();
legacyExtMux.setMaxListeners(25);
notificationTransformStream = getNotificationTransformStream();
pipeline(
legacyExtMux,
extensionStream,
notificationTransformStream,
legacyExtMux,
(err) => {
logStreamDisconnectWarning('MetaMask Background Legacy Multiplex', err);
notifyInpageOfStreamFailure();
},
);
legacyExtChannel = legacyExtMux.createStream(PROVIDER);
pipeline(
legacyPageMuxLegacyProviderChannel,
legacyExtChannel,
legacyPageMuxLegacyProviderChannel,
(error) =>
console.debug(
`MetaMask: Muxed traffic between channels "${LEGACY_PROVIDER}" and "${PROVIDER}" failed.`,
error,
),
);
legacyExtPublicConfigChannel =
legacyExtMux.createStream(LEGACY_PUBLIC_CONFIG);
pipeline(
legacyPagePublicConfigChannel,
legacyExtPublicConfigChannel,
legacyPagePublicConfigChannel,
(error) =>
console.debug(
`MetaMask: Muxed traffic for channel "${LEGACY_PUBLIC_CONFIG}" failed.`,
error,
),
);
};
/**
* Destroys all of the legacy extension streams
* TODO:LegacyProvider: Delete
*/
const destroyLegacyExtensionStreams = () => {
legacyPageMuxLegacyProviderChannel.removeAllListeners();
legacyPagePublicConfigChannel.removeAllListeners();
legacyExtMux.removeAllListeners();
legacyExtMux.destroy();
legacyExtChannel.removeAllListeners();
legacyExtChannel.destroy();
legacyExtPublicConfigChannel.removeAllListeners();
legacyExtPublicConfigChannel.destroy();
};
/**
* When the extension background is loaded it sends the EXTENSION_MESSAGES.READY message to the browser tabs.
* This listener/callback receives the message to set up the streams after service worker in-activity.
*
* @param {object} msg
* @param {string} msg.name - custom property and name to identify the message received
* @returns {Promise|undefined}
*/
const onMessageSetUpExtensionStreams = (msg) => {
if (msg.name === EXTENSION_MESSAGES.READY) {
if (!extensionStream) {
setupExtensionStreams();
setupLegacyExtensionStreams();
}
return Promise.resolve(`MetaMask: handled ${EXTENSION_MESSAGES.READY}`);
}
return undefined;
};
/**
* This listener destroys the extension streams when the extension port is disconnected,
* so that streams may be re-established later when the extension port is reconnected.
*
* @param {Error} [err] - Stream connection error
*/
const onDisconnectDestroyStreams = (err) => {
const lastErr = err || checkForLastError();
extensionPort.onDisconnect.removeListener(onDisconnectDestroyStreams);
destroyExtensionStreams();
destroyLegacyExtensionStreams();
/**
* If an error is found, reset the streams. When running two or more dapps, resetting the service
* worker may cause the error, "Error: Could not establish connection. Receiving end does not
* exist.", due to a race-condition. The disconnect event may be called by runtime.connect which
* may cause issues. We suspect that this is a chromium bug as this event should only be called
* once the port and connections are ready. Delay time is arbitrary.
*/
if (lastErr) {
console.warn(`${lastErr} Resetting the streams.`);
setTimeout(setupExtensionStreams, 1000);
}
};
/**
* Initializes two-way communication streams between the browser extension and
* the local per-page browser context. This function also creates an event listener to
* reset the streams if the service worker resets.
*/
const initStreams = () => {
setupPageStreams();
setupLegacyPageStreams();
setupExtensionStreams();
setupLegacyExtensionStreams();
browser.runtime.onMessage.addListener(onMessageSetUpExtensionStreams);
};
// TODO:LegacyProvider: Delete
function getNotificationTransformStream() {
const stream = new Transform({
highWaterMark: 16,
objectMode: true,
transform: (chunk, _, cb) => {
if (chunk?.name === PROVIDER) {
if (chunk.data?.method === 'metamask_accountsChanged') {
chunk.data.method = 'wallet_accountsChanged';
chunk.data.result = chunk.data.params;
delete chunk.data.params;
}
}
cb(null, chunk);
},
});
return stream;
}
/**
* Error handler for page to extension stream disconnections
*
* @param {string} remoteLabel - Remote stream name
* @param {Error} error - Stream connection error
*/
function logStreamDisconnectWarning(remoteLabel, error) {
console.debug(
`MetaMask: Content script lost connection to "${remoteLabel}".`,
error,
);
}
/**
* The function notifies inpage when the extension stream connection is ready. When the
* 'metamask_chainChanged' method is received from the extension, it implies that the
* background state is completely initialized and it is ready to process method calls.
* This is used as a notification to replay any pending messages in MV3.
*
* @param {object} msg - instance of message received
*/
function extensionStreamMessageListener(msg) {
if (
METAMASK_EXTENSION_CONNECT_SENT &&
msg.data.method === 'metamask_chainChanged'
) {
METAMASK_EXTENSION_CONNECT_SENT = false;
window.postMessage(
{
target: INPAGE, // the post-message-stream "target"
data: {
// this object gets passed to @metamask/object-multiplex
name: PROVIDER, // the @metamask/object-multiplex channel name
data: {
jsonrpc: '2.0',
method: 'METAMASK_EXTENSION_CONNECT_CAN_RETRY',
},
},
},
window.location.origin,
);
}
}
/**
* This function must ONLY be called in pipeline destruction/close callbacks.
* Notifies the inpage context that streams have failed, via window.postMessage.
* Relies on @metamask/object-multiplex and post-message-stream implementation details.
*/
function notifyInpageOfStreamFailure() {
window.postMessage(
{
target: INPAGE, // the post-message-stream "target"
data: {
// this object gets passed to @metamask/object-multiplex
name: PROVIDER, // the @metamask/object-multiplex channel name
data: {
jsonrpc: '2.0',
method: 'METAMASK_STREAM_FAILURE',
},
},
},
window.location.origin,
);
}
/**
* Redirects the current page to a phishing information page
*/
function redirectToPhishingWarning() {
console.debug('MetaMask: Routing to Phishing Warning page.');
const { hostname, href } = window.location;
const baseUrl = process.env.PHISHING_WARNING_PAGE_URL;
const querystring = new URLSearchParams({ hostname, href });
window.location.href = `${baseUrl}#${querystring}`;
// eslint-disable-next-line no-constant-condition
while (1) {
console.log(
'MetaMask: Locking js execution, redirection will complete shortly',
);
}
}
const start = () => {
const isDetectedPhishingSite =
window.location.origin === phishingPageUrl.origin &&
window.location.pathname === phishingPageUrl.pathname;
if (isDetectedPhishingSite) {
initPhishingStreams();
return;
}
if (shouldInjectProvider()) {
initStreams();
if (document.prerendering && getIsBrowserPrerenderBroken()) {
document.addEventListener('prerenderingchange', () => {
onDisconnectDestroyStreams(
new Error('Prerendered page has become active.'),
);
});
}
}
};
start();