Connect distinct accounts per site (#7004)
* add PermissionsController remove provider approval controller integrate rpc-cap create PermissionsController move provider approval functionality to permissions controller add permissions approval ui, settings page add permissions activity and history move some functionality to metamask-inpage-provider rename siteMetadata -> domainMetadata add accountsChange notification to inpage provider move functionality to inpage provider update inpage provider Remove 'Connections' settings page (#7369) add hooks for exposing accounts in settings rename unused messages in non-English locales Add external extension id to metadata (#7396) update inpage provider, rpc-cap add eth_requestAccounts handling to background prevent notifying connections if extension is locked update inpage provider Fix lint errors add migration review fixes transaction controller review updates removed unused messages * Login Per Site UI (#7368) * LoginPerSite original UI changes to keep * First commit * Get necessary connected tab info for redirect and icon display for permissioned sites * Fix up designs and add missing features * Some lint fixes * More lint fixes * Ensures the tx controller + tx-state-manager orders transactions in the order they are received * Code cleanup for LoginPerSite-ui * Update e2e tests to use new connection flow * Fix display of connect screen and app header after login when connect request present * Update metamask-responsive-ui.spec for new item in accounts dropdown * Fix approve container by replacing approvedOrigins with domainMetaData * Adds test/e2e/permissions.spec.js * Correctly handle cancellation of a permissions request * Redirect to home after disconnecting all sites / cancelling all permissions * Fix display of site icons in menu * Fix height of permissions page container * Remove unused locale messages * Set default values for openExternalTabs and tabIdOrigins in account-menu.container * More code cleanup for LoginPerSite-ui * Use extensions api to close tab in permissions-connect * Remove unnecessary change in domIsReady() in contentscript * Remove unnecessary private function markers and class methods (for background tab info) in metamask-controller. * Adds getOriginOfCurrentTab selector * Adds IconWithFallback component and substitutes for appropriate cases * Add and utilize font mixins * Remove unused method in disconnect-all.container.js * Simplify buttonSizeLarge code in page-container-footer.component.js * Add and utilize getAccountsWithLabels selector * Remove console.log in ui/app/store/actions.js * Change last connected time format to yyyy-M-d * Fix css associated with IconWithFallback change * Ensure tracked openNonMetamaskTabsIDs are correctly set to inactive on tab changes * Code cleanup for LoginPerSite-ui * Use reusable function for modifying openNonMetamaskTabsIDs in background.js * Enables automatic switching to connected account when connected domain is open * Prevent exploit of tabIdOriginMap in background.js * Remove unneeded code from contentscript.js * Simplify current tab origin and window opener logic using remotePort listener tabs.queryTabs * Design and styling fixes for LoginPerSite-ui * Fix permissionHistory and permission logging for eth_requestAccounts and eth_accounts * Front end changes to support display of lastConnected time in connected and permissions screens * Fix lint errors * Refactor structure of permissionsHistory * Fix default values and object modifications for domain and permissionsHistory related data * Fix connecting to new accounts from modal * Replace retweet.svg with connect-white.svg * Fix signature-request.spec * Update metamask-inpage-provider version * Fix permissions e2e tests * Remove unneeded delay from test/e2e/signature-request.spec.js * Add delay before attempting to retrieve network id in dapp in ethereum-on=.spec * Use requestAccountTabIds strategy for determining tab id that opened a given window * Improve default values for permissions requests * Add some message descriptions to app/_locales/en/messages.json * Code clean up in permission controller * Stopped deep cloning object in mapObjectValues * Bump metamask-inpage-provider version * Add missing description in app/_locales/en/messages.json * Return promises from queryTabs and switchToTab of extension.js * Remove unused getAllPermissions function * Use default props in icon-with-fallback.component.js * Stop passing to permissions controller * Delete no longer used clear-approved-origins modal code * Remove duplicate imports in ui/app/components/app/index.scss * Use URL instead of regex in getOriginFromUrl() * Add runtime error checking to platform, promise based extension.tab methods * Support permission requests from external extensions * Improve font size and colour of the domain origin on the permission confirmation screen * Add support for toggling permissions * Ensure getRenderablePermissionsDomains only returns domains with exposedAccount caveat permissions * Remove unused code from LoginPerSite-ui branch * Ensure modal closes on Enter press for new-account-modal.component.js * Lint fix * fixup! Login Per Site UI (#7368) * Some code cleanup for LoginPerSite * Adds UX for connecting to dapps via the connected sites screen (#7593) * Adds UX for connecting to dapps via the connected sites screen * Use openMetaMaskTabIds from background.js to determine if current active tab is MetaMask * Delete unused permissions controller methods * Fixes two small bugs in the LoginPerSite ui (#7595) * Restore `providerRequest` message translations (#7600) This message was removed, but it was replaced with a very similar message called `likeToConnect`. The only difference is that the new message has "MetaMask" in it. Preserving these messages without "MetaMask" is probably better than deleting them, so these messages have all been restored and renamed to `likeToConnect`. * Login per site no sitemetadata fix (#7610) * Support connected sites for which we have no site metadata. * Change property containing subtitle info often populated by origin to a more accurate of purpose name * Lint fix * Improve disconnection modal messages (#7612) * Improve disconnectAccountModalDescription and disconnectAllModalDescription messages * Update disconnectAccountModalDescription app/_locales/en/messages.json Co-Authored-By: Mark Stacey <markjstacey@gmail.com> * Improve disconnectAccount modal message clarity * Adds cancel button to the account selection screen of the permissions request flow (#7613) * Fix eth_accounts permission language & selectability (#7614) * fix eth_accounts language & selectability * fix MetaMask capitalization in all messages * Close sidebar when opening connected sites (#7611) The 'Connected Sites' button in the accounts details now closes the sidebar, if it is open. This was accomplished by pulling the click handler for that button up to the wallet view component, where another button already followed a similar pattern of closing the sidebar. It seemed confusing to me that one handler was in the `AccountsDetails` container component, and one was handed down from above, so I added PropTypes to the container component. I'm not sure that the WalletView component is the best place for this logic, but I've put it there for now to be consistent with the add token button. * Reject permissions request upon tab close (#7618) Permissions requests are now rejected when the page is closed. This only applies to the full-screen view, as that is the view permission requests should be handled in. The case where the user deals with the request through a different view is handled in #7617 * Handle tab update failure (#7619) `extension.tabs.update` can sometimes fail if the user interacts with the tabs directly around the same time. The redirect flow has been updated to ensure that the permissions tab is still closed in that case. The user is on their own to find the dapp tab again in that case. * Login per site tab popup fixes (#7617) * Handle redirect in response to state update in permissions-connect * Ensure origin is available to permissions-connect subcomponents during redirect * Hide app bar whenever on redirect route * Improvements to handling of redirects in permissions-connect * Ensure permission request id change handling only happens when page is not null * Lint fix * Decouple confirm transaction screen from the selected address (#7622) * Avoid race condtion that could prevent contextual account switching (#7623) There was a race condition in the logic responsible for switching the selected account based upon the active tab. It was asynchronously querying the active tab, then assuming it had been retrieved later. The active tab info itself was already in the redux store in another spot, one that is guaranteed to be set before the UI renders. The race condition was avoided by deleting the duplicate state, and using the other active tab state. * Only redirect back to dapp if current tab is active (#7621) The "redirect back to dapp" behaviour can be disruptive when the permissions connect tab is not active. The purpose of the redirect was to maintain context between the dapp and the permissions request, but if the user has already moved to another tab, that no longer applies. * Fix JSX style lint errors * Remove unused statefeature/default_network_editable
parent
bb4c4189fb
commit
76b1699621
After Width: | Height: | Size: 188 B |
After Width: | Height: | Size: 1.2 KiB |
Before Width: | Height: | Size: 937 B After Width: | Height: | Size: 937 B |
@ -0,0 +1,377 @@ |
||||
const JsonRpcEngine = require('json-rpc-engine') |
||||
const asMiddleware = require('json-rpc-engine/src/asMiddleware') |
||||
const ObservableStore = require('obs-store') |
||||
const RpcCap = require('rpc-cap').CapabilitiesController |
||||
const { ethErrors } = require('eth-json-rpc-errors') |
||||
|
||||
const getRestrictedMethods = require('./restrictedMethods') |
||||
const createMethodMiddleware = require('./methodMiddleware') |
||||
const createLoggerMiddleware = require('./loggerMiddleware') |
||||
|
||||
// Methods that do not require any permissions to use:
|
||||
const SAFE_METHODS = require('./permissions-safe-methods.json') |
||||
|
||||
// some constants
|
||||
const METADATA_STORE_KEY = 'domainMetadata' |
||||
const LOG_STORE_KEY = 'permissionsLog' |
||||
const HISTORY_STORE_KEY = 'permissionsHistory' |
||||
const WALLET_METHOD_PREFIX = 'wallet_' |
||||
const CAVEAT_NAMES = { |
||||
exposedAccounts: 'exposedAccounts', |
||||
} |
||||
const ACCOUNTS_CHANGED_NOTIFICATION = 'wallet_accountsChanged' |
||||
|
||||
class PermissionsController { |
||||
|
||||
constructor ( |
||||
{ |
||||
platform, notifyDomain, notifyAllDomains, keyringController, |
||||
} = {}, |
||||
restoredPermissions = {}, |
||||
restoredState = {}) { |
||||
this.store = new ObservableStore({ |
||||
[METADATA_STORE_KEY]: restoredState[METADATA_STORE_KEY] || {}, |
||||
[LOG_STORE_KEY]: restoredState[LOG_STORE_KEY] || [], |
||||
[HISTORY_STORE_KEY]: restoredState[HISTORY_STORE_KEY] || {}, |
||||
}) |
||||
this.notifyDomain = notifyDomain |
||||
this.notifyAllDomains = notifyAllDomains |
||||
this.keyringController = keyringController |
||||
this._platform = platform |
||||
this._restrictedMethods = getRestrictedMethods(this) |
||||
this._initializePermissions(restoredPermissions) |
||||
} |
||||
|
||||
createMiddleware ({ origin, extensionId }) { |
||||
|
||||
if (extensionId) { |
||||
this.store.updateState({ |
||||
[METADATA_STORE_KEY]: { |
||||
...this.store.getState()[METADATA_STORE_KEY], |
||||
[origin]: { extensionId }, |
||||
}, |
||||
}) |
||||
} |
||||
|
||||
const engine = new JsonRpcEngine() |
||||
|
||||
engine.push(createLoggerMiddleware({ |
||||
walletPrefix: WALLET_METHOD_PREFIX, |
||||
restrictedMethods: Object.keys(this._restrictedMethods), |
||||
ignoreMethods: [ 'wallet_sendDomainMetadata' ], |
||||
store: this.store, |
||||
logStoreKey: LOG_STORE_KEY, |
||||
historyStoreKey: HISTORY_STORE_KEY, |
||||
})) |
||||
|
||||
engine.push(createMethodMiddleware({ |
||||
store: this.store, |
||||
storeKey: METADATA_STORE_KEY, |
||||
getAccounts: this.getAccounts.bind(this, origin), |
||||
requestAccountsPermission: this._requestPermissions.bind( |
||||
this, origin, { eth_accounts: {} } |
||||
), |
||||
})) |
||||
|
||||
engine.push(this.permissions.providerMiddlewareFunction.bind( |
||||
this.permissions, { origin } |
||||
)) |
||||
return asMiddleware(engine) |
||||
} |
||||
|
||||
/** |
||||
* Returns the accounts that should be exposed for the given origin domain, |
||||
* if any. This method exists for when a trusted context needs to know |
||||
* which accounts are exposed to a given domain. |
||||
* |
||||
* @param {string} origin - The origin string. |
||||
*/ |
||||
getAccounts (origin) { |
||||
return new Promise((resolve, _) => { |
||||
|
||||
const req = { method: 'eth_accounts' } |
||||
const res = {} |
||||
this.permissions.providerMiddlewareFunction( |
||||
{ origin }, req, res, () => {}, _end |
||||
) |
||||
|
||||
function _end () { |
||||
if (res.error || !Array.isArray(res.result)) { |
||||
resolve([]) |
||||
} else { |
||||
resolve(res.result) |
||||
} |
||||
} |
||||
}) |
||||
} |
||||
|
||||
/** |
||||
* Submits a permissions request to rpc-cap. Internal use only. |
||||
* |
||||
* @param {string} origin - The origin string. |
||||
* @param {IRequestedPermissions} permissions - The requested permissions. |
||||
*/ |
||||
_requestPermissions (origin, permissions) { |
||||
return new Promise((resolve, reject) => { |
||||
|
||||
const req = { method: 'wallet_requestPermissions', params: [permissions] } |
||||
const res = {} |
||||
this.permissions.providerMiddlewareFunction( |
||||
{ origin }, req, res, () => {}, _end |
||||
) |
||||
|
||||
function _end (err) { |
||||
if (err || res.error) { |
||||
reject(err || res.error) |
||||
} else { |
||||
resolve(res.result) |
||||
} |
||||
} |
||||
}) |
||||
} |
||||
|
||||
/** |
||||
* User approval callback. The request can fail if the request is invalid. |
||||
* |
||||
* @param {object} approved the approved request object |
||||
*/ |
||||
async approvePermissionsRequest (approved, accounts) { |
||||
|
||||
const { id } = approved.metadata |
||||
const approval = this.pendingApprovals[id] |
||||
|
||||
try { |
||||
|
||||
// attempt to finalize the request and resolve it
|
||||
await this.finalizePermissionsRequest(approved.permissions, accounts) |
||||
approval.resolve(approved.permissions) |
||||
|
||||
} catch (err) { |
||||
|
||||
// if finalization fails, reject the request
|
||||
approval.reject(ethErrors.rpc.invalidRequest({ |
||||
message: err.message, data: err, |
||||
})) |
||||
} |
||||
|
||||
delete this.pendingApprovals[id] |
||||
} |
||||
|
||||
/** |
||||
* User rejection callback. |
||||
* |
||||
* @param {string} id the id of the rejected request |
||||
*/ |
||||
async rejectPermissionsRequest (id) { |
||||
const approval = this.pendingApprovals[id] |
||||
approval.reject(ethErrors.provider.userRejectedRequest()) |
||||
delete this.pendingApprovals[id] |
||||
} |
||||
|
||||
/** |
||||
* Grants the given origin the eth_accounts permission for the given account(s). |
||||
* This method should ONLY be called as a result of direct user action in the UI, |
||||
* with the intention of supporting legacy dapps that don't support EIP 1102. |
||||
* |
||||
* @param {string} origin - The origin to expose the account(s) to. |
||||
* @param {Array<string>} accounts - The account(s) to expose. |
||||
*/ |
||||
async legacyExposeAccounts (origin, accounts) { |
||||
|
||||
const permissions = { |
||||
eth_accounts: {}, |
||||
} |
||||
|
||||
await this.finalizePermissionsRequest(permissions, accounts) |
||||
|
||||
let error |
||||
try { |
||||
await new Promise((resolve, reject) => { |
||||
this.permissions.grantNewPermissions(origin, permissions, {}, err => err ? resolve() : reject(err)) |
||||
}) |
||||
} catch (err) { |
||||
error = err |
||||
} |
||||
|
||||
if (error) { |
||||
if (error.code === 4001) { |
||||
throw error |
||||
} else { |
||||
throw ethErrors.rpc.internal({ |
||||
message: `Failed to add 'eth_accounts' to '${origin}'.`, |
||||
data: { |
||||
originalError: error, |
||||
accounts, |
||||
}, |
||||
}) |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Update the accounts exposed to the given origin. |
||||
* Throws error if the update fails. |
||||
* |
||||
* @param {string} origin - The origin to change the exposed accounts for. |
||||
* @param {string[]} accounts - The new account(s) to expose. |
||||
*/ |
||||
async updateExposedAccounts (origin, accounts) { |
||||
|
||||
await this.validateExposedAccounts(accounts) |
||||
|
||||
this.permissions.updateCaveatFor( |
||||
origin, 'eth_accounts', CAVEAT_NAMES.exposedAccounts, accounts |
||||
) |
||||
|
||||
this.notifyDomain(origin, { |
||||
method: ACCOUNTS_CHANGED_NOTIFICATION, |
||||
result: accounts, |
||||
}) |
||||
} |
||||
|
||||
/** |
||||
* Finalizes a permissions request. |
||||
* Throws if request validation fails. |
||||
* |
||||
* @param {Object} requestedPermissions - The requested permissions. |
||||
* @param {string[]} accounts - The accounts to expose, if any. |
||||
*/ |
||||
async finalizePermissionsRequest (requestedPermissions, accounts) { |
||||
|
||||
const { eth_accounts: ethAccounts } = requestedPermissions |
||||
|
||||
if (ethAccounts) { |
||||
|
||||
await this.validateExposedAccounts(accounts) |
||||
|
||||
if (!ethAccounts.caveats) { |
||||
ethAccounts.caveats = [] |
||||
} |
||||
|
||||
// caveat names are unique, and we will only construct this caveat here
|
||||
ethAccounts.caveats = ethAccounts.caveats.filter(c => ( |
||||
c.name !== CAVEAT_NAMES.exposedAccounts |
||||
)) |
||||
|
||||
ethAccounts.caveats.push( |
||||
{ |
||||
type: 'filterResponse', |
||||
value: accounts, |
||||
name: CAVEAT_NAMES.exposedAccounts, |
||||
}, |
||||
) |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Validate an array of accounts representing accounts to be exposed |
||||
* to a domain. Throws error if validation fails. |
||||
* |
||||
* @param {string[]} accounts - An array of addresses. |
||||
*/ |
||||
async validateExposedAccounts (accounts) { |
||||
|
||||
if (!Array.isArray(accounts) || accounts.length === 0) { |
||||
throw new Error('Must provide non-empty array of account(s).') |
||||
} |
||||
|
||||
// assert accounts exist
|
||||
const allAccounts = await this.keyringController.getAccounts() |
||||
accounts.forEach(acc => { |
||||
if (!allAccounts.includes(acc)) { |
||||
throw new Error(`Unknown account: ${acc}`) |
||||
} |
||||
}) |
||||
} |
||||
|
||||
/** |
||||
* Removes the given permissions for the given domain. |
||||
* @param {object} domains { origin: [permissions] } |
||||
*/ |
||||
removePermissionsFor (domains) { |
||||
|
||||
Object.entries(domains).forEach(([origin, perms]) => { |
||||
|
||||
this.permissions.removePermissionsFor( |
||||
origin, |
||||
perms.map(methodName => { |
||||
|
||||
if (methodName === 'eth_accounts') { |
||||
this.notifyDomain( |
||||
origin, |
||||
{ method: ACCOUNTS_CHANGED_NOTIFICATION, result: [] } |
||||
) |
||||
} |
||||
|
||||
return { parentCapability: methodName } |
||||
}) |
||||
) |
||||
}) |
||||
} |
||||
|
||||
/** |
||||
* Removes all known domains and their related permissions. |
||||
*/ |
||||
clearPermissions () { |
||||
this.permissions.clearDomains() |
||||
this.notifyAllDomains({ |
||||
method: ACCOUNTS_CHANGED_NOTIFICATION, |
||||
result: [], |
||||
}) |
||||
} |
||||
|
||||
/** |
||||
* A convenience method for retrieving a login object |
||||
* or creating a new one if needed. |
||||
* |
||||
* @param {string} origin = The origin string representing the domain. |
||||
*/ |
||||
_initializePermissions (restoredState) { |
||||
|
||||
// these permission requests are almost certainly stale
|
||||
const initState = { ...restoredState, permissionsRequests: [] } |
||||
|
||||
this.pendingApprovals = {} |
||||
|
||||
this.permissions = new RpcCap({ |
||||
|
||||
// Supports passthrough methods:
|
||||
safeMethods: SAFE_METHODS, |
||||
|
||||
// optional prefix for internal methods
|
||||
methodPrefix: WALLET_METHOD_PREFIX, |
||||
|
||||
restrictedMethods: this._restrictedMethods, |
||||
|
||||
/** |
||||
* A promise-returning callback used to determine whether to approve |
||||
* permissions requests or not. |
||||
* |
||||
* Currently only returns a boolean, but eventually should return any |
||||
* specific parameters or amendments to the permissions. |
||||
* |
||||
* @param {string} req - The internal rpc-cap user request object. |
||||
*/ |
||||
requestUserApproval: async (req) => { |
||||
const { metadata: { id } } = req |
||||
|
||||
this._platform.openExtensionInBrowser('connect') |
||||
|
||||
return new Promise((resolve, reject) => { |
||||
this.pendingApprovals[id] = { resolve, reject } |
||||
}) |
||||
}, |
||||
}, initState) |
||||
} |
||||
} |
||||
|
||||
module.exports = { |
||||
PermissionsController, |
||||
addInternalMethodPrefix: prefix, |
||||
CAVEAT_NAMES, |
||||
} |
||||
|
||||
|
||||
function prefix (method) { |
||||
return WALLET_METHOD_PREFIX + method |
||||
} |
@ -0,0 +1,169 @@ |
||||
|
||||
const clone = require('clone') |
||||
const { isValidAddress } = require('ethereumjs-util') |
||||
|
||||
const LOG_LIMIT = 100 |
||||
|
||||
/** |
||||
* Create middleware for logging requests and responses to restricted and |
||||
* permissions-related methods. |
||||
*/ |
||||
module.exports = function createLoggerMiddleware ({ |
||||
walletPrefix, restrictedMethods, store, logStoreKey, historyStoreKey, ignoreMethods, |
||||
}) { |
||||
return (req, res, next, _end) => { |
||||
let activityEntry, requestedMethods |
||||
const { origin, method } = req |
||||
const isInternal = method.startsWith(walletPrefix) |
||||
if ((isInternal || restrictedMethods.includes(method)) && !ignoreMethods.includes(method)) { |
||||
activityEntry = logActivity(req, isInternal) |
||||
if (method === `${walletPrefix}requestPermissions`) { |
||||
requestedMethods = getRequestedMethods(req) |
||||
} |
||||
} else if (method === 'eth_requestAccounts') { |
||||
activityEntry = logActivity(req, isInternal) |
||||
requestedMethods = [ 'eth_accounts' ] |
||||
} else { |
||||
return next() |
||||
} |
||||
|
||||
next(cb => { |
||||
const time = Date.now() |
||||
addResponse(activityEntry, res, time) |
||||
if (!res.error && requestedMethods) { |
||||
logHistory(requestedMethods, origin, res.result, time, method === 'eth_requestAccounts') |
||||
} |
||||
cb() |
||||
}) |
||||
} |
||||
|
||||
function logActivity (request, isInternal) { |
||||
const activityEntry = { |
||||
id: request.id, |
||||
method: request.method, |
||||
methodType: isInternal ? 'internal' : 'restricted', |
||||
origin: request.origin, |
||||
request: cloneObj(request), |
||||
requestTime: Date.now(), |
||||
response: null, |
||||
responseTime: null, |
||||
success: null, |
||||
} |
||||
commitActivity(activityEntry) |
||||
return activityEntry |
||||
} |
||||
|
||||
function addResponse (activityEntry, response, time) { |
||||
if (!response) { |
||||
return |
||||
} |
||||
activityEntry.response = cloneObj(response) |
||||
activityEntry.responseTime = time |
||||
activityEntry.success = !response.error |
||||
} |
||||
|
||||
function commitActivity (entry) { |
||||
const logs = store.getState()[logStoreKey] |
||||
if (logs.length > LOG_LIMIT - 2) { |
||||
logs.pop() |
||||
} |
||||
logs.push(entry) |
||||
store.updateState({ [logStoreKey]: logs }) |
||||
} |
||||
|
||||
function getRequestedMethods (request) { |
||||
if ( |
||||
!request.params || |
||||
typeof request.params[0] !== 'object' || |
||||
Array.isArray(request.params[0]) |
||||
) { |
||||
return null |
||||
} |
||||
return Object.keys(request.params[0]) |
||||
} |
||||
|
||||
function logHistory (requestedMethods, origin, result, time, isEthRequestAccounts) { |
||||
let accounts, entries |
||||
if (isEthRequestAccounts) { |
||||
accounts = result |
||||
const accountToTimeMap = accounts.reduce((acc, account) => ({ ...acc, [account]: time }), {}) |
||||
entries = { 'eth_accounts': { accounts: accountToTimeMap, lastApproved: time } } |
||||
} else { |
||||
entries = result |
||||
? result |
||||
.map(perm => { |
||||
if (perm.parentCapability === 'eth_accounts') { |
||||
accounts = getAccountsFromPermission(perm) |
||||
} |
||||
return perm.parentCapability |
||||
}) |
||||
.reduce((acc, m) => { |
||||
if (requestedMethods.includes(m)) { |
||||
if (m === 'eth_accounts') { |
||||
const accountToTimeMap = accounts.reduce((acc, account) => ({ ...acc, [account]: time }), {}) |
||||
acc[m] = { lastApproved: time, accounts: accountToTimeMap } |
||||
} else { |
||||
acc[m] = { lastApproved: time } |
||||
} |
||||
} |
||||
return acc |
||||
}, {}) |
||||
: {} |
||||
} |
||||
|
||||
if (Object.keys(entries).length > 0) { |
||||
commitHistory(origin, entries) |
||||
} |
||||
} |
||||
|
||||
function commitHistory (origin, entries) { |
||||
const history = store.getState()[historyStoreKey] || {} |
||||
const newOriginHistory = { |
||||
...history[origin], |
||||
...entries, |
||||
} |
||||
|
||||
if (history[origin] && history[origin]['eth_accounts'] && entries['eth_accounts']) { |
||||
newOriginHistory['eth_accounts'] = { |
||||
lastApproved: entries['eth_accounts'].lastApproved, |
||||
accounts: { |
||||
...history[origin]['eth_accounts'].accounts, |
||||
...entries['eth_accounts'].accounts, |
||||
}, |
||||
} |
||||
} |
||||
|
||||
history[origin] = newOriginHistory |
||||
|
||||
store.updateState({ [historyStoreKey]: history }) |
||||
} |
||||
} |
||||
|
||||
// the call to clone is set to disallow circular references
|
||||
// we attempt cloning at a depth of 3 and 2, then return a
|
||||
// shallow copy of the object
|
||||
function cloneObj (obj) { |
||||
for (let i = 3; i > 1; i--) { |
||||
try { |
||||
return clone(obj, false, i) |
||||
} catch (_) {} |
||||
} |
||||
return { ...obj } |
||||
} |
||||
|
||||
function getAccountsFromPermission (perm) { |
||||
if (perm.parentCapability !== 'eth_accounts' || !perm.caveats) { |
||||
return [] |
||||
} |
||||
const accounts = {} |
||||
for (const c of perm.caveats) { |
||||
if (c.type === 'filterResponse' && Array.isArray(c.value)) { |
||||
for (const v of c.value) { |
||||
if (isValidAddress(v)) { |
||||
accounts[v] = true |
||||
} |
||||
} |
||||
} |
||||
} |
||||
return Object.keys(accounts) |
||||
} |
@ -0,0 +1,90 @@ |
||||
|
||||
const createAsyncMiddleware = require('json-rpc-engine/src/createAsyncMiddleware') |
||||
const { ethErrors } = require('eth-json-rpc-errors') |
||||
|
||||
/** |
||||
* Create middleware for handling certain methods and preprocessing permissions requests. |
||||
*/ |
||||
module.exports = function createMethodMiddleware ({ |
||||
store, storeKey, getAccounts, requestAccountsPermission, |
||||
}) { |
||||
return createAsyncMiddleware(async (req, res, next) => { |
||||
|
||||
if (typeof req.method !== 'string') { |
||||
res.error = ethErrors.rpc.invalidRequest({ data: req}) |
||||
return |
||||
} |
||||
|
||||
switch (req.method) { |
||||
|
||||
// intercepting eth_accounts requests for backwards compatibility,
|
||||
// i.e. return an empty array instead of an error
|
||||
case 'eth_accounts': |
||||
|
||||
res.result = await getAccounts() |
||||
return |
||||
|
||||
case 'eth_requestAccounts': |
||||
|
||||
// first, just try to get accounts
|
||||
let accounts = await getAccounts() |
||||
if (accounts.length > 0) { |
||||
res.result = accounts |
||||
return |
||||
} |
||||
|
||||
// if no accounts, request the accounts permission
|
||||
try { |
||||
await requestAccountsPermission() |
||||
} catch (err) { |
||||
res.error = err |
||||
return |
||||
} |
||||
|
||||
// get the accounts again
|
||||
accounts = await getAccounts() |
||||
if (accounts.length > 0) { |
||||
res.result = accounts |
||||
} else { |
||||
// this should never happen
|
||||
res.error = ethErrors.rpc.internal( |
||||
'Accounts unexpectedly unavailable. Please report this bug.' |
||||
) |
||||
} |
||||
|
||||
return |
||||
|
||||
// custom method for getting metadata from the requesting domain
|
||||
case 'wallet_sendDomainMetadata': |
||||
|
||||
const storeState = store.getState()[storeKey] |
||||
const extensionId = storeState[req.origin] |
||||
? storeState[req.origin].extensionId |
||||
: undefined |
||||
|
||||
if ( |
||||
req.domainMetadata && |
||||
typeof req.domainMetadata.name === 'string' |
||||
) { |
||||
|
||||
store.updateState({ |
||||
[storeKey]: { |
||||
...storeState, |
||||
[req.origin]: { |
||||
extensionId, |
||||
...req.domainMetadata, |
||||
}, |
||||
}, |
||||
}) |
||||
} |
||||
|
||||
res.result = true |
||||
return |
||||
|
||||
default: |
||||
break |
||||
} |
||||
|
||||
next() |
||||
}) |
||||
} |
@ -0,0 +1,49 @@ |
||||
[ |
||||
"web3_sha3", |
||||
"net_listening", |
||||
"net_peerCount", |
||||
"net_version", |
||||
"eth_blockNumber", |
||||
"eth_call", |
||||
"eth_chainId", |
||||
"eth_coinbase", |
||||
"eth_estimateGas", |
||||
"eth_gasPrice", |
||||
"eth_getBalance", |
||||
"eth_getBlockByHash", |
||||
"eth_getBlockByNumber", |
||||
"eth_getBlockTransactionCountByHash", |
||||
"eth_getBlockTransactionCountByNumber", |
||||
"eth_getCode", |
||||
"eth_getFilterChanges", |
||||
"eth_getFilterLogs", |
||||
"eth_getLogs", |
||||
"eth_getStorageAt", |
||||
"eth_getTransactionByBlockHashAndIndex", |
||||
"eth_getTransactionByBlockNumberAndIndex", |
||||
"eth_getTransactionByHash", |
||||
"eth_getTransactionCount", |
||||
"eth_getTransactionReceipt", |
||||
"eth_getUncleByBlockHashAndIndex", |
||||
"eth_getUncleByBlockNumberAndIndex", |
||||
"eth_getUncleCountByBlockHash", |
||||
"eth_getUncleCountByBlockNumber", |
||||
"eth_getWork", |
||||
"eth_hashrate", |
||||
"eth_mining", |
||||
"eth_newBlockFilter", |
||||
"eth_newFilter", |
||||
"eth_newPendingTransactionFilter", |
||||
"eth_protocolVersion", |
||||
"eth_sendRawTransaction", |
||||
"eth_sendTransaction", |
||||
"eth_sign", |
||||
"personal_sign", |
||||
"eth_signTypedData", |
||||
"eth_signTypedData_v1", |
||||
"eth_signTypedData_v3", |
||||
"eth_submitHashrate", |
||||
"eth_submitWork", |
||||
"eth_syncing", |
||||
"eth_uninstallFilter" |
||||
] |
@ -0,0 +1,20 @@ |
||||
|
||||
module.exports = function getRestrictedMethods (permissionsController) { |
||||
return { |
||||
|
||||
'eth_accounts': { |
||||
description: 'View the address of the selected account', |
||||
method: (_, res, __, end) => { |
||||
permissionsController.keyringController.getAccounts() |
||||
.then((accounts) => { |
||||
res.result = accounts |
||||
end() |
||||
}) |
||||
.catch((err) => { |
||||
res.error = err |
||||
end(err) |
||||
}) |
||||
}, |
||||
}, |
||||
} |
||||
} |
@ -1,177 +0,0 @@ |
||||
const ObservableStore = require('obs-store') |
||||
const SafeEventEmitter = require('safe-event-emitter') |
||||
const createAsyncMiddleware = require('json-rpc-engine/src/createAsyncMiddleware') |
||||
const { errors: rpcErrors } = require('eth-json-rpc-errors') |
||||
|
||||
/** |
||||
* A controller that services user-approved requests for a full Ethereum provider API |
||||
*/ |
||||
class ProviderApprovalController extends SafeEventEmitter { |
||||
/** |
||||
* Creates a ProviderApprovalController |
||||
* |
||||
* @param {Object} [config] - Options to configure controller |
||||
*/ |
||||
constructor ({ closePopup, initState, keyringController, openPopup, preferencesController } = {}) { |
||||
super() |
||||
this.closePopup = closePopup |
||||
this.keyringController = keyringController |
||||
this.openPopup = openPopup |
||||
this.preferencesController = preferencesController |
||||
this.memStore = new ObservableStore({ |
||||
providerRequests: [], |
||||
}) |
||||
|
||||
const defaultState = { approvedOrigins: {} } |
||||
this.store = new ObservableStore(Object.assign(defaultState, initState)) |
||||
} |
||||
|
||||
/** |
||||
* Called when a user approves access to a full Ethereum provider API |
||||
* |
||||
* @param {object} opts - opts for the middleware contains the origin for the middleware |
||||
*/ |
||||
createMiddleware ({ senderUrl, extensionId, getSiteMetadata }) { |
||||
return createAsyncMiddleware(async (req, res, next) => { |
||||
// only handle requestAccounts
|
||||
if (req.method !== 'eth_requestAccounts') { |
||||
return next() |
||||
} |
||||
// if already approved or privacy mode disabled, return early
|
||||
const isUnlocked = this.keyringController.memStore.getState().isUnlocked |
||||
const origin = senderUrl.hostname |
||||
if (this.shouldExposeAccounts(origin) && isUnlocked) { |
||||
res.result = [this.preferencesController.getSelectedAddress()] |
||||
return |
||||
} |
||||
// register the provider request
|
||||
const metadata = { hostname: senderUrl.hostname, origin } |
||||
if (extensionId) { |
||||
metadata.extensionId = extensionId |
||||
} else { |
||||
const siteMetadata = await getSiteMetadata(origin) |
||||
Object.assign(metadata, { siteTitle: siteMetadata.name, siteImage: siteMetadata.icon}) |
||||
} |
||||
this._handleProviderRequest(metadata) |
||||
// wait for resolution of request
|
||||
const approved = await new Promise(resolve => this.once(`resolvedRequest:${origin}`, ({ approved }) => resolve(approved))) |
||||
if (approved) { |
||||
res.result = [this.preferencesController.getSelectedAddress()] |
||||
} else { |
||||
throw rpcErrors.eth.userRejectedRequest('User denied account authorization') |
||||
} |
||||
}) |
||||
} |
||||
|
||||
/** |
||||
* @typedef {Object} SiteMetadata |
||||
* @param {string} hostname - The hostname of the site |
||||
* @param {string} origin - The origin of the site |
||||
* @param {string} [siteTitle] - The title of the site |
||||
* @param {string} [siteImage] - The icon for the site |
||||
* @param {string} [extensionId] - The extension ID of the extension |
||||
*/ |
||||
/** |
||||
* Called when a tab requests access to a full Ethereum provider API |
||||
* |
||||
* @param {SiteMetadata} siteMetadata - The metadata for the site requesting full provider access |
||||
*/ |
||||
_handleProviderRequest (siteMetadata) { |
||||
const { providerRequests } = this.memStore.getState() |
||||
const origin = siteMetadata.origin |
||||
this.memStore.updateState({ |
||||
providerRequests: [ |
||||
...providerRequests, |
||||
siteMetadata, |
||||
], |
||||
}) |
||||
const isUnlocked = this.keyringController.memStore.getState().isUnlocked |
||||
const { approvedOrigins } = this.store.getState() |
||||
const originAlreadyHandled = approvedOrigins[origin] |
||||
if (originAlreadyHandled && isUnlocked) { |
||||
return |
||||
} |
||||
this.openPopup && this.openPopup() |
||||
} |
||||
|
||||
/** |
||||
* Called when a user approves access to a full Ethereum provider API |
||||
* |
||||
* @param {string} origin - origin of the domain that had provider access approved |
||||
*/ |
||||
approveProviderRequestByOrigin (origin) { |
||||
if (this.closePopup) { |
||||
this.closePopup() |
||||
} |
||||
|
||||
const { approvedOrigins } = this.store.getState() |
||||
const { providerRequests } = this.memStore.getState() |
||||
const providerRequest = providerRequests.find((request) => request.origin === origin) |
||||
const remainingProviderRequests = providerRequests.filter(request => request.origin !== origin) |
||||
this.store.updateState({ |
||||
approvedOrigins: { |
||||
...approvedOrigins, |
||||
[origin]: { |
||||
siteTitle: providerRequest ? providerRequest.siteTitle : null, |
||||
siteImage: providerRequest ? providerRequest.siteImage : null, |
||||
hostname: providerRequest ? providerRequest.hostname : null, |
||||
}, |
||||
}, |
||||
}) |
||||
this.memStore.updateState({ providerRequests: remainingProviderRequests }) |
||||
this.emit(`resolvedRequest:${origin}`, { approved: true }) |
||||
} |
||||
|
||||
/** |
||||
* Called when a tab rejects access to a full Ethereum provider API |
||||
* |
||||
* @param {string} origin - origin of the domain that had provider access approved |
||||
*/ |
||||
rejectProviderRequestByOrigin (origin) { |
||||
if (this.closePopup) { |
||||
this.closePopup() |
||||
} |
||||
|
||||
const { approvedOrigins } = this.store.getState() |
||||
const { providerRequests } = this.memStore.getState() |
||||
const remainingProviderRequests = providerRequests.filter(request => request.origin !== origin) |
||||
|
||||
// We're cloning and deleting keys here because we don't want to keep unneeded keys
|
||||
const _approvedOrigins = Object.assign({}, approvedOrigins) |
||||
delete _approvedOrigins[origin] |
||||
|
||||
this.store.putState({ approvedOrigins: _approvedOrigins }) |
||||
this.memStore.putState({ providerRequests: remainingProviderRequests }) |
||||
this.emit(`resolvedRequest:${origin}`, { approved: false }) |
||||
} |
||||
|
||||
/** |
||||
* Clears any approvals for user-approved origins |
||||
*/ |
||||
clearApprovedOrigins () { |
||||
this.store.updateState({ |
||||
approvedOrigins: {}, |
||||
}) |
||||
} |
||||
|
||||
/** |
||||
* Determines if a given origin should have accounts exposed |
||||
* |
||||
* @param {string} origin - Domain origin to check for approval status |
||||
* @returns {boolean} - True if the origin has been approved |
||||
*/ |
||||
shouldExposeAccounts (origin) { |
||||
return Boolean(this.store.getState().approvedOrigins[origin]) |
||||
} |
||||
|
||||
/** |
||||
* Returns a merged state representation |
||||
* @return {object} |
||||
* @private |
||||
*/ |
||||
_getMergedState () { |
||||
return Object.assign({}, this.memStore.getState(), this.store.getState()) |
||||
} |
||||
} |
||||
|
||||
module.exports = ProviderApprovalController |
@ -1,73 +0,0 @@ |
||||
class StandardProvider { |
||||
_isConnected |
||||
_provider |
||||
|
||||
constructor (provider) { |
||||
this._provider = provider |
||||
this._subscribe() |
||||
// indicate that we've connected, mostly just for standard compliance
|
||||
setTimeout(() => { |
||||
this._onConnect() |
||||
}) |
||||
} |
||||
|
||||
_onClose () { |
||||
if (this._isConnected === undefined || this._isConnected) { |
||||
this._provider.emit('close', { |
||||
code: 1011, |
||||
reason: 'Network connection error', |
||||
}) |
||||
} |
||||
this._isConnected = false |
||||
} |
||||
|
||||
_onConnect () { |
||||
!this._isConnected && this._provider.emit('connect') |
||||
this._isConnected = true |
||||
} |
||||
|
||||
_subscribe () { |
||||
this._provider.on('data', (error, { method, params }) => { |
||||
if (!error && method === 'eth_subscription') { |
||||
this._provider.emit('notification', params.result) |
||||
} |
||||
}) |
||||
} |
||||
|
||||
/** |
||||
* Initiate an RPC method call |
||||
* |
||||
* @param {string} method - RPC method name to call |
||||
* @param {string[]} params - Array of RPC method parameters |
||||
* @returns {Promise<*>} Promise resolving to the result if successful |
||||
*/ |
||||
send (method, params = []) { |
||||
return new Promise((resolve, reject) => { |
||||
try { |
||||
this._provider.sendAsync({ id: 1, jsonrpc: '2.0', method, params }, (error, response) => { |
||||
error = error || response.error |
||||
error ? reject(error) : resolve(response) |
||||
}) |
||||
} catch (error) { |
||||
reject(error) |
||||
} |
||||
}) |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Converts a legacy provider into an EIP-1193-compliant standard provider |
||||
* @param {Object} provider - Legacy provider to convert |
||||
* @returns {Object} Standard provider |
||||
*/ |
||||
export default function createStandardProvider (provider) { |
||||
const standardProvider = new StandardProvider(provider) |
||||
const sendLegacy = provider.send |
||||
provider.send = (methodOrPayload, callbackOrArgs) => { |
||||
if (typeof methodOrPayload === 'string' && !callbackOrArgs || Array.isArray(callbackOrArgs)) { |
||||
return standardProvider.send(methodOrPayload, callbackOrArgs) |
||||
} |
||||
return sendLegacy.call(provider, methodOrPayload, callbackOrArgs) |
||||
} |
||||
return provider |
||||
} |
@ -0,0 +1,23 @@ |
||||
const version = 40 |
||||
const clone = require('clone') |
||||
|
||||
/** |
||||
* Site connections are now managed by the PermissionsController, and the |
||||
* ProviderApprovalController is removed. This migration deletes all |
||||
* ProviderApprovalController state. |
||||
*/ |
||||
module.exports = { |
||||
version, |
||||
migrate: async function (originalVersionedData) { |
||||
const versionedData = clone(originalVersionedData) |
||||
versionedData.meta.version = version |
||||
const state = versionedData.data |
||||
versionedData.data = transformState(state) |
||||
return versionedData |
||||
}, |
||||
} |
||||
|
||||
function transformState (state) { |
||||
delete state.ProviderApprovalController |
||||
return state |
||||
} |
@ -0,0 +1,201 @@ |
||||
const assert = require('assert') |
||||
const webdriver = require('selenium-webdriver') |
||||
const { By, until } = webdriver |
||||
const { |
||||
delay, |
||||
} = require('./func') |
||||
const { |
||||
checkBrowserForConsoleErrors, |
||||
findElement, |
||||
findElements, |
||||
openNewPage, |
||||
verboseReportOnFailure, |
||||
waitUntilXWindowHandles, |
||||
switchToWindowWithTitle, |
||||
setupFetchMocking, |
||||
prepareExtensionForTesting, |
||||
} = require('./helpers') |
||||
const enLocaleMessages = require('../../app/_locales/en/messages.json') |
||||
|
||||
describe('MetaMask', function () { |
||||
let driver |
||||
let publicAddress |
||||
|
||||
const tinyDelayMs = 200 |
||||
const regularDelayMs = tinyDelayMs * 2 |
||||
const largeDelayMs = regularDelayMs * 2 |
||||
|
||||
this.timeout(0) |
||||
this.bail(true) |
||||
|
||||
before(async function () { |
||||
const result = await prepareExtensionForTesting() |
||||
driver = result.driver |
||||
await setupFetchMocking(driver) |
||||
}) |
||||
|
||||
afterEach(async function () { |
||||
if (process.env.SELENIUM_BROWSER === 'chrome') { |
||||
const errors = await checkBrowserForConsoleErrors(driver) |
||||
if (errors.length) { |
||||
const errorReports = errors.map(err => err.message) |
||||
const errorMessage = `Errors found in browser console:\n${errorReports.join('\n')}` |
||||
console.error(new Error(errorMessage)) |
||||
} |
||||
} |
||||
if (this.currentTest.state === 'failed') { |
||||
await verboseReportOnFailure(driver, this.currentTest) |
||||
} |
||||
}) |
||||
|
||||
after(async function () { |
||||
await driver.quit() |
||||
}) |
||||
|
||||
describe('Going through the first time flow, but skipping the seed phrase challenge', () => { |
||||
it('clicks the continue button on the welcome screen', async () => { |
||||
await findElement(driver, By.css('.welcome-page__header')) |
||||
const welcomeScreenBtn = await findElement(driver, By.xpath(`//button[contains(text(), '${enLocaleMessages.getStarted.message}')]`)) |
||||
welcomeScreenBtn.click() |
||||
await delay(largeDelayMs) |
||||
}) |
||||
|
||||
it('clicks the "Create New Wallet" option', async () => { |
||||
const customRpcButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Create a Wallet')]`)) |
||||
customRpcButton.click() |
||||
await delay(largeDelayMs) |
||||
}) |
||||
|
||||
it('clicks the "No thanks" option on the metametrics opt-in screen', async () => { |
||||
const optOutButton = await findElement(driver, By.css('.btn-default')) |
||||
optOutButton.click() |
||||
await delay(largeDelayMs) |
||||
}) |
||||
|
||||
it('accepts a secure password', async () => { |
||||
const passwordBox = await findElement(driver, By.css('.first-time-flow__form #create-password')) |
||||
const passwordBoxConfirm = await findElement(driver, By.css('.first-time-flow__form #confirm-password')) |
||||
const button = await findElement(driver, By.css('.first-time-flow__form button')) |
||||
|
||||
await passwordBox.sendKeys('correct horse battery staple') |
||||
await passwordBoxConfirm.sendKeys('correct horse battery staple') |
||||
|
||||
const tosCheckBox = await findElement(driver, By.css('.first-time-flow__checkbox')) |
||||
await tosCheckBox.click() |
||||
|
||||
await button.click() |
||||
await delay(largeDelayMs) |
||||
}) |
||||
|
||||
it('skips the seed phrase challenge', async () => { |
||||
const button = await findElement(driver, By.xpath(`//button[contains(text(), '${enLocaleMessages.remindMeLater.message}')]`)) |
||||
await button.click() |
||||
await delay(regularDelayMs) |
||||
|
||||
const detailsButton = await findElement(driver, By.css('.account-details__details-button')) |
||||
await detailsButton.click() |
||||
await delay(regularDelayMs) |
||||
}) |
||||
|
||||
it('gets the current accounts address', async () => { |
||||
const addressInput = await findElement(driver, By.css('.qr-ellip-address')) |
||||
publicAddress = await addressInput.getAttribute('value') |
||||
const accountModal = await driver.findElement(By.css('span .modal')) |
||||
|
||||
await driver.executeScript("document.querySelector('.account-modal-close').click()") |
||||
|
||||
await driver.wait(until.stalenessOf(accountModal)) |
||||
await delay(regularDelayMs) |
||||
}) |
||||
}) |
||||
|
||||
describe('sets permissions', () => { |
||||
let extension |
||||
let popup |
||||
let dapp |
||||
|
||||
it('connects to the dapp', async () => { |
||||
await openNewPage(driver, 'http://127.0.0.1:8080/') |
||||
await delay(regularDelayMs) |
||||
|
||||
const connectButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Connect')]`)) |
||||
await connectButton.click() |
||||
|
||||
await waitUntilXWindowHandles(driver, 3) |
||||
const windowHandles = await driver.getAllWindowHandles() |
||||
|
||||
extension = windowHandles[0] |
||||
dapp = await switchToWindowWithTitle(driver, 'E2E Test Dapp', windowHandles) |
||||
popup = windowHandles.find(handle => handle !== extension && handle !== dapp) |
||||
|
||||
await driver.switchTo().window(popup) |
||||
|
||||
await delay(regularDelayMs) |
||||
|
||||
const accountButton = await findElement(driver, By.css('.permissions-connect-choose-account__account')) |
||||
await accountButton.click() |
||||
|
||||
const submitButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Submit')]`)) |
||||
await submitButton.click() |
||||
|
||||
await waitUntilXWindowHandles(driver, 2) |
||||
await driver.switchTo().window(extension) |
||||
await delay(regularDelayMs) |
||||
}) |
||||
|
||||
it('shows connected sites', async () => { |
||||
const connectedSites = await findElement(driver, By.xpath(`//button[contains(text(), 'Connected Sites')]`)) |
||||
await connectedSites.click() |
||||
|
||||
await findElement(driver, By.css('.connected-sites__title')) |
||||
|
||||
const domains = await findElements(driver, By.css('.connected-sites-list__domain')) |
||||
assert.equal(domains.length, 1) |
||||
|
||||
const domainName = await findElement(driver, By.css('.connected-sites-list__domain-name')) |
||||
assert.equal(await domainName.getText(), 'E2E Test Dapp') |
||||
|
||||
await domains[0].click() |
||||
|
||||
const permissionDescription = await findElement(driver, By.css('.connected-sites-list__permission-description')) |
||||
assert.equal(await permissionDescription.getText(), 'View the address of the selected account') |
||||
}) |
||||
|
||||
it('can get accounts within the dapp', async () => { |
||||
await driver.switchTo().window(dapp) |
||||
await delay(regularDelayMs) |
||||
|
||||
const getAccountsButton = await findElement(driver, By.xpath(`//button[contains(text(), 'eth_accounts')]`)) |
||||
await getAccountsButton.click() |
||||
|
||||
const getAccountsResult = await findElement(driver, By.css('#getAccountsResult')) |
||||
assert.equal((await getAccountsResult.getText()).toLowerCase(), publicAddress.toLowerCase()) |
||||
}) |
||||
|
||||
it('can disconnect all accounts', async () => { |
||||
await driver.switchTo().window(extension) |
||||
|
||||
const disconnectAllButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Disconnect All')]`)) |
||||
await disconnectAllButton.click() |
||||
|
||||
const disconnectModal = await driver.findElement(By.css('span .modal')) |
||||
|
||||
const disconnectAllModalButton = await findElement(driver, By.css('.disconnect-all-modal .btn-danger')) |
||||
await disconnectAllModalButton.click() |
||||
|
||||
await driver.wait(until.stalenessOf(disconnectModal)) |
||||
await delay(regularDelayMs) |
||||
}) |
||||
|
||||
it('can no longer get accounts within the dapp', async () => { |
||||
await driver.switchTo().window(dapp) |
||||
await delay(regularDelayMs) |
||||
|
||||
const getAccountsButton = await findElement(driver, By.xpath(`//button[contains(text(), 'eth_accounts')]`)) |
||||
await getAccountsButton.click() |
||||
|
||||
const getAccountsResult = await findElement(driver, By.css('#getAccountsResult')) |
||||
assert.equal(await getAccountsResult.getText(), 'Not able to get accounts') |
||||
}) |
||||
}) |
||||
}) |
@ -1,330 +0,0 @@ |
||||
const assert = require('assert') |
||||
const sinon = require('sinon') |
||||
const ProviderApprovalController = require('../../../../app/scripts/controllers/provider-approval') |
||||
|
||||
const mockLockedKeyringController = { |
||||
memStore: { |
||||
getState: () => ({ |
||||
isUnlocked: false, |
||||
}), |
||||
}, |
||||
} |
||||
|
||||
const mockUnlockedKeyringController = { |
||||
memStore: { |
||||
getState: () => ({ |
||||
isUnlocked: true, |
||||
}), |
||||
}, |
||||
} |
||||
|
||||
describe('ProviderApprovalController', () => { |
||||
describe('#_handleProviderRequest', () => { |
||||
it('should add a pending provider request when unlocked', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = { |
||||
hostname: 'https://example.com', |
||||
origin: 'example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
} |
||||
|
||||
controller._handleProviderRequest(metadata) |
||||
assert.deepEqual(controller._getMergedState(), { |
||||
approvedOrigins: {}, |
||||
providerRequests: [metadata], |
||||
}) |
||||
}) |
||||
|
||||
it('should add a pending provider request when locked', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockLockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = { |
||||
hostname: 'https://example.com', |
||||
origin: 'example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
} |
||||
controller._handleProviderRequest(metadata) |
||||
assert.deepEqual(controller._getMergedState(), { |
||||
approvedOrigins: {}, |
||||
providerRequests: [metadata], |
||||
}) |
||||
}) |
||||
|
||||
it('should add a 2nd pending provider request when unlocked', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = [{ |
||||
hostname: 'https://example1.com', |
||||
origin: 'example1.com', |
||||
siteTitle: 'Example 1', |
||||
siteImage: 'https://example1.com/logo.svg', |
||||
}, { |
||||
hostname: 'https://example2.com', |
||||
origin: 'example2.com', |
||||
siteTitle: 'Example 2', |
||||
siteImage: 'https://example2.com/logo.svg', |
||||
}] |
||||
|
||||
controller._handleProviderRequest(metadata[0]) |
||||
controller._handleProviderRequest(metadata[1]) |
||||
assert.deepEqual(controller._getMergedState(), { |
||||
approvedOrigins: {}, |
||||
providerRequests: metadata, |
||||
}) |
||||
}) |
||||
|
||||
it('should add a 2nd pending provider request when locked', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockLockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = [{ |
||||
hostname: 'https://example1.com', |
||||
origin: 'example1.com', |
||||
siteTitle: 'Example 1', |
||||
siteImage: 'https://example1.com/logo.svg', |
||||
}, { |
||||
hostname: 'https://example2.com', |
||||
origin: 'example2.com', |
||||
siteTitle: 'Example 2', |
||||
siteImage: 'https://example2.com/logo.svg', |
||||
}] |
||||
|
||||
controller._handleProviderRequest(metadata[0]) |
||||
controller._handleProviderRequest(metadata[1]) |
||||
assert.deepEqual(controller._getMergedState(), { |
||||
approvedOrigins: {}, |
||||
providerRequests: metadata, |
||||
}) |
||||
}) |
||||
|
||||
it('should call openPopup when unlocked and when given', () => { |
||||
const openPopup = sinon.spy() |
||||
const controller = new ProviderApprovalController({ |
||||
openPopup, |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = { |
||||
hostname: 'https://example.com', |
||||
origin: 'example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
} |
||||
controller._handleProviderRequest(metadata) |
||||
assert.ok(openPopup.calledOnce) |
||||
}) |
||||
|
||||
it('should call openPopup when locked and when given', () => { |
||||
const openPopup = sinon.spy() |
||||
const controller = new ProviderApprovalController({ |
||||
openPopup, |
||||
keyringController: mockLockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = { |
||||
hostname: 'https://example.com', |
||||
origin: 'example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
} |
||||
controller._handleProviderRequest(metadata) |
||||
assert.ok(openPopup.calledOnce) |
||||
}) |
||||
|
||||
it('should NOT call openPopup when unlocked and when the domain has already been approved', () => { |
||||
const openPopup = sinon.spy() |
||||
const controller = new ProviderApprovalController({ |
||||
openPopup, |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
controller.store.updateState({ |
||||
approvedOrigins: { |
||||
'example.com': { |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
}, |
||||
}, |
||||
}) |
||||
const metadata = { |
||||
hostname: 'https://example.com', |
||||
origin: 'example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
} |
||||
controller._handleProviderRequest(metadata) |
||||
assert.ok(openPopup.notCalled) |
||||
}) |
||||
}) |
||||
|
||||
describe('#approveProviderRequestByOrigin', () => { |
||||
it('should mark the origin as approved and remove the provider request', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = { |
||||
hostname: 'https://example.com', |
||||
origin: 'example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
} |
||||
controller._handleProviderRequest(metadata) |
||||
controller.approveProviderRequestByOrigin('example.com') |
||||
assert.deepEqual(controller._getMergedState(), { |
||||
providerRequests: [], |
||||
approvedOrigins: { |
||||
'example.com': { |
||||
hostname: 'https://example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
}, |
||||
}, |
||||
}) |
||||
}) |
||||
|
||||
it('should mark the origin as approved and multiple requests for the same domain', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = { |
||||
hostname: 'https://example.com', |
||||
origin: 'example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
} |
||||
controller._handleProviderRequest(metadata) |
||||
controller._handleProviderRequest(metadata) |
||||
controller.approveProviderRequestByOrigin('example.com') |
||||
assert.deepEqual(controller._getMergedState(), { |
||||
providerRequests: [], |
||||
approvedOrigins: { |
||||
'example.com': { |
||||
hostname: 'https://example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
}, |
||||
}, |
||||
}) |
||||
}) |
||||
|
||||
it('should mark the origin as approved without a provider request', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
controller.approveProviderRequestByOrigin('example.com') |
||||
assert.deepEqual(controller._getMergedState(), { |
||||
providerRequests: [], |
||||
approvedOrigins: { |
||||
'example.com': { |
||||
hostname: null, |
||||
siteTitle: null, |
||||
siteImage: null, |
||||
}, |
||||
}, |
||||
}) |
||||
}) |
||||
}) |
||||
|
||||
describe('#rejectProviderRequestByOrigin', () => { |
||||
it('should remove the origin from approved', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = { |
||||
hostname: 'https://example.com', |
||||
origin: 'example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
} |
||||
controller._handleProviderRequest(metadata) |
||||
controller.approveProviderRequestByOrigin('example.com') |
||||
controller.rejectProviderRequestByOrigin('example.com') |
||||
assert.deepEqual(controller._getMergedState(), { |
||||
providerRequests: [], |
||||
approvedOrigins: {}, |
||||
}) |
||||
}) |
||||
|
||||
it('should reject the origin even without a pending request', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
controller.rejectProviderRequestByOrigin('example.com') |
||||
assert.deepEqual(controller._getMergedState(), { |
||||
providerRequests: [], |
||||
approvedOrigins: {}, |
||||
}) |
||||
}) |
||||
}) |
||||
|
||||
describe('#clearApprovedOrigins', () => { |
||||
it('should clear the approved origins', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = { |
||||
hostname: 'https://example.com', |
||||
origin: 'example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
} |
||||
controller._handleProviderRequest(metadata) |
||||
controller.approveProviderRequestByOrigin('example.com') |
||||
controller.clearApprovedOrigins() |
||||
assert.deepEqual(controller._getMergedState(), { |
||||
providerRequests: [], |
||||
approvedOrigins: {}, |
||||
}) |
||||
}) |
||||
}) |
||||
|
||||
describe('#shouldExposeAccounts', () => { |
||||
it('should return true for an approved origin', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = { |
||||
hostname: 'https://example.com', |
||||
origin: 'example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
} |
||||
controller._handleProviderRequest(metadata) |
||||
controller.approveProviderRequestByOrigin('example.com') |
||||
assert.ok(controller.shouldExposeAccounts('example.com')) |
||||
}) |
||||
|
||||
it('should return false for an origin not yet approved', () => { |
||||
const controller = new ProviderApprovalController({ |
||||
keyringController: mockUnlockedKeyringController, |
||||
}) |
||||
|
||||
const metadata = { |
||||
hostname: 'https://example.com', |
||||
origin: 'example.com', |
||||
siteTitle: 'Example', |
||||
siteImage: 'https://example.com/logo.svg', |
||||
} |
||||
controller._handleProviderRequest(metadata) |
||||
controller.approveProviderRequestByOrigin('example.com') |
||||
assert.ok(!controller.shouldExposeAccounts('bad.website')) |
||||
}) |
||||
}) |
||||
}) |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue