@ -1,18 +1,17 @@
const fs = require ( 'fs' )
const fs = require ( 'fs' )
const path = require ( 'path' )
const path = require ( 'path' )
const pump = require ( 'pump' )
const pump = require ( 'pump' )
const log = require ( 'loglevel' )
const Dnode = require ( 'dnode' )
const querystring = require ( 'querystring' )
const querystring = require ( 'querystring' )
const LocalMessageDuplexStream = require ( 'post-message-stream' )
const LocalMessageDuplexStream = require ( 'post-message-stream' )
const PongStream = require ( 'ping-pong-stream/pong' )
const ObjectMultiplex = require ( 'obj-multiplex' )
const ObjectMultiplex = require ( 'obj-multiplex' )
const extension = require ( 'extensionizer' )
const extension = require ( 'extensionizer' )
const PortStream = require ( 'extension-port-stream' )
const PortStream = require ( 'extension-port-stream' )
const { Transform : TransformStream } = require ( 'stream' )
const inpageContent = fs . readFileSync ( path . join ( _ _dirname , '..' , '..' , 'dist' , 'chrome' , 'inpage.js' ) ) . toString ( )
const inpageContent = fs . readFileSync ( path . join ( _ _dirname , '..' , '..' , 'dist' , 'chrome' , 'inpage.js' ) ) . toString ( )
const inpageSuffix = '//# sourceURL=' + extension . extension . getURL ( 'inpage.js' ) + '\n'
const inpageSuffix = '//# sourceURL=' + extension . extension . getURL ( 'inpage.js' ) + '\n'
const inpageBundle = inpageContent + inpageSuffix
const inpageBundle = inpageContent + inpageSuffix
let isEnabled = false
// Eventually this streaming injection could be replaced with:
// Eventually this streaming injection could be replaced with:
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.exportFunction
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.exportFunction
@ -23,9 +22,7 @@ let isEnabled = false
if ( shouldInjectWeb3 ( ) ) {
if ( shouldInjectWeb3 ( ) ) {
injectScript ( inpageBundle )
injectScript ( inpageBundle )
setupStreams ( )
start ( )
listenForProviderRequest ( )
checkPrivacyMode ( )
}
}
/ * *
/ * *
@ -46,149 +43,108 @@ function injectScript (content) {
}
}
}
}
/ * *
* Sets up the stream communication and submits site metadata
*
* /
async function start ( ) {
await setupStreams ( )
await domIsReady ( )
}
/ * *
/ * *
* Sets up two - way communication streams between the
* Sets up two - way communication streams between the
* browser extension and local per - page browser context
* browser extension and local per - page browser context .
*
* /
* /
function setupStreams ( ) {
async function setupStreams ( ) {
// setup communication to page and plugin
// the transport-specific streams for communication between inpage and background
const pageStream = new LocalMessageDuplexStream ( {
const pageStream = new LocalMessageDuplexStream ( {
name : 'contentscript' ,
name : 'contentscript' ,
target : 'inpage' ,
target : 'inpage' ,
} )
} )
const plugi nPort = extension . runtime . connect ( { name : 'contentscript' } )
const extensio nPort = extension . runtime . connect ( { name : 'contentscript' } )
const plugi nStream = new PortStream ( plugi nPort)
const extensio nStream = new PortStream ( extensio nPort)
// Filter out selectedAddress until this origin is enabled
// create and connect channel muxers
const approvalTransform = new TransformStream ( {
// so we can handle the channels individually
objectMode : true ,
const pageMux = new ObjectMultiplex ( )
transform : ( data , _ , done ) => {
pageMux . setMaxListeners ( 25 )
if ( typeof data === 'object' && data . name && data . name === 'publicConfig' && ! isEnabled ) {
const extensionMux = new ObjectMultiplex ( )
data . data . selectedAddress = undefined
extensionMux . setMaxListeners ( 25 )
}
done ( null , { ... data } )
} ,
} )
// forward communication plugin->inpage
pump (
pump (
pageMux ,
pageStream ,
pageStream ,
pluginStream ,
pageMux ,
approvalTransform ,
( err ) => logStreamDisconnectWarning ( 'MetaMask Inpage Multiplex' , err )
pageStream ,
( err ) => logStreamDisconnectWarning ( 'MetaMask Contentscript Forwarding' , err )
)
)
// setup local multistream channels
const mux = new ObjectMultiplex ( )
mux . setMaxListeners ( 25 )
pump (
pump (
mux ,
extensionMux ,
pageStream ,
extensionStream ,
mux ,
extensionMux ,
( err ) => logStreamDisconnectWarning ( 'MetaMask Inpage' , err )
( err ) => logStreamDisconnectWarning ( 'MetaMask Background Multiplex' , err )
)
pump (
mux ,
pluginStream ,
mux ,
( err ) => logStreamDisconnectWarning ( 'MetaMask Background' , err )
)
)
// connect ping stream
// forward communication across inpage-background for these channels only
const pongStream = new PongStream ( { objectMode : true } )
forwardTrafficBetweenMuxers ( 'provider' , pageMux , extensionMux )
pump (
forwardTrafficBetweenMuxers ( 'publicConfig' , pageMux , extensionMux )
mux ,
pongStream ,
mux ,
( err ) => logStreamDisconnectWarning ( 'MetaMask PingPongStream' , err )
)
// connect phishing warning str ea m
// connect "phishing" channel to warning system
const phishingStream = m ux. createStream ( 'phishing' )
const phishingStream = extensionMux . createStream ( 'phishing' )
phishingStream . once ( 'data' , redirectToPhishingWarning )
phishingStream . once ( 'data' , redirectToPhishingWarning )
// ignore unused channels (handled by background, inpage)
// connect "publicApi" channel to submit page metadata
mux . ignoreStream ( 'provider' )
const publicApiStream = extensionMux . createStream ( 'publicApi' )
mux . ignoreStream ( 'publicConfig' )
const background = await setupPublicApi ( publicApiStream )
return { background }
}
}
/ * *
function forwardTrafficBetweenMuxers ( channelName , muxA , muxB ) {
* Establishes listeners for requests to fully - enable the provider from the dapp context
const channelA = muxA . createStream ( channelName )
* and for full - provider approvals and rejections from the background script context . Dapps
const channelB = muxB . createStream ( channelName )
* should not post messages directly and should instead call provider . enable ( ) , which
pump (
* handles posting these messages internally .
channelA ,
* /
channelB ,
function listenForProviderRequest ( ) {
channelA ,
window . addEventListener ( 'message' , ( { source , data } ) => {
( err ) => logStreamDisconnectWarning ( ` MetaMask muxed traffic for channel " ${ channelName } " failed. ` , err )
if ( source !== window || ! data || ! data . type ) { return }
)
switch ( data . type ) {
}
case 'ETHEREUM_ENABLE_PROVIDER' :
extension . runtime . sendMessage ( {
action : 'init-provider-request' ,
force : data . force ,
origin : source . location . hostname ,
siteImage : getSiteIcon ( source ) ,
siteTitle : getSiteName ( source ) ,
} )
break
case 'ETHEREUM_IS_APPROVED' :
extension . runtime . sendMessage ( {
action : 'init-is-approved' ,
origin : source . location . hostname ,
} )
break
case 'METAMASK_IS_UNLOCKED' :
extension . runtime . sendMessage ( {
action : 'init-is-unlocked' ,
} )
break
}
} )
extension . runtime . onMessage . addListener ( ( { action = '' , isApproved , caching , isUnlocked , selectedAddress } ) => {
async function setupPublicApi ( outStream ) {
switch ( action ) {
const api = {
case 'approve-provider-request' :
getSiteMetadata : ( cb ) => cb ( null , getSiteMetadata ( ) ) ,
isEnabled = true
}
window . postMessage ( { type : 'ethereumprovider' , selectedAddress } , '*' )
const dnode = Dnode ( api )
break
pump (
case 'approve-legacy-provider-request' :
outStream ,
isEnabled = true
dnode ,
window . postMessage ( { type : 'ethereumproviderlegacy' , selectedAddress } , '*' )
outStream ,
break
( err ) => {
case 'reject-provider-request' :
// report any error
window . postMessage ( { type : 'ethereumprovider' , error : 'User denied account authorization' } , '*' )
if ( err ) log . error ( err )
break
case 'answer-is-approved' :
window . postMessage ( { type : 'ethereumisapproved' , isApproved , caching } , '*' )
break
case 'answer-is-unlocked' :
window . postMessage ( { type : 'metamaskisunlocked' , isUnlocked } , '*' )
break
case 'metamask-set-locked' :
isEnabled = false
window . postMessage ( { type : 'metamasksetlocked' } , '*' )
break
case 'ethereum-ping-success' :
window . postMessage ( { type : 'ethereumpingsuccess' } , '*' )
break
case 'ethereum-ping-error' :
window . postMessage ( { type : 'ethereumpingerror' } , '*' )
}
}
} )
)
const background = await new Promise ( resolve => dnode . once ( 'remote' , resolve ) )
return background
}
}
/ * *
/ * *
* Checks if MetaMask is currently operating in "privacy mode" , meaning
* Gets site metadata and returns it
* dapps must call ethereum . enable in order to access user accounts
*
* /
* /
function checkPrivacyMode ( ) {
function getSiteMetadata ( ) {
extension . runtime . sendMessage ( { action : 'init-privacy-request' } )
// get metadata
const metadata = {
name : getSiteName ( window ) ,
icon : getSiteIcon ( window ) ,
}
return metadata
}
}
/ * *
/ * *
* Error handler for page to plugin stream disconnections
* Error handler for page to extensio n stream disconnections
*
*
* @ param { string } remoteLabel Remote stream name
* @ param { string } remoteLabel Remote stream name
* @ param { Error } err Stream connection error
* @ param { Error } err Stream connection error
@ -301,6 +257,10 @@ function redirectToPhishingWarning () {
} ) } `
} ) } `
}
}
/ * *
* Extracts a name for the site from the DOM
* /
function getSiteName ( window ) {
function getSiteName ( window ) {
const document = window . document
const document = window . document
const siteName = document . querySelector ( 'head > meta[property="og:site_name"]' )
const siteName = document . querySelector ( 'head > meta[property="og:site_name"]' )
@ -316,6 +276,9 @@ function getSiteName (window) {
return document . title
return document . title
}
}
/ * *
* Extracts an icon for the site from the DOM
* /
function getSiteIcon ( window ) {
function getSiteIcon ( window ) {
const document = window . document
const document = window . document
@ -333,3 +296,13 @@ function getSiteIcon (window) {
return null
return null
}
}
/ * *
* Returns a promise that resolves when the DOM is loaded ( does not wait for images to load )
* /
async function domIsReady ( ) {
// already loaded
if ( [ 'interactive' , 'complete' ] . includes ( document . readyState ) ) return
// wait for load
await new Promise ( resolve => window . addEventListener ( 'DOMContentLoaded' , resolve , { once : true } ) )
}