1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-22 18:00:18 +01:00
metamask-extension/app/scripts/platforms/extension.js

237 lines
6.7 KiB
JavaScript
Raw Normal View History

import browser from 'webextension-polyfill';
import { getBlockExplorerLink } from '@metamask/etherscan-link';
import { startCase, toLower } from 'lodash';
import { getEnvironmentType } from '../lib/util';
import { ENVIRONMENT_TYPE_BACKGROUND } from '../../../shared/constants/app';
import { TransactionStatus } from '../../../shared/constants/transaction';
import { getURLHostName } from '../../../ui/helpers/utils/util';
import { t } from '../translate';
export default class ExtensionPlatform {
//
// Public
//
2020-11-03 00:41:28 +01:00
reload() {
browser.runtime.reload();
}
async openTab(options) {
const newTab = await browser.tabs.create(options);
return newTab;
}
async openWindow(options) {
const newWindow = await browser.windows.create(options);
return newWindow;
}
async focusWindow(windowId) {
await browser.windows.update(windowId, { focused: true });
}
async updateWindowPosition(windowId, left, top) {
await browser.windows.update(windowId, { left, top });
}
async getLastFocusedWindow() {
const windowObject = await browser.windows.getLastFocused();
return windowObject;
}
async closeCurrentWindow() {
const windowDetails = await browser.windows.getCurrent();
browser.windows.remove(windowDetails.id);
}
2020-11-03 00:41:28 +01:00
getVersion() {
2022-07-31 20:26:40 +02:00
const { version, version_name: versionName } =
browser.runtime.getManifest();
const versionParts = version.split('.');
if (versionName) {
if (versionParts.length < 4) {
throw new Error(`Version missing build number: '${version}'`);
}
// On Chrome, a more descriptive representation of the version is stored in the
// `version_name` field for display purposes. We use this field instead of the `version`
// field on Chrome for non-main builds (i.e. Flask, Beta) because we want to show the
// version in the SemVer-compliant format "v[major].[minor].[patch]-[build-type].[build-number]",
// yet Chrome does not allow letters in the `version` field.
return versionName;
// A fourth version part is sometimes present for "rollback" Chrome builds
} else if (![3, 4].includes(versionParts.length)) {
throw new Error(`Invalid version: ${version}`);
} else if (versionParts[2].match(/[^\d]/u)) {
// On Firefox, the build type and build version are in the third part of the version.
const [major, minor, patchAndPrerelease] = versionParts;
const matches = patchAndPrerelease.match(/^(\d+)([A-Za-z]+)(\d)+$/u);
if (matches === null) {
throw new Error(`Version contains invalid prerelease: ${version}`);
}
const [, patch, buildType, buildVersion] = matches;
return `${major}.${minor}.${patch}-${buildType}.${buildVersion}`;
}
// If there is no `version_name` and there are only 3 or 4 version parts, then this is not a
// prerelease and the version requires no modification.
return version;
}
getExtensionURL(route = null, queryString = null) {
let extensionURL = browser.runtime.getURL('home.html');
if (route) {
extensionURL += `#${route}`;
}
if (queryString) {
extensionURL += `?${queryString}`;
}
return extensionURL;
}
openExtensionInBrowser(
route = null,
queryString = null,
keepWindowOpen = false,
) {
const extensionURL = this.getExtensionURL(
route,
queryString,
keepWindowOpen,
);
this.openTab({ url: extensionURL });
Connect Ledger via WebHID (#12411) * Connect ledger via webhid if that option is available * Explicitly setting preference for webhid * Use ledgerTransportType enum instead of booleans for ledger live and webhid preferences * Use single setLEdgerTransport preference methods and property * Temp * Lint fix * Unit test fix * Remove async keyword from setLedgerTransportPreference function definition in preferences controller * Fix ledgelive setting toggle logic * Migrate useLedgerLive preference property to ledgerTransportType * Use shared constants for ledger transport type enums * Use constant for ledger usb vendor id * Use correct property to check if ledgerLive preference is set when deciding whether to ask for webhid connection * Update eth-ledger-bridge-keyring to v0.9.0 * Only show ledger live transaction helper messages if using ledger live * Only show ledger live part of tutorial if ledger live setting is on * Fix ledger related prop type errors * Explicitly use u2f enum instead of empty string as a transport type; default transport type to webhid if available; use constants for u2f and webhid * Cleanup * Wrap ledger webhid device request in try/catch * Clean up * Lint fix * Ensure user can easily connect their ledger wallet when they need to. * Fix locales * Fix/improve locales changes * Remove unused isFirefox property from confirm-transaction-base.container.js * Disable transaction and message signing confirmation if ledger webhid requires connection * Ensure translation keys for ledger connection options in settings dropdown can be properly detected by verify-locales * Drop .component from ledger-instruction-field file name * Move renderLedgerLiveStep to module scope * Remove ledgerLive from function and message names in ledger-instruction-field * Wrap ledger connection logic in ledger-instruction-field in try catch * Clean up signature-request.component.js * Check whether the signing address, and not the selected address, is a ledger account in singature-request.container * Ensure ledger instructions and webhid connection button are shown on signature-request-original signatures * Improve webhid selection handling in select-ledger-transport-type onChange handler * Move metamask redux focused ledger selectors to metamask duck * Lint fix * Use async await in checkWebHidStatusRef.current * Remove unnecessary use of ref in ledger-instruction-field.js * Lint fix * Remove unnecessary try/catch in ledger-instruction-field.js * Check if from address, not selected address, is from a ledger account in confirm-approve * Move findKeyringForAddress to metamask duck * Fix typo in function name * Ensure isEqualCaseInsensitive handles possible differences in address casing * Fix Learn More link size in advanced settings tab * Update app/scripts/migrations/066.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> * Update ui/pages/settings/advanced-tab/advanced-tab.component.test.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> * Add jsdoc comments for new selectors * Use jest.spyOn for mocking navigator in ledger webhid migration tests * Use LEDGER_TRANSPORT_TYPES values to set proptype of ledgerTransportType * Use LEDGER_TRANSPORT_TYPES values to set proptype of ledgerTransportType * Fix font size of link in ledger connection description in advanced settings * Fix return type in setLedgerTransportPreference comment * Clean up connectHardware code for webhid connection in actions.js * Update app/scripts/migrations/066.test.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> * Update ui/ducks/metamask/metamask.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> * Add migration test for when useLedgerLive is true in a browser that supports webhid * Lint fix * Fix inline-link size Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-10-21 21:17:03 +02:00
if (
getEnvironmentType() !== ENVIRONMENT_TYPE_BACKGROUND &&
!keepWindowOpen
) {
window.close();
}
}
2020-11-03 00:41:28 +01:00
getPlatformInfo(cb) {
2017-10-06 02:13:58 +02:00
try {
const platformInfo = browser.runtime.getPlatformInfo();
cb(platformInfo);
return;
2017-10-06 02:13:58 +02:00
} catch (e) {
cb(e);
// eslint-disable-next-line no-useless-return
return;
2017-10-06 02:13:58 +02:00
}
2017-10-04 18:56:18 +02:00
}
2018-07-20 13:20:40 +02:00
async showTransactionNotification(txMeta, rpcPrefs) {
const { status, txReceipt: { status: receiptStatus } = {} } = txMeta;
2018-07-27 03:11:58 +02:00
if (status === TransactionStatus.confirmed) {
// There was an on-chain failure
receiptStatus === '0x0'
? await this._showFailedTransaction(
2020-11-03 00:41:28 +01:00
txMeta,
'Transaction encountered an error.',
)
: await this._showConfirmedTransaction(txMeta, rpcPrefs);
} else if (status === TransactionStatus.failed) {
await this._showFailedTransaction(txMeta);
2018-07-27 03:11:58 +02:00
}
}
addOnRemovedListener(listener) {
browser.windows.onRemoved.addListener(listener);
}
async getAllWindows() {
const windows = await browser.windows.getAll();
return windows;
}
async getActiveTabs() {
const tabs = await browser.tabs.query({ active: true });
return tabs;
}
async currentTab() {
const tab = await browser.tabs.getCurrent();
return tab;
}
async switchToTab(tabId) {
const tab = await browser.tabs.update(tabId, { highlighted: true });
return tab;
}
async switchToAnotherURL(tabId, url) {
await browser.tabs.update(tabId, { url });
}
async closeTab(tabId) {
await browser.tabs.remove(tabId);
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 state
2019-12-03 18:35:56 +01:00
}
async _showConfirmedTransaction(txMeta, rpcPrefs) {
this._subscribeToNotificationClicked();
2018-07-27 03:11:58 +02:00
const url = getBlockExplorerLink(txMeta, rpcPrefs);
const nonce = parseInt(txMeta.txParams.nonce, 16);
const view = startCase(
toLower(getURLHostName(url).replace(/([.]\w+)$/u, '')),
);
2018-07-27 03:11:58 +02:00
const title = t('notificationTransactionSuccessTitle');
let message = t('notificationTransactionSuccessMessage', nonce);
if (url.length) {
message += ` ${t('notificationTransactionSuccessView', view)}`;
}
await this._showNotification(title, message, url);
2018-07-20 13:20:40 +02:00
}
async _showFailedTransaction(txMeta, errorMessage) {
const nonce = parseInt(txMeta.txParams.nonce, 16);
const title = t('notificationTransactionFailedTitle');
let message = t(
'notificationTransactionFailedMessage',
nonce,
errorMessage || txMeta.err.message,
);
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
if (isNaN(nonce)) {
message = t(
'notificationTransactionFailedMessageMMI',
errorMessage || txMeta.err.message,
);
}
///: END:ONLY_INCLUDE_IN
await this._showNotification(title, message);
2018-07-27 03:11:58 +02:00
}
async _showNotification(title, message, url) {
const iconUrl = await browser.runtime.getURL('../../images/icon-64.png');
await browser.notifications.create(url, {
2020-11-03 00:41:28 +01:00
type: 'basic',
title,
iconUrl,
2020-11-03 00:41:28 +01:00
message,
});
2018-07-27 03:11:58 +02:00
}
2020-11-03 00:41:28 +01:00
_subscribeToNotificationClicked() {
if (!browser.notifications.onClicked.hasListener(this._viewOnEtherscan)) {
browser.notifications.onClicked.addListener(this._viewOnEtherscan);
2018-07-27 03:11:58 +02:00
}
}
_viewOnEtherscan(url) {
if (url.startsWith('https://')) {
browser.tabs.create({ url });
2018-07-27 03:11:58 +02:00
}
}
}