2021-02-04 19:15:23 +01:00
import EventEmitter from 'events' ;
import pump from 'pump' ;
import { ObservableStore } from '@metamask/obs-store' ;
import { storeAsStream } from '@metamask/obs-store/dist/asStream' ;
import { JsonRpcEngine } from 'json-rpc-engine' ;
2023-02-08 15:45:00 +01:00
import { createEngineStream } from 'json-rpc-middleware-stream' ;
2023-02-27 17:49:08 +01:00
import { providerAsMiddleware } from '@metamask/eth-json-rpc-middleware' ;
2023-03-09 22:00:28 +01:00
import { debounce } from 'lodash' ;
2023-01-21 00:03:11 +01:00
import {
KeyringController ,
keyringBuilderFactory ,
} from '@metamask/eth-keyring-controller' ;
2023-03-15 15:46:31 +01:00
import createFilterMiddleware from 'eth-json-rpc-filters' ;
import createSubscriptionManager from 'eth-json-rpc-filters/subscriptionManager' ;
2023-03-20 14:19:50 +01:00
import { errorCodes as rpcErrorCodes , EthereumRpcError } from 'eth-rpc-errors' ;
2021-02-04 19:15:23 +01:00
import { Mutex } from 'await-semaphore' ;
import log from 'loglevel' ;
2023-05-05 17:55:41 +02:00
import TrezorKeyring from '@metamask/eth-trezor-keyring' ;
2021-02-04 19:15:23 +01:00
import LedgerBridgeKeyring from '@metamask/eth-ledger-bridge-keyring' ;
2021-11-08 15:48:41 +01:00
import LatticeKeyring from 'eth-lattice-keyring' ;
2021-11-23 18:28:39 +01:00
import { MetaMaskKeyring as QRHardwareKeyring } from '@keystonehq/metamask-airgapped-keyring' ;
2021-02-04 19:15:23 +01:00
import EthQuery from 'eth-query' ;
import nanoid from 'nanoid' ;
2021-11-11 04:27:04 +01:00
import { captureException } from '@sentry/browser' ;
2022-11-24 20:59:07 +01:00
import { AddressBookController } from '@metamask/address-book-controller' ;
2020-08-18 21:18:25 +02:00
import {
2020-12-14 17:04:26 +01:00
ApprovalController ,
2022-11-24 20:59:07 +01:00
ApprovalRequestNotFoundError ,
} from '@metamask/approval-controller' ;
import { ControllerMessenger } from '@metamask/base-controller' ;
import {
2020-08-18 21:18:25 +02:00
CurrencyRateController ,
2021-07-16 01:08:16 +02:00
TokenListController ,
2021-09-10 19:37:19 +02:00
TokensController ,
2021-09-15 21:02:28 +02:00
TokenRatesController ,
2022-11-15 19:49:42 +01:00
NftController ,
2021-11-19 17:16:41 +01:00
AssetsContractController ,
2022-11-15 19:49:42 +01:00
NftDetectionController ,
2022-11-24 20:59:07 +01:00
} from '@metamask/assets-controllers' ;
import { PhishingController } from '@metamask/phishing-controller' ;
import { AnnouncementController } from '@metamask/announcement-controller' ;
import { GasFeeController } from '@metamask/gas-fee-controller' ;
import {
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
PermissionController ,
2022-10-31 06:52:31 +01:00
PermissionsRequestNotFoundError ,
2022-11-24 20:59:07 +01:00
} from '@metamask/permission-controller' ;
2023-01-24 16:03:01 +01:00
import {
SubjectMetadataController ,
SubjectType ,
} from '@metamask/subject-metadata-controller' ;
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2023-05-15 19:36:24 +02:00
import { encrypt , decrypt } from '@metamask/browser-passworder' ;
2022-11-24 20:59:07 +01:00
import { RateLimitController } from '@metamask/rate-limit-controller' ;
import { NotificationController } from '@metamask/notification-controller' ;
///: END:ONLY_INCLUDE_IN
2022-03-10 00:37:40 +01:00
import SmartTransactionsController from '@metamask/smart-transactions-controller' ;
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-05-11 08:08:42 +02:00
import {
2022-11-09 13:18:47 +01:00
CronjobController ,
2023-03-30 23:57:28 +02:00
JsonSnapsRegistry ,
2022-05-11 08:08:42 +02:00
SnapController ,
IframeExecutionService ,
2022-11-22 13:07:08 +01:00
} from '@metamask/snaps-controllers' ;
2022-02-15 01:02:51 +01:00
///: END:ONLY_INCLUDE_IN
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
import {
CUSTODIAN _TYPES ,
MmiConfigurationController ,
} from '@metamask-institutional/custody-keyring' ;
import { InstitutionalFeaturesController } from '@metamask-institutional/institutional-features' ;
import { CustodyController } from '@metamask-institutional/custody-controller' ;
import { TransactionUpdateController } from '@metamask-institutional/transaction-update' ;
///: END:ONLY_INCLUDE_IN
2023-05-05 14:05:52 +02:00
import { SignatureController } from '@metamask/signature-controller' ;
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(desktop)
// eslint-disable-next-line import/order
import { DesktopController } from '@metamask/desktop/dist/controllers/desktop' ;
///: END:ONLY_INCLUDE_IN
2023-05-08 12:09:46 +02:00
import { ApprovalType } from '@metamask/controller-utils' ;
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
import { toChecksumHexAddress } from '../../shared/modules/hexstring-utils' ;
///: END:ONLY_INCLUDE_IN
2022-01-10 17:23:53 +01:00
import {
2023-01-18 15:47:29 +01:00
AssetType ,
TransactionStatus ,
TransactionType ,
2023-03-08 18:35:45 +01:00
TokenStandard ,
2022-01-10 17:23:53 +01:00
} from '../../shared/constants/transaction' ;
2021-09-08 19:26:37 +02:00
import {
GAS _API _BASE _URL ,
GAS _DEV _API _BASE _URL ,
2021-09-29 15:11:19 +02:00
SWAPS _CLIENT _ID ,
2021-09-08 19:26:37 +02:00
} from '../../shared/constants/swaps' ;
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556)
The `network` store of the network controller crams two types of data
into one place. It roughly tracks whether we have enough information to
make requests to the network and whether the network is capable of
receiving requests, but it also stores the ID of the network (as
obtained via `net_version`).
Generally we shouldn't be using the network ID for anything, as it has
been completely replaced by chain ID, which all custom RPC endpoints
have been required to support for over a year now. However, as the
network ID is used in various places within the extension codebase,
removing it entirely would be a non-trivial effort. So, minimally, this
commit splits `network` into two stores: `networkId` and
`networkStatus`. But it also expands the concept of network status.
Previously, the network was in one of two states: "loading" and
"not-loading". But now it can be in one of four states:
- `available`: The network is able to receive and respond to requests.
- `unavailable`: The network is not able to receive and respond to
requests for unknown reasons.
- `blocked`: The network is actively blocking requests based on the
user's geolocation. (This is specific to Infura.)
- `unknown`: We don't know whether the network can receive and respond
to requests, either because we haven't checked or we tried to check
and were unsuccessful.
This commit also changes how the network status is determined —
specifically, how many requests are used to determine that status, when
they occur, and whether they are awaited. Previously, the network
controller would make 2 to 3 requests during the course of running
`lookupNetwork`.
* First, if it was an Infura network, it would make a request for
`eth_blockNumber` to determine whether Infura was blocking requests or
not, then emit an appropriate event. This operation was not awaited.
* Then, regardless of the network, it would fetch the network ID via
`net_version`. This operation was awaited.
* Finally, regardless of the network, it would fetch the latest block
via `eth_getBlockByNumber`, then use the result to determine whether
the network supported EIP-1559. This operation was awaited.
Now:
* One fewer request is made, specifically `eth_blockNumber`, as we don't
need to make an extra request to determine whether Infura is blocking
requests; we can reuse `eth_getBlockByNumber`;
* All requests are awaited, which makes `lookupNetwork` run fully
in-band instead of partially out-of-band; and
* Both requests for `net_version` and `eth_getBlockByNumber` are
performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
import {
CHAIN _IDS ,
NETWORK _TYPES ,
NetworkStatus ,
} from '../../shared/constants/network' ;
2023-03-21 15:43:22 +01:00
import { HardwareDeviceNames } from '../../shared/constants/hardware-wallets' ;
import { KeyringType } from '../../shared/constants/keyring' ;
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
import {
CaveatTypes ,
RestrictedMethods ,
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-02-15 01:02:51 +01:00
EndowmentPermissions ,
2023-02-15 11:09:47 +01:00
ExcludedSnapPermissions ,
ExcludedSnapEndowments ,
2022-02-15 01:02:51 +01:00
///: END:ONLY_INCLUDE_IN
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
} from '../../shared/constants/permissions' ;
2021-04-28 18:51:41 +02:00
import { UI _NOTIFICATIONS } from '../../shared/notifications' ;
2022-10-25 06:54:02 +02:00
import { MILLISECOND , SECOND } from '../../shared/constants/time' ;
2021-12-09 00:37:29 +01:00
import {
2022-04-26 19:07:39 +02:00
ORIGIN _METAMASK ,
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-12-01 16:46:06 +01:00
SNAP _DIALOG _TYPES ,
2022-02-15 01:02:51 +01:00
///: END:ONLY_INCLUDE_IN
2021-12-09 00:37:29 +01:00
POLLING _TOKEN _ENVIRONMENT _TYPES ,
} from '../../shared/constants/app' ;
2023-04-03 17:31:04 +02:00
import {
MetaMetricsEventCategory ,
MetaMetricsEventName ,
} from '../../shared/constants/metametrics' ;
2021-04-28 18:51:41 +02:00
2023-03-08 18:35:45 +01:00
import {
getTokenIdParam ,
fetchTokenBalance ,
} from '../../shared/lib/token-util.ts' ;
2022-03-07 19:54:36 +01:00
import { isEqualCaseInsensitive } from '../../shared/modules/string-utils' ;
2022-03-17 19:35:40 +01:00
import { parseStandardTokenTransactionData } from '../../shared/modules/transaction.utils' ;
2022-08-10 03:26:25 +02:00
import { STATIC _MAINNET _TOKEN _LIST } from '../../shared/constants/tokens' ;
2023-01-20 18:04:37 +01:00
import { getTokenValueParam } from '../../shared/lib/metamask-controller-utils' ;
2022-11-22 17:56:26 +01:00
import { isManifestV3 } from '../../shared/modules/mv3.utils' ;
2023-01-20 18:04:37 +01:00
import { hexToDecimal } from '../../shared/modules/conversion.utils' ;
2023-03-31 15:22:33 +02:00
import { ACTION _QUEUE _METRICS _E2E _TEST } from '../../shared/constants/test-flags' ;
2023-05-29 17:38:28 +02:00
2022-04-27 20:14:10 +02:00
import {
onMessageReceived ,
checkForMultipleVersionsRunning ,
} from './detect-multiple-instances' ;
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
import MMIController from './controllers/mmi-controller' ;
import { mmiKeyringBuilderFactory } from './mmi-keyring-builder-factory' ;
///: END:ONLY_INCLUDE_IN
2021-02-04 19:15:23 +01:00
import ComposableObservableStore from './lib/ComposableObservableStore' ;
import AccountTracker from './lib/account-tracker' ;
2022-12-02 16:38:12 +01:00
import createDupeReqFilterMiddleware from './lib/createDupeReqFilterMiddleware' ;
2021-02-04 19:15:23 +01:00
import createLoggerMiddleware from './lib/createLoggerMiddleware' ;
2022-02-15 01:02:51 +01:00
import {
createMethodMiddleware ,
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-02-15 01:02:51 +01:00
createSnapMethodMiddleware ,
///: END:ONLY_INCLUDE_IN
} from './lib/rpc-method-middleware' ;
2021-02-04 19:15:23 +01:00
import createOriginMiddleware from './lib/createOriginMiddleware' ;
import createTabIdMiddleware from './lib/createTabIdMiddleware' ;
import createOnboardingMiddleware from './lib/createOnboardingMiddleware' ;
import { setupMultiplex } from './lib/stream-utils' ;
import EnsController from './controllers/ens' ;
2023-05-26 18:35:52 +02:00
import { NetworkController } from './controllers/network' ;
2021-02-04 19:15:23 +01:00
import PreferencesController from './controllers/preferences' ;
import AppStateController from './controllers/app-state' ;
import CachedBalancesController from './controllers/cached-balances' ;
import AlertController from './controllers/alert' ;
import OnboardingController from './controllers/onboarding' ;
2022-08-09 20:36:32 +02:00
import BackupController from './controllers/backup' ;
2021-02-04 19:15:23 +01:00
import IncomingTransactionsController from './controllers/incoming-transactions' ;
2023-04-26 17:02:33 +02:00
import DecryptMessageController from './controllers/decrypt-message' ;
2021-02-04 19:15:23 +01:00
import TransactionController from './controllers/transactions' ;
import DetectTokensController from './controllers/detect-tokens' ;
import SwapsController from './controllers/swaps' ;
import accountImporter from './account-import-strategies' ;
import seedPhraseVerifier from './lib/seed-phrase-verifier' ;
import MetaMetricsController from './controllers/metametrics' ;
2021-04-26 18:05:43 +02:00
import { segment } from './lib/segment' ;
2021-03-18 19:23:46 +01:00
import createMetaRPCHandler from './lib/createMetaRPCHandler' ;
2022-12-02 18:59:03 +01:00
import { previousValueComparator } from './lib/util' ;
2023-01-06 18:14:50 +01:00
import createMetamaskMiddleware from './lib/createMetamaskMiddleware' ;
2023-04-13 10:24:59 +02:00
import EncryptionPublicKeyController from './controllers/encryption-public-key' ;
2022-11-24 01:49:24 +01:00
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
import {
CaveatMutatorFactories ,
getCaveatSpecifications ,
getChangedAccounts ,
getPermissionBackgroundApiMethods ,
getPermissionSpecifications ,
getPermittedAccountsByOrigin ,
2021-12-08 11:37:35 +01:00
NOTIFICATION _NAMES ,
2022-02-15 01:02:51 +01:00
PermissionLogController ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
unrestrictedMethods ,
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-02-15 01:02:51 +01:00
buildSnapEndowmentSpecifications ,
buildSnapRestrictedMethodSpecifications ,
///: END:ONLY_INCLUDE_IN
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
} from './controllers/permissions' ;
2022-04-04 21:26:13 +02:00
import createRPCMethodTrackingMiddleware from './lib/createRPCMethodTrackingMiddleware' ;
2023-01-23 15:32:01 +01:00
import { securityProviderCheck } from './lib/security-provider-helpers' ;
2016-11-22 01:46:26 +01:00
2021-02-09 00:22:30 +01:00
export const METAMASK _CONTROLLER _EVENTS = {
// Fired after state changes that impact the extension badge (unapproved msg count)
// The process of updating the badge happens in app/scripts/background.js.
UPDATE _BADGE : 'updateBadge' ,
2022-11-24 20:59:07 +01:00
// TODO: Add this and similar enums to the `controllers` repo and export them
2021-08-31 21:27:13 +02:00
APPROVAL _STATE _CHANGE : 'ApprovalController:stateChange' ,
2021-02-09 00:22:30 +01:00
} ;
2022-05-06 00:28:48 +02:00
// stream channels
const PHISHING _SAFELIST = 'metamask-phishing-safelist' ;
2020-01-09 04:34:58 +01:00
export default class MetamaskController extends EventEmitter {
2018-03-15 23:27:10 +01:00
/ * *
2022-07-27 15:28:05 +02:00
* @ param { object } opts
2018-03-15 23:27:10 +01:00
* /
2020-11-03 00:41:28 +01:00
constructor ( opts ) {
2021-02-04 19:15:23 +01:00
super ( ) ;
2017-06-16 03:00:24 +02:00
2023-04-06 16:43:01 +02:00
const { isFirstMetaMaskControllerSetup } = opts ;
2021-02-04 19:15:23 +01:00
this . defaultMaxListeners = 20 ;
2018-01-25 21:28:11 +01:00
2021-06-10 21:27:03 +02:00
this . sendUpdate = debounce (
this . privateSendUpdate . bind ( this ) ,
MILLISECOND * 200 ,
) ;
2021-02-04 19:15:23 +01:00
this . opts = opts ;
2022-03-18 20:07:05 +01:00
this . extension = opts . browser ;
2021-02-04 19:15:23 +01:00
this . platform = opts . platform ;
2022-01-05 18:09:19 +01:00
this . notificationManager = opts . notificationManager ;
2021-02-04 19:15:23 +01:00
const initState = opts . initState || { } ;
const version = this . platform . getVersion ( ) ;
this . recordFirstTimeInfo ( initState ) ;
2017-01-12 04:04:19 +01:00
2018-08-22 01:30:11 +02:00
// this keeps track of how many "controllerStream" connections are open
// the only thing that uses controller connections are open metamask UI instances
2021-02-04 19:15:23 +01:00
this . activeControllerConnections = 0 ;
2018-08-22 01:30:11 +02:00
2021-02-04 19:15:23 +01:00
this . getRequestAccountTabIds = opts . getRequestAccountTabIds ;
this . getOpenMetamaskTabsIds = opts . getOpenMetamaskTabsIds ;
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
2021-08-31 21:27:13 +02:00
this . controllerMessenger = new ControllerMessenger ( ) ;
2021-05-20 04:57:51 +02:00
2022-10-11 00:10:44 +02:00
// instance of a class that wraps the extension's storage local API.
this . localStoreApiWrapper = opts . localStore ;
2017-01-12 04:04:19 +01:00
// observable state store
2021-05-20 04:57:51 +02:00
this . store = new ComposableObservableStore ( {
state : initState ,
2021-08-31 21:27:13 +02:00
controllerMessenger : this . controllerMessenger ,
2021-09-06 04:33:37 +02:00
persist : true ,
2021-05-20 04:57:51 +02:00
} ) ;
2017-01-28 01:11:59 +01:00
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
// external connections by origin
// Do not modify directly. Use the associated methods.
2021-02-04 19:15:23 +01:00
this . connections = { } ;
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
2017-11-20 22:47:35 +01:00
// lock to ensure only one vault created at once
2021-02-04 19:15:23 +01:00
this . createVaultMutex = new Mutex ( ) ;
2017-11-20 22:47:35 +01:00
2020-10-06 20:28:38 +02:00
this . extension . runtime . onInstalled . addListener ( ( details ) => {
if ( details . reason === 'update' && version === '8.1.0' ) {
2021-02-04 19:15:23 +01:00
this . platform . openExtensionInBrowser ( ) ;
2020-10-06 20:28:38 +02:00
}
2021-02-04 19:15:23 +01:00
} ) ;
2020-10-06 20:28:38 +02:00
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
// next, we will initialize the controllers
2020-05-27 19:57:42 +02:00
// controller initialization order matters
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
2020-12-14 17:04:26 +01:00
this . approvalController = new ApprovalController ( {
2021-08-31 21:27:13 +02:00
messenger : this . controllerMessenger . getRestricted ( {
name : 'ApprovalController' ,
} ) ,
2020-12-14 17:04:26 +01:00
showApprovalRequest : opts . showUserConfirmation ,
2023-04-14 19:33:53 +02:00
typesExcludedFromRateLimiting : [
2023-05-08 12:09:46 +02:00
ApprovalType . EthSign ,
ApprovalType . PersonalSign ,
ApprovalType . EthSignTypedData ,
ApprovalType . Transaction ,
ApprovalType . WatchAsset ,
ApprovalType . EthGetEncryptionPublicKey ,
ApprovalType . EthDecrypt ,
2023-04-14 19:33:53 +02:00
] ,
2021-02-04 19:15:23 +01:00
} ) ;
2020-12-14 17:04:26 +01:00
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
this . mmiConfigurationController = new MmiConfigurationController ( {
initState : initState . MmiConfigurationController ,
mmiConfigurationServiceUrl : process . env . MMI _CONFIGURATION _SERVICE _URL ,
} ) ;
///: END:ONLY_INCLUDE_IN
2023-03-30 20:39:36 +02:00
const networkControllerMessenger = this . controllerMessenger . getRestricted ( {
name : 'NetworkController' ,
2023-05-26 18:35:52 +02:00
allowedEvents : [
'NetworkController:networkWillChange' ,
'NetworkController:networkDidChange' ,
'NetworkController:infuraIsBlocked' ,
'NetworkController:infuraIsUnblocked' ,
] ,
2023-03-30 20:39:36 +02:00
} ) ;
2023-05-29 17:38:28 +02:00
2022-12-13 16:39:21 +01:00
this . networkController = new NetworkController ( {
2023-03-30 20:39:36 +02:00
messenger : networkControllerMessenger ,
2022-12-13 16:39:21 +01:00
state : initState . NetworkController ,
infuraProjectId : opts . infuraProjectId ,
2023-03-09 22:00:28 +01:00
trackMetaMetricsEvent : ( ... args ) =>
this . metaMetricsController . trackEvent ( ... args ) ,
2022-12-13 16:39:21 +01:00
} ) ;
2023-01-06 18:14:50 +01:00
this . networkController . initializeProvider ( ) ;
2022-07-31 20:26:40 +02:00
this . provider =
this . networkController . getProviderAndBlockTracker ( ) . provider ;
this . blockTracker =
this . networkController . getProviderAndBlockTracker ( ) . blockTracker ;
2021-06-22 19:39:44 +02:00
2022-08-10 03:26:25 +02:00
const tokenListMessenger = this . controllerMessenger . getRestricted ( {
name : 'TokenListController' ,
} ) ;
this . tokenListController = new TokenListController ( {
2023-02-22 18:43:37 +01:00
chainId : hexToDecimal (
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig . chainId ,
2023-02-22 18:43:37 +01:00
) ,
2022-10-11 16:21:31 +02:00
preventPollingOnNetworkRestart : initState . TokenListController
? initState . TokenListController . preventPollingOnNetworkRestart
: true ,
2022-08-10 03:26:25 +02:00
onNetworkStateChange : ( cb ) => {
this . networkController . store . subscribe ( ( networkState ) => {
const modifiedNetworkState = {
... networkState ,
2023-01-17 16:23:04 +01:00
providerConfig : {
2023-05-02 17:53:20 +02:00
... networkState . providerConfig ,
chainId : hexToDecimal ( networkState . providerConfig . chainId ) ,
2022-08-10 03:26:25 +02:00
} ,
} ;
return cb ( modifiedNetworkState ) ;
} ) ;
} ,
messenger : tokenListMessenger ,
state : initState . TokenListController ,
} ) ;
2017-01-30 22:01:07 +01:00
this . preferencesController = new PreferencesController ( {
initState : initState . PreferencesController ,
2018-03-22 16:09:16 +01:00
initLangCode : opts . initLangCode ,
2023-03-30 20:39:36 +02:00
onInfuraIsBlocked : networkControllerMessenger . subscribe . bind (
networkControllerMessenger ,
2023-05-26 18:35:52 +02:00
'NetworkController:infuraIsBlocked' ,
2023-03-30 20:39:36 +02:00
) ,
onInfuraIsUnblocked : networkControllerMessenger . subscribe . bind (
networkControllerMessenger ,
2023-05-26 18:35:52 +02:00
'NetworkController:infuraIsUnblocked' ,
2023-03-30 20:39:36 +02:00
) ,
2022-08-10 03:26:25 +02:00
tokenListController : this . tokenListController ,
2021-06-22 19:39:44 +02:00
provider : this . provider ,
2021-02-04 19:15:23 +01:00
} ) ;
2017-01-30 21:42:24 +01:00
2021-09-10 19:37:19 +02:00
this . tokensController = new TokensController ( {
onPreferencesStateChange : this . preferencesController . store . subscribe . bind (
this . preferencesController . store ,
) ,
2023-01-17 16:23:04 +01:00
onNetworkStateChange : ( cb ) =>
this . networkController . store . subscribe ( ( networkState ) => {
const modifiedNetworkState = {
... networkState ,
providerConfig : {
2023-05-02 17:53:20 +02:00
... networkState . providerConfig ,
2023-01-17 16:23:04 +01:00
} ,
} ;
return cb ( modifiedNetworkState ) ;
} ) ,
2021-09-10 19:37:19 +02:00
config : { provider : this . provider } ,
state : initState . TokensController ,
2023-04-21 10:05:27 +02:00
messenger : this . controllerMessenger . getRestricted ( {
name : 'TokensController' ,
allowedActions : [
` ${ this . approvalController . name } :addRequest ` ,
` ${ this . approvalController . name } :acceptRequest ` ,
` ${ this . approvalController . name } :rejectRequest ` ,
] ,
} ) ,
2021-09-10 19:37:19 +02:00
} ) ;
2022-07-18 16:43:30 +02:00
this . assetsContractController = new AssetsContractController (
{
onPreferencesStateChange : ( listener ) =>
this . preferencesController . store . subscribe ( listener ) ,
2023-04-18 18:33:12 +02:00
// This handler is misnamed, and is a known issue that will be resolved
// by planned refactors. It should be onNetworkDidChange which happens
// AFTER the provider in the network controller is updated to reflect
// the new state of the network controller. In #18041 we changed this
// handler to be triggered by the change in the network state because
// that is what the handler name implies, but this triggers too soon
// causing the provider of the AssetsContractController to trail the
// network provider by one update.
onNetworkStateChange : ( cb ) =>
networkControllerMessenger . subscribe (
2023-05-26 18:35:52 +02:00
'NetworkController:networkDidChange' ,
2023-04-18 18:33:12 +02:00
( ) => {
const networkState = this . networkController . store . getState ( ) ;
const modifiedNetworkState = {
... networkState ,
providerConfig : {
2023-05-02 17:53:20 +02:00
... networkState . providerConfig ,
chainId : hexToDecimal ( networkState . providerConfig . chainId ) ,
2023-04-18 18:33:12 +02:00
} ,
} ;
return cb ( modifiedNetworkState ) ;
} ,
) ,
2022-07-18 16:43:30 +02:00
} ,
{
provider : this . provider ,
} ,
initState . AssetsContractController ,
) ;
2021-11-19 17:16:41 +01:00
2022-11-15 19:49:42 +01:00
this . nftController = new NftController (
2021-12-14 00:41:10 +01:00
{
2022-07-31 20:26:40 +02:00
onPreferencesStateChange :
this . preferencesController . store . subscribe . bind (
this . preferencesController . store ,
) ,
2023-01-17 16:23:04 +01:00
onNetworkStateChange : ( cb ) =>
this . networkController . store . subscribe ( ( networkState ) => {
const modifiedNetworkState = {
... networkState ,
providerConfig : {
2023-05-02 17:53:20 +02:00
... networkState . providerConfig ,
chainId : hexToDecimal ( networkState . providerConfig . chainId ) ,
2023-01-17 16:23:04 +01:00
} ,
} ;
return cb ( modifiedNetworkState ) ;
} ) ,
2022-07-31 20:26:40 +02:00
getERC721AssetName :
this . assetsContractController . getERC721AssetName . bind (
this . assetsContractController ,
) ,
getERC721AssetSymbol :
this . assetsContractController . getERC721AssetSymbol . bind (
this . assetsContractController ,
) ,
2022-01-19 15:38:33 +01:00
getERC721TokenURI : this . assetsContractController . getERC721TokenURI . bind (
2021-12-14 00:41:10 +01:00
this . assetsContractController ,
) ,
2022-01-19 15:38:33 +01:00
getERC721OwnerOf : this . assetsContractController . getERC721OwnerOf . bind (
2021-12-14 00:41:10 +01:00
this . assetsContractController ,
) ,
2022-07-31 20:26:40 +02:00
getERC1155BalanceOf :
this . assetsContractController . getERC1155BalanceOf . bind (
this . assetsContractController ,
) ,
getERC1155TokenURI :
this . assetsContractController . getERC1155TokenURI . bind (
this . assetsContractController ,
) ,
2022-11-15 19:49:42 +01:00
onNftAdded : ( { address , symbol , tokenId , standard , source } ) =>
2022-07-18 16:43:30 +02:00
this . metaMetricsController . trackEvent ( {
2023-04-03 17:31:04 +02:00
event : MetaMetricsEventName . NftAdded ,
category : MetaMetricsEventCategory . Wallet ,
2022-07-18 16:43:30 +02:00
properties : {
token _contract _address : address ,
token _symbol : symbol ,
2023-01-18 15:47:29 +01:00
asset _type : AssetType . NFT ,
2022-07-18 16:43:30 +02:00
token _standard : standard ,
source ,
} ,
sensitiveProperties : {
tokenId ,
} ,
} ) ,
2021-12-14 00:41:10 +01:00
} ,
{ } ,
2022-11-15 19:49:42 +01:00
initState . NftController ,
2021-12-14 00:41:10 +01:00
) ;
2021-11-19 17:16:41 +01:00
2022-11-15 19:49:42 +01:00
this . nftController . setApiKey ( process . env . OPENSEA _KEY ) ;
2022-01-20 18:49:49 +01:00
2023-03-13 20:29:37 +01:00
this . nftDetectionController = new NftDetectionController ( {
onNftsStateChange : ( listener ) => this . nftController . subscribe ( listener ) ,
onPreferencesStateChange : this . preferencesController . store . subscribe . bind (
this . preferencesController . store ,
) ,
onNetworkStateChange : ( cb ) =>
this . networkController . store . subscribe ( ( networkState ) => {
const modifiedNetworkState = {
... networkState ,
providerConfig : {
2023-05-02 17:53:20 +02:00
... networkState . providerConfig ,
chainId : hexToDecimal ( networkState . providerConfig . chainId ) ,
2023-03-13 20:29:37 +01:00
} ,
} ;
return cb ( modifiedNetworkState ) ;
} ) ,
getOpenSeaApiKey : ( ) => this . nftController . openSeaApiKey ,
getBalancesInSingleCall :
this . assetsContractController . getBalancesInSingleCall . bind (
this . assetsContractController ,
) ,
addNft : this . nftController . addNft . bind ( this . nftController ) ,
getNftState : ( ) => this . nftController . state ,
} ) ;
2021-11-19 17:16:41 +01:00
2020-12-02 22:41:30 +01:00
this . metaMetricsController = new MetaMetricsController ( {
segment ,
preferencesStore : this . preferencesController . store ,
2023-03-30 20:39:36 +02:00
onNetworkDidChange : networkControllerMessenger . subscribe . bind (
networkControllerMessenger ,
2023-05-26 18:35:52 +02:00
'NetworkController:networkDidChange' ,
2020-12-02 22:41:30 +01:00
) ,
2023-02-22 18:43:37 +01:00
getNetworkIdentifier : ( ) => {
const { type , rpcUrl } =
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig ;
2023-02-22 18:43:37 +01:00
return type === NETWORK _TYPES . RPC ? rpcUrl : type ;
} ,
getCurrentChainId : ( ) =>
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig . chainId ,
2020-12-02 22:41:30 +01:00
version : this . platform . getVersion ( ) ,
environment : process . env . METAMASK _ENVIRONMENT ,
2022-08-11 19:33:33 +02:00
extension : this . extension ,
2020-12-02 22:41:30 +01:00
initState : initState . MetaMetricsController ,
2021-11-11 04:27:04 +01:00
captureException ,
2021-02-04 19:15:23 +01:00
} ) ;
2020-10-08 18:41:23 +02:00
2022-03-28 23:56:56 +02:00
this . on ( 'update' , ( update ) => {
this . metaMetricsController . handleMetaMaskStateUpdate ( update ) ;
} ) ;
2021-08-31 21:27:13 +02:00
const gasFeeMessenger = this . controllerMessenger . getRestricted ( {
2021-07-08 22:23:00 +02:00
name : 'GasFeeController' ,
} ) ;
2021-09-08 19:26:37 +02:00
const gasApiBaseUrl = process . env . SWAPS _USE _DEV _APIS
? GAS _DEV _API _BASE _URL
: GAS _API _BASE _URL ;
2021-07-08 22:23:00 +02:00
this . gasFeeController = new GasFeeController ( {
2022-11-22 17:56:26 +01:00
state : initState . GasFeeController ,
2021-07-08 22:23:00 +02:00
interval : 10000 ,
messenger : gasFeeMessenger ,
2021-09-29 15:11:19 +02:00
clientId : SWAPS _CLIENT _ID ,
2021-07-08 22:23:00 +02:00
getProvider : ( ) =>
this . networkController . getProviderAndBlockTracker ( ) . provider ,
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556)
The `network` store of the network controller crams two types of data
into one place. It roughly tracks whether we have enough information to
make requests to the network and whether the network is capable of
receiving requests, but it also stores the ID of the network (as
obtained via `net_version`).
Generally we shouldn't be using the network ID for anything, as it has
been completely replaced by chain ID, which all custom RPC endpoints
have been required to support for over a year now. However, as the
network ID is used in various places within the extension codebase,
removing it entirely would be a non-trivial effort. So, minimally, this
commit splits `network` into two stores: `networkId` and
`networkStatus`. But it also expands the concept of network status.
Previously, the network was in one of two states: "loading" and
"not-loading". But now it can be in one of four states:
- `available`: The network is able to receive and respond to requests.
- `unavailable`: The network is not able to receive and respond to
requests for unknown reasons.
- `blocked`: The network is actively blocking requests based on the
user's geolocation. (This is specific to Infura.)
- `unknown`: We don't know whether the network can receive and respond
to requests, either because we haven't checked or we tried to check
and were unsuccessful.
This commit also changes how the network status is determined —
specifically, how many requests are used to determine that status, when
they occur, and whether they are awaited. Previously, the network
controller would make 2 to 3 requests during the course of running
`lookupNetwork`.
* First, if it was an Infura network, it would make a request for
`eth_blockNumber` to determine whether Infura was blocking requests or
not, then emit an appropriate event. This operation was not awaited.
* Then, regardless of the network, it would fetch the network ID via
`net_version`. This operation was awaited.
* Finally, regardless of the network, it would fetch the latest block
via `eth_getBlockByNumber`, then use the result to determine whether
the network supported EIP-1559. This operation was awaited.
Now:
* One fewer request is made, specifically `eth_blockNumber`, as we don't
need to make an extra request to determine whether Infura is blocking
requests; we can reuse `eth_getBlockByNumber`;
* All requests are awaited, which makes `lookupNetwork` run fully
in-band instead of partially out-of-band; and
* Both requests for `net_version` and `eth_getBlockByNumber` are
performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
// NOTE: This option is inaccurately named; it should be called
// onNetworkDidChange
2023-03-30 20:39:36 +02:00
onNetworkStateChange : networkControllerMessenger . subscribe . bind (
networkControllerMessenger ,
2023-05-26 18:35:52 +02:00
'NetworkController:networkDidChange' ,
2021-07-08 22:23:00 +02:00
) ,
2022-07-31 20:26:40 +02:00
getCurrentNetworkEIP1559Compatibility :
this . networkController . getEIP1559Compatibility . bind (
this . networkController ,
) ,
getCurrentAccountEIP1559Compatibility :
this . getCurrentAccountEIP1559Compatibility . bind ( this ) ,
2021-09-08 19:26:37 +02:00
legacyAPIEndpoint : ` ${ gasApiBaseUrl } /networks/<chain_id>/gasPrices ` ,
EIP1559APIEndpoint : ` ${ gasApiBaseUrl } /networks/<chain_id>/suggestedGasFees ` ,
2021-07-16 18:06:32 +02:00
getCurrentNetworkLegacyGasAPICompatibility : ( ) => {
2023-05-02 17:53:20 +02:00
const { chainId } =
this . networkController . store . getState ( ) . providerConfig ;
2022-09-14 16:55:31 +02:00
return process . env . IN _TEST || chainId === CHAIN _IDS . MAINNET ;
2021-07-16 18:06:32 +02:00
} ,
getChainId : ( ) => {
return process . env . IN _TEST
2022-09-14 16:55:31 +02:00
? CHAIN _IDS . MAINNET
2023-05-02 17:53:20 +02:00
: this . networkController . store . getState ( ) . providerConfig . chainId ;
2021-07-16 18:06:32 +02:00
} ,
2021-07-08 22:23:00 +02:00
} ) ;
2021-11-23 18:28:39 +01:00
this . qrHardwareKeyring = new QRHardwareKeyring ( ) ;
2019-05-13 18:16:09 +02:00
this . appStateController = new AppStateController ( {
2020-03-23 17:25:55 +01:00
addUnlockListener : this . on . bind ( this , 'unlock' ) ,
isUnlocked : this . isUnlocked . bind ( this ) ,
2019-11-26 22:24:53 +01:00
initState : initState . AppStateController ,
2020-03-23 17:25:55 +01:00
onInactiveTimeout : ( ) => this . setLocked ( ) ,
preferencesStore : this . preferencesController . store ,
2021-11-23 18:28:39 +01:00
qrHardwareStore : this . qrHardwareKeyring . getMemStore ( ) ,
2023-04-14 06:50:17 +02:00
messenger : this . controllerMessenger . getRestricted ( {
name : 'AppStateController' ,
allowedActions : [
` ${ this . approvalController . name } :addRequest ` ,
` ${ this . approvalController . name } :acceptRequest ` ,
] ,
} ) ,
2021-02-04 19:15:23 +01:00
} ) ;
2019-05-13 18:16:09 +02:00
2021-08-31 21:27:13 +02:00
const currencyRateMessenger = this . controllerMessenger . getRestricted ( {
2021-05-20 04:57:51 +02:00
name : 'CurrencyRateController' ,
} ) ;
this . currencyRateController = new CurrencyRateController ( {
2022-05-05 16:14:06 +02:00
includeUsdRate : true ,
2021-05-20 04:57:51 +02:00
messenger : currencyRateMessenger ,
2022-04-21 21:09:41 +02:00
state : {
... initState . CurrencyController ,
2023-05-02 17:53:20 +02:00
nativeCurrency :
this . networkController . store . getState ( ) . providerConfig . ticker ,
2022-04-21 21:09:41 +02:00
} ,
2021-05-20 04:57:51 +02:00
} ) ;
2017-02-03 08:32:24 +01:00
2023-01-18 16:44:19 +01:00
this . phishingController = new PhishingController (
{ } ,
initState . PhishingController ,
) ;
2023-02-24 16:09:00 +01:00
this . phishingController . maybeUpdateState ( ) ;
2023-01-18 16:44:19 +01:00
2022-10-25 06:54:02 +02:00
if ( process . env . IN _TEST ) {
2023-02-24 16:09:00 +01:00
this . phishingController . setHotlistRefreshInterval ( 5 * SECOND ) ;
this . phishingController . setStalelistRefreshInterval ( 30 * SECOND ) ;
2022-10-25 06:54:02 +02:00
}
2017-06-22 21:32:08 +02:00
2023-04-06 21:51:13 +02:00
const announcementMessenger = this . controllerMessenger . getRestricted ( {
name : 'AnnouncementController' ,
} ) ;
this . announcementController = new AnnouncementController ( {
messenger : announcementMessenger ,
allAnnouncements : UI _NOTIFICATIONS ,
state : initState . AnnouncementController ,
} ) ;
2021-04-28 18:51:41 +02:00
2021-09-15 21:02:28 +02:00
// token exchange rate tracker
2022-11-22 17:56:26 +01:00
this . tokenRatesController = new TokenRatesController (
{
onTokensStateChange : ( listener ) =>
this . tokensController . subscribe ( listener ) ,
onCurrencyRateStateChange : ( listener ) =>
this . controllerMessenger . subscribe (
` ${ this . currencyRateController . name } :stateChange ` ,
listener ,
) ,
onNetworkStateChange : ( cb ) =>
this . networkController . store . subscribe ( ( networkState ) => {
const modifiedNetworkState = {
... networkState ,
2023-01-17 16:23:04 +01:00
providerConfig : {
2023-05-02 17:53:20 +02:00
... networkState . providerConfig ,
chainId : hexToDecimal ( networkState . providerConfig . chainId ) ,
2022-11-22 17:56:26 +01:00
} ,
} ;
return cb ( modifiedNetworkState ) ;
} ) ,
} ,
2023-01-17 16:23:04 +01:00
{
disabled :
! this . preferencesController . store . getState ( ) . useCurrencyRateCheck ,
} ,
2022-11-22 17:56:26 +01:00
initState . TokenRatesController ,
) ;
2023-01-17 16:23:04 +01:00
this . preferencesController . store . subscribe (
previousValueComparator ( ( prevState , currState ) => {
const { useCurrencyRateCheck : prevUseCurrencyRateCheck } = prevState ;
const { useCurrencyRateCheck : currUseCurrencyRateCheck } = currState ;
if ( currUseCurrencyRateCheck && ! prevUseCurrencyRateCheck ) {
this . currencyRateController . start ( ) ;
this . tokenRatesController . configure (
{ disabled : false } ,
false ,
false ,
) ;
} else if ( ! currUseCurrencyRateCheck && prevUseCurrencyRateCheck ) {
this . currencyRateController . stop ( ) ;
this . tokenRatesController . configure ( { disabled : true } , false , false ) ;
}
} , this . preferencesController . store . getState ( ) ) ,
) ;
2018-04-16 17:21:06 +02:00
2019-11-01 18:54:00 +01:00
this . ensController = new EnsController ( {
provider : this . provider ,
2023-02-22 18:43:37 +01:00
getCurrentChainId : ( ) =>
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig . chainId ,
2023-03-30 20:39:36 +02:00
onNetworkDidChange : networkControllerMessenger . subscribe . bind (
networkControllerMessenger ,
2023-05-26 18:35:52 +02:00
'NetworkController:networkDidChange' ,
2021-02-25 12:40:57 +01:00
) ,
2021-02-04 19:15:23 +01:00
} ) ;
2019-11-01 18:54:00 +01:00
2022-12-02 18:59:03 +01:00
this . onboardingController = new OnboardingController ( {
initState : initState . OnboardingController ,
} ) ;
2019-08-16 20:54:10 +02:00
this . incomingTransactionsController = new IncomingTransactionsController ( {
blockTracker : this . blockTracker ,
2023-03-30 20:39:36 +02:00
onNetworkDidChange : networkControllerMessenger . subscribe . bind (
networkControllerMessenger ,
2023-05-26 18:35:52 +02:00
'NetworkController:networkDidChange' ,
2021-03-19 22:54:30 +01:00
) ,
2023-02-22 18:43:37 +01:00
getCurrentChainId : ( ) =>
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig . chainId ,
2019-08-16 20:54:10 +02:00
preferencesController : this . preferencesController ,
2022-12-02 18:59:03 +01:00
onboardingController : this . onboardingController ,
2019-08-16 20:54:10 +02:00
initState : initState . IncomingTransactionsController ,
2021-02-04 19:15:23 +01:00
} ) ;
2019-08-16 20:54:10 +02:00
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
// account tracker watches balances, nonces, and any code at their address
2017-09-22 23:16:19 +02:00
this . accountTracker = new AccountTracker ( {
2017-02-03 07:05:06 +01:00
provider : this . provider ,
2017-09-08 06:26:25 +02:00
blockTracker : this . blockTracker ,
2023-02-22 18:43:37 +01:00
getCurrentChainId : ( ) =>
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig . chainId ,
2023-02-22 18:43:37 +01:00
getNetworkIdentifier : ( ) => {
const { type , rpcUrl } =
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig ;
2023-02-22 18:43:37 +01:00
return type === NETWORK _TYPES . RPC ? rpcUrl : type ;
} ,
2022-12-01 22:16:04 +01:00
preferencesController : this . preferencesController ,
2022-12-02 18:59:03 +01:00
onboardingController : this . onboardingController ,
2023-04-06 16:43:01 +02:00
initState :
isManifestV3 &&
isFirstMetaMaskControllerSetup === false &&
initState . AccountTracker ? . accounts
? { accounts : initState . AccountTracker . accounts }
: { accounts : { } } ,
2021-02-04 19:15:23 +01:00
} ) ;
2018-09-28 08:45:16 +02:00
2018-08-22 01:49:24 +02:00
// start and stop polling for balances based on activeControllerConnections
this . on ( 'controllerConnectionChanged' , ( activeControllerConnections ) => {
2022-12-02 18:59:03 +01:00
const { completedOnboarding } =
this . onboardingController . store . getState ( ) ;
if ( activeControllerConnections > 0 && completedOnboarding ) {
this . triggerNetworkrequests ( ) ;
2018-08-22 01:49:24 +02:00
} else {
2022-12-02 18:59:03 +01:00
this . stopNetworkRequests ( ) ;
2018-08-22 01:49:24 +02:00
}
2021-02-04 19:15:23 +01:00
} ) ;
2018-10-26 10:26:43 +02:00
2022-12-02 18:59:03 +01:00
this . onboardingController . store . subscribe (
previousValueComparator ( async ( prevState , currState ) => {
const { completedOnboarding : prevCompletedOnboarding } = prevState ;
const { completedOnboarding : currCompletedOnboarding } = currState ;
if ( ! prevCompletedOnboarding && currCompletedOnboarding ) {
this . triggerNetworkrequests ( ) ;
}
} , this . onboardingController . store . getState ( ) ) ,
) ;
2018-11-30 23:51:24 +01:00
this . cachedBalancesController = new CachedBalancesController ( {
accountTracker : this . accountTracker ,
2023-02-22 18:43:37 +01:00
getCurrentChainId : ( ) =>
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig . chainId ,
2018-11-30 23:51:24 +01:00
initState : initState . CachedBalancesController ,
2021-02-04 19:15:23 +01:00
} ) ;
2018-11-30 23:51:24 +01:00
2023-01-25 22:12:08 +01:00
let additionalKeyrings = [ keyringBuilderFactory ( QRHardwareKeyring ) ] ;
if ( this . canUseHardwareWallets ( ) ) {
2023-02-20 18:13:12 +01:00
const keyringOverrides = this . opts . overrides ? . keyrings ;
2023-01-21 00:03:11 +01:00
const additionalKeyringTypes = [
2023-02-20 18:13:12 +01:00
keyringOverrides ? . trezor || TrezorKeyring ,
keyringOverrides ? . ledger || LedgerBridgeKeyring ,
keyringOverrides ? . lattice || LatticeKeyring ,
2022-11-29 18:04:11 +01:00
QRHardwareKeyring ,
] ;
2023-05-29 17:38:28 +02:00
2023-01-21 00:03:11 +01:00
additionalKeyrings = additionalKeyringTypes . map ( ( keyringType ) =>
keyringBuilderFactory ( keyringType ) ,
) ;
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
for ( const custodianType of Object . keys ( CUSTODIAN _TYPES ) ) {
additionalKeyrings . push (
mmiKeyringBuilderFactory (
CUSTODIAN _TYPES [ custodianType ] . keyringClass ,
{ mmiConfigurationController : this . mmiConfigurationController } ,
) ,
) ;
}
///: END:ONLY_INCLUDE_IN
2022-11-29 18:04:11 +01:00
}
2023-01-21 00:03:11 +01:00
2016-10-21 04:01:04 +02:00
this . keyringController = new KeyringController ( {
2023-01-21 00:03:11 +01:00
keyringBuilders : additionalKeyrings ,
2017-01-28 22:12:12 +01:00
initState : initState . KeyringController ,
2017-09-22 22:25:08 +02:00
encryptor : opts . encryptor || undefined ,
2022-11-24 01:49:24 +01:00
cacheEncryptionKey : isManifestV3 ,
2021-02-04 19:15:23 +01:00
} ) ;
2023-01-25 22:12:08 +01:00
2020-12-08 20:48:47 +01:00
this . keyringController . memStore . subscribe ( ( state ) =>
this . _onKeyringControllerUpdate ( state ) ,
2021-02-04 19:15:23 +01:00
) ;
2023-03-31 15:22:33 +02:00
2021-10-14 19:50:07 +02:00
this . keyringController . on ( 'unlock' , ( ) => this . _onUnlock ( ) ) ;
2021-02-04 19:15:23 +01:00
this . keyringController . on ( 'lock' , ( ) => this . _onLock ( ) ) ;
2017-01-27 00:09:31 +01:00
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
const getIdentities = ( ) =>
this . preferencesController . store . getState ( ) . identities ;
this . permissionController = new PermissionController ( {
messenger : this . controllerMessenger . getRestricted ( {
name : 'PermissionController' ,
allowedActions : [
` ${ this . approvalController . name } :addRequest ` ,
` ${ this . approvalController . name } :hasRequest ` ,
` ${ this . approvalController . name } :acceptRequest ` ,
` ${ this . approvalController . name } :rejectRequest ` ,
2023-03-30 23:57:28 +02:00
` SnapController:getPermitted ` ,
` SnapController:install ` ,
2023-05-15 19:36:24 +02:00
` SubjectMetadataController:getSubjectMetadata ` ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
] ,
} ) ,
state : initState . PermissionController ,
caveatSpecifications : getCaveatSpecifications ( { getIdentities } ) ,
2022-02-15 01:02:51 +01:00
permissionSpecifications : {
... getPermissionSpecifications ( {
getIdentities ,
getAllAccounts : this . keyringController . getAccounts . bind (
this . keyringController ,
) ,
captureKeyringTypesWithMissingIdentities : (
identities = { } ,
accounts = [ ] ,
) => {
const accountsMissingIdentities = accounts . filter (
( address ) => ! identities [ address ] ,
) ;
2022-07-31 20:26:40 +02:00
const keyringTypesWithMissingIdentities =
accountsMissingIdentities . map (
( address ) =>
this . keyringController . getKeyringForAccount ( address ) ? . type ,
) ;
2022-02-07 20:00:37 +01:00
2022-02-15 01:02:51 +01:00
const identitiesCount = Object . keys ( identities || { } ) . length ;
2022-02-07 20:00:37 +01:00
2022-02-15 01:02:51 +01:00
const accountTrackerCount = Object . keys (
this . accountTracker . store . getState ( ) . accounts || { } ,
) . length ;
2022-02-07 20:00:37 +01:00
2022-02-15 01:02:51 +01:00
captureException (
new Error (
` Attempt to get permission specifications failed because their were ${ accounts . length } accounts, but ${ identitiesCount } identities, and the ${ keyringTypesWithMissingIdentities } keyrings included accounts with missing identities. Meanwhile, there are ${ accountTrackerCount } accounts in the account tracker. ` ,
) ,
) ;
} ,
} ) ,
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-02-15 01:02:51 +01:00
... this . getSnapPermissionSpecifications ( ) ,
///: END:ONLY_INCLUDE_IN
} ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
unrestrictedMethods ,
} ) ;
this . permissionLogController = new PermissionLogController ( {
restrictedMethods : new Set ( Object . keys ( RestrictedMethods ) ) ,
initState : initState . PermissionLogController ,
} ) ;
this . subjectMetadataController = new SubjectMetadataController ( {
messenger : this . controllerMessenger . getRestricted ( {
name : 'SubjectMetadataController' ,
allowedActions : [ ` ${ this . permissionController . name } :hasPermissions ` ] ,
} ) ,
state : initState . SubjectMetadataController ,
subjectCacheLimit : 100 ,
} ) ;
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
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2023-02-20 18:13:12 +01:00
const snapExecutionServiceArgs = {
2023-05-15 19:36:24 +02:00
iframeUrl : new URL ( process . env . IFRAME _EXECUTION _ENVIRONMENT _URL ) ,
2022-02-15 01:02:51 +01:00
messenger : this . controllerMessenger . getRestricted ( {
name : 'ExecutionService' ,
} ) ,
setupSnapProvider : this . setupSnapProvider . bind ( this ) ,
2023-02-20 18:13:12 +01:00
} ;
this . snapExecutionService =
this . opts . overrides ? . createSnapExecutionService ? . (
snapExecutionServiceArgs ,
) || new IframeExecutionService ( snapExecutionServiceArgs ) ;
2022-02-15 01:02:51 +01:00
const snapControllerMessenger = this . controllerMessenger . getRestricted ( {
name : 'SnapController' ,
allowedEvents : [
'ExecutionService:unhandledError' ,
2022-07-19 17:41:06 +02:00
'ExecutionService:outboundRequest' ,
'ExecutionService:outboundResponse' ,
2022-02-15 01:02:51 +01:00
] ,
allowedActions : [
` ${ this . permissionController . name } :getEndowments ` ,
` ${ this . permissionController . name } :getPermissions ` ,
` ${ this . permissionController . name } :hasPermission ` ,
2022-03-14 20:37:19 +01:00
` ${ this . permissionController . name } :hasPermissions ` ,
2022-02-15 01:02:51 +01:00
` ${ this . permissionController . name } :requestPermissions ` ,
` ${ this . permissionController . name } :revokeAllPermissions ` ,
2022-08-03 18:02:44 +02:00
` ${ this . permissionController . name } :revokePermissions ` ,
2022-04-28 18:17:28 +02:00
` ${ this . permissionController . name } :revokePermissionForAllSubjects ` ,
2023-03-08 19:29:23 +01:00
` ${ this . permissionController . name } :getSubjectNames ` ,
` ${ this . permissionController . name } :updateCaveat ` ,
2022-08-03 18:02:44 +02:00
` ${ this . approvalController . name } :addRequest ` ,
2023-03-17 12:00:05 +01:00
` ${ this . approvalController . name } :updateRequestState ` ,
2022-08-03 18:02:44 +02:00
` ${ this . permissionController . name } :grantPermissions ` ,
2022-11-30 13:19:33 +01:00
` ${ this . subjectMetadataController . name } :getSubjectMetadata ` ,
2022-07-19 17:41:06 +02:00
'ExecutionService:executeSnap' ,
'ExecutionService:getRpcRequestHandler' ,
'ExecutionService:terminateSnap' ,
'ExecutionService:terminateAllSnaps' ,
2022-08-18 17:07:34 +02:00
'ExecutionService:handleRpcRequest' ,
2023-03-30 23:57:28 +02:00
'SnapsRegistry:get' ,
'SnapsRegistry:getMetadata' ,
2022-02-15 01:02:51 +01:00
] ,
} ) ;
2023-04-25 16:32:51 +02:00
const allowLocalSnaps = process . env . ALLOW _LOCAL _SNAPS ;
const requireAllowlist = process . env . REQUIRE _SNAPS _ALLOWLIST ;
2022-02-15 01:02:51 +01:00
this . snapController = new SnapController ( {
2022-05-18 13:49:26 +02:00
environmentEndowmentPermissions : Object . values ( EndowmentPermissions ) ,
2023-02-15 11:09:47 +01:00
excludedPermissions : {
... ExcludedSnapPermissions ,
... ExcludedSnapEndowments ,
} ,
2022-02-15 01:02:51 +01:00
closeAllConnections : this . removeAllConnections . bind ( this ) ,
state : initState . SnapController ,
messenger : snapControllerMessenger ,
2023-01-23 20:41:04 +01:00
featureFlags : {
dappsCanUpdateSnaps : true ,
2023-04-25 16:32:51 +02:00
allowLocalSnaps ,
requireAllowlist ,
2023-01-23 20:41:04 +01:00
} ,
2022-02-15 01:02:51 +01:00
} ) ;
2022-03-17 17:43:18 +01:00
2022-06-01 19:09:13 +02:00
this . notificationController = new NotificationController ( {
messenger : this . controllerMessenger . getRestricted ( {
name : 'NotificationController' ,
} ) ,
state : initState . NotificationController ,
} ) ;
2022-03-17 17:43:18 +01:00
this . rateLimitController = new RateLimitController ( {
2022-11-22 17:56:26 +01:00
state : initState . RateLimitController ,
2022-03-17 17:43:18 +01:00
messenger : this . controllerMessenger . getRestricted ( {
name : 'RateLimitController' ,
} ) ,
implementations : {
showNativeNotification : ( origin , message ) => {
const subjectMetadataState = this . controllerMessenger . call (
'SubjectMetadataController:getState' ,
) ;
const originMetadata = subjectMetadataState . subjectMetadata [ origin ] ;
2023-03-29 13:19:50 +02:00
this . platform
. _showNotification ( originMetadata ? . name ? ? origin , message )
. catch ( ( error ) => {
log . error ( 'Failed to create notification' , error ) ;
} ) ;
2022-03-17 17:43:18 +01:00
return null ;
} ,
2022-06-01 19:09:13 +02:00
showInAppNotification : ( origin , message ) => {
this . controllerMessenger . call (
'NotificationController:show' ,
origin ,
message ,
) ;
return null ;
} ,
2022-03-17 17:43:18 +01:00
} ,
} ) ;
2022-11-09 13:18:47 +01:00
const cronjobControllerMessenger = this . controllerMessenger . getRestricted ( {
name : 'CronjobController' ,
allowedEvents : [
'SnapController:snapInstalled' ,
'SnapController:snapUpdated' ,
'SnapController:snapRemoved' ,
] ,
allowedActions : [
` ${ this . permissionController . name } :getPermissions ` ,
'SnapController:handleRequest' ,
'SnapController:getAll' ,
] ,
} ) ;
this . cronjobController = new CronjobController ( {
state : initState . CronjobController ,
messenger : cronjobControllerMessenger ,
} ) ;
2023-03-06 20:35:00 +01:00
2023-03-30 23:57:28 +02:00
const snapsRegistryMessenger = this . controllerMessenger . getRestricted ( {
name : 'SnapsRegistry' ,
allowedEvents : [ ] ,
allowedActions : [ ] ,
} ) ;
this . snapsRegistry = new JsonSnapsRegistry ( {
state : initState . SnapsRegistry ,
messenger : snapsRegistryMessenger ,
2023-04-25 16:32:51 +02:00
refetchOnAllowlistMiss : requireAllowlist ,
failOnUnavailableRegistry : requireAllowlist ,
2023-03-30 23:57:28 +02:00
url : {
registry : 'https://acl.execution.metamask.io/latest/registry.json' ,
signature : 'https://acl.execution.metamask.io/latest/signature.json' ,
} ,
publicKey :
'0x025b65308f0f0fb8bc7f7ff87bfc296e0330eee5d3c1d1ee4a048b2fd6a86fa0a6' ,
} ) ;
2023-04-25 16:32:51 +02:00
///: END:ONLY_INCLUDE_IN
///: BEGIN:ONLY_INCLUDE_IN(desktop)
2023-03-06 20:35:00 +01:00
this . desktopController = new DesktopController ( {
initState : initState . DesktopController ,
} ) ;
2022-02-15 01:02:51 +01:00
///: END:ONLY_INCLUDE_IN
2023-02-20 18:13:12 +01:00
2022-08-10 03:26:25 +02:00
this . detectTokensController = new DetectTokensController ( {
preferences : this . preferencesController ,
tokensController : this . tokensController ,
assetsContractController : this . assetsContractController ,
network : this . networkController ,
keyringMemStore : this . keyringController . memStore ,
tokenList : this . tokenListController ,
trackMetaMetricsEvent : this . metaMetricsController . trackEvent . bind (
this . metaMetricsController ,
) ,
} ) ;
2018-07-20 01:46:46 +02:00
2020-11-03 00:41:28 +01:00
this . addressBookController = new AddressBookController (
undefined ,
initState . AddressBookController ,
2021-02-04 19:15:23 +01:00
) ;
2017-03-10 19:34:46 +01:00
2020-05-12 15:01:52 +02:00
this . alertController = new AlertController ( {
initState : initState . AlertController ,
preferencesStore : this . preferencesController . store ,
2021-02-04 19:15:23 +01:00
} ) ;
2020-05-08 21:45:52 +02:00
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
this . custodyController = new CustodyController ( {
initState : initState . CustodyController ,
} ) ;
this . institutionalFeaturesController = new InstitutionalFeaturesController ( {
initState : initState . InstitutionalFeaturesController ,
showConfirmRequest : opts . showUserConfirmation ,
} ) ;
this . transactionUpdateController = new TransactionUpdateController ( {
initState : initState . TransactionUpdateController ,
getCustodyKeyring : this . getCustodyKeyringIfExists . bind ( this ) ,
mmiConfigurationController : this . mmiConfigurationController ,
captureException ,
} ) ;
///: END:ONLY_INCLUDE_IN
2022-08-09 20:36:32 +02:00
this . backupController = new BackupController ( {
preferencesController : this . preferencesController ,
addressBookController : this . addressBookController ,
2023-03-09 22:00:28 +01:00
networkController : this . networkController ,
2022-08-09 20:36:32 +02:00
trackMetaMetricsEvent : this . metaMetricsController . trackEvent . bind (
this . metaMetricsController ,
) ,
} ) ;
2017-05-16 19:27:41 +02:00
this . txController = new TransactionController ( {
2020-11-03 00:41:28 +01:00
initState :
initState . TransactionController || initState . TransactionManager ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
getPermittedAccounts : this . getPermittedAccounts . bind ( this ) ,
2023-05-02 17:53:20 +02:00
getProviderConfig : ( ) =>
this . networkController . store . getState ( ) . providerConfig ,
2022-07-31 20:26:40 +02:00
getCurrentNetworkEIP1559Compatibility :
this . networkController . getEIP1559Compatibility . bind (
this . networkController ,
) ,
getCurrentAccountEIP1559Compatibility :
this . getCurrentAccountEIP1559Compatibility . bind ( this ) ,
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556)
The `network` store of the network controller crams two types of data
into one place. It roughly tracks whether we have enough information to
make requests to the network and whether the network is capable of
receiving requests, but it also stores the ID of the network (as
obtained via `net_version`).
Generally we shouldn't be using the network ID for anything, as it has
been completely replaced by chain ID, which all custom RPC endpoints
have been required to support for over a year now. However, as the
network ID is used in various places within the extension codebase,
removing it entirely would be a non-trivial effort. So, minimally, this
commit splits `network` into two stores: `networkId` and
`networkStatus`. But it also expands the concept of network status.
Previously, the network was in one of two states: "loading" and
"not-loading". But now it can be in one of four states:
- `available`: The network is able to receive and respond to requests.
- `unavailable`: The network is not able to receive and respond to
requests for unknown reasons.
- `blocked`: The network is actively blocking requests based on the
user's geolocation. (This is specific to Infura.)
- `unknown`: We don't know whether the network can receive and respond
to requests, either because we haven't checked or we tried to check
and were unsuccessful.
This commit also changes how the network status is determined —
specifically, how many requests are used to determine that status, when
they occur, and whether they are awaited. Previously, the network
controller would make 2 to 3 requests during the course of running
`lookupNetwork`.
* First, if it was an Infura network, it would make a request for
`eth_blockNumber` to determine whether Infura was blocking requests or
not, then emit an appropriate event. This operation was not awaited.
* Then, regardless of the network, it would fetch the network ID via
`net_version`. This operation was awaited.
* Finally, regardless of the network, it would fetch the latest block
via `eth_getBlockByNumber`, then use the result to determine whether
the network supported EIP-1559. This operation was awaited.
Now:
* One fewer request is made, specifically `eth_blockNumber`, as we don't
need to make an extra request to determine whether Infura is blocking
requests; we can reuse `eth_getBlockByNumber`;
* All requests are awaited, which makes `lookupNetwork` run fully
in-band instead of partially out-of-band; and
* Both requests for `net_version` and `eth_getBlockByNumber` are
performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
getNetworkId : ( ) => this . networkController . store . getState ( ) . networkId ,
getNetworkStatus : ( ) =>
this . networkController . store . getState ( ) . networkStatus ,
2023-04-17 17:54:13 +02:00
onNetworkStateChange : ( listener ) => {
let previousNetworkId =
this . networkController . store . getState ( ) . networkId ;
this . networkController . store . subscribe ( ( state ) => {
if ( previousNetworkId !== state . networkId ) {
listener ( ) ;
previousNetworkId = state . networkId ;
}
} ) ;
} ,
2023-02-22 18:43:37 +01:00
getCurrentChainId : ( ) =>
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig . chainId ,
2017-02-03 06:09:17 +01:00
preferencesStore : this . preferencesController . store ,
2022-02-24 17:51:33 +01:00
txHistoryLimit : 60 ,
2020-11-03 00:41:28 +01:00
signTransaction : this . keyringController . signTransaction . bind (
this . keyringController ,
) ,
2016-12-16 19:33:36 +01:00
provider : this . provider ,
2017-09-08 06:26:25 +02:00
blockTracker : this . blockTracker ,
2022-01-20 17:26:39 +01:00
createEventFragment : this . metaMetricsController . createEventFragment . bind (
this . metaMetricsController ,
) ,
updateEventFragment : this . metaMetricsController . updateEventFragment . bind (
this . metaMetricsController ,
) ,
2022-07-31 20:26:40 +02:00
finalizeEventFragment :
this . metaMetricsController . finalizeEventFragment . bind (
this . metaMetricsController ,
) ,
getEventFragmentById :
this . metaMetricsController . getEventFragmentById . bind (
this . metaMetricsController ,
) ,
2020-12-08 17:10:55 +01:00
trackMetaMetricsEvent : this . metaMetricsController . trackEvent . bind (
this . metaMetricsController ,
) ,
2020-11-03 00:41:28 +01:00
getParticipateInMetrics : ( ) =>
2020-12-02 22:41:30 +01:00
this . metaMetricsController . state . participateInMetaMetrics ,
2022-07-31 20:26:40 +02:00
getEIP1559GasFeeEstimates :
this . gasFeeController . fetchGasFeeEstimates . bind ( this . gasFeeController ) ,
getExternalPendingTransactions :
this . getExternalPendingTransactions . bind ( this ) ,
2022-02-23 16:15:41 +01:00
getAccountType : this . getAccountType . bind ( this ) ,
getDeviceModel : this . getDeviceModel . bind ( this ) ,
2023-03-08 18:35:45 +01:00
getTokenStandardAndDetails : this . getTokenStandardAndDetails . bind ( this ) ,
2023-01-23 15:32:01 +01:00
securityProviderRequest : this . securityProviderRequest . bind ( this ) ,
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
transactionUpdateController : this . transactionUpdateController ,
///: END:ONLY_INCLUDE_IN
2023-04-11 15:18:43 +02:00
messenger : this . controllerMessenger . getRestricted ( {
name : 'TransactionController' ,
allowedActions : [
` ${ this . approvalController . name } :addRequest ` ,
` ${ this . approvalController . name } :acceptRequest ` ,
` ${ this . approvalController . name } :rejectRequest ` ,
] ,
} ) ,
2021-02-04 19:15:23 +01:00
} ) ;
2017-01-28 01:11:59 +01:00
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
this . mmiController = new MMIController ( {
mmiConfigurationController : this . mmiConfigurationController ,
keyringController : this . keyringController ,
txController : this . txController ,
securityProviderRequest : this . securityProviderRequest . bind ( this ) ,
preferencesController : this . preferencesController ,
appStateController : this . appStateController ,
transactionUpdateController : this . transactionUpdateController ,
custodyController : this . custodyController ,
institutionalFeaturesController : this . institutionalFeaturesController ,
getState : this . getState . bind ( this ) ,
getPendingNonce : this . getPendingNonce . bind ( this ) ,
accountTracker : this . accountTracker ,
metaMetricsController : this . metaMetricsController ,
networkController : this . networkController ,
permissionController : this . permissionController ,
platform : this . platform ,
extension : this . extension ,
} ) ;
///: END:ONLY_INCLUDE_IN
2019-04-29 08:18:40 +02:00
this . txController . on ( ` tx:status-update ` , async ( txId , status ) => {
2020-11-07 08:38:12 +01:00
if (
2023-01-18 15:47:29 +01:00
status === TransactionStatus . confirmed ||
status === TransactionStatus . failed
2020-11-07 08:38:12 +01:00
) {
2021-03-30 16:54:05 +02:00
const txMeta = this . txController . txStateManager . getTransaction ( txId ) ;
2021-03-09 22:37:19 +01:00
let rpcPrefs = { } ;
if ( txMeta . chainId ) {
2023-03-09 22:00:28 +01:00
const { networkConfigurations } =
this . networkController . store . getState ( ) ;
const matchingNetworkConfig = Object . values (
networkConfigurations ,
) . find (
( networkConfiguration ) =>
networkConfiguration . chainId === txMeta . chainId ,
2021-03-09 22:37:19 +01:00
) ;
2023-03-09 22:00:28 +01:00
rpcPrefs = matchingNetworkConfig ? . rpcPrefs ? ? { } ;
2021-03-09 22:37:19 +01:00
}
2023-03-29 13:19:50 +02:00
try {
await this . platform . showTransactionNotification ( txMeta , rpcPrefs ) ;
} catch ( error ) {
log . error ( 'Failed to create transaction notification' , error ) ;
}
2019-04-29 08:18:40 +02:00
2021-02-04 19:15:23 +01:00
const { txReceipt } = txMeta ;
2022-01-10 17:23:53 +01:00
2023-02-16 20:23:29 +01:00
// if this is a transferFrom method generated from within the app it may be an NFT transfer transaction
// in which case we will want to check and update ownership status of the transferred NFT.
2022-01-10 17:23:53 +01:00
if (
2023-01-18 15:47:29 +01:00
txMeta . type === TransactionType . tokenMethodTransferFrom &&
2022-01-10 17:23:53 +01:00
txMeta . txParams !== undefined
) {
const {
data ,
to : contractAddress ,
from : userAddress ,
} = txMeta . txParams ;
const { chainId } = txMeta ;
2022-03-17 19:35:40 +01:00
const transactionData = parseStandardTokenTransactionData ( data ) ;
2022-07-23 16:37:31 +02:00
// Sometimes the tokenId value is parsed as "_value" param. Not seeing this often any more, but still occasionally:
// i.e. call approve() on BAYC contract - https://etherscan.io/token/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#writeContract, and tokenId shows up as _value,
// not sure why since it doesn't match the ERC721 ABI spec we use to parse these transactions - https://github.com/MetaMask/metamask-eth-abis/blob/d0474308a288f9252597b7c93a3a8deaad19e1b2/src/abis/abiERC721.ts#L62.
const transactionDataTokenId =
getTokenIdParam ( transactionData ) ? ?
getTokenValueParam ( transactionData ) ;
2022-11-15 19:49:42 +01:00
const { allNfts } = this . nftController . state ;
2022-01-10 17:23:53 +01:00
2023-01-25 17:33:06 +01:00
const chainIdAsDecimal = hexToDecimal ( chainId ) ;
2023-02-16 20:23:29 +01:00
// check if its a known NFT
const knownNft = allNfts ? . [ userAddress ] ? . [ chainIdAsDecimal ] ? . find (
2022-01-10 17:23:53 +01:00
( { address , tokenId } ) =>
isEqualCaseInsensitive ( address , contractAddress ) &&
2022-07-23 16:37:31 +02:00
tokenId === transactionDataTokenId ,
2022-01-10 17:23:53 +01:00
) ;
// if it is we check and update ownership status.
2023-02-16 20:23:29 +01:00
if ( knownNft ) {
2022-11-15 19:49:42 +01:00
this . nftController . checkAndUpdateSingleNftOwnershipStatus (
2023-02-16 20:23:29 +01:00
knownNft ,
2022-01-10 17:23:53 +01:00
false ,
2023-01-25 17:33:06 +01:00
{ userAddress , chainId : chainIdAsDecimal } ,
2022-01-10 17:23:53 +01:00
) ;
}
}
2022-11-16 15:52:35 +01:00
const metamaskState = this . getState ( ) ;
2021-03-12 23:23:26 +01:00
2020-08-07 21:28:23 +02:00
if ( txReceipt && txReceipt . status === '0x0' ) {
2021-03-12 23:23:26 +01:00
this . metaMetricsController . trackEvent (
{
2021-05-24 21:02:26 +02:00
event : 'Tx Status Update: On-Chain Failure' ,
2023-04-03 17:31:04 +02:00
category : MetaMetricsEventCategory . Background ,
2021-03-12 23:23:26 +01:00
properties : {
action : 'Transactions' ,
errorMessage : txMeta . simulationFails ? . reason ,
numberOfTokens : metamaskState . tokens . length ,
numberOfAccounts : Object . keys ( metamaskState . accounts ) . length ,
} ,
} ,
{
matomoEvent : true ,
} ,
) ;
2019-04-29 08:18:40 +02:00
}
2018-07-20 13:20:40 +02:00
}
2021-02-04 19:15:23 +01:00
} ) ;
2018-07-20 13:20:40 +02:00
2023-03-30 20:39:36 +02:00
networkControllerMessenger . subscribe (
2023-05-26 18:35:52 +02:00
'NetworkController:networkDidChange' ,
2023-03-30 20:39:36 +02:00
async ( ) => {
2023-05-02 17:53:20 +02:00
const { ticker } =
this . networkController . store . getState ( ) . providerConfig ;
2023-03-30 20:39:36 +02:00
try {
await this . currencyRateController . setNativeCurrency ( ticker ) ;
} catch ( error ) {
// TODO: Handle failure to get conversion rate more gracefully
console . error ( error ) ;
}
} ,
) ;
2021-11-26 21:03:35 +01:00
2021-02-04 19:15:23 +01:00
this . networkController . lookupNetwork ( ) ;
2023-04-26 17:02:33 +02:00
this . decryptMessageController = new DecryptMessageController ( {
getState : this . getState . bind ( this ) ,
keyringController : this . keyringController ,
messenger : this . controllerMessenger . getRestricted ( {
name : 'DecryptMessageController' ,
allowedActions : [
` ${ this . approvalController . name } :addRequest ` ,
` ${ this . approvalController . name } :acceptRequest ` ,
` ${ this . approvalController . name } :rejectRequest ` ,
] ,
} ) ,
2021-11-15 17:13:51 +01:00
metricsEvent : this . metaMetricsController . trackEvent . bind (
this . metaMetricsController ,
) ,
} ) ;
2023-04-13 10:24:59 +02:00
this . encryptionPublicKeyController = new EncryptionPublicKeyController ( {
messenger : this . controllerMessenger . getRestricted ( {
name : 'EncryptionPublicKeyController' ,
allowedActions : [
` ${ this . approvalController . name } :addRequest ` ,
` ${ this . approvalController . name } :acceptRequest ` ,
` ${ this . approvalController . name } :rejectRequest ` ,
] ,
} ) ,
keyringController : this . keyringController ,
getState : this . getState . bind ( this ) ,
2021-11-15 17:13:51 +01:00
metricsEvent : this . metaMetricsController . trackEvent . bind (
this . metaMetricsController ,
) ,
} ) ;
2023-03-20 14:19:50 +01:00
2023-05-05 14:05:52 +02:00
this . signatureController = new SignatureController ( {
2023-03-20 14:19:50 +01:00
messenger : this . controllerMessenger . getRestricted ( {
2023-05-05 14:05:52 +02:00
name : 'SignatureController' ,
2023-03-20 14:19:50 +01:00
allowedActions : [
` ${ this . approvalController . name } :addRequest ` ,
` ${ this . approvalController . name } :acceptRequest ` ,
` ${ this . approvalController . name } :rejectRequest ` ,
] ,
} ) ,
keyringController : this . keyringController ,
2023-05-05 14:05:52 +02:00
isEthSignEnabled : ( ) =>
this . preferencesController . store . getState ( )
? . disabledRpcMethodPreferences ? . eth _sign ,
getAllState : this . getState . bind ( this ) ,
2023-01-23 15:32:01 +01:00
securityProviderRequest : this . securityProviderRequest . bind ( this ) ,
2023-05-11 10:22:42 +02:00
getCurrentChainId : ( ) =>
this . networkController . store . getState ( ) . providerConfig . chainId ,
2023-05-05 14:05:52 +02:00
} ) ;
2023-05-25 15:10:45 +02:00
this . signatureController . hub . on (
'cancelWithReason' ,
( { message , reason } ) => {
this . metaMetricsController . trackEvent ( {
event : reason ,
category : MetaMetricsEventCategory . Transactions ,
properties : {
action : 'Sign Request' ,
type : message . type ,
} ,
} ) ;
} ,
) ;
2019-05-03 19:32:05 +02:00
2020-10-06 20:28:38 +02:00
this . swapsController = new SwapsController ( {
2020-11-03 00:41:28 +01:00
getBufferedGasLimit : this . txController . txGasUtil . getBufferedGasLimit . bind (
this . txController . txGasUtil ,
) ,
2020-10-28 19:47:32 +01:00
networkController : this . networkController ,
2023-04-19 22:45:26 +02:00
onNetworkStateChange : ( listener ) =>
this . networkController . store . subscribe ( listener ) ,
2020-10-06 20:28:38 +02:00
provider : this . provider ,
2023-05-02 17:53:20 +02:00
getProviderConfig : ( ) =>
this . networkController . store . getState ( ) . providerConfig ,
2021-11-22 13:04:31 +01:00
getTokenRatesState : ( ) => this . tokenRatesController . state ,
2023-02-22 18:43:37 +01:00
getCurrentChainId : ( ) =>
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig . chainId ,
2022-07-31 20:26:40 +02:00
getEIP1559GasFeeEstimates :
this . gasFeeController . fetchGasFeeEstimates . bind ( this . gasFeeController ) ,
2021-02-04 19:15:23 +01:00
} ) ;
2022-03-04 21:20:18 +01:00
this . smartTransactionsController = new SmartTransactionsController (
{
2023-01-12 19:57:01 +01:00
onNetworkStateChange : ( cb ) => {
this . networkController . store . subscribe ( ( networkState ) => {
const modifiedNetworkState = {
... networkState ,
providerConfig : {
2023-05-02 17:53:20 +02:00
... networkState . providerConfig ,
2023-01-12 19:57:01 +01:00
} ,
} ;
return cb ( modifiedNetworkState ) ;
} ) ;
} ,
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556)
The `network` store of the network controller crams two types of data
into one place. It roughly tracks whether we have enough information to
make requests to the network and whether the network is capable of
receiving requests, but it also stores the ID of the network (as
obtained via `net_version`).
Generally we shouldn't be using the network ID for anything, as it has
been completely replaced by chain ID, which all custom RPC endpoints
have been required to support for over a year now. However, as the
network ID is used in various places within the extension codebase,
removing it entirely would be a non-trivial effort. So, minimally, this
commit splits `network` into two stores: `networkId` and
`networkStatus`. But it also expands the concept of network status.
Previously, the network was in one of two states: "loading" and
"not-loading". But now it can be in one of four states:
- `available`: The network is able to receive and respond to requests.
- `unavailable`: The network is not able to receive and respond to
requests for unknown reasons.
- `blocked`: The network is actively blocking requests based on the
user's geolocation. (This is specific to Infura.)
- `unknown`: We don't know whether the network can receive and respond
to requests, either because we haven't checked or we tried to check
and were unsuccessful.
This commit also changes how the network status is determined —
specifically, how many requests are used to determine that status, when
they occur, and whether they are awaited. Previously, the network
controller would make 2 to 3 requests during the course of running
`lookupNetwork`.
* First, if it was an Infura network, it would make a request for
`eth_blockNumber` to determine whether Infura was blocking requests or
not, then emit an appropriate event. This operation was not awaited.
* Then, regardless of the network, it would fetch the network ID via
`net_version`. This operation was awaited.
* Finally, regardless of the network, it would fetch the latest block
via `eth_getBlockByNumber`, then use the result to determine whether
the network supported EIP-1559. This operation was awaited.
Now:
* One fewer request is made, specifically `eth_blockNumber`, as we don't
need to make an extra request to determine whether Infura is blocking
requests; we can reuse `eth_getBlockByNumber`;
* All requests are awaited, which makes `lookupNetwork` run fully
in-band instead of partially out-of-band; and
* Both requests for `net_version` and `eth_getBlockByNumber` are
performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
getNetwork : ( ) =>
this . networkController . store . getState ( ) . networkId ? ? 'loading' ,
2022-03-04 21:20:18 +01:00
getNonceLock : this . txController . nonceTracker . getNonceLock . bind (
this . txController . nonceTracker ,
) ,
2022-07-31 20:26:40 +02:00
confirmExternalTransaction :
this . txController . confirmExternalTransaction . bind ( this . txController ) ,
2022-03-04 21:20:18 +01:00
provider : this . provider ,
trackMetaMetricsEvent : this . metaMetricsController . trackEvent . bind (
this . metaMetricsController ,
) ,
} ,
2022-11-16 15:02:57 +01:00
{
supportedChainIds : [ CHAIN _IDS . MAINNET , CHAIN _IDS . GOERLI ] ,
} ,
2022-03-04 21:20:18 +01:00
initState . SmartTransactionsController ,
) ;
2020-10-06 20:28:38 +02:00
2021-02-09 00:22:30 +01:00
// ensure accountTracker updates balances after network change
2023-03-30 20:39:36 +02:00
networkControllerMessenger . subscribe (
2023-05-26 18:35:52 +02:00
'NetworkController:networkDidChange' ,
2023-03-30 20:39:36 +02:00
( ) => {
this . accountTracker . _updateAccounts ( ) ;
} ,
) ;
2021-02-09 00:22:30 +01:00
// clear unapproved transactions and messages when the network will change
2023-03-30 20:39:36 +02:00
networkControllerMessenger . subscribe (
2023-05-26 18:35:52 +02:00
'NetworkController:networkWillChange' ,
2023-03-30 20:39:36 +02:00
( ) => {
this . txController . txStateManager . clearUnapprovedTxs ( ) ;
2023-04-13 10:24:59 +02:00
this . encryptionPublicKeyController . clearUnapproved ( ) ;
2023-04-26 17:02:33 +02:00
this . decryptMessageController . clearUnapproved ( ) ;
2023-05-05 14:05:52 +02:00
this . signatureController . clearUnapproved ( ) ;
2023-03-30 20:39:36 +02:00
} ,
) ;
2021-02-09 00:22:30 +01:00
2023-05-04 08:38:09 +02:00
if ( isManifestV3 && globalThis . isFirstTimeProfileLoaded === undefined ) {
2023-03-31 15:22:33 +02:00
const { serviceWorkerLastActiveTime } =
this . appStateController . store . getState ( ) ;
const metametricsPayload = {
2023-04-03 17:31:04 +02:00
category : MetaMetricsEventCategory . ServiceWorkers ,
event : MetaMetricsEventName . ServiceWorkerRestarted ,
2023-03-31 15:22:33 +02:00
properties : {
service _worker _restarted _time :
Date . now ( ) - serviceWorkerLastActiveTime ,
} ,
} ;
try {
this . metaMetricsController . trackEvent ( metametricsPayload ) ;
} catch ( e ) {
log . warn ( 'Failed to track service worker restart metric:' , e ) ;
}
}
2023-01-06 18:14:50 +01:00
this . metamaskMiddleware = createMetamaskMiddleware ( {
static : {
eth _syncing : false ,
web3 _clientVersion : ` MetaMask/v ${ version } ` ,
} ,
version ,
// account mgmt
getAccounts : async (
{ origin : innerOrigin } ,
{ suppressUnauthorizedError = true } = { } ,
) => {
if ( innerOrigin === ORIGIN _METAMASK ) {
const selectedAddress =
this . preferencesController . getSelectedAddress ( ) ;
return selectedAddress ? [ selectedAddress ] : [ ] ;
} else if ( this . isUnlocked ( ) ) {
return await this . getPermittedAccounts ( innerOrigin , {
suppressUnauthorizedError ,
} ) ;
}
return [ ] ; // changing this is a breaking change
} ,
// tx signing
processTransaction : this . newUnapprovedTransaction . bind ( this ) ,
// msg signing
2023-05-05 14:05:52 +02:00
processEthSignMessage : this . signatureController . newUnsignedMessage . bind (
this . signatureController ,
2023-03-20 14:19:50 +01:00
) ,
2023-05-05 14:05:52 +02:00
processTypedMessage :
this . signatureController . newUnsignedTypedMessage . bind (
this . signatureController ,
) ,
processTypedMessageV3 :
this . signatureController . newUnsignedTypedMessage . bind (
this . signatureController ,
) ,
processTypedMessageV4 :
this . signatureController . newUnsignedTypedMessage . bind (
this . signatureController ,
) ,
2023-03-20 14:19:50 +01:00
processPersonalMessage :
2023-05-05 14:05:52 +02:00
this . signatureController . newUnsignedPersonalMessage . bind (
this . signatureController ,
2023-03-20 14:19:50 +01:00
) ,
2023-04-13 10:24:59 +02:00
processEncryptionPublicKey :
this . encryptionPublicKeyController . newRequestEncryptionPublicKey . bind (
this . encryptionPublicKeyController ,
) ,
2023-04-26 17:02:33 +02:00
processDecryptMessage :
this . decryptMessageController . newRequestDecryptMessage . bind (
this . decryptMessageController ,
) ,
2023-01-06 18:14:50 +01:00
getPendingNonce : this . getPendingNonce . bind ( this ) ,
getPendingTransactionByHash : ( hash ) =>
this . txController . getTransactions ( {
searchCriteria : {
hash ,
2023-01-18 15:47:29 +01:00
status : TransactionStatus . submitted ,
2023-01-06 18:14:50 +01:00
} ,
} ) [ 0 ] ,
} ) ;
2020-12-08 20:48:47 +01:00
// ensure isClientOpenAndUnlocked is updated when memState updates
2021-02-04 19:15:23 +01:00
this . on ( 'update' , ( memState ) => this . _onStateUpdate ( memState ) ) ;
2020-12-08 20:48:47 +01:00
2022-11-22 17:56:26 +01:00
/ * *
* All controllers in Memstore but not in store . They are not persisted .
* On chrome profile re - start , they will be re - initialized .
* /
const resetOnRestartStore = {
AccountTracker : this . accountTracker . store ,
TxController : this . txController . memStore ,
TokenRatesController : this . tokenRatesController ,
2023-04-26 17:02:33 +02:00
DecryptMessageController : this . decryptMessageController ,
2023-04-13 10:24:59 +02:00
EncryptionPublicKeyController : this . encryptionPublicKeyController ,
2023-05-05 14:05:52 +02:00
SignatureController : this . signatureController ,
2022-11-22 17:56:26 +01:00
SwapsController : this . swapsController . store ,
EnsController : this . ensController . store ,
ApprovalController : this . approvalController ,
} ;
2018-04-13 05:26:50 +02:00
this . store . updateStructure ( {
2019-05-13 18:16:09 +02:00
AppStateController : this . appStateController . store ,
2018-04-13 05:26:50 +02:00
TransactionController : this . txController . store ,
KeyringController : this . keyringController . store ,
PreferencesController : this . preferencesController . store ,
2020-12-02 22:41:30 +01:00
MetaMetricsController : this . metaMetricsController . store ,
2019-03-12 05:40:41 +01:00
AddressBookController : this . addressBookController ,
2019-06-01 00:14:22 +02:00
CurrencyController : this . currencyRateController ,
2018-04-13 05:26:50 +02:00
NetworkController : this . networkController . store ,
2018-11-30 23:51:24 +01:00
CachedBalancesController : this . cachedBalancesController . store ,
2020-05-08 21:45:52 +02:00
AlertController : this . alertController . store ,
2019-08-02 05:57:26 +02:00
OnboardingController : this . onboardingController . store ,
2019-08-16 20:54:10 +02:00
IncomingTransactionsController : this . incomingTransactionsController . store ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
PermissionController : this . permissionController ,
PermissionLogController : this . permissionLogController . store ,
SubjectMetadataController : this . subjectMetadataController ,
2022-08-09 20:36:32 +02:00
BackupController : this . backupController ,
2022-04-27 10:36:32 +02:00
AnnouncementController : this . announcementController ,
2021-07-08 22:23:00 +02:00
GasFeeController : this . gasFeeController ,
2021-07-16 01:08:16 +02:00
TokenListController : this . tokenListController ,
2021-09-10 19:37:19 +02:00
TokensController : this . tokensController ,
2022-02-18 17:48:38 +01:00
SmartTransactionsController : this . smartTransactionsController ,
2022-11-15 19:49:42 +01:00
NftController : this . nftController ,
2023-01-18 16:44:19 +01:00
PhishingController : this . phishingController ,
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-02-15 01:02:51 +01:00
SnapController : this . snapController ,
2022-11-09 13:18:47 +01:00
CronjobController : this . cronjobController ,
2023-03-30 23:57:28 +02:00
SnapsRegistry : this . snapsRegistry ,
2022-06-01 19:09:13 +02:00
NotificationController : this . notificationController ,
2023-04-25 16:32:51 +02:00
///: END:ONLY_INCLUDE_IN
///: BEGIN:ONLY_INCLUDE_IN(desktop)
2023-02-20 18:13:12 +01:00
DesktopController : this . desktopController . store ,
///: END:ONLY_INCLUDE_IN
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
CustodyController : this . custodyController . store ,
InstitutionalFeaturesController :
this . institutionalFeaturesController . store ,
MmiConfigurationController : this . mmiConfigurationController . store ,
///: END:ONLY_INCLUDE_IN
2022-11-22 17:56:26 +01:00
... resetOnRestartStore ,
2021-02-04 19:15:23 +01:00
} ) ;
2018-01-31 19:49:58 +01:00
2021-05-20 04:57:51 +02:00
this . memStore = new ComposableObservableStore ( {
config : {
AppStateController : this . appStateController . store ,
NetworkController : this . networkController . store ,
CachedBalancesController : this . cachedBalancesController . store ,
KeyringController : this . keyringController . memStore ,
PreferencesController : this . preferencesController . store ,
MetaMetricsController : this . metaMetricsController . store ,
AddressBookController : this . addressBookController ,
CurrencyController : this . currencyRateController ,
AlertController : this . alertController . store ,
OnboardingController : this . onboardingController . store ,
2022-07-31 20:26:40 +02:00
IncomingTransactionsController :
this . incomingTransactionsController . store ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
PermissionController : this . permissionController ,
PermissionLogController : this . permissionLogController . store ,
SubjectMetadataController : this . subjectMetadataController ,
2022-08-09 20:36:32 +02:00
BackupController : this . backupController ,
2022-04-27 10:36:32 +02:00
AnnouncementController : this . announcementController ,
2021-07-08 22:23:00 +02:00
GasFeeController : this . gasFeeController ,
2021-07-16 01:08:16 +02:00
TokenListController : this . tokenListController ,
2021-09-10 19:37:19 +02:00
TokensController : this . tokensController ,
2022-02-18 17:48:38 +01:00
SmartTransactionsController : this . smartTransactionsController ,
2022-11-15 19:49:42 +01:00
NftController : this . nftController ,
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-02-15 01:02:51 +01:00
SnapController : this . snapController ,
2022-11-09 13:18:47 +01:00
CronjobController : this . cronjobController ,
2023-03-30 23:57:28 +02:00
SnapsRegistry : this . snapsRegistry ,
2022-06-01 19:09:13 +02:00
NotificationController : this . notificationController ,
2023-04-25 16:32:51 +02:00
///: END:ONLY_INCLUDE_IN
///: BEGIN:ONLY_INCLUDE_IN(desktop)
2023-02-20 18:13:12 +01:00
DesktopController : this . desktopController . store ,
///: END:ONLY_INCLUDE_IN
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
CustodyController : this . custodyController . store ,
InstitutionalFeaturesController :
this . institutionalFeaturesController . store ,
MmiConfigurationController : this . mmiConfigurationController . store ,
///: END:ONLY_INCLUDE_IN
2022-11-22 17:56:26 +01:00
... resetOnRestartStore ,
2021-05-20 04:57:51 +02:00
} ,
2021-08-31 21:27:13 +02:00
controllerMessenger : this . controllerMessenger ,
2021-02-04 19:15:23 +01:00
} ) ;
2020-05-15 21:40:06 +02:00
2022-11-22 17:56:26 +01:00
// if this is the first time, clear the state of by calling these methods
const resetMethods = [
this . accountTracker . resetState ,
this . txController . resetState ,
2023-04-26 17:02:33 +02:00
this . decryptMessageController . resetState . bind (
this . decryptMessageController ,
) ,
2023-04-13 10:24:59 +02:00
this . encryptionPublicKeyController . resetState . bind (
this . encryptionPublicKeyController ,
) ,
2023-05-05 14:05:52 +02:00
this . signatureController . resetState . bind ( this . signatureController ) ,
2022-11-22 17:56:26 +01:00
this . swapsController . resetState ,
this . ensController . resetState ,
this . approvalController . clear . bind ( this . approvalController ) ,
// WE SHOULD ADD TokenListController.resetState here too. But it's not implemented yet.
] ;
if ( isManifestV3 ) {
2023-04-06 16:43:01 +02:00
if ( isFirstMetaMaskControllerSetup === true ) {
2022-11-22 17:56:26 +01:00
this . resetStates ( resetMethods ) ;
2023-04-06 16:43:01 +02:00
this . extension . storage . session . set ( {
isFirstMetaMaskControllerSetup : false ,
} ) ;
2022-11-22 17:56:26 +01:00
}
} else {
// it's always the first time in MV2
this . resetStates ( resetMethods ) ;
}
2022-11-24 01:49:24 +01:00
// Automatic login via config password or loginToken
2020-05-15 21:40:06 +02:00
if (
2020-11-03 00:41:28 +01:00
! this . isUnlocked ( ) &&
2021-10-15 20:52:52 +02:00
this . onboardingController . store . getState ( ) . completedOnboarding
2020-05-15 21:40:06 +02:00
) {
2022-11-24 01:49:24 +01:00
this . _loginUser ( ) ;
} else {
this . _startUISync ( ) ;
2020-05-15 21:40:06 +02:00
}
2021-01-13 02:43:45 +01:00
2021-04-30 17:28:07 +02:00
// Lazily update the store with the current extension environment
2022-03-18 20:07:05 +01:00
this . extension . runtime . getPlatformInfo ( ) . then ( ( { os } ) => {
2021-04-30 17:28:07 +02:00
this . appStateController . setBrowserEnvironment (
os ,
// This method is presently only supported by Firefox
this . extension . runtime . getBrowserInfo === undefined
? 'chrome'
: 'firefox' ,
) ;
} ) ;
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
this . setupControllerEventSubscriptions ( ) ;
2022-08-05 21:22:07 +02:00
// For more information about these legacy streams, see here:
// https://github.com/MetaMask/metamask-extension/issues/15491
2021-01-13 02:43:45 +01:00
// TODO:LegacyProvider: Delete
2021-02-04 19:15:23 +01:00
this . publicConfigStore = this . createPublicConfigStore ( ) ;
2022-04-27 20:14:10 +02:00
// Multiple MetaMask instances launched warning
this . extension . runtime . onMessageExternal . addListener ( onMessageReceived ) ;
// Fire a ping message to check if other extensions are running
checkForMultipleVersionsRunning ( ) ;
2016-06-24 22:05:21 +02:00
}
2022-12-02 18:59:03 +01:00
triggerNetworkrequests ( ) {
this . accountTracker . start ( ) ;
this . incomingTransactionsController . start ( ) ;
2023-01-17 16:23:04 +01:00
if ( this . preferencesController . store . getState ( ) . useCurrencyRateCheck ) {
this . currencyRateController . start ( ) ;
}
2022-12-02 18:59:03 +01:00
if ( this . preferencesController . store . getState ( ) . useTokenDetection ) {
this . tokenListController . start ( ) ;
}
}
stopNetworkRequests ( ) {
this . accountTracker . stop ( ) ;
this . incomingTransactionsController . stop ( ) ;
2023-01-17 16:23:04 +01:00
if ( this . preferencesController . store . getState ( ) . useCurrencyRateCheck ) {
this . currencyRateController . stop ( ) ;
}
2022-12-02 18:59:03 +01:00
if ( this . preferencesController . store . getState ( ) . useTokenDetection ) {
this . tokenListController . stop ( ) ;
}
}
2023-01-25 22:12:08 +01:00
canUseHardwareWallets ( ) {
2023-04-25 16:32:51 +02:00
return ! isManifestV3 || process . env . HARDWARE _WALLETS _MV3 ;
2023-01-25 22:12:08 +01:00
}
2022-11-22 17:56:26 +01:00
resetStates ( resetMethods ) {
resetMethods . forEach ( ( resetMethod ) => {
try {
resetMethod ( ) ;
} catch ( err ) {
console . error ( err ) ;
}
} ) ;
}
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-02-15 01:02:51 +01:00
/ * *
* Constructor helper for getting Snap permission specifications .
* /
getSnapPermissionSpecifications ( ) {
return {
... buildSnapEndowmentSpecifications ( ) ,
... buildSnapRestrictedMethodSpecifications ( {
2023-05-15 19:36:24 +02:00
encrypt ,
decrypt ,
2022-04-28 18:17:28 +02:00
clearSnapState : this . controllerMessenger . call . bind (
this . controllerMessenger ,
'SnapController:clearSnapState' ,
) ,
2022-02-15 01:02:51 +01:00
getMnemonic : this . getPrimaryKeyringMnemonic . bind ( this ) ,
2022-04-28 18:17:28 +02:00
getUnlockPromise : this . appStateController . getUnlockPromise . bind (
this . appStateController ,
) ,
2022-02-15 01:02:51 +01:00
getSnap : this . controllerMessenger . call . bind (
this . controllerMessenger ,
'SnapController:get' ,
) ,
2022-07-19 17:41:06 +02:00
handleSnapRpcRequest : this . controllerMessenger . call . bind (
2022-02-15 01:02:51 +01:00
this . controllerMessenger ,
2022-08-26 13:48:53 +02:00
'SnapController:handleRequest' ,
2022-02-15 01:02:51 +01:00
) ,
2022-04-04 16:32:49 +02:00
getSnapState : this . controllerMessenger . call . bind (
this . controllerMessenger ,
'SnapController:getSnapState' ,
) ,
2022-12-20 11:44:22 +01:00
showDialog : ( origin , type , content , placeholder ) =>
2022-12-01 16:46:06 +01:00
this . approvalController . addAndShowApprovalRequest ( {
origin ,
type : SNAP _DIALOG _TYPES [ type ] ,
2022-12-20 11:44:22 +01:00
requestData : { content , placeholder } ,
2022-12-01 16:46:06 +01:00
} ) ,
2022-06-01 19:09:13 +02:00
showNativeNotification : ( origin , args ) =>
2022-03-17 17:43:18 +01:00
this . controllerMessenger . call (
'RateLimitController:call' ,
origin ,
'showNativeNotification' ,
origin ,
args . message ,
) ,
2022-06-01 19:09:13 +02:00
showInAppNotification : ( origin , args ) =>
this . controllerMessenger . call (
'RateLimitController:call' ,
origin ,
'showInAppNotification' ,
origin ,
args . message ,
) ,
2022-02-15 01:02:51 +01:00
updateSnapState : this . controllerMessenger . call . bind (
this . controllerMessenger ,
'SnapController:updateSnapState' ,
) ,
} ) ,
} ;
}
2022-06-01 19:09:13 +02:00
/ * *
* Deletes the specified notifications from state .
*
* @ param { string [ ] } ids - The notifications ids to delete .
* /
dismissNotifications ( ids ) {
this . notificationController . dismiss ( ids ) ;
}
/ * *
* Updates the readDate attribute of the specified notifications .
*
* @ param { string [ ] } ids - The notifications ids to mark as read .
* /
markNotificationsAsRead ( ids ) {
this . notificationController . markRead ( ids ) ;
}
2022-02-15 01:02:51 +01:00
///: END:ONLY_INCLUDE_IN
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
/ * *
* Sets up BaseController V2 event subscriptions . Currently , this includes
* the subscriptions necessary to notify permission subjects of account
* changes .
*
* Some of the subscriptions in this method are ControllerMessenger selector
2022-11-24 20:59:07 +01:00
* event subscriptions . See the relevant documentation for
* ` @metamask/base-controller ` for more information .
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
*
* Note that account - related notifications emitted when the extension
* becomes unlocked are handled in MetaMaskController . _onUnlock .
* /
setupControllerEventSubscriptions ( ) {
const handleAccountsChange = async ( origin , newAccounts ) => {
if ( this . isUnlocked ( ) ) {
this . notifyConnections ( origin , {
method : NOTIFICATION _NAMES . accountsChanged ,
// This should be the same as the return value of `eth_accounts`,
// namely an array of the current / most recently selected Ethereum
// account.
params :
newAccounts . length < 2
? // If the length is 1 or 0, the accounts are sorted by definition.
newAccounts
: // If the length is 2 or greater, we have to execute
// `eth_accounts` vi this method.
await this . getPermittedAccounts ( origin ) ,
} ) ;
}
this . permissionLogController . updateAccountsHistory ( origin , newAccounts ) ;
} ;
// This handles account changes whenever the selected address changes.
let lastSelectedAddress ;
this . preferencesController . store . subscribe ( async ( { selectedAddress } ) => {
if ( selectedAddress && selectedAddress !== lastSelectedAddress ) {
lastSelectedAddress = selectedAddress ;
const permittedAccountsMap = getPermittedAccountsByOrigin (
this . permissionController . state ,
) ;
for ( const [ origin , accounts ] of permittedAccountsMap . entries ( ) ) {
if ( accounts . includes ( selectedAddress ) ) {
handleAccountsChange ( origin , accounts ) ;
}
}
}
} ) ;
// This handles account changes every time relevant permission state
// changes, for any reason.
this . controllerMessenger . subscribe (
` ${ this . permissionController . name } :stateChange ` ,
async ( currentValue , previousValue ) => {
const changedAccounts = getChangedAccounts ( currentValue , previousValue ) ;
for ( const [ origin , accounts ] of changedAccounts . entries ( ) ) {
handleAccountsChange ( origin , accounts ) ;
}
} ,
getPermittedAccountsByOrigin ,
) ;
2022-02-15 01:02:51 +01:00
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-02-15 01:02:51 +01:00
// Record Snap metadata whenever a Snap is added to state.
this . controllerMessenger . subscribe (
` ${ this . snapController . name } :snapAdded ` ,
2022-07-19 17:41:06 +02:00
( snap , svgIcon = null ) => {
2022-02-15 01:02:51 +01:00
const {
manifest : { proposedName } ,
version ,
} = snap ;
this . subjectMetadataController . addSubjectMetadata ( {
2023-01-24 16:03:01 +01:00
subjectType : SubjectType . Snap ,
2022-02-15 01:02:51 +01:00
name : proposedName ,
2022-07-19 17:41:06 +02:00
origin : snap . id ,
2022-02-15 01:02:51 +01:00
version ,
svgIcon ,
} ) ;
} ,
) ;
this . controllerMessenger . subscribe (
` ${ this . snapController . name } :snapInstalled ` ,
2022-07-19 17:41:06 +02:00
( truncatedSnap ) => {
2022-02-15 01:02:51 +01:00
this . metaMetricsController . trackEvent ( {
event : 'Snap Installed' ,
2023-04-03 17:31:04 +02:00
category : MetaMetricsEventCategory . Snaps ,
2022-02-15 01:02:51 +01:00
properties : {
2022-07-19 17:41:06 +02:00
snap _id : truncatedSnap . id ,
version : truncatedSnap . version ,
2022-02-15 01:02:51 +01:00
} ,
} ) ;
} ,
) ;
2022-05-11 16:15:26 +02:00
2022-07-22 16:08:43 +02:00
this . controllerMessenger . subscribe (
` ${ this . snapController . name } :snapUpdated ` ,
( newSnap , oldVersion ) => {
this . metaMetricsController . trackEvent ( {
event : 'Snap Updated' ,
2023-04-03 17:31:04 +02:00
category : MetaMetricsEventCategory . Snaps ,
2022-07-22 16:08:43 +02:00
properties : {
snap _id : newSnap . id ,
old _version : oldVersion ,
new _version : newSnap . version ,
} ,
} ) ;
} ,
) ;
2022-05-11 16:15:26 +02:00
this . controllerMessenger . subscribe (
` ${ this . snapController . name } :snapTerminated ` ,
2022-07-19 17:41:06 +02:00
( truncatedSnap ) => {
2022-05-11 16:15:26 +02:00
const approvals = Object . values (
this . approvalController . state . pendingApprovals ,
) . filter (
( approval ) =>
2022-07-19 17:41:06 +02:00
approval . origin === truncatedSnap . id &&
2022-12-01 16:46:06 +01:00
approval . type . startsWith ( RestrictedMethods . snap _dialog ) ,
2022-05-11 16:15:26 +02:00
) ;
for ( const approval of approvals ) {
this . approvalController . reject (
approval . id ,
new Error ( 'Snap was terminated.' ) ,
) ;
}
} ,
) ;
2023-01-30 13:43:47 +01:00
this . controllerMessenger . subscribe (
` ${ this . snapController . name } :snapRemoved ` ,
( truncatedSnap ) => {
const notificationIds = Object . values (
this . notificationController . state . notifications ,
) . reduce ( ( idList , notification ) => {
if ( notification . origin === truncatedSnap . id ) {
idList . push ( notification . id ) ;
}
return idList ;
} , [ ] ) ;
this . dismissNotifications ( notificationIds ) ;
} ,
) ;
2022-02-15 01:02:51 +01:00
///: END:ONLY_INCLUDE_IN
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
}
2021-01-13 02:43:45 +01:00
/ * *
* TODO : LegacyProvider : Delete
* Constructor helper : initialize a public config store .
* This store is used to make some config info available to Dapps synchronously .
* /
createPublicConfigStore ( ) {
// subset of state for metamask inpage provider
2021-02-04 19:15:23 +01:00
const publicConfigStore = new ObservableStore ( ) ;
const { networkController } = this ;
2021-01-13 02:43:45 +01:00
// setup memStore subscription hooks
2021-02-04 19:15:23 +01:00
this . on ( 'update' , updatePublicConfigStore ) ;
updatePublicConfigStore ( this . getState ( ) ) ;
2021-01-13 02:43:45 +01:00
function updatePublicConfigStore ( memState ) {
2023-05-02 17:53:20 +02:00
const { chainId } = networkController . store . getState ( ) . providerConfig ;
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556)
The `network` store of the network controller crams two types of data
into one place. It roughly tracks whether we have enough information to
make requests to the network and whether the network is capable of
receiving requests, but it also stores the ID of the network (as
obtained via `net_version`).
Generally we shouldn't be using the network ID for anything, as it has
been completely replaced by chain ID, which all custom RPC endpoints
have been required to support for over a year now. However, as the
network ID is used in various places within the extension codebase,
removing it entirely would be a non-trivial effort. So, minimally, this
commit splits `network` into two stores: `networkId` and
`networkStatus`. But it also expands the concept of network status.
Previously, the network was in one of two states: "loading" and
"not-loading". But now it can be in one of four states:
- `available`: The network is able to receive and respond to requests.
- `unavailable`: The network is not able to receive and respond to
requests for unknown reasons.
- `blocked`: The network is actively blocking requests based on the
user's geolocation. (This is specific to Infura.)
- `unknown`: We don't know whether the network can receive and respond
to requests, either because we haven't checked or we tried to check
and were unsuccessful.
This commit also changes how the network status is determined —
specifically, how many requests are used to determine that status, when
they occur, and whether they are awaited. Previously, the network
controller would make 2 to 3 requests during the course of running
`lookupNetwork`.
* First, if it was an Infura network, it would make a request for
`eth_blockNumber` to determine whether Infura was blocking requests or
not, then emit an appropriate event. This operation was not awaited.
* Then, regardless of the network, it would fetch the network ID via
`net_version`. This operation was awaited.
* Finally, regardless of the network, it would fetch the latest block
via `eth_getBlockByNumber`, then use the result to determine whether
the network supported EIP-1559. This operation was awaited.
Now:
* One fewer request is made, specifically `eth_blockNumber`, as we don't
need to make an extra request to determine whether Infura is blocking
requests; we can reuse `eth_getBlockByNumber`;
* All requests are awaited, which makes `lookupNetwork` run fully
in-band instead of partially out-of-band; and
* Both requests for `net_version` and `eth_getBlockByNumber` are
performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
if ( memState . networkStatus === NetworkStatus . Available ) {
2021-02-04 19:15:23 +01:00
publicConfigStore . putState ( selectPublicState ( chainId , memState ) ) ;
2021-01-13 02:43:45 +01:00
}
}
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556)
The `network` store of the network controller crams two types of data
into one place. It roughly tracks whether we have enough information to
make requests to the network and whether the network is capable of
receiving requests, but it also stores the ID of the network (as
obtained via `net_version`).
Generally we shouldn't be using the network ID for anything, as it has
been completely replaced by chain ID, which all custom RPC endpoints
have been required to support for over a year now. However, as the
network ID is used in various places within the extension codebase,
removing it entirely would be a non-trivial effort. So, minimally, this
commit splits `network` into two stores: `networkId` and
`networkStatus`. But it also expands the concept of network status.
Previously, the network was in one of two states: "loading" and
"not-loading". But now it can be in one of four states:
- `available`: The network is able to receive and respond to requests.
- `unavailable`: The network is not able to receive and respond to
requests for unknown reasons.
- `blocked`: The network is actively blocking requests based on the
user's geolocation. (This is specific to Infura.)
- `unknown`: We don't know whether the network can receive and respond
to requests, either because we haven't checked or we tried to check
and were unsuccessful.
This commit also changes how the network status is determined —
specifically, how many requests are used to determine that status, when
they occur, and whether they are awaited. Previously, the network
controller would make 2 to 3 requests during the course of running
`lookupNetwork`.
* First, if it was an Infura network, it would make a request for
`eth_blockNumber` to determine whether Infura was blocking requests or
not, then emit an appropriate event. This operation was not awaited.
* Then, regardless of the network, it would fetch the network ID via
`net_version`. This operation was awaited.
* Finally, regardless of the network, it would fetch the latest block
via `eth_getBlockByNumber`, then use the result to determine whether
the network supported EIP-1559. This operation was awaited.
Now:
* One fewer request is made, specifically `eth_blockNumber`, as we don't
need to make an extra request to determine whether Infura is blocking
requests; we can reuse `eth_getBlockByNumber`;
* All requests are awaited, which makes `lookupNetwork` run fully
in-band instead of partially out-of-band; and
* Both requests for `net_version` and `eth_getBlockByNumber` are
performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
function selectPublicState ( chainId , { isUnlocked , networkId } ) {
2021-01-13 02:43:45 +01:00
return {
isUnlocked ,
chainId ,
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556)
The `network` store of the network controller crams two types of data
into one place. It roughly tracks whether we have enough information to
make requests to the network and whether the network is capable of
receiving requests, but it also stores the ID of the network (as
obtained via `net_version`).
Generally we shouldn't be using the network ID for anything, as it has
been completely replaced by chain ID, which all custom RPC endpoints
have been required to support for over a year now. However, as the
network ID is used in various places within the extension codebase,
removing it entirely would be a non-trivial effort. So, minimally, this
commit splits `network` into two stores: `networkId` and
`networkStatus`. But it also expands the concept of network status.
Previously, the network was in one of two states: "loading" and
"not-loading". But now it can be in one of four states:
- `available`: The network is able to receive and respond to requests.
- `unavailable`: The network is not able to receive and respond to
requests for unknown reasons.
- `blocked`: The network is actively blocking requests based on the
user's geolocation. (This is specific to Infura.)
- `unknown`: We don't know whether the network can receive and respond
to requests, either because we haven't checked or we tried to check
and were unsuccessful.
This commit also changes how the network status is determined —
specifically, how many requests are used to determine that status, when
they occur, and whether they are awaited. Previously, the network
controller would make 2 to 3 requests during the course of running
`lookupNetwork`.
* First, if it was an Infura network, it would make a request for
`eth_blockNumber` to determine whether Infura was blocking requests or
not, then emit an appropriate event. This operation was not awaited.
* Then, regardless of the network, it would fetch the network ID via
`net_version`. This operation was awaited.
* Finally, regardless of the network, it would fetch the latest block
via `eth_getBlockByNumber`, then use the result to determine whether
the network supported EIP-1559. This operation was awaited.
Now:
* One fewer request is made, specifically `eth_blockNumber`, as we don't
need to make an extra request to determine whether Infura is blocking
requests; we can reuse `eth_getBlockByNumber`;
* All requests are awaited, which makes `lookupNetwork` run fully
in-band instead of partially out-of-band; and
* Both requests for `net_version` and `eth_getBlockByNumber` are
performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
networkVersion : networkId ? ? 'loading' ,
2021-02-04 19:15:23 +01:00
} ;
2021-01-13 02:43:45 +01:00
}
2021-02-04 19:15:23 +01:00
return publicConfigStore ;
2021-01-13 02:43:45 +01:00
}
2018-03-15 23:27:10 +01:00
/ * *
2020-12-08 20:48:47 +01:00
* Gets relevant state for the provider of an external origin .
*
* @ param { string } origin - The origin to get the provider state for .
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556)
The `network` store of the network controller crams two types of data
into one place. It roughly tracks whether we have enough information to
make requests to the network and whether the network is capable of
receiving requests, but it also stores the ID of the network (as
obtained via `net_version`).
Generally we shouldn't be using the network ID for anything, as it has
been completely replaced by chain ID, which all custom RPC endpoints
have been required to support for over a year now. However, as the
network ID is used in various places within the extension codebase,
removing it entirely would be a non-trivial effort. So, minimally, this
commit splits `network` into two stores: `networkId` and
`networkStatus`. But it also expands the concept of network status.
Previously, the network was in one of two states: "loading" and
"not-loading". But now it can be in one of four states:
- `available`: The network is able to receive and respond to requests.
- `unavailable`: The network is not able to receive and respond to
requests for unknown reasons.
- `blocked`: The network is actively blocking requests based on the
user's geolocation. (This is specific to Infura.)
- `unknown`: We don't know whether the network can receive and respond
to requests, either because we haven't checked or we tried to check
and were unsuccessful.
This commit also changes how the network status is determined —
specifically, how many requests are used to determine that status, when
they occur, and whether they are awaited. Previously, the network
controller would make 2 to 3 requests during the course of running
`lookupNetwork`.
* First, if it was an Infura network, it would make a request for
`eth_blockNumber` to determine whether Infura was blocking requests or
not, then emit an appropriate event. This operation was not awaited.
* Then, regardless of the network, it would fetch the network ID via
`net_version`. This operation was awaited.
* Finally, regardless of the network, it would fetch the latest block
via `eth_getBlockByNumber`, then use the result to determine whether
the network supported EIP-1559. This operation was awaited.
Now:
* One fewer request is made, specifically `eth_blockNumber`, as we don't
need to make an extra request to determine whether Infura is blocking
requests; we can reuse `eth_getBlockByNumber`;
* All requests are awaited, which makes `lookupNetwork` run fully
in-band instead of partially out-of-band; and
* Both requests for `net_version` and `eth_getBlockByNumber` are
performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
* @ returns { Promise < { isUnlocked : boolean , networkVersion : string , chainId : string , accounts : string [ ] } > } An object with relevant state properties .
2018-03-15 23:27:10 +01:00
* /
2020-12-08 20:48:47 +01:00
async getProviderState ( origin ) {
return {
isUnlocked : this . isUnlocked ( ) ,
... this . getProviderNetworkState ( ) ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
accounts : await this . getPermittedAccounts ( origin ) ,
2021-02-04 19:15:23 +01:00
} ;
2020-12-08 20:48:47 +01:00
}
2017-05-05 02:50:59 +02:00
2020-12-08 20:48:47 +01:00
/ * *
* Gets network state relevant for external providers .
*
2022-07-27 15:28:05 +02:00
* @ param { object } [ memState ] - The MetaMask memState . If not provided ,
2020-12-08 20:48:47 +01:00
* this function will retrieve the most recent state .
2022-07-27 15:28:05 +02:00
* @ returns { object } An object with relevant network state properties .
2020-12-08 20:48:47 +01:00
* /
getProviderNetworkState ( memState ) {
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556)
The `network` store of the network controller crams two types of data
into one place. It roughly tracks whether we have enough information to
make requests to the network and whether the network is capable of
receiving requests, but it also stores the ID of the network (as
obtained via `net_version`).
Generally we shouldn't be using the network ID for anything, as it has
been completely replaced by chain ID, which all custom RPC endpoints
have been required to support for over a year now. However, as the
network ID is used in various places within the extension codebase,
removing it entirely would be a non-trivial effort. So, minimally, this
commit splits `network` into two stores: `networkId` and
`networkStatus`. But it also expands the concept of network status.
Previously, the network was in one of two states: "loading" and
"not-loading". But now it can be in one of four states:
- `available`: The network is able to receive and respond to requests.
- `unavailable`: The network is not able to receive and respond to
requests for unknown reasons.
- `blocked`: The network is actively blocking requests based on the
user's geolocation. (This is specific to Infura.)
- `unknown`: We don't know whether the network can receive and respond
to requests, either because we haven't checked or we tried to check
and were unsuccessful.
This commit also changes how the network status is determined —
specifically, how many requests are used to determine that status, when
they occur, and whether they are awaited. Previously, the network
controller would make 2 to 3 requests during the course of running
`lookupNetwork`.
* First, if it was an Infura network, it would make a request for
`eth_blockNumber` to determine whether Infura was blocking requests or
not, then emit an appropriate event. This operation was not awaited.
* Then, regardless of the network, it would fetch the network ID via
`net_version`. This operation was awaited.
* Finally, regardless of the network, it would fetch the latest block
via `eth_getBlockByNumber`, then use the result to determine whether
the network supported EIP-1559. This operation was awaited.
Now:
* One fewer request is made, specifically `eth_blockNumber`, as we don't
need to make an extra request to determine whether Infura is blocking
requests; we can reuse `eth_getBlockByNumber`;
* All requests are awaited, which makes `lookupNetwork` run fully
in-band instead of partially out-of-band; and
* Both requests for `net_version` and `eth_getBlockByNumber` are
performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
const { networkId } = memState || this . getState ( ) ;
2020-12-08 20:48:47 +01:00
return {
2023-05-02 17:53:20 +02:00
chainId : this . networkController . store . getState ( ) . providerConfig . chainId ,
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556)
The `network` store of the network controller crams two types of data
into one place. It roughly tracks whether we have enough information to
make requests to the network and whether the network is capable of
receiving requests, but it also stores the ID of the network (as
obtained via `net_version`).
Generally we shouldn't be using the network ID for anything, as it has
been completely replaced by chain ID, which all custom RPC endpoints
have been required to support for over a year now. However, as the
network ID is used in various places within the extension codebase,
removing it entirely would be a non-trivial effort. So, minimally, this
commit splits `network` into two stores: `networkId` and
`networkStatus`. But it also expands the concept of network status.
Previously, the network was in one of two states: "loading" and
"not-loading". But now it can be in one of four states:
- `available`: The network is able to receive and respond to requests.
- `unavailable`: The network is not able to receive and respond to
requests for unknown reasons.
- `blocked`: The network is actively blocking requests based on the
user's geolocation. (This is specific to Infura.)
- `unknown`: We don't know whether the network can receive and respond
to requests, either because we haven't checked or we tried to check
and were unsuccessful.
This commit also changes how the network status is determined —
specifically, how many requests are used to determine that status, when
they occur, and whether they are awaited. Previously, the network
controller would make 2 to 3 requests during the course of running
`lookupNetwork`.
* First, if it was an Infura network, it would make a request for
`eth_blockNumber` to determine whether Infura was blocking requests or
not, then emit an appropriate event. This operation was not awaited.
* Then, regardless of the network, it would fetch the network ID via
`net_version`. This operation was awaited.
* Finally, regardless of the network, it would fetch the latest block
via `eth_getBlockByNumber`, then use the result to determine whether
the network supported EIP-1559. This operation was awaited.
Now:
* One fewer request is made, specifically `eth_blockNumber`, as we don't
need to make an extra request to determine whether Infura is blocking
requests; we can reuse `eth_getBlockByNumber`;
* All requests are awaited, which makes `lookupNetwork` run fully
in-band instead of partially out-of-band; and
* Both requests for `net_version` and `eth_getBlockByNumber` are
performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
networkVersion : networkId ? ? 'loading' ,
2021-02-04 19:15:23 +01:00
} ;
2017-01-27 06:19:09 +01:00
}
2019-07-31 22:17:11 +02:00
//=============================================================================
// EXPOSED TO THE UI SUBSYSTEM
//=============================================================================
2017-01-27 06:19:09 +01:00
2018-03-15 23:27:10 +01:00
/ * *
2018-03-16 01:29:53 +01:00
* The metamask - state of the various controllers , made available to the UI
2018-03-28 03:07:51 +02:00
*
2022-07-27 15:28:05 +02:00
* @ returns { object } status
2018-03-15 23:27:10 +01:00
* /
2020-11-03 00:41:28 +01:00
getState ( ) {
2021-02-04 19:15:23 +01:00
const { vault } = this . keyringController . store . getState ( ) ;
const isInitialized = Boolean ( vault ) ;
2017-09-13 23:20:19 +02:00
2018-04-13 05:26:50 +02:00
return {
2021-03-12 23:23:26 +01:00
isInitialized ,
2018-04-13 05:26:50 +02:00
... this . memStore . getFlatState ( ) ,
2021-02-04 19:15:23 +01:00
} ;
2016-06-24 22:05:21 +02:00
}
2018-03-15 23:27:10 +01:00
/ * *
2018-04-20 18:26:24 +02:00
* Returns an Object containing API Callback Functions .
* These functions are the interface for the UI .
2021-03-18 19:23:46 +01:00
* The API object can be transmitted over a stream via JSON - RPC .
2018-03-28 03:07:51 +02:00
*
2022-07-27 15:28:05 +02:00
* @ returns { object } Object containing API functions .
2018-03-15 23:27:10 +01:00
* /
2020-11-03 00:41:28 +01:00
getApi ( ) {
2020-08-18 22:06:58 +02:00
const {
2021-12-08 22:36:53 +01:00
addressBookController ,
2020-12-11 00:40:29 +01:00
alertController ,
2021-12-08 22:36:53 +01:00
appStateController ,
2022-11-15 19:49:42 +01:00
nftController ,
nftDetectionController ,
2021-12-08 22:36:53 +01:00
currencyRateController ,
detectTokensController ,
ensController ,
gasFeeController ,
2020-12-11 00:40:29 +01:00
metaMetricsController ,
2020-08-18 22:06:58 +02:00
networkController ,
2022-04-27 10:36:32 +02:00
announcementController ,
2020-08-18 22:06:58 +02:00
onboardingController ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
permissionController ,
2020-08-18 22:06:58 +02:00
preferencesController ,
2021-12-08 22:36:53 +01:00
qrHardwareKeyring ,
2020-12-11 00:40:29 +01:00
swapsController ,
2021-09-10 19:37:19 +02:00
tokensController ,
2022-02-18 17:48:38 +01:00
smartTransactionsController ,
2021-12-08 22:36:53 +01:00
txController ,
2022-04-13 18:23:41 +02:00
assetsContractController ,
2022-08-09 20:36:32 +02:00
backupController ,
2023-03-09 22:00:28 +01:00
approvalController ,
2021-02-04 19:15:23 +01:00
} = this ;
2016-06-24 22:05:21 +02:00
return {
2017-01-27 07:30:12 +01:00
// etc
2021-12-08 22:36:53 +01:00
getState : this . getState . bind ( this ) ,
setCurrentCurrency : currencyRateController . setCurrentCurrency . bind (
currencyRateController ,
) ,
setUseBlockie : preferencesController . setUseBlockie . bind (
preferencesController ,
) ,
setUseNonceField : preferencesController . setUseNonceField . bind (
preferencesController ,
) ,
setUsePhishDetect : preferencesController . setUsePhishDetect . bind (
preferencesController ,
) ,
2022-12-01 22:16:04 +01:00
setUseMultiAccountBalanceChecker :
preferencesController . setUseMultiAccountBalanceChecker . bind (
preferencesController ,
) ,
2021-12-08 22:36:53 +01:00
setUseTokenDetection : preferencesController . setUseTokenDetection . bind (
preferencesController ,
) ,
2022-11-15 19:49:42 +01:00
setUseNftDetection : preferencesController . setUseNftDetection . bind (
preferencesController ,
) ,
2023-01-17 16:23:04 +01:00
setUseCurrencyRateCheck :
preferencesController . setUseCurrencyRateCheck . bind (
preferencesController ,
) ,
2021-12-08 22:36:53 +01:00
setOpenSeaEnabled : preferencesController . setOpenSeaEnabled . bind (
preferencesController ,
) ,
setIpfsGateway : preferencesController . setIpfsGateway . bind (
preferencesController ,
2021-11-26 19:54:57 +01:00
) ,
2022-07-31 20:26:40 +02:00
setParticipateInMetaMetrics :
metaMetricsController . setParticipateInMetaMetrics . bind (
metaMetricsController ,
) ,
2021-12-08 22:36:53 +01:00
setCurrentLocale : preferencesController . setCurrentLocale . bind (
preferencesController ,
2021-12-01 05:12:27 +01:00
) ,
2018-02-08 01:38:55 +01:00
markPasswordForgotten : this . markPasswordForgotten . bind ( this ) ,
unMarkPasswordForgotten : this . unMarkPasswordForgotten . bind ( this ) ,
2021-12-08 22:36:53 +01:00
getRequestAccountTabIds : this . getRequestAccountTabIds ,
getOpenMetamaskTabsIds : this . getOpenMetamaskTabsIds ,
2022-01-05 18:09:19 +01:00
markNotificationPopupAsAutomaticallyClosed : ( ) =>
this . notificationManager . markAsAutomaticallyClosed ( ) ,
2017-01-28 01:11:59 +01:00
2023-03-09 22:00:28 +01:00
// approval
requestUserApproval :
approvalController . addAndShowApprovalRequest . bind ( approvalController ) ,
2017-01-27 07:30:12 +01:00
// primary HD keyring management
2021-12-08 22:36:53 +01:00
addNewAccount : this . addNewAccount . bind ( this ) ,
verifySeedPhrase : this . verifySeedPhrase . bind ( this ) ,
resetAccount : this . resetAccount . bind ( this ) ,
removeAccount : this . removeAccount . bind ( this ) ,
importAccountWithStrategy : this . importAccountWithStrategy . bind ( this ) ,
2017-01-27 07:30:12 +01:00
2018-07-12 03:21:36 +02:00
// hardware wallets
2021-12-08 22:36:53 +01:00
connectHardware : this . connectHardware . bind ( this ) ,
forgetDevice : this . forgetDevice . bind ( this ) ,
checkHardwareStatus : this . checkHardwareStatus . bind ( this ) ,
unlockHardwareWalletAccount : this . unlockHardwareWalletAccount . bind ( this ) ,
2022-07-31 20:26:40 +02:00
setLedgerTransportPreference :
this . setLedgerTransportPreference . bind ( this ) ,
attemptLedgerTransportCreation :
this . attemptLedgerTransportCreation . bind ( this ) ,
establishLedgerTransportPreference :
this . establishLedgerTransportPreference . bind ( this ) ,
2018-06-10 09:52:32 +02:00
2021-11-23 18:28:39 +01:00
// qr hardware devices
2022-07-31 20:26:40 +02:00
submitQRHardwareCryptoHDKey :
qrHardwareKeyring . submitCryptoHDKey . bind ( qrHardwareKeyring ) ,
submitQRHardwareCryptoAccount :
qrHardwareKeyring . submitCryptoAccount . bind ( qrHardwareKeyring ) ,
cancelSyncQRHardware :
qrHardwareKeyring . cancelSync . bind ( qrHardwareKeyring ) ,
submitQRHardwareSignature :
qrHardwareKeyring . submitSignature . bind ( qrHardwareKeyring ) ,
cancelQRHardwareSignRequest :
qrHardwareKeyring . cancelSignRequest . bind ( qrHardwareKeyring ) ,
2021-11-23 18:28:39 +01:00
2017-01-27 07:30:12 +01:00
// vault management
2021-12-08 22:36:53 +01:00
submitPassword : this . submitPassword . bind ( this ) ,
verifyPassword : this . verifyPassword . bind ( this ) ,
2017-01-27 07:30:12 +01:00
2017-09-30 01:09:38 +02:00
// network management
2022-07-31 20:26:40 +02:00
setProviderType :
networkController . setProviderType . bind ( networkController ) ,
rollbackToPreviousProvider :
networkController . rollbackToPreviousProvider . bind ( networkController ) ,
2023-03-09 22:00:28 +01:00
removeNetworkConfiguration :
networkController . removeNetworkConfiguration . bind ( networkController ) ,
setActiveNetwork :
networkController . setActiveNetwork . bind ( networkController ) ,
upsertNetworkConfiguration :
this . networkController . upsertNetworkConfiguration . bind (
this . networkController ,
) ,
2023-04-27 06:46:36 +02:00
getCurrentNetworkEIP1559Compatibility :
this . networkController . getEIP1559Compatibility . bind (
this . networkController ,
) ,
2017-01-30 22:01:07 +01:00
// PreferencesController
2021-12-08 22:36:53 +01:00
setSelectedAddress : preferencesController . setSelectedAddress . bind (
2020-11-03 00:41:28 +01:00
preferencesController ,
) ,
2021-12-08 22:36:53 +01:00
addToken : tokensController . addToken . bind ( tokensController ) ,
updateTokenType : tokensController . updateTokenType . bind ( tokensController ) ,
setAccountLabel : preferencesController . setAccountLabel . bind (
2020-11-03 00:41:28 +01:00
preferencesController ,
) ,
2021-12-08 22:36:53 +01:00
setFeatureFlag : preferencesController . setFeatureFlag . bind (
2020-11-03 00:41:28 +01:00
preferencesController ,
) ,
2021-12-08 22:36:53 +01:00
setPreference : preferencesController . setPreference . bind (
2020-11-03 00:41:28 +01:00
preferencesController ,
) ,
2021-10-15 20:52:52 +02:00
2021-12-08 22:36:53 +01:00
addKnownMethodData : preferencesController . addKnownMethodData . bind (
2020-11-03 00:41:28 +01:00
preferencesController ,
) ,
2022-07-31 20:26:40 +02:00
setDismissSeedBackUpReminder :
preferencesController . setDismissSeedBackUpReminder . bind (
preferencesController ,
) ,
2023-02-06 17:47:50 +01:00
setDisabledRpcMethodPreference :
preferencesController . setDisabledRpcMethodPreference . bind (
preferencesController ,
) ,
getRpcMethodPreferences :
preferencesController . getRpcMethodPreferences . bind (
preferencesController ,
) ,
2021-12-08 22:36:53 +01:00
setAdvancedGasFee : preferencesController . setAdvancedGasFee . bind (
2021-11-11 20:18:50 +01:00
preferencesController ,
) ,
2022-03-07 19:53:19 +01:00
setTheme : preferencesController . setTheme . bind ( preferencesController ) ,
2022-11-17 15:13:02 +01:00
setTransactionSecurityCheckEnabled :
preferencesController . setTransactionSecurityCheckEnabled . bind (
preferencesController ,
) ,
2022-01-19 15:38:33 +01:00
// AssetsContractController
2022-03-09 15:38:12 +01:00
getTokenStandardAndDetails : this . getTokenStandardAndDetails . bind ( this ) ,
2022-01-19 15:38:33 +01:00
2022-11-15 19:49:42 +01:00
// NftController
addNft : nftController . addNft . bind ( nftController ) ,
2021-11-19 17:16:41 +01:00
2022-11-15 19:49:42 +01:00
addNftVerifyOwnership :
nftController . addNftVerifyOwnership . bind ( nftController ) ,
2021-11-26 21:03:35 +01:00
2022-11-15 19:49:42 +01:00
removeAndIgnoreNft : nftController . removeAndIgnoreNft . bind ( nftController ) ,
2021-11-19 17:16:41 +01:00
2022-11-15 19:49:42 +01:00
removeNft : nftController . removeNft . bind ( nftController ) ,
2021-11-19 17:16:41 +01:00
2022-11-15 19:49:42 +01:00
checkAndUpdateAllNftsOwnershipStatus :
nftController . checkAndUpdateAllNftsOwnershipStatus . bind ( nftController ) ,
2022-01-10 17:23:53 +01:00
2022-11-15 19:49:42 +01:00
checkAndUpdateSingleNftOwnershipStatus :
nftController . checkAndUpdateSingleNftOwnershipStatus . bind (
nftController ,
2022-07-31 20:26:40 +02:00
) ,
2022-01-10 17:23:53 +01:00
2022-11-15 19:49:42 +01:00
isNftOwner : nftController . isNftOwner . bind ( nftController ) ,
2022-01-03 21:39:41 +01:00
2017-03-10 00:10:27 +01:00
// AddressController
2021-12-08 22:36:53 +01:00
setAddressBook : addressBookController . set . bind ( addressBookController ) ,
removeFromAddressBook : addressBookController . delete . bind (
addressBookController ,
2020-11-03 00:41:28 +01:00
) ,
2017-03-10 00:10:27 +01:00
2019-05-13 18:16:09 +02:00
// AppStateController
2022-07-31 20:26:40 +02:00
setLastActiveTime :
appStateController . setLastActiveTime . bind ( appStateController ) ,
setDefaultHomeActiveTabName :
appStateController . setDefaultHomeActiveTabName . bind ( appStateController ) ,
setConnectedStatusPopoverHasBeenShown :
appStateController . setConnectedStatusPopoverHasBeenShown . bind (
appStateController ,
) ,
setRecoveryPhraseReminderHasBeenShown :
appStateController . setRecoveryPhraseReminderHasBeenShown . bind (
appStateController ,
) ,
setRecoveryPhraseReminderLastShown :
appStateController . setRecoveryPhraseReminderLastShown . bind (
appStateController ,
) ,
2023-04-14 18:51:13 +02:00
setTermsOfUseLastAgreed :
appStateController . setTermsOfUseLastAgreed . bind ( appStateController ) ,
2023-05-31 14:43:39 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
setSnapsInstallPrivacyWarningShownStatus :
appStateController . setSnapsInstallPrivacyWarningShownStatus . bind (
appStateController ,
) ,
///: END:ONLY_INCLUDE_IN
2023-02-02 19:56:41 +01:00
setOutdatedBrowserWarningLastShown :
appStateController . setOutdatedBrowserWarningLastShown . bind (
appStateController ,
) ,
2022-07-31 20:26:40 +02:00
setShowTestnetMessageInDropdown :
appStateController . setShowTestnetMessageInDropdown . bind (
appStateController ,
) ,
2022-11-16 18:41:15 +01:00
setShowBetaHeader :
appStateController . setShowBetaHeader . bind ( appStateController ) ,
2023-04-21 17:28:18 +02:00
setShowProductTour :
appStateController . setShowProductTour . bind ( appStateController ) ,
2023-02-16 20:23:29 +01:00
updateNftDropDownState :
appStateController . updateNftDropDownState . bind ( appStateController ) ,
2022-08-23 17:04:07 +02:00
setFirstTimeUsedNetwork :
appStateController . setFirstTimeUsedNetwork . bind ( appStateController ) ,
2023-03-02 17:50:00 +01:00
2019-11-01 18:54:00 +01:00
// EnsController
2022-07-31 20:26:40 +02:00
tryReverseResolveAddress :
ensController . reverseResolveAddress . bind ( ensController ) ,
2019-11-01 18:54:00 +01:00
2017-01-27 07:30:12 +01:00
// KeyringController
2021-12-08 22:36:53 +01:00
setLocked : this . setLocked . bind ( this ) ,
createNewVaultAndKeychain : this . createNewVaultAndKeychain . bind ( this ) ,
createNewVaultAndRestore : this . createNewVaultAndRestore . bind ( this ) ,
2023-01-17 16:01:12 +01:00
exportAccount : this . exportAccount . bind ( this ) ,
2017-01-27 07:30:12 +01:00
2017-05-16 19:27:41 +02:00
// txController
2021-12-08 22:36:53 +01:00
cancelTransaction : txController . cancelTransaction . bind ( txController ) ,
updateTransaction : txController . updateTransaction . bind ( txController ) ,
2022-07-31 20:26:40 +02:00
updateAndApproveTransaction :
txController . updateAndApproveTransaction . bind ( txController ) ,
approveTransactionsWithSameNonce :
txController . approveTransactionsWithSameNonce . bind ( txController ) ,
2021-12-08 22:36:53 +01:00
createCancelTransaction : this . createCancelTransaction . bind ( this ) ,
createSpeedUpTransaction : this . createSpeedUpTransaction . bind ( this ) ,
estimateGas : this . estimateGas . bind ( this ) ,
getNextNonce : this . getNextNonce . bind ( this ) ,
2022-07-31 20:26:40 +02:00
addUnapprovedTransaction :
txController . addUnapprovedTransaction . bind ( txController ) ,
createTransactionEventFragment :
txController . createTransactionEventFragment . bind ( txController ) ,
2022-02-14 19:29:24 +01:00
getTransactions : txController . getTransactions . bind ( txController ) ,
2017-02-03 05:20:13 +01:00
2022-07-31 20:26:40 +02:00
updateEditableParams :
txController . updateEditableParams . bind ( txController ) ,
updateTransactionGasFees :
txController . updateTransactionGasFees . bind ( txController ) ,
updateTransactionSendFlowHistory :
txController . updateTransactionSendFlowHistory . bind ( txController ) ,
2022-03-10 03:31:04 +01:00
2022-07-31 20:26:40 +02:00
updateSwapApprovalTransaction :
txController . updateSwapApprovalTransaction . bind ( txController ) ,
updateSwapTransaction :
txController . updateSwapTransaction . bind ( txController ) ,
2022-03-10 03:31:04 +01:00
2022-07-31 20:26:40 +02:00
updatePreviousGasParams :
txController . updatePreviousGasParams . bind ( txController ) ,
2017-01-27 07:30:12 +01:00
2023-05-05 14:05:52 +02:00
// signatureController
signMessage : this . signatureController . signMessage . bind (
this . signatureController ,
2023-03-20 14:19:50 +01:00
) ,
2023-05-05 14:05:52 +02:00
cancelMessage : this . signatureController . cancelMessage . bind (
this . signatureController ,
2023-03-20 14:19:50 +01:00
) ,
2023-05-05 14:05:52 +02:00
signPersonalMessage : this . signatureController . signPersonalMessage . bind (
this . signatureController ,
2023-03-20 14:19:50 +01:00
) ,
2023-05-05 14:05:52 +02:00
cancelPersonalMessage :
this . signatureController . cancelPersonalMessage . bind (
this . signatureController ,
) ,
signTypedMessage : this . signatureController . signTypedMessage . bind (
this . signatureController ,
2023-03-20 14:19:50 +01:00
) ,
2023-05-05 14:05:52 +02:00
cancelTypedMessage : this . signatureController . cancelTypedMessage . bind (
this . signatureController ,
2023-03-20 14:19:50 +01:00
) ,
2017-09-29 18:24:08 +02:00
2023-04-26 17:02:33 +02:00
// decryptMessageController
decryptMessage : this . decryptMessageController . decryptMessage . bind (
this . decryptMessageController ,
) ,
decryptMessageInline :
this . decryptMessageController . decryptMessageInline . bind (
this . decryptMessageController ,
) ,
cancelDecryptMessage :
this . decryptMessageController . cancelDecryptMessage . bind (
this . decryptMessageController ,
) ,
2020-02-19 19:24:16 +01:00
2023-04-13 10:24:59 +02:00
// EncryptionPublicKeyController
encryptionPublicKey :
this . encryptionPublicKeyController . encryptionPublicKey . bind (
this . encryptionPublicKeyController ,
) ,
cancelEncryptionPublicKey :
this . encryptionPublicKeyController . cancelEncryptionPublicKey . bind (
this . encryptionPublicKeyController ,
) ,
2020-02-19 19:24:16 +01:00
2019-08-02 05:57:26 +02:00
// onboarding controller
2022-07-31 20:26:40 +02:00
setSeedPhraseBackedUp :
onboardingController . setSeedPhraseBackedUp . bind ( onboardingController ) ,
completeOnboarding :
onboardingController . completeOnboarding . bind ( onboardingController ) ,
setFirstTimeFlowType :
onboardingController . setFirstTimeFlowType . bind ( onboardingController ) ,
2019-09-16 19:11:01 +02:00
2020-05-08 21:45:52 +02:00
// alert controller
2022-07-31 20:26:40 +02:00
setAlertEnabledness :
alertController . setAlertEnabledness . bind ( alertController ) ,
setUnconnectedAccountAlertShown :
alertController . setUnconnectedAccountAlertShown . bind ( alertController ) ,
setWeb3ShimUsageAlertDismissed :
alertController . setWeb3ShimUsageAlertDismissed . bind ( alertController ) ,
2020-05-08 21:45:52 +02:00
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
// permissions
2022-10-31 06:52:31 +01:00
removePermissionsFor : this . removePermissionsFor ,
approvePermissionsRequest : this . acceptPermissionsRequest ,
rejectPermissionsRequest : this . rejectPermissionsRequest ,
2021-12-08 22:36:53 +01:00
... getPermissionBackgroundApiMethods ( permissionController ) ,
2020-10-06 20:28:38 +02:00
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
connectCustodyAddresses :
this . mmiController . connectCustodyAddresses . bind ( this ) ,
getCustodianAccounts : this . mmiController . getCustodianAccounts . bind ( this ) ,
getCustodianAccountsByAddress :
this . mmiController . getCustodianAccountsByAddress . bind ( this ) ,
getCustodianTransactionDeepLink :
this . mmiController . getCustodianTransactionDeepLink . bind ( this ) ,
getCustodianConfirmDeepLink :
this . mmiController . getCustodianConfirmDeepLink . bind ( this ) ,
getCustodianSignMessageDeepLink :
this . mmiController . getCustodianSignMessageDeepLink . bind ( this ) ,
getCustodianToken : this . mmiController . getCustodianToken . bind ( this ) ,
getCustodianJWTList : this . mmiController . getCustodianJWTList . bind ( this ) ,
setWaitForConfirmDeepLinkDialog :
this . custodyController . setWaitForConfirmDeepLinkDialog . bind (
this . custodyController ,
) ,
setCustodianConnectRequest :
this . custodyController . setCustodianConnectRequest . bind (
this . custodyController ,
) ,
getCustodianConnectRequest :
this . custodyController . getCustodianConnectRequest . bind (
this . custodyController ,
) ,
getAllCustodianAccountsWithToken :
this . mmiController . getAllCustodianAccountsWithToken . bind ( this ) ,
getMmiConfiguration :
this . mmiConfigurationController . getConfiguration . bind (
this . mmiConfigurationController ,
) ,
setComplianceAuthData :
this . institutionalFeaturesController . setComplianceAuthData . bind (
this . institutionalFeaturesController ,
) ,
deleteComplianceAuthData :
this . institutionalFeaturesController . deleteComplianceAuthData . bind (
this . institutionalFeaturesController ,
) ,
generateComplianceReport :
this . institutionalFeaturesController . generateComplianceReport . bind (
this . institutionalFeaturesController ,
) ,
syncReportsInProgress :
this . institutionalFeaturesController . syncReportsInProgress . bind (
this . institutionalFeaturesController ,
) ,
removeConnectInstitutionalFeature :
this . institutionalFeaturesController . removeConnectInstitutionalFeature . bind (
this . institutionalFeaturesController ,
) ,
getComplianceHistoricalReportsByAddress :
this . institutionalFeaturesController . getComplianceHistoricalReportsByAddress . bind (
this . institutionalFeaturesController ,
) ,
removeAddTokenConnectRequest :
this . institutionalFeaturesController . removeAddTokenConnectRequest . bind (
this . institutionalFeaturesController ,
) ,
setCustodianNewRefreshToken :
this . mmiController . setCustodianNewRefreshToken . bind ( this ) ,
///: END:ONLY_INCLUDE_IN
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-02-15 01:02:51 +01:00
// snaps
2022-08-26 13:48:53 +02:00
removeSnapError : this . controllerMessenger . call . bind (
this . controllerMessenger ,
'SnapController:removeSnapError' ,
) ,
disableSnap : this . controllerMessenger . call . bind (
this . controllerMessenger ,
'SnapController:disable' ,
) ,
enableSnap : this . controllerMessenger . call . bind (
this . controllerMessenger ,
'SnapController:enable' ,
) ,
removeSnap : this . controllerMessenger . call . bind (
this . controllerMessenger ,
'SnapController:remove' ,
2022-02-15 01:02:51 +01:00
) ,
2022-09-20 19:00:07 +02:00
handleSnapRequest : this . controllerMessenger . call . bind (
this . controllerMessenger ,
'SnapController:handleRequest' ,
) ,
2022-06-01 19:09:13 +02:00
dismissNotifications : this . dismissNotifications . bind ( this ) ,
markNotificationsAsRead : this . markNotificationsAsRead . bind ( this ) ,
2023-04-25 16:32:51 +02:00
///: END:ONLY_INCLUDE_IN
///: BEGIN:ONLY_INCLUDE_IN(desktop)
2023-03-06 20:35:00 +01:00
// Desktop
getDesktopEnabled : this . desktopController . getDesktopEnabled . bind (
this . desktopController ,
) ,
setDesktopEnabled : this . desktopController . setDesktopEnabled . bind (
this . desktopController ,
) ,
generateDesktopOtp : this . desktopController . generateOtp . bind (
this . desktopController ,
) ,
testDesktopConnection : this . desktopController . testDesktopConnection . bind (
this . desktopController ,
) ,
disableDesktop : this . desktopController . disableDesktop . bind (
this . desktopController ,
) ,
2022-02-15 01:02:51 +01:00
///: END:ONLY_INCLUDE_IN
2020-10-06 20:28:38 +02:00
// swaps
2022-07-31 20:26:40 +02:00
fetchAndSetQuotes :
swapsController . fetchAndSetQuotes . bind ( swapsController ) ,
setSelectedQuoteAggId :
swapsController . setSelectedQuoteAggId . bind ( swapsController ) ,
2021-12-08 22:36:53 +01:00
resetSwapsState : swapsController . resetSwapsState . bind ( swapsController ) ,
setSwapsTokens : swapsController . setSwapsTokens . bind ( swapsController ) ,
clearSwapsQuotes : swapsController . clearSwapsQuotes . bind ( swapsController ) ,
setApproveTxId : swapsController . setApproveTxId . bind ( swapsController ) ,
setTradeTxId : swapsController . setTradeTxId . bind ( swapsController ) ,
2022-07-31 20:26:40 +02:00
setSwapsTxGasPrice :
swapsController . setSwapsTxGasPrice . bind ( swapsController ) ,
setSwapsTxGasLimit :
swapsController . setSwapsTxGasLimit . bind ( swapsController ) ,
setSwapsTxMaxFeePerGas :
swapsController . setSwapsTxMaxFeePerGas . bind ( swapsController ) ,
setSwapsTxMaxFeePriorityPerGas :
swapsController . setSwapsTxMaxFeePriorityPerGas . bind ( swapsController ) ,
safeRefetchQuotes :
swapsController . safeRefetchQuotes . bind ( swapsController ) ,
stopPollingForQuotes :
swapsController . stopPollingForQuotes . bind ( swapsController ) ,
setBackgroundSwapRouteState :
swapsController . setBackgroundSwapRouteState . bind ( swapsController ) ,
resetPostFetchState :
swapsController . resetPostFetchState . bind ( swapsController ) ,
2021-12-08 22:36:53 +01:00
setSwapsErrorKey : swapsController . setSwapsErrorKey . bind ( swapsController ) ,
2022-07-31 20:26:40 +02:00
setInitialGasEstimate :
swapsController . setInitialGasEstimate . bind ( swapsController ) ,
setCustomApproveTxData :
swapsController . setCustomApproveTxData . bind ( swapsController ) ,
2021-12-08 22:36:53 +01:00
setSwapsLiveness : swapsController . setSwapsLiveness . bind ( swapsController ) ,
2022-07-31 20:26:40 +02:00
setSwapsFeatureFlags :
swapsController . setSwapsFeatureFlags . bind ( swapsController ) ,
setSwapsUserFeeLevel :
swapsController . setSwapsUserFeeLevel . bind ( swapsController ) ,
setSwapsQuotesPollingLimitEnabled :
swapsController . setSwapsQuotesPollingLimitEnabled . bind ( swapsController ) ,
2020-12-02 22:41:30 +01:00
2022-02-18 17:48:38 +01:00
// Smart Transactions
2022-07-31 20:26:40 +02:00
setSmartTransactionsOptInStatus :
smartTransactionsController . setOptInState . bind (
smartTransactionsController ,
) ,
2022-02-18 17:48:38 +01:00
fetchSmartTransactionFees : smartTransactionsController . getFees . bind (
smartTransactionsController ,
) ,
2022-08-09 19:56:52 +02:00
clearSmartTransactionFees : smartTransactionsController . clearFees . bind (
smartTransactionsController ,
) ,
2022-07-31 20:26:40 +02:00
submitSignedTransactions :
smartTransactionsController . submitSignedTransactions . bind (
smartTransactionsController ,
) ,
cancelSmartTransaction :
smartTransactionsController . cancelSmartTransaction . bind (
smartTransactionsController ,
) ,
fetchSmartTransactionsLiveness :
smartTransactionsController . fetchLiveness . bind (
smartTransactionsController ,
) ,
updateSmartTransaction :
smartTransactionsController . updateSmartTransaction . bind (
smartTransactionsController ,
) ,
setStatusRefreshInterval :
smartTransactionsController . setStatusRefreshInterval . bind (
smartTransactionsController ,
) ,
2022-02-18 17:48:38 +01:00
2020-12-02 22:41:30 +01:00
// MetaMetrics
2021-12-08 22:36:53 +01:00
trackMetaMetricsEvent : metaMetricsController . trackEvent . bind (
2020-12-02 22:41:30 +01:00
metaMetricsController ,
) ,
2021-12-08 22:36:53 +01:00
trackMetaMetricsPage : metaMetricsController . trackPage . bind (
2020-12-02 22:41:30 +01:00
metaMetricsController ,
) ,
2022-01-12 20:31:54 +01:00
createEventFragment : metaMetricsController . createEventFragment . bind (
metaMetricsController ,
) ,
updateEventFragment : metaMetricsController . updateEventFragment . bind (
metaMetricsController ,
) ,
finalizeEventFragment : metaMetricsController . finalizeEventFragment . bind (
metaMetricsController ,
) ,
2021-02-12 16:25:58 +01:00
// approval controller
2022-10-31 06:52:31 +01:00
resolvePendingApproval : this . resolvePendingApproval ,
rejectPendingApproval : this . rejectPendingApproval ,
2021-04-28 18:51:41 +02:00
// Notifications
2022-04-27 10:36:32 +02:00
updateViewedNotifications : announcementController . updateViewed . bind (
announcementController ,
2021-07-08 22:23:00 +02:00
) ,
// GasFeeController
2022-07-31 20:26:40 +02:00
getGasFeeEstimatesAndStartPolling :
gasFeeController . getGasFeeEstimatesAndStartPolling . bind (
gasFeeController ,
) ,
2021-07-08 22:23:00 +02:00
2022-07-31 20:26:40 +02:00
disconnectGasFeeEstimatePoller :
gasFeeController . disconnectPoller . bind ( gasFeeController ) ,
2021-07-30 15:00:02 +02:00
2022-07-31 20:26:40 +02:00
getGasFeeTimeEstimate :
gasFeeController . getTimeEstimate . bind ( gasFeeController ) ,
2021-08-04 23:53:13 +02:00
2022-07-31 20:26:40 +02:00
addPollingTokenToAppState :
appStateController . addPollingToken . bind ( appStateController ) ,
2021-08-04 23:53:13 +02:00
2022-07-31 20:26:40 +02:00
removePollingTokenFromAppState :
appStateController . removePollingToken . bind ( appStateController ) ,
2021-09-10 20:03:42 +02:00
2022-08-09 20:36:32 +02:00
// BackupController
backupUserData : backupController . backupUserData . bind ( backupController ) ,
restoreUserData : backupController . restoreUserData . bind ( backupController ) ,
2021-09-10 20:03:42 +02:00
// DetectTokenController
2021-12-08 22:36:53 +01:00
detectNewTokens : detectTokensController . detectNewTokens . bind (
detectTokensController ,
2021-09-10 20:03:42 +02:00
) ,
2021-11-19 17:16:41 +01:00
2023-03-13 20:29:37 +01:00
// DetectCollectibleController
detectNfts : nftDetectionController . detectNfts . bind (
nftDetectionController ,
) ,
2022-04-13 18:23:41 +02:00
/** Token Detection V2 */
2022-07-31 20:26:40 +02:00
addDetectedTokens :
tokensController . addDetectedTokens . bind ( tokensController ) ,
2022-07-18 16:43:30 +02:00
addImportedTokens : tokensController . addTokens . bind ( tokensController ) ,
ignoreTokens : tokensController . ignoreTokens . bind ( tokensController ) ,
2022-07-31 20:26:40 +02:00
getBalancesInSingleCall :
assetsContractController . getBalancesInSingleCall . bind (
assetsContractController ,
) ,
2021-02-04 19:15:23 +01:00
} ;
2016-06-24 22:05:21 +02:00
}
2023-01-17 16:01:12 +01:00
async exportAccount ( address , password ) {
await this . verifyPassword ( password ) ;
return this . keyringController . exportAccount ( address , password ) ;
}
2022-03-09 15:38:12 +01:00
async getTokenStandardAndDetails ( address , userAddress , tokenId ) {
2023-03-08 18:35:45 +01:00
const { tokenList } = this . tokenListController . state ;
const { tokens } = this . tokensController . state ;
const staticTokenListDetails =
STATIC _MAINNET _TOKEN _LIST [ address . toLowerCase ( ) ] || { } ;
const tokenListDetails = tokenList [ address . toLowerCase ( ) ] || { } ;
const userDefinedTokenDetails =
tokens . find ( ( { address : _address } ) =>
isEqualCaseInsensitive ( _address , address ) ,
) || { } ;
const tokenDetails = {
... staticTokenListDetails ,
... tokenListDetails ,
... userDefinedTokenDetails ,
} ;
const tokenDetailsStandardIsERC20 =
isEqualCaseInsensitive ( tokenDetails . standard , TokenStandard . ERC20 ) ||
tokenDetails . erc20 === true ;
const noEvidenceThatTokenIsAnNFT =
! tokenId &&
! isEqualCaseInsensitive ( tokenDetails . standard , TokenStandard . ERC1155 ) &&
! isEqualCaseInsensitive ( tokenDetails . standard , TokenStandard . ERC721 ) &&
! tokenDetails . erc721 ;
const otherDetailsAreERC20Like =
tokenDetails . decimals !== undefined && tokenDetails . symbol ;
const tokenCanBeTreatedAsAnERC20 =
tokenDetailsStandardIsERC20 ||
( noEvidenceThatTokenIsAnNFT && otherDetailsAreERC20Like ) ;
let details ;
if ( tokenCanBeTreatedAsAnERC20 ) {
try {
const balance = await fetchTokenBalance (
address ,
userAddress ,
this . provider ,
) ;
details = {
address ,
balance ,
standard : TokenStandard . ERC20 ,
decimals : tokenDetails . decimals ,
symbol : tokenDetails . symbol ,
} ;
} catch ( e ) {
// If the `fetchTokenBalance` call failed, `details` remains undefined, and we
// fall back to the below `assetsContractController.getTokenStandardAndDetails` call
log . warning ( ` Failed to get token balance. Error: ${ e } ` ) ;
}
}
// `details`` will be undefined if `tokenCanBeTreatedAsAnERC20`` is false,
// or if it is true but the `fetchTokenBalance`` call failed. In either case, we should
// attempt to retrieve details from `assetsContractController.getTokenStandardAndDetails`
if ( details === undefined ) {
details = await this . assetsContractController . getTokenStandardAndDetails (
2022-07-31 20:26:40 +02:00
address ,
userAddress ,
tokenId ,
) ;
2023-03-08 18:35:45 +01:00
}
2022-03-09 15:38:12 +01:00
return {
... details ,
decimals : details ? . decimals ? . toString ( 10 ) ,
balance : details ? . balance ? . toString ( 10 ) ,
} ;
}
2019-07-31 22:17:11 +02:00
//=============================================================================
// VAULT / KEYRING RELATED METHODS
//=============================================================================
2017-01-27 07:30:12 +01:00
2018-03-15 23:27:10 +01:00
/ * *
2018-04-19 02:54:50 +02:00
* Creates a new Vault and create a new keychain .
2018-03-28 03:07:51 +02:00
*
2018-04-19 02:54:50 +02:00
* A vault , or KeyringController , is a controller that contains
* many different account strategies , currently called Keyrings .
* Creating it new means wiping all previous keyrings .
2018-03-28 03:07:51 +02:00
*
2018-04-19 02:54:50 +02:00
* A keychain , or keyring , controls many accounts with a single backup and signing strategy .
* For example , a mnemonic phrase can generate many accounts , and is a keyring .
2018-03-28 03:07:51 +02:00
*
2020-11-10 18:30:41 +01:00
* @ param { string } password
2022-07-27 15:28:05 +02:00
* @ returns { object } vault
2018-03-15 23:27:10 +01:00
* /
2020-11-03 00:41:28 +01:00
async createNewVaultAndKeychain ( password ) {
2021-02-04 19:15:23 +01:00
const releaseLock = await this . createVaultMutex . acquire ( ) ;
2017-11-20 22:47:35 +01:00
try {
2021-02-04 19:15:23 +01:00
let vault ;
const accounts = await this . keyringController . getAccounts ( ) ;
2017-11-20 22:47:35 +01:00
if ( accounts . length > 0 ) {
2021-02-04 19:15:23 +01:00
vault = await this . keyringController . fullUpdate ( ) ;
2017-11-20 22:47:35 +01:00
} else {
2021-02-04 19:15:23 +01:00
vault = await this . keyringController . createNewVaultAndKeychain (
password ,
) ;
const addresses = await this . keyringController . getAccounts ( ) ;
this . preferencesController . setAddresses ( addresses ) ;
this . selectFirstIdentity ( ) ;
2017-11-20 22:47:35 +01:00
}
2021-11-05 17:13:29 +01:00
2021-02-04 19:15:23 +01:00
return vault ;
2020-03-23 17:25:55 +01:00
} finally {
2021-02-04 19:15:23 +01:00
releaseLock ( ) ;
2017-11-20 22:27:29 +01:00
}
}
2018-03-15 23:27:10 +01:00
/ * *
2018-04-19 02:54:50 +02:00
* Create a new Vault and restore an existent keyring .
2022-01-07 16:57:33 +01:00
*
2020-11-10 18:30:41 +01:00
* @ param { string } password
2021-07-30 23:37:40 +02:00
* @ param { number [ ] } encodedSeedPhrase - The seed phrase , encoded as an array
* of UTF - 8 bytes .
2018-03-15 23:27:10 +01:00
* /
2021-07-30 23:37:40 +02:00
async createNewVaultAndRestore ( password , encodedSeedPhrase ) {
2021-02-04 19:15:23 +01:00
const releaseLock = await this . createVaultMutex . acquire ( ) ;
2018-01-04 01:06:46 +01:00
try {
2021-02-04 19:15:23 +01:00
let accounts , lastBalance ;
2018-07-27 05:40:11 +02:00
2021-07-30 23:37:40 +02:00
const seedPhraseAsBuffer = Buffer . from ( encodedSeedPhrase ) ;
2021-02-04 19:15:23 +01:00
const { keyringController } = this ;
2018-07-27 05:40:11 +02:00
2018-06-03 21:02:35 +02:00
// clear known identities
2021-02-04 19:15:23 +01:00
this . preferencesController . setAddresses ( [ ] ) ;
2020-06-14 03:42:39 +02:00
// clear permissions
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
this . permissionController . clearState ( ) ;
2020-06-14 03:42:39 +02:00
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-10-24 14:08:08 +02:00
// Clear snap state
this . snapController . clearState ( ) ;
2022-11-22 13:32:15 +01:00
// Clear notification state
this . notificationController . clear ( ) ;
2022-10-24 14:08:08 +02:00
///: END:ONLY_INCLUDE_IN
2020-07-17 04:09:38 +02:00
// clear accounts in accountTracker
2021-02-04 19:15:23 +01:00
this . accountTracker . clearAccounts ( ) ;
2020-07-17 04:09:38 +02:00
// clear cachedBalances
2021-02-04 19:15:23 +01:00
this . cachedBalancesController . clearCachedBalances ( ) ;
2020-07-17 04:09:38 +02:00
2020-07-17 03:37:56 +02:00
// clear unapproved transactions
2021-02-04 19:15:23 +01:00
this . txController . txStateManager . clearUnapprovedTxs ( ) ;
2020-07-17 03:37:56 +02:00
2018-06-03 21:02:35 +02:00
// create new vault
2020-11-03 00:41:28 +01:00
const vault = await keyringController . createNewVaultAndRestore (
password ,
2021-07-30 23:37:40 +02:00
seedPhraseAsBuffer ,
2021-02-04 19:15:23 +01:00
) ;
2018-07-27 05:40:11 +02:00
2021-02-04 19:15:23 +01:00
const ethQuery = new EthQuery ( this . provider ) ;
accounts = await keyringController . getAccounts ( ) ;
2020-11-03 00:41:28 +01:00
lastBalance = await this . getBalance (
accounts [ accounts . length - 1 ] ,
ethQuery ,
2021-02-04 19:15:23 +01:00
) ;
2018-07-27 05:40:11 +02:00
2022-11-21 15:23:35 +01:00
const [ primaryKeyring ] = keyringController . getKeyringsByType (
2023-03-21 15:43:22 +01:00
KeyringType . hdKeyTree ,
2022-11-21 15:23:35 +01:00
) ;
2018-07-27 05:40:11 +02:00
if ( ! primaryKeyring ) {
2021-02-04 19:15:23 +01:00
throw new Error ( 'MetamaskController - No HD Key Tree found' ) ;
2018-07-27 05:40:11 +02:00
}
// seek out the first zero balance
while ( lastBalance !== '0x0' ) {
2021-02-04 19:15:23 +01:00
await keyringController . addNewAccount ( primaryKeyring ) ;
accounts = await keyringController . getAccounts ( ) ;
2020-11-03 00:41:28 +01:00
lastBalance = await this . getBalance (
accounts [ accounts . length - 1 ] ,
ethQuery ,
2021-02-04 19:15:23 +01:00
) ;
2018-07-27 05:40:11 +02:00
}
2021-09-16 23:20:57 +02:00
// remove extra zero balance account potentially created from seeking ahead
if ( accounts . length > 1 && lastBalance === '0x0' ) {
await this . removeAccount ( accounts [ accounts . length - 1 ] ) ;
accounts = await keyringController . getAccounts ( ) ;
}
2021-11-03 17:23:13 +01:00
// This must be set as soon as possible to communicate to the
// keyring's iframe and have the setting initialized properly
2022-06-03 18:32:50 +02:00
// Optimistically called to not block MetaMask login due to
2021-11-03 17:23:13 +01:00
// Ledger Keyring GitHub downtime
2022-07-31 20:26:40 +02:00
const transportPreference =
this . preferencesController . getLedgerTransportPreference ( ) ;
2021-11-03 17:23:13 +01:00
this . setLedgerTransportPreference ( transportPreference ) ;
2018-06-03 21:02:35 +02:00
// set new identities
2021-02-04 19:15:23 +01:00
this . preferencesController . setAddresses ( accounts ) ;
this . selectFirstIdentity ( ) ;
return vault ;
2020-03-23 17:25:55 +01:00
} finally {
2021-02-04 19:15:23 +01:00
releaseLock ( ) ;
2018-01-04 01:06:46 +01:00
}
2017-10-17 22:19:57 +02:00
}
2018-07-27 05:40:11 +02:00
/ * *
* Get an account balance from the AccountTracker or request it directly from the network .
2022-01-07 16:57:33 +01:00
*
2018-07-27 05:40:11 +02:00
* @ param { string } address - The account address
* @ param { EthQuery } ethQuery - The EthQuery instance to use when asking the network
* /
2020-11-03 00:41:28 +01:00
getBalance ( address , ethQuery ) {
2018-07-27 05:40:11 +02:00
return new Promise ( ( resolve , reject ) => {
2021-02-04 19:15:23 +01:00
const cached = this . accountTracker . store . getState ( ) . accounts [ address ] ;
2018-07-27 05:40:11 +02:00
if ( cached && cached . balance ) {
2021-02-04 19:15:23 +01:00
resolve ( cached . balance ) ;
2018-07-27 05:40:11 +02:00
} else {
ethQuery . getBalance ( address , ( error , balance ) => {
if ( error ) {
2021-02-04 19:15:23 +01:00
reject ( error ) ;
log . error ( error ) ;
2018-07-27 05:40:11 +02:00
} else {
2021-02-04 19:15:23 +01:00
resolve ( balance || '0x0' ) ;
2018-07-27 05:40:11 +02:00
}
2021-02-04 19:15:23 +01:00
} ) ;
2018-07-27 05:40:11 +02:00
}
2021-02-04 19:15:23 +01:00
} ) ;
2018-07-27 05:40:11 +02:00
}
2022-01-07 16:57:33 +01:00
/ * *
2018-06-04 22:43:26 +02:00
* Submits the user ' s password and attempts to unlock the vault .
* Also synchronizes the preferencesController , to ensure its schema
* is up to date with known accounts once the vault is decrypted .
*
* @ param { string } password - The user ' s password
2020-11-10 18:30:41 +01:00
* @ returns { Promise < object > } The keyringController update .
2018-06-04 22:43:26 +02:00
* /
2020-11-03 00:41:28 +01:00
async submitPassword ( password ) {
2021-02-04 19:15:23 +01:00
await this . keyringController . submitPassword ( password ) ;
2018-06-04 22:43:26 +02:00
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
this . mmiController . onSubmitPassword ( ) ;
///: END:ONLY_INCLUDE_IN
2020-09-09 07:29:24 +02:00
try {
2021-02-04 19:15:23 +01:00
await this . blockTracker . checkForLatestBlock ( ) ;
2020-09-09 07:29:24 +02:00
} catch ( error ) {
2021-02-04 19:15:23 +01:00
log . error ( 'Error while unlocking extension.' , error ) ;
2020-09-09 07:29:24 +02:00
}
2019-09-16 19:11:01 +02:00
2021-04-26 20:05:48 +02:00
// This must be set as soon as possible to communicate to the
// keyring's iframe and have the setting initialized properly
2022-06-03 18:32:50 +02:00
// Optimistically called to not block MetaMask login due to
2021-04-26 20:05:48 +02:00
// Ledger Keyring GitHub downtime
2022-07-31 20:26:40 +02:00
const transportPreference =
this . preferencesController . getLedgerTransportPreference ( ) ;
2021-10-21 21:17:03 +02:00
this . setLedgerTransportPreference ( transportPreference ) ;
2021-04-26 20:05:48 +02:00
2021-02-04 19:15:23 +01:00
return this . keyringController . fullUpdate ( ) ;
2018-06-04 22:43:26 +02:00
}
2022-11-24 01:49:24 +01:00
async _loginUser ( ) {
try {
// Automatic login via config password
2023-04-25 16:32:51 +02:00
const password = process . env . PASSWORD ;
2023-03-31 15:22:33 +02:00
if ( password && ! process . env . IN _TEST ) {
2022-11-24 01:49:24 +01:00
await this . submitPassword ( password ) ;
}
// Automatic login via storage encryption key
else if ( isManifestV3 ) {
await this . submitEncryptionKey ( ) ;
}
// Updating accounts in this.accountTracker before starting UI syncing ensure that
// state has account balance before it is synced with UI
await this . accountTracker . _updateAccounts ( ) ;
} finally {
this . _startUISync ( ) ;
}
}
_startUISync ( ) {
// Message startUISync is used in MV3 to start syncing state with UI
// Sending this message after login is completed helps to ensure that incomplete state without
// account details are not flushed to UI.
this . emit ( 'startUISync' ) ;
this . startUISync = true ;
this . memStore . subscribe ( this . sendUpdate . bind ( this ) ) ;
}
/ * *
* Submits a user ' s encryption key to log the user in via login token
* /
async submitEncryptionKey ( ) {
try {
2023-04-06 16:43:01 +02:00
const { loginToken , loginSalt } =
await this . extension . storage . session . get ( [ 'loginToken' , 'loginSalt' ] ) ;
2022-11-24 01:49:24 +01:00
if ( loginToken && loginSalt ) {
const { vault } = this . keyringController . store . getState ( ) ;
2023-03-01 19:20:50 +01:00
const jsonVault = JSON . parse ( vault ) ;
if ( jsonVault . salt !== loginSalt ) {
2022-11-24 01:49:24 +01:00
console . warn (
'submitEncryptionKey: Stored salt and vault salt do not match' ,
) ;
await this . clearLoginArtifacts ( ) ;
return ;
}
await this . keyringController . submitEncryptionKey ( loginToken , loginSalt ) ;
}
} catch ( e ) {
// If somehow this login token doesn't work properly,
// remove it and the user will get shown back to the unlock screen
await this . clearLoginArtifacts ( ) ;
throw e ;
}
}
async clearLoginArtifacts ( ) {
2023-04-06 16:43:01 +02:00
await this . extension . storage . session . remove ( [ 'loginToken' , 'loginSalt' ] ) ;
2022-11-24 01:49:24 +01:00
}
2020-07-25 00:47:40 +02:00
/ * *
* Submits a user ' s password to check its validity .
*
2022-01-07 16:57:33 +01:00
* @ param { string } password - The user ' s password
2020-07-25 00:47:40 +02:00
* /
2020-11-03 00:41:28 +01:00
async verifyPassword ( password ) {
2021-02-04 19:15:23 +01:00
await this . keyringController . verifyPassword ( password ) ;
2020-07-25 00:47:40 +02:00
}
2018-04-19 02:54:50 +02:00
/ * *
* @ type Identity
* @ property { string } name - The account nickname .
* @ property { string } address - The account ' s ethereum address , in lower case .
* receiving funds from our automatic Ropsten faucet .
* /
2018-03-15 23:27:10 +01:00
/ * *
2018-04-19 05:33:51 +02:00
* Sets the first address in the state to the selected address
2018-03-15 23:27:10 +01:00
* /
2020-11-03 00:41:28 +01:00
selectFirstIdentity ( ) {
2021-02-04 19:15:23 +01:00
const { identities } = this . preferencesController . store . getState ( ) ;
2022-09-27 17:52:01 +02:00
const [ address ] = Object . keys ( identities ) ;
2021-02-04 19:15:23 +01:00
this . preferencesController . setSelectedAddress ( address ) ;
2017-10-17 22:19:57 +02:00
}
2022-02-15 01:02:51 +01:00
/ * *
* Gets the mnemonic of the user ' s primary keyring .
* /
getPrimaryKeyringMnemonic ( ) {
2022-11-21 15:23:35 +01:00
const [ keyring ] = this . keyringController . getKeyringsByType (
2023-03-21 15:43:22 +01:00
KeyringType . hdKeyTree ,
2022-11-21 15:23:35 +01:00
) ;
2022-02-15 01:02:51 +01:00
if ( ! keyring . mnemonic ) {
throw new Error ( 'Primary keyring mnemonic unavailable.' ) ;
}
2023-01-21 00:03:11 +01:00
2023-01-23 20:41:04 +01:00
return keyring . mnemonic ;
2022-02-15 01:02:51 +01:00
}
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
async getCustodyKeyringIfExists ( address ) {
const custodyType = this . custodyController . getCustodyTypeByAddress (
toChecksumHexAddress ( address ) ,
) ;
const keyring = this . keyringController . getKeyringsByType ( custodyType ) [ 0 ] ;
return keyring ? . getAccountDetails ( address ) ? keyring : undefined ;
}
///: END:ONLY_INCLUDE_IN
2018-06-10 09:52:32 +02:00
//
// Hardware
//
2020-11-03 00:41:28 +01:00
async getKeyringForDevice ( deviceName , hdPath = null ) {
2023-02-20 18:13:12 +01:00
const keyringOverrides = this . opts . overrides ? . keyrings ;
2021-02-04 19:15:23 +01:00
let keyringName = null ;
2023-01-25 22:12:08 +01:00
if (
deviceName !== HardwareDeviceNames . QR &&
! this . canUseHardwareWallets ( )
) {
throw new Error ( 'Hardware wallets are not supported on this version.' ) ;
}
2018-08-11 03:54:34 +02:00
switch ( deviceName ) {
2023-01-20 16:14:40 +01:00
case HardwareDeviceNames . trezor :
2023-02-20 18:13:12 +01:00
keyringName = keyringOverrides ? . trezor ? . type || TrezorKeyring . type ;
2021-02-04 19:15:23 +01:00
break ;
2023-01-20 16:14:40 +01:00
case HardwareDeviceNames . ledger :
2023-02-20 18:13:12 +01:00
keyringName =
keyringOverrides ? . ledger ? . type || LedgerBridgeKeyring . type ;
2021-02-04 19:15:23 +01:00
break ;
2023-01-20 16:14:40 +01:00
case HardwareDeviceNames . qr :
2021-11-23 18:28:39 +01:00
keyringName = QRHardwareKeyring . type ;
break ;
2023-01-20 16:14:40 +01:00
case HardwareDeviceNames . lattice :
2023-02-20 18:13:12 +01:00
keyringName = keyringOverrides ? . lattice ? . type || LatticeKeyring . type ;
2021-11-08 15:48:41 +01:00
break ;
2018-08-11 03:54:34 +02:00
default :
2020-11-03 00:41:28 +01:00
throw new Error (
'MetamaskController:getKeyringForDevice - Unknown device' ,
2021-02-04 19:15:23 +01:00
) ;
2018-08-11 03:54:34 +02:00
}
2022-09-27 17:52:01 +02:00
let [ keyring ] = await this . keyringController . getKeyringsByType ( keyringName ) ;
2018-08-11 03:54:34 +02:00
if ( ! keyring ) {
2021-02-04 19:15:23 +01:00
keyring = await this . keyringController . addNewKeyring ( keyringName ) ;
2018-08-11 03:54:34 +02:00
}
2018-08-14 09:42:23 +02:00
if ( hdPath && keyring . setHdPath ) {
2021-02-04 19:15:23 +01:00
keyring . setHdPath ( hdPath ) ;
2018-08-14 01:29:43 +02:00
}
2023-01-20 16:14:40 +01:00
if ( deviceName === HardwareDeviceNames . lattice ) {
2021-11-08 15:48:41 +01:00
keyring . appName = 'MetaMask' ;
}
2023-01-20 16:14:40 +01:00
if ( deviceName === HardwareDeviceNames . trezor ) {
2021-11-30 15:28:28 +01:00
const model = keyring . getModel ( ) ;
this . appStateController . setTrezorModel ( model ) ;
}
2023-05-02 17:53:20 +02:00
keyring . network =
this . networkController . store . getState ( ) . providerConfig . type ;
2018-08-14 07:26:18 +02:00
2021-02-04 19:15:23 +01:00
return keyring ;
2018-08-11 03:54:34 +02:00
}
2021-11-04 19:19:53 +01:00
async attemptLedgerTransportCreation ( ) {
2023-01-20 16:14:40 +01:00
const keyring = await this . getKeyringForDevice ( HardwareDeviceNames . ledger ) ;
2021-11-04 19:19:53 +01:00
return await keyring . attemptMakeApp ( ) ;
}
2021-11-05 17:13:29 +01:00
async establishLedgerTransportPreference ( ) {
2022-07-31 20:26:40 +02:00
const transportPreference =
this . preferencesController . getLedgerTransportPreference ( ) ;
2021-11-05 17:13:29 +01:00
return await this . setLedgerTransportPreference ( transportPreference ) ;
}
2018-08-11 03:54:34 +02:00
2018-06-10 09:52:32 +02:00
/ * *
* Fetch account list from a trezor device .
*
2022-01-07 16:57:33 +01:00
* @ param deviceName
* @ param page
* @ param hdPath
2018-06-10 09:52:32 +02:00
* @ returns [ ] accounts
* /
2020-11-03 00:41:28 +01:00
async connectHardware ( deviceName , page , hdPath ) {
2021-02-04 19:15:23 +01:00
const keyring = await this . getKeyringForDevice ( deviceName , hdPath ) ;
let accounts = [ ] ;
2018-08-11 03:54:34 +02:00
switch ( page ) {
2019-07-31 22:17:11 +02:00
case - 1 :
2021-02-04 19:15:23 +01:00
accounts = await keyring . getPreviousPage ( ) ;
break ;
2019-07-31 22:17:11 +02:00
case 1 :
2021-02-04 19:15:23 +01:00
accounts = await keyring . getNextPage ( ) ;
break ;
2019-07-31 22:17:11 +02:00
default :
2021-02-04 19:15:23 +01:00
accounts = await keyring . getFirstPage ( ) ;
2018-06-13 08:09:25 +02:00
}
2018-08-11 03:54:34 +02:00
// Merge with existing accounts
// and make sure addresses are not repeated
2021-02-04 19:15:23 +01:00
const oldAccounts = await this . keyringController . getAccounts ( ) ;
2020-11-03 00:41:28 +01:00
const accountsToTrack = [
... new Set (
oldAccounts . concat ( accounts . map ( ( a ) => a . address . toLowerCase ( ) ) ) ,
) ,
2021-02-04 19:15:23 +01:00
] ;
this . accountTracker . syncWithAddresses ( accountsToTrack ) ;
return accounts ;
2018-06-10 09:52:32 +02:00
}
2018-07-17 01:36:08 +02:00
/ * *
* Check if the device is unlocked
*
2022-01-07 16:57:33 +01:00
* @ param deviceName
* @ param hdPath
2018-07-17 01:36:08 +02:00
* @ returns { Promise < boolean > }
* /
2020-11-03 00:41:28 +01:00
async checkHardwareStatus ( deviceName , hdPath ) {
2021-02-04 19:15:23 +01:00
const keyring = await this . getKeyringForDevice ( deviceName , hdPath ) ;
return keyring . isUnlocked ( ) ;
2018-07-12 03:21:36 +02:00
}
2018-07-17 01:36:08 +02:00
/ * *
* Clear
*
2022-01-07 16:57:33 +01:00
* @ param deviceName
2018-07-17 01:36:08 +02:00
* @ returns { Promise < boolean > }
* /
2020-11-03 00:41:28 +01:00
async forgetDevice ( deviceName ) {
2021-02-04 19:15:23 +01:00
const keyring = await this . getKeyringForDevice ( deviceName ) ;
keyring . forgetDevice ( ) ;
return true ;
2018-07-12 03:21:36 +02:00
}
2022-02-23 16:15:41 +01:00
/ * *
* Retrieves the keyring for the selected address and using the . type returns
* a subtype for the account . Either 'hardware' , 'imported' or 'MetaMask' .
*
* @ param { string } address - Address to retrieve keyring for
* @ returns { 'hardware' | 'imported' | 'MetaMask' }
* /
async getAccountType ( address ) {
const keyring = await this . keyringController . getKeyringForAccount ( address ) ;
switch ( keyring . type ) {
2023-03-21 15:43:22 +01:00
case KeyringType . trezor :
case KeyringType . lattice :
case KeyringType . qr :
case KeyringType . ledger :
2022-02-23 16:15:41 +01:00
return 'hardware' ;
2023-03-21 15:43:22 +01:00
case KeyringType . imported :
2022-02-23 16:15:41 +01:00
return 'imported' ;
default :
return 'MetaMask' ;
}
}
/ * *
* Retrieves the keyring for the selected address and using the . type
* determines if a more specific name for the device is available . Returns
* 'N/A' for non hardware wallets .
*
* @ param { string } address - Address to retrieve keyring for
* @ returns { 'ledger' | 'lattice' | 'N/A' | string }
* /
async getDeviceModel ( address ) {
const keyring = await this . keyringController . getKeyringForAccount ( address ) ;
switch ( keyring . type ) {
2023-03-21 15:43:22 +01:00
case KeyringType . trezor :
2022-02-23 16:15:41 +01:00
return keyring . getModel ( ) ;
2023-03-21 15:43:22 +01:00
case KeyringType . qr :
2022-02-23 16:15:41 +01:00
return keyring . getName ( ) ;
2023-03-21 15:43:22 +01:00
case KeyringType . ledger :
2022-02-23 16:15:41 +01:00
// TODO: get model after ledger keyring exposes method
2023-01-20 16:14:40 +01:00
return HardwareDeviceNames . ledger ;
2023-03-21 15:43:22 +01:00
case KeyringType . lattice :
2022-02-23 16:15:41 +01:00
// TODO: get model after lattice keyring exposes method
2023-01-20 16:14:40 +01:00
return HardwareDeviceNames . lattice ;
2022-02-23 16:15:41 +01:00
default :
return 'N/A' ;
}
}
2021-11-23 18:28:39 +01:00
/ * *
* get hardware account label
*
2022-01-07 16:57:33 +01:00
* @ returns string label
* /
2021-11-23 18:28:39 +01:00
getAccountLabel ( name , index , hdPathDescription ) {
return ` ${ name [ 0 ] . toUpperCase ( ) } ${ name . slice ( 1 ) } ${
parseInt ( index , 10 ) + 1
} $ { hdPathDescription || '' } ` .trim();
}
2018-06-10 09:52:32 +02:00
/ * *
2021-03-09 21:39:16 +01:00
* Imports an account from a Trezor or Ledger device .
2018-06-10 09:52:32 +02:00
*
2022-01-07 16:57:33 +01:00
* @ param index
* @ param deviceName
* @ param hdPath
* @ param hdPathDescription
2018-06-10 09:52:32 +02:00
* @ returns { } keyState
* /
2021-03-09 21:39:16 +01:00
async unlockHardwareWalletAccount (
index ,
deviceName ,
hdPath ,
hdPathDescription ,
) {
2021-02-04 19:15:23 +01:00
const keyring = await this . getKeyringForDevice ( deviceName , hdPath ) ;
2018-06-10 09:52:32 +02:00
2021-02-04 19:15:23 +01:00
keyring . setAccountToUnlock ( index ) ;
const oldAccounts = await this . keyringController . getAccounts ( ) ;
const keyState = await this . keyringController . addNewAccount ( keyring ) ;
const newAccounts = await this . keyringController . getAccounts ( ) ;
this . preferencesController . setAddresses ( newAccounts ) ;
2020-02-15 21:34:12 +01:00
newAccounts . forEach ( ( address ) => {
2018-06-10 09:52:32 +02:00
if ( ! oldAccounts . includes ( address ) ) {
2021-11-23 18:28:39 +01:00
const label = this . getAccountLabel (
2023-01-20 16:14:40 +01:00
deviceName === HardwareDeviceNames . qr
? keyring . getName ( )
: deviceName ,
2021-11-23 18:28:39 +01:00
index ,
hdPathDescription ,
) ;
// Set the account label to Trezor 1 / Ledger 1 / QR Hardware 1, etc
2021-03-09 21:39:16 +01:00
this . preferencesController . setAccountLabel ( address , label ) ;
2018-08-21 06:04:30 +02:00
// Select the account
2021-02-04 19:15:23 +01:00
this . preferencesController . setSelectedAddress ( address ) ;
2018-06-10 09:52:32 +02:00
}
2021-02-04 19:15:23 +01:00
} ) ;
2018-06-10 09:52:32 +02:00
2021-02-04 19:15:23 +01:00
const { identities } = this . preferencesController . store . getState ( ) ;
return { ... keyState , identities } ;
2019-07-31 22:17:11 +02:00
}
2018-06-13 08:09:25 +02:00
2018-04-19 02:54:50 +02:00
//
// Account Management
2017-01-27 07:30:12 +01:00
//
2018-03-15 23:27:10 +01:00
/ * *
2018-04-19 02:54:50 +02:00
* Adds a new account to the default ( first ) HD seed phrase Keyring .
2018-03-28 03:07:51 +02:00
*
2022-08-16 08:12:00 +02:00
* @ param accountCount
2018-03-15 23:27:10 +01:00
* @ returns { } keyState
* /
2022-08-16 08:12:00 +02:00
async addNewAccount ( accountCount ) {
2023-03-31 15:22:33 +02:00
const isActionMetricsQueueE2ETest =
this . appStateController . store . getState ( ) [ ACTION _QUEUE _METRICS _E2E _TEST ] ;
if ( process . env . IN _TEST && isActionMetricsQueueE2ETest ) {
await new Promise ( ( resolve ) => setTimeout ( resolve , 5_000 ) ) ;
}
2022-11-21 15:23:35 +01:00
const [ primaryKeyring ] = this . keyringController . getKeyringsByType (
2023-03-21 15:43:22 +01:00
KeyringType . hdKeyTree ,
2022-11-21 15:23:35 +01:00
) ;
2018-03-06 15:56:27 +01:00
if ( ! primaryKeyring ) {
2021-02-04 19:15:23 +01:00
throw new Error ( 'MetamaskController - No HD Key Tree found' ) ;
2018-03-06 15:56:27 +01:00
}
2021-02-04 19:15:23 +01:00
const { keyringController } = this ;
2022-08-16 08:12:00 +02:00
const { identities : oldIdentities } =
this . preferencesController . store . getState ( ) ;
2017-10-19 21:15:26 +02:00
2022-08-16 08:12:00 +02:00
if ( Object . keys ( oldIdentities ) . length === accountCount ) {
const oldAccounts = await keyringController . getAccounts ( ) ;
const keyState = await keyringController . addNewAccount ( primaryKeyring ) ;
const newAccounts = await keyringController . getAccounts ( ) ;
2018-03-06 15:56:27 +01:00
2022-08-16 08:12:00 +02:00
await this . verifySeedPhrase ( ) ;
2017-10-19 21:15:26 +02:00
2022-08-16 08:12:00 +02:00
this . preferencesController . setAddresses ( newAccounts ) ;
newAccounts . forEach ( ( address ) => {
if ( ! oldAccounts . includes ( address ) ) {
this . preferencesController . setSelectedAddress ( address ) ;
}
} ) ;
const { identities } = this . preferencesController . store . getState ( ) ;
return { ... keyState , identities } ;
}
return {
... keyringController . memStore . getState ( ) ,
identities : oldIdentities ,
} ;
2017-01-27 07:30:12 +01:00
}
2018-03-15 23:27:10 +01:00
/ * *
* Verifies the validity of the current vault ' s seed phrase .
2018-03-28 03:07:51 +02:00
*
2018-03-16 01:29:53 +01:00
* Validity : seed phrase restores the accounts belonging to the current vault .
2018-03-15 23:27:10 +01:00
*
* Called when the first account is created and on unlocking the vault .
2018-04-19 02:54:50 +02:00
*
2021-07-30 23:37:40 +02:00
* @ returns { Promise < number [ ] > } The seed phrase to be confirmed by the user ,
* encoded as an array of UTF - 8 bytes .
2018-03-15 23:27:10 +01:00
* /
2020-11-03 00:41:28 +01:00
async verifySeedPhrase ( ) {
2022-11-21 15:23:35 +01:00
const [ primaryKeyring ] = this . keyringController . getKeyringsByType (
2023-03-21 15:43:22 +01:00
KeyringType . hdKeyTree ,
2022-11-21 15:23:35 +01:00
) ;
2018-03-06 15:56:27 +01:00
if ( ! primaryKeyring ) {
2021-02-04 19:15:23 +01:00
throw new Error ( 'MetamaskController - No HD Key Tree found' ) ;
2018-03-06 15:56:27 +01:00
}
2021-02-04 19:15:23 +01:00
const serialized = await primaryKeyring . serialize ( ) ;
2021-07-30 23:37:40 +02:00
const seedPhraseAsBuffer = Buffer . from ( serialized . mnemonic ) ;
2018-03-06 15:56:27 +01:00
2021-02-04 19:15:23 +01:00
const accounts = await primaryKeyring . getAccounts ( ) ;
2018-03-06 15:56:27 +01:00
if ( accounts . length < 1 ) {
2021-02-04 19:15:23 +01:00
throw new Error ( 'MetamaskController - No accounts found' ) ;
2018-03-06 15:56:27 +01:00
}
try {
2021-07-30 23:37:40 +02:00
await seedPhraseVerifier . verifyAccounts ( accounts , seedPhraseAsBuffer ) ;
return Array . from ( seedPhraseAsBuffer . values ( ) ) ;
2018-03-06 15:56:27 +01:00
} catch ( err ) {
2021-02-04 19:15:23 +01:00
log . error ( err . message ) ;
throw err ;
2018-03-06 15:56:27 +01:00
}
2017-01-27 07:30:12 +01:00
}
2018-03-15 23:27:10 +01:00
/ * *
2018-04-19 02:54:50 +02:00
* Clears the transaction history , to allow users to force - reset their nonces .
* Mostly used in development environments , when networks are restarted with
* the same network ID .
*
2020-11-10 18:30:41 +01:00
* @ returns { Promise < string > } The current selected address .
2018-03-15 23:27:10 +01:00
* /
2020-11-03 00:41:28 +01:00
async resetAccount ( ) {
2021-02-04 19:15:23 +01:00
const selectedAddress = this . preferencesController . getSelectedAddress ( ) ;
this . txController . wipeTransactions ( selectedAddress ) ;
this . networkController . resetConnection ( ) ;
2018-03-28 03:07:51 +02:00
2021-02-04 19:15:23 +01:00
return selectedAddress ;
2018-01-31 09:33:15 +01:00
}
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
/ * *
* Gets the permitted accounts for the specified origin . Returns an empty
* array if no accounts are permitted .
*
* @ param { string } origin - The origin whose exposed accounts to retrieve .
2022-04-29 15:05:14 +02:00
* @ param { boolean } [ suppressUnauthorizedError ] - Suppresses the unauthorized error .
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
* @ returns { Promise < string [ ] > } The origin ' s permitted accounts , or an empty
* array .
* /
2022-04-29 15:05:14 +02:00
async getPermittedAccounts (
origin ,
{ suppressUnauthorizedError = true } = { } ,
) {
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
try {
return await this . permissionController . executeRestrictedMethod (
origin ,
RestrictedMethods . eth _accounts ,
) ;
} catch ( error ) {
2022-04-29 15:05:14 +02:00
if (
suppressUnauthorizedError &&
error . code === rpcErrorCodes . provider . unauthorized
) {
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
return [ ] ;
}
throw error ;
}
}
/ * *
* Stops exposing the account with the specified address to all third parties .
* Exposed accounts are stored in caveats of the eth _accounts permission . This
* method uses ` PermissionController.updatePermissionsByCaveat ` to
* remove the specified address from every eth _accounts permission . If a
* permission only included this address , the permission is revoked entirely .
*
* @ param { string } targetAccount - The address of the account to stop exposing
* to third parties .
* /
removeAllAccountPermissions ( targetAccount ) {
this . permissionController . updatePermissionsByCaveat (
CaveatTypes . restrictReturnedAccounts ,
( existingAccounts ) =>
CaveatMutatorFactories [
CaveatTypes . restrictReturnedAccounts
] . removeAccount ( targetAccount , existingAccounts ) ,
) ;
}
2018-07-11 06:20:40 +02:00
/ * *
2018-07-12 02:01:44 +02:00
* Removes an account from state / storage .
2018-07-11 06:20:40 +02:00
*
2020-01-13 19:36:36 +01:00
* @ param { string [ ] } address - A hex address
2018-07-11 06:20:40 +02:00
* /
2020-11-03 00:41:28 +01:00
async removeAccount ( address ) {
2020-06-15 15:27:27 +02:00
// Remove all associated permissions
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
this . removeAllAccountPermissions ( address ) ;
2018-07-12 02:01:44 +02:00
// Remove account from the preferences controller
2021-02-04 19:15:23 +01:00
this . preferencesController . removeAddress ( address ) ;
2018-07-12 02:01:44 +02:00
// Remove account from the account tracker controller
2021-02-04 19:15:23 +01:00
this . accountTracker . removeAccount ( [ address ] ) ;
2018-08-21 06:04:07 +02:00
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
this . custodyController . removeAccount ( address ) ;
///: END:ONLY_INCLUDE_IN(build-mmi)
2022-06-21 21:03:54 +02:00
const keyring = await this . keyringController . getKeyringForAccount ( address ) ;
2018-07-12 02:01:44 +02:00
// Remove account from the keyring
2021-02-04 19:15:23 +01:00
await this . keyringController . removeAccount ( address ) ;
2022-06-21 21:03:54 +02:00
const updatedKeyringAccounts = keyring ? await keyring . getAccounts ( ) : { } ;
if ( updatedKeyringAccounts ? . length === 0 ) {
keyring . destroy ? . ( ) ;
}
2021-02-04 19:15:23 +01:00
return address ;
2018-07-11 06:20:40 +02:00
}
2018-03-15 23:27:10 +01:00
/ * *
2018-04-19 02:54:50 +02:00
* Imports an account with the specified import strategy .
* These are defined in app / scripts / account - import - strategies
* Each strategy represents a different way of serializing an Ethereum key pair .
2018-03-28 03:07:51 +02:00
*
2020-11-10 18:30:41 +01:00
* @ param { string } strategy - A unique identifier for an account import strategy .
* @ param { any } args - The data required by that strategy to import an account .
2018-03-15 23:27:10 +01:00
* /
2020-11-03 00:41:28 +01:00
async importAccountWithStrategy ( strategy , args ) {
2021-02-04 19:15:23 +01:00
const privateKey = await accountImporter . importAccount ( strategy , args ) ;
2020-11-03 00:41:28 +01:00
const keyring = await this . keyringController . addNewKeyring (
2023-03-21 15:43:22 +01:00
KeyringType . imported ,
2020-11-03 00:41:28 +01:00
[ privateKey ] ,
2021-02-04 19:15:23 +01:00
) ;
2022-09-27 17:52:01 +02:00
const [ firstAccount ] = await keyring . getAccounts ( ) ;
2018-05-29 07:58:14 +02:00
// update accounts in preferences controller
2021-02-04 19:15:23 +01:00
const allAccounts = await this . keyringController . getAccounts ( ) ;
this . preferencesController . setAddresses ( allAccounts ) ;
2018-05-29 07:58:14 +02:00
// set new account as selected
2022-11-16 15:52:35 +01:00
this . preferencesController . setSelectedAddress ( firstAccount ) ;
2017-01-27 07:30:12 +01:00
}
2018-03-16 01:29:53 +01:00
// ---------------------------------------------------------------------------
2018-04-19 02:54:50 +02:00
// Identity Management (signature operations)
2018-08-17 18:56:07 +02:00
/ * *
* Called when a Dapp suggests a new tx to be signed .
* this wrapper needs to exist so we can provide a reference to
* "newUnapprovedTransaction" before "txController" is instantiated
*
2022-07-27 15:28:05 +02:00
* @ param { object } txParams - The transaction parameters .
* @ param { object } [ req ] - The original request , containing the origin .
2018-08-17 18:56:07 +02:00
* /
2020-11-03 00:41:28 +01:00
async newUnapprovedTransaction ( txParams , req ) {
2021-02-04 19:15:23 +01:00
return await this . txController . newUnapprovedTransaction ( txParams , req ) ;
2018-08-17 18:56:07 +02:00
}
2021-06-28 19:29:08 +02:00
/ * *
* @ returns { boolean } true if the keyring type supports EIP - 1559
* /
2021-12-09 03:46:54 +01:00
async getCurrentAccountEIP1559Compatibility ( ) {
2021-11-30 15:28:28 +01:00
return true ;
2021-06-28 19:29:08 +02:00
}
2019-07-31 22:17:11 +02:00
//=============================================================================
// END (VAULT / KEYRING RELATED METHODS)
//=============================================================================
2018-03-16 01:29:53 +01:00
2018-09-09 19:07:23 +02:00
/ * *
2021-07-08 20:48:23 +02:00
* Allows a user to attempt to cancel a previously submitted transaction
* by creating a new transaction .
2022-01-07 16:57:33 +01:00
*
2021-07-08 20:48:23 +02:00
* @ param { number } originalTxId - the id of the txMeta that you want to
* attempt to cancel
* @ param { import (
* './controllers/transactions'
* ) . CustomGasSettings } [ customGasSettings ] - overrides to use for gas params
* instead of allowing this method to generate them
2022-09-09 13:50:31 +02:00
* @ param options
2022-07-27 15:28:05 +02:00
* @ returns { object } MetaMask state
2018-09-09 19:07:23 +02:00
* /
2022-09-09 13:50:31 +02:00
async createCancelTransaction ( originalTxId , customGasSettings , options ) {
2020-11-03 00:41:28 +01:00
await this . txController . createCancelTransaction (
originalTxId ,
2021-07-08 20:48:23 +02:00
customGasSettings ,
2022-09-09 13:50:31 +02:00
options ,
2021-02-04 19:15:23 +01:00
) ;
2022-11-16 15:52:35 +01:00
const state = this . getState ( ) ;
2021-02-04 19:15:23 +01:00
return state ;
2017-12-07 05:20:15 +01:00
}
2021-07-08 20:48:23 +02:00
/ * *
* Allows a user to attempt to speed up a previously submitted transaction
* by creating a new transaction .
2022-01-07 16:57:33 +01:00
*
2021-07-08 20:48:23 +02:00
* @ param { number } originalTxId - the id of the txMeta that you want to
* attempt to speed up
* @ param { import (
* './controllers/transactions'
* ) . CustomGasSettings } [ customGasSettings ] - overrides to use for gas params
* instead of allowing this method to generate them
2022-09-13 14:43:38 +02:00
* @ param options
2022-07-27 15:28:05 +02:00
* @ returns { object } MetaMask state
2021-07-08 20:48:23 +02:00
* /
2022-09-13 14:43:38 +02:00
async createSpeedUpTransaction ( originalTxId , customGasSettings , options ) {
2020-11-03 00:41:28 +01:00
await this . txController . createSpeedUpTransaction (
originalTxId ,
2021-07-08 20:48:23 +02:00
customGasSettings ,
2022-09-13 14:43:38 +02:00
options ,
2021-02-04 19:15:23 +01:00
) ;
2022-11-16 15:52:35 +01:00
const state = this . getState ( ) ;
2021-02-04 19:15:23 +01:00
return state ;
2018-10-26 06:42:59 +02:00
}
2020-11-03 00:41:28 +01:00
estimateGas ( estimateGasParams ) {
2018-05-23 18:43:25 +02:00
return new Promise ( ( resolve , reject ) => {
2020-11-03 00:41:28 +01:00
return this . txController . txGasUtil . query . estimateGas (
estimateGasParams ,
( err , res ) => {
if ( err ) {
2021-02-04 19:15:23 +01:00
return reject ( err ) ;
2020-11-03 00:41:28 +01:00
}
2018-05-23 18:43:25 +02:00
2021-06-10 02:48:05 +02:00
return resolve ( res . toString ( 16 ) ) ;
2020-11-03 00:41:28 +01:00
} ,
2021-02-04 19:15:23 +01:00
) ;
} ) ;
2018-05-23 18:43:25 +02:00
}
2019-07-31 22:17:11 +02:00
//=============================================================================
// PASSWORD MANAGEMENT
//=============================================================================
2017-01-27 07:30:12 +01:00
2018-04-20 18:26:24 +02:00
/ * *
2018-04-19 02:54:50 +02:00
* Allows a user to begin the seed phrase recovery process .
* /
2021-12-08 22:36:53 +01:00
markPasswordForgotten ( ) {
2021-02-04 19:15:23 +01:00
this . preferencesController . setPasswordForgotten ( true ) ;
this . sendUpdate ( ) ;
2018-02-08 01:38:55 +01:00
}
2018-04-20 18:26:24 +02:00
/ * *
2018-04-19 02:54:50 +02:00
* Allows a user to end the seed phrase recovery process .
* /
2021-12-08 22:36:53 +01:00
unMarkPasswordForgotten ( ) {
2021-02-04 19:15:23 +01:00
this . preferencesController . setPasswordForgotten ( false ) ;
this . sendUpdate ( ) ;
2018-02-08 01:38:55 +01:00
}
2019-07-31 22:17:11 +02:00
//=============================================================================
// SETUP
//=============================================================================
2017-01-28 04:35:03 +01:00
2019-12-20 16:32:31 +01:00
/ * *
* A runtime . MessageSender object , as provided by the browser :
2022-01-07 16:57:33 +01:00
*
2019-12-20 16:32:31 +01:00
* @ see https : //developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/MessageSender
2022-07-27 15:28:05 +02:00
* @ typedef { object } MessageSender
2022-01-07 16:57:33 +01:00
* @ property { string } - The URL of the page or frame hosting the script that sent the message .
2019-12-20 16:32:31 +01:00
* /
2022-02-15 01:02:51 +01:00
/ * *
* A Snap sender object .
*
2022-07-27 15:28:05 +02:00
* @ typedef { object } SnapSender
2022-02-15 01:02:51 +01:00
* @ property { string } snapId - The ID of the snap .
* /
2018-04-20 18:26:24 +02:00
/ * *
2018-04-19 02:54:50 +02:00
* Used to create a multiplexed stream for connecting to an untrusted context
* like a Dapp or other extension .
2022-01-07 16:57:33 +01:00
*
2022-01-28 22:42:32 +01:00
* @ param options - Options bag .
* @ param { ReadableStream } options . connectionStream - The Duplex stream to connect to .
* @ param { MessageSender | SnapSender } options . sender - The sender of the messages on this stream .
* @ param { string } [ options . subjectType ] - The type of the sender , i . e . subject .
2018-04-19 02:54:50 +02:00
* /
2022-01-28 22:42:32 +01:00
setupUntrustedCommunication ( { connectionStream , sender , subjectType } ) {
2021-02-04 19:15:23 +01:00
const { usePhishDetect } = this . preferencesController . store . getState ( ) ;
2022-02-15 01:02:51 +01:00
2022-01-28 22:42:32 +01:00
let _subjectType ;
if ( subjectType ) {
_subjectType = subjectType ;
} else if ( sender . id && sender . id !== this . extension . runtime . id ) {
2023-01-24 16:03:01 +01:00
_subjectType = SubjectType . Extension ;
2022-01-28 22:42:32 +01:00
} else {
2023-01-24 16:03:01 +01:00
_subjectType = SubjectType . Website ;
2022-01-28 22:42:32 +01:00
}
if ( sender . url ) {
const { hostname } = new URL ( sender . url ) ;
2023-02-24 16:09:00 +01:00
this . phishingController . maybeUpdateState ( ) ;
2022-01-28 22:42:32 +01:00
// Check if new connection is blocked if phishing detection is on
2022-07-18 16:43:30 +02:00
const phishingTestResponse = this . phishingController . test ( hostname ) ;
if ( usePhishDetect && phishingTestResponse ? . result ) {
2023-02-24 16:09:00 +01:00
this . sendPhishingWarning ( connectionStream , hostname ) ;
2023-02-06 18:06:38 +01:00
this . metaMetricsController . trackEvent ( {
2023-04-03 17:31:04 +02:00
event : MetaMetricsEventName . PhishingPageDisplayed ,
category : MetaMetricsEventCategory . Phishing ,
2023-02-06 18:06:38 +01:00
properties : {
url : hostname ,
} ,
} ) ;
2022-01-28 22:42:32 +01:00
return ;
}
2016-06-24 22:05:21 +02:00
}
2018-03-16 17:37:56 +01:00
// setup multiplexing
2021-02-04 19:15:23 +01:00
const mux = setupMultiplex ( connectionStream ) ;
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
// messages between inpage and background
2022-01-28 22:42:32 +01:00
this . setupProviderConnection (
mux . createStream ( 'metamask-provider' ) ,
sender ,
_subjectType ,
) ;
2021-01-13 02:43:45 +01:00
// TODO:LegacyProvider: Delete
2022-01-28 22:42:32 +01:00
if ( sender . url ) {
// legacy streams
this . setupPublicConfig ( mux . createStream ( 'publicConfig' ) ) ;
}
2016-06-24 22:05:21 +02:00
}
2018-04-20 18:26:24 +02:00
/ * *
2018-04-19 02:54:50 +02:00
* Used to create a multiplexed stream for connecting to a trusted context ,
* like our own user interfaces , which have the provider APIs , but also
* receive the exported API from this controller , which includes trusted
* functions , like the ability to approve transactions or sign messages .
*
* @ param { * } connectionStream - The duplex stream to connect to .
2019-12-20 16:32:31 +01:00
* @ param { MessageSender } sender - The sender of the messages on this stream
2018-04-19 02:54:50 +02:00
* /
2020-11-03 00:41:28 +01:00
setupTrustedCommunication ( connectionStream , sender ) {
2018-03-16 17:37:56 +01:00
// setup multiplexing
2021-02-04 19:15:23 +01:00
const mux = setupMultiplex ( connectionStream ) ;
2018-03-16 17:37:56 +01:00
// connect features
2021-02-04 19:15:23 +01:00
this . setupControllerConnection ( mux . createStream ( 'controller' ) ) ;
2022-01-28 22:42:32 +01:00
this . setupProviderConnection (
mux . createStream ( 'provider' ) ,
sender ,
2023-01-24 16:03:01 +01:00
SubjectType . Internal ,
2022-01-28 22:42:32 +01:00
) ;
2018-03-16 17:37:56 +01:00
}
2022-05-06 00:28:48 +02:00
/ * *
* Used to create a multiplexed stream for connecting to the phishing warning page .
*
* @ param options - Options bag .
* @ param { ReadableStream } options . connectionStream - The Duplex stream to connect to .
* /
setupPhishingCommunication ( { connectionStream } ) {
const { usePhishDetect } = this . preferencesController . store . getState ( ) ;
if ( ! usePhishDetect ) {
return ;
}
// setup multiplexing
const mux = setupMultiplex ( connectionStream ) ;
const phishingStream = mux . createStream ( PHISHING _SAFELIST ) ;
// set up postStream transport
phishingStream . on (
'data' ,
createMetaRPCHandler (
2023-03-31 11:00:44 +02:00
{
safelistPhishingDomain : this . safelistPhishingDomain . bind ( this ) ,
backToSafetyPhishingWarning :
this . backToSafetyPhishingWarning . bind ( this ) ,
} ,
2022-05-06 00:28:48 +02:00
phishingStream ,
) ,
) ;
}
2018-04-20 18:26:24 +02:00
/ * *
2018-04-19 02:54:50 +02:00
* Called when we detect a suspicious domain . Requests the browser redirects
* to our anti - phishing page .
*
* @ private
* @ param { * } connectionStream - The duplex stream to the per - page script ,
* for sending the reload attempt to .
2020-06-02 01:24:27 +02:00
* @ param { string } hostname - The hostname that triggered the suspicion .
2018-04-19 02:54:50 +02:00
* /
2023-02-24 16:09:00 +01:00
sendPhishingWarning ( connectionStream , hostname ) {
2021-02-04 19:15:23 +01:00
const mux = setupMultiplex ( connectionStream ) ;
const phishingStream = mux . createStream ( 'phishing' ) ;
2023-02-24 16:09:00 +01:00
phishingStream . write ( { hostname } ) ;
2018-03-16 17:37:56 +01:00
}
2018-04-20 18:26:24 +02:00
/ * *
2021-03-18 19:23:46 +01:00
* A method for providing our API over a stream using JSON - RPC .
2022-01-07 16:57:33 +01:00
*
2018-04-19 02:54:50 +02:00
* @ param { * } outStream - The stream to provide our API over .
* /
2020-11-03 00:41:28 +01:00
setupControllerConnection ( outStream ) {
2021-02-04 19:15:23 +01:00
const api = this . getApi ( ) ;
2021-03-18 19:23:46 +01:00
2018-08-22 01:30:11 +02:00
// report new active controller connection
2021-02-04 19:15:23 +01:00
this . activeControllerConnections += 1 ;
this . emit ( 'controllerConnectionChanged' , this . activeControllerConnections ) ;
2021-03-18 19:23:46 +01:00
// set up postStream transport
2022-10-11 00:10:44 +02:00
outStream . on (
'data' ,
createMetaRPCHandler (
api ,
outStream ,
this . store ,
this . localStoreApiWrapper ,
) ,
) ;
2021-03-18 19:23:46 +01:00
const handleUpdate = ( update ) => {
2021-05-13 00:12:46 +02:00
if ( outStream . _writableState . ended ) {
return ;
}
2021-03-18 19:23:46 +01:00
// send notification to client-side
outStream . write ( {
jsonrpc : '2.0' ,
method : 'sendUpdate' ,
params : [ update ] ,
} ) ;
} ;
this . on ( 'update' , handleUpdate ) ;
2022-11-24 01:49:24 +01:00
const startUISync = ( ) => {
if ( outStream . _writableState . ended ) {
return ;
}
// send notification to client-side
outStream . write ( {
jsonrpc : '2.0' ,
method : 'startUISync' ,
} ) ;
} ;
if ( this . startUISync ) {
startUISync ( ) ;
} else {
this . once ( 'startUISync' , startUISync ) ;
}
2021-03-18 19:23:46 +01:00
outStream . on ( 'end' , ( ) => {
2021-02-04 19:15:23 +01:00
this . activeControllerConnections -= 1 ;
this . emit (
'controllerConnectionChanged' ,
this . activeControllerConnections ,
) ;
2021-03-18 19:23:46 +01:00
this . removeListener ( 'update' , handleUpdate ) ;
2021-02-04 19:15:23 +01:00
} ) ;
2017-01-28 04:35:03 +01:00
}
2018-04-20 18:26:24 +02:00
/ * *
2018-04-19 02:54:50 +02:00
* A method for serving our ethereum provider over a given stream .
2022-01-07 16:57:33 +01:00
*
2018-04-19 02:54:50 +02:00
* @ param { * } outStream - The stream to provide over .
2022-02-15 01:02:51 +01:00
* @ param { MessageSender | SnapSender } sender - The sender of the messages on this stream
2023-01-24 16:03:01 +01:00
* @ param { SubjectType } subjectType - The type of the sender , i . e . subject .
2018-04-19 02:54:50 +02:00
* /
2022-01-28 22:42:32 +01:00
setupProviderConnection ( outStream , sender , subjectType ) {
let origin ;
2023-01-24 16:03:01 +01:00
if ( subjectType === SubjectType . Internal ) {
2022-04-26 19:07:39 +02:00
origin = ORIGIN _METAMASK ;
2022-02-15 01:02:51 +01:00
}
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2023-01-24 16:03:01 +01:00
else if ( subjectType === SubjectType . Snap ) {
2022-02-15 01:02:51 +01:00
origin = sender . snapId ;
}
///: END:ONLY_INCLUDE_IN
else {
2022-01-28 22:42:32 +01:00
origin = new URL ( sender . url ) . origin ;
}
if ( sender . id && sender . id !== this . extension . runtime . id ) {
this . subjectMetadataController . addSubjectMetadata ( {
origin ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
extensionId : sender . id ,
2023-01-24 16:03:01 +01:00
subjectType : SubjectType . Extension ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
} ) ;
2019-12-20 16:32:31 +01:00
}
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
2021-02-04 19:15:23 +01:00
let tabId ;
2019-12-20 16:32:31 +01:00
if ( sender . tab && sender . tab . id ) {
2021-02-04 19:15:23 +01:00
tabId = sender . tab . id ;
2019-12-20 16:32:31 +01:00
}
2020-11-03 00:41:28 +01:00
const engine = this . setupProviderEngine ( {
origin ,
2022-01-28 22:42:32 +01:00
sender ,
2021-12-09 00:37:29 +01:00
subjectType ,
2022-02-15 01:02:51 +01:00
tabId ,
2021-02-04 19:15:23 +01:00
} ) ;
2019-07-16 01:28:04 +02:00
// setup connection
2021-02-04 19:15:23 +01:00
const providerStream = createEngineStream ( { engine } ) ;
2019-07-16 01:28:04 +02:00
2021-02-04 19:15:23 +01:00
const connectionId = this . addConnection ( origin , { engine } ) ;
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
2020-11-03 00:41:28 +01:00
pump ( outStream , providerStream , outStream , ( err ) => {
// handle any middleware cleanup
engine . _middleware . forEach ( ( mid ) => {
if ( mid . destroy && typeof mid . destroy === 'function' ) {
2021-02-04 19:15:23 +01:00
mid . destroy ( ) ;
2019-11-20 01:03:20 +01:00
}
2021-02-04 19:15:23 +01:00
} ) ;
connectionId && this . removeConnection ( origin , connectionId ) ;
2020-11-03 00:41:28 +01:00
if ( err ) {
2021-02-04 19:15:23 +01:00
log . error ( err ) ;
2020-11-03 00:41:28 +01:00
}
2021-02-04 19:15:23 +01:00
} ) ;
2019-07-16 01:28:04 +02:00
}
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-02-15 01:02:51 +01:00
/ * *
* For snaps running in workers .
*
* @ param snapId
* @ param connectionStream
* /
setupSnapProvider ( snapId , connectionStream ) {
this . setupUntrustedCommunication ( {
connectionStream ,
sender : { snapId } ,
2023-01-24 16:03:01 +01:00
subjectType : SubjectType . Snap ,
2022-02-15 01:02:51 +01:00
} ) ;
}
///: END:ONLY_INCLUDE_IN
2019-07-16 01:28:04 +02:00
/ * *
2021-12-09 00:37:29 +01:00
* A method for creating a provider that is safely restricted for the requesting subject .
*
2022-07-27 15:28:05 +02:00
* @ param { object } options - Provider engine options
2020-06-02 01:24:27 +02:00
* @ param { string } options . origin - The origin of the sender
2022-01-28 22:42:32 +01:00
* @ param { MessageSender | SnapSender } options . sender - The sender object .
2021-12-09 00:37:29 +01:00
* @ param { string } options . subjectType - The type of the sender subject .
2019-12-20 16:32:31 +01:00
* @ param { tabId } [ options . tabId ] - The tab ID of the sender - if the sender is within a tab
2022-01-07 16:57:33 +01:00
* /
2022-01-28 22:42:32 +01:00
setupProviderEngine ( { origin , subjectType , sender , tabId } ) {
2018-03-16 17:37:56 +01:00
// setup json rpc engine stack
2021-02-04 19:15:23 +01:00
const engine = new JsonRpcEngine ( ) ;
2023-03-15 15:46:31 +01:00
const { blockTracker , provider } = this ;
2019-07-16 01:28:04 +02:00
2023-03-15 15:46:31 +01:00
// create filter polyfill middleware
const filterMiddleware = createFilterMiddleware ( { provider , blockTracker } ) ;
// create subscription polyfill middleware
const subscriptionManager = createSubscriptionManager ( {
provider ,
blockTracker ,
2021-02-04 19:15:23 +01:00
} ) ;
2023-03-15 15:46:31 +01:00
subscriptionManager . events . on ( 'notification' , ( message ) =>
engine . emit ( 'notification' , message ) ,
) ;
2018-03-16 17:37:56 +01:00
2022-12-02 16:38:12 +01:00
if ( isManifestV3 ) {
engine . push ( createDupeReqFilterMiddleware ( ) ) ;
}
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
// append origin to each request
2021-02-04 19:15:23 +01:00
engine . push ( createOriginMiddleware ( { origin } ) ) ;
2022-02-15 01:02:51 +01:00
2020-02-20 23:39:00 +01:00
// append tabId to each request if it exists
if ( tabId ) {
2021-02-04 19:15:23 +01:00
engine . push ( createTabIdMiddleware ( { tabId } ) ) ;
2020-02-20 23:39:00 +01:00
}
2022-02-15 01:02:51 +01:00
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
// logging
2021-02-04 19:15:23 +01:00
engine . push ( createLoggerMiddleware ( { origin } ) ) ;
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
engine . push ( this . permissionLogController . createMiddleware ( ) ) ;
2022-02-15 01:02:51 +01:00
2022-04-04 21:26:13 +02:00
engine . push (
createRPCMethodTrackingMiddleware ( {
trackEvent : this . metaMetricsController . trackEvent . bind (
this . metaMetricsController ,
) ,
getMetricsState : this . metaMetricsController . store . getState . bind (
this . metaMetricsController . store ,
) ,
2023-03-23 18:01:51 +01:00
securityProviderRequest : this . securityProviderRequest . bind ( this ) ,
2022-04-04 21:26:13 +02:00
} ) ,
) ;
2022-01-28 22:42:32 +01:00
// onboarding
2023-01-24 16:03:01 +01:00
if ( subjectType === SubjectType . Website ) {
2022-01-28 22:42:32 +01:00
engine . push (
createOnboardingMiddleware ( {
location : sender . url ,
registerOnboarding : this . onboardingController . registerOnboarding ,
} ) ,
) ;
}
2022-02-15 01:02:51 +01:00
// Unrestricted/permissionless RPC method implementations
2020-11-03 00:41:28 +01:00
engine . push (
createMethodMiddleware ( {
origin ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
2021-12-09 00:37:29 +01:00
subjectType ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
// Miscellaneous
2022-07-31 20:26:40 +02:00
addSubjectMetadata :
this . subjectMetadataController . addSubjectMetadata . bind (
this . subjectMetadataController ,
) ,
2020-12-08 20:48:47 +01:00
getProviderState : this . getProviderState . bind ( this ) ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
getUnlockPromise : this . appStateController . getUnlockPromise . bind (
this . appStateController ,
2020-12-08 17:10:55 +01:00
) ,
2021-09-10 19:37:19 +02:00
handleWatchAssetRequest : this . tokensController . watchAsset . bind (
this . tokensController ,
2020-12-02 17:49:49 +01:00
) ,
2022-07-31 20:26:40 +02:00
requestUserApproval :
this . approvalController . addAndShowApprovalRequest . bind (
this . approvalController ,
) ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
sendMetrics : this . metaMetricsController . trackEvent . bind (
this . metaMetricsController ,
2020-12-11 00:40:29 +01:00
) ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
// Permission-related
getAccounts : this . getPermittedAccounts . bind ( this , origin ) ,
getPermissionsForOrigin : this . permissionController . getPermissions . bind (
this . permissionController ,
origin ,
2021-02-23 19:33:33 +01:00
) ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
hasPermission : this . permissionController . hasPermission . bind (
this . permissionController ,
origin ,
2021-02-12 16:25:58 +01:00
) ,
2022-07-31 20:26:40 +02:00
requestAccountsPermission :
this . permissionController . requestPermissions . bind (
this . permissionController ,
{ origin } ,
{ eth _accounts : { } } ,
) ,
requestPermissionsForOrigin :
this . permissionController . requestPermissions . bind (
this . permissionController ,
{ origin } ,
) ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
2023-02-22 18:43:37 +01:00
getCurrentChainId : ( ) =>
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig . chainId ,
2023-03-09 22:00:28 +01:00
getCurrentRpcUrl : ( ) =>
2023-05-02 17:53:20 +02:00
this . networkController . store . getState ( ) . providerConfig . rpcUrl ,
2023-03-09 22:00:28 +01:00
// network configuration-related
getNetworkConfigurations : ( ) =>
this . networkController . store . getState ( ) . networkConfigurations ,
upsertNetworkConfiguration :
this . networkController . upsertNetworkConfiguration . bind (
this . networkController ,
) ,
setActiveNetwork : this . networkController . setActiveNetwork . bind (
this . networkController ,
) ,
findNetworkConfigurationBy : this . findNetworkConfigurationBy . bind ( this ) ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
setProviderType : this . networkController . setProviderType . bind (
this . networkController ,
) ,
// Web3 shim-related
getWeb3ShimUsageState : this . alertController . getWeb3ShimUsageState . bind (
this . alertController ,
) ,
2022-07-31 20:26:40 +02:00
setWeb3ShimUsageRecorded :
this . alertController . setWeb3ShimUsageRecorded . bind (
this . alertController ,
) ,
2023-05-29 17:38:28 +02:00
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
handleMmiAuthenticate :
this . institutionalFeaturesController . handleMmiAuthenticate . bind (
this . institutionalFeaturesController ,
) ,
handleMmiCheckIfTokenIsPresent :
this . mmiController . handleMmiCheckIfTokenIsPresent . bind ( this ) ,
handleMmiPortfolio : this . mmiController . setMmiPortfolioCookie . bind ( this ) ,
handleMmiOpenSwaps : this . mmiController . handleMmiOpenSwaps . bind ( this ) ,
handleMmiSetAccountAndNetwork :
this . mmiController . setAccountAndNetwork . bind ( this ) ,
handleMmiOpenAddHardwareWallet :
this . mmiController . handleMmiOpenAddHardwareWallet . bind ( this ) ,
///: END:ONLY_INCLUDE_IN
2020-11-03 00:41:28 +01:00
} ) ,
2021-02-04 19:15:23 +01:00
) ;
2022-02-15 01:02:51 +01:00
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2022-02-15 01:02:51 +01:00
engine . push (
2023-01-24 16:03:01 +01:00
createSnapMethodMiddleware ( subjectType === SubjectType . Snap , {
2022-07-27 16:49:57 +02:00
getUnlockPromise : this . appStateController . getUnlockPromise . bind (
this . appStateController ,
) ,
2022-08-26 13:48:53 +02:00
getSnaps : this . controllerMessenger . call . bind (
this . controllerMessenger ,
2022-10-07 20:35:53 +02:00
'SnapController:getPermitted' ,
2022-02-15 01:02:51 +01:00
origin ,
) ,
2023-03-30 23:57:28 +02:00
requestPermissions : async ( requestedPermissions ) =>
await this . permissionController . requestPermissions (
{ origin } ,
requestedPermissions ,
) ,
2022-04-28 18:17:28 +02:00
getPermissions : this . permissionController . getPermissions . bind (
this . permissionController ,
origin ,
) ,
2022-02-15 01:02:51 +01:00
getAccounts : this . getPermittedAccounts . bind ( this , origin ) ,
2022-08-26 13:48:53 +02:00
installSnaps : this . controllerMessenger . call . bind (
this . controllerMessenger ,
'SnapController:install' ,
2022-02-15 01:02:51 +01:00
origin ,
) ,
} ) ,
) ;
///: END:ONLY_INCLUDE_IN
2023-03-15 15:46:31 +01:00
// filter and subscription polyfills
engine . push ( filterMiddleware ) ;
engine . push ( subscriptionManager . middleware ) ;
2023-01-24 16:03:01 +01:00
if ( subjectType !== SubjectType . Internal ) {
2020-05-29 19:53:31 +02:00
// permissions
2020-11-03 00:41:28 +01:00
engine . push (
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
this . permissionController . createPermissionMiddleware ( {
origin ,
} ) ,
2021-02-04 19:15:23 +01:00
) ;
2020-05-29 19:53:31 +02:00
}
2022-02-15 01:02:51 +01:00
2023-01-06 18:14:50 +01:00
engine . push ( this . metamaskMiddleware ) ;
2018-10-08 17:55:07 +02:00
// forward to metamask primary provider
2021-02-04 19:15:23 +01:00
engine . push ( providerAsMiddleware ( provider ) ) ;
return engine ;
2018-03-16 17:37:56 +01:00
}
2021-01-13 02:43:45 +01:00
/ * *
* TODO : LegacyProvider : Delete
* A method for providing our public config info over a stream .
* This includes info we like to be synchronous if possible , like
* the current selected account , and network ID .
*
* Since synchronous methods have been deprecated in web3 ,
* this is a good candidate for deprecation .
*
* @ param { * } outStream - The stream to provide public config over .
* /
setupPublicConfig ( outStream ) {
2021-02-04 19:15:23 +01:00
const configStream = storeAsStream ( this . publicConfigStore ) ;
2021-01-13 02:43:45 +01:00
pump ( configStream , outStream , ( err ) => {
2021-02-04 19:15:23 +01:00
configStream . destroy ( ) ;
2021-01-13 02:43:45 +01:00
if ( err ) {
2021-02-04 19:15:23 +01:00
log . error ( err ) ;
2021-01-13 02:43:45 +01:00
}
2021-02-04 19:15:23 +01:00
} ) ;
2021-01-13 02:43:45 +01:00
}
2019-05-03 19:32:05 +02:00
/ * *
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
* Adds a reference to a connection by origin . Ignores the 'metamask' origin .
* Caller must ensure that the returned id is stored such that the reference
* can be deleted later .
2019-05-03 19:32:05 +02:00
*
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
* @ param { string } origin - The connection ' s origin string .
2022-07-27 15:28:05 +02:00
* @ param { object } options - Data associated with the connection
* @ param { object } options . engine - The connection ' s JSON Rpc Engine
2020-11-10 18:30:41 +01:00
* @ returns { string } The connection ' s id ( so that it can be deleted later )
2019-05-03 19:32:05 +02:00
* /
2020-11-03 00:41:28 +01:00
addConnection ( origin , { engine } ) {
2022-04-26 19:07:39 +02:00
if ( origin === ORIGIN _METAMASK ) {
2021-02-04 19:15:23 +01:00
return null ;
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
}
2019-05-03 19:32:05 +02:00
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
if ( ! this . connections [ origin ] ) {
2021-02-04 19:15:23 +01:00
this . connections [ origin ] = { } ;
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
}
2019-05-03 19:32:05 +02:00
2021-02-04 19:15:23 +01:00
const id = nanoid ( ) ;
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
this . connections [ origin ] [ id ] = {
engine ,
2021-02-04 19:15:23 +01:00
} ;
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
2021-02-04 19:15:23 +01:00
return id ;
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
}
/ * *
* Deletes a reference to a connection , by origin and id .
* Ignores unknown origins .
*
* @ param { string } origin - The connection ' s origin string .
* @ param { string } id - The connection ' s id , as returned from addConnection .
* /
2020-11-03 00:41:28 +01:00
removeConnection ( origin , id ) {
2021-02-04 19:15:23 +01:00
const connections = this . connections [ origin ] ;
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
if ( ! connections ) {
2021-02-04 19:15:23 +01:00
return ;
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
}
2021-02-04 19:15:23 +01:00
delete connections [ id ] ;
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
2020-08-04 22:02:48 +02:00
if ( Object . keys ( connections ) . length === 0 ) {
2021-02-04 19:15:23 +01:00
delete this . connections [ origin ] ;
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
}
}
2022-02-15 01:02:51 +01:00
/ * *
* Closes all connections for the given origin , and removes the references
* to them .
* Ignores unknown origins .
*
* @ param { string } origin - The origin string .
* /
removeAllConnections ( origin ) {
const connections = this . connections [ origin ] ;
if ( ! connections ) {
return ;
}
Object . keys ( connections ) . forEach ( ( id ) => {
this . removeConnection ( origin , id ) ;
} ) ;
}
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
/ * *
* Causes the RPC engines associated with the connections to the given origin
* to emit a notification event with the given payload .
2020-12-08 20:48:47 +01:00
*
* The caller is responsible for ensuring that only permitted notifications
* are sent .
*
* Ignores unknown origins .
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
*
* @ param { string } origin - The connection ' s origin string .
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
* @ param { unknown } payload - The event payload .
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
* /
2020-11-03 00:41:28 +01:00
notifyConnections ( origin , payload ) {
2021-02-04 19:15:23 +01:00
const connections = this . connections [ origin ] ;
2019-05-03 19:32:05 +02:00
2020-12-08 20:48:47 +01:00
if ( connections ) {
Object . values ( connections ) . forEach ( ( conn ) => {
if ( conn . engine ) {
2021-02-04 19:15:23 +01:00
conn . engine . emit ( 'notification' , payload ) ;
2020-12-08 20:48:47 +01:00
}
2021-02-04 19:15:23 +01:00
} ) ;
2020-12-08 20:48:47 +01:00
}
2019-05-03 19:32:05 +02:00
}
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
/ * *
* Causes the RPC engines associated with all connections to emit a
* notification event with the given payload .
*
2020-12-08 20:48:47 +01:00
* If the "payload" parameter is a function , the payload for each connection
* will be the return value of that function called with the connection ' s
* origin .
*
* The caller is responsible for ensuring that only permitted notifications
* are sent .
*
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
* @ param { unknown } payload - The event payload , or payload getter function .
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
* /
2020-11-03 00:41:28 +01:00
notifyAllConnections ( payload ) {
2020-12-08 20:48:47 +01:00
const getPayload =
typeof payload === 'function'
? ( origin ) => payload ( origin )
2021-02-04 19:15:23 +01:00
: ( ) => payload ;
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
2021-10-14 19:50:07 +02:00
Object . keys ( this . connections ) . forEach ( ( origin ) => {
Object . values ( this . connections [ origin ] ) . forEach ( async ( conn ) => {
2020-12-08 20:48:47 +01:00
if ( conn . engine ) {
2021-10-14 19:50:07 +02:00
conn . engine . emit ( 'notification' , await getPayload ( origin ) ) ;
2020-12-08 20:48:47 +01:00
}
2021-02-04 19:15:23 +01:00
} ) ;
} ) ;
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
}
// handlers
2018-04-20 18:26:24 +02:00
/ * *
2018-08-16 17:29:39 +02:00
* Handle a KeyringController update
2022-01-07 16:57:33 +01:00
*
2022-07-27 15:28:05 +02:00
* @ param { object } state - the KC state
2020-01-13 19:36:36 +01:00
* @ returns { Promise < void > }
2018-08-16 17:29:39 +02:00
* @ private
* /
2020-11-03 00:41:28 +01:00
async _onKeyringControllerUpdate ( state ) {
2022-11-24 01:49:24 +01:00
const {
keyrings ,
encryptionKey : loginToken ,
encryptionSalt : loginSalt ,
} = state ;
2020-11-03 00:41:28 +01:00
const addresses = keyrings . reduce (
( acc , { accounts } ) => acc . concat ( accounts ) ,
[ ] ,
2021-02-04 19:15:23 +01:00
) ;
2018-08-16 17:29:39 +02:00
2022-11-24 01:49:24 +01:00
if ( isManifestV3 ) {
2023-04-06 16:43:01 +02:00
await this . extension . storage . session . set ( { loginToken , loginSalt } ) ;
2022-11-24 01:49:24 +01:00
}
2018-08-16 17:29:39 +02:00
if ( ! addresses . length ) {
2021-02-04 19:15:23 +01:00
return ;
2018-08-16 17:29:39 +02:00
}
// Ensure preferences + identities controller know about all addresses
2021-02-04 19:15:23 +01:00
this . preferencesController . syncAddresses ( addresses ) ;
this . accountTracker . syncWithAddresses ( addresses ) ;
2018-08-16 17:29:39 +02:00
}
2020-12-08 20:48:47 +01:00
/ * *
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
* Handle global application unlock .
* Notifies all connections that the extension is unlocked , and which
* account ( s ) are currently accessible , if any .
2020-12-08 20:48:47 +01:00
* /
_onUnlock ( ) {
2021-10-14 19:50:07 +02:00
this . notifyAllConnections ( async ( origin ) => {
2020-12-08 20:48:47 +01:00
return {
method : NOTIFICATION _NAMES . unlockStateChanged ,
params : {
isUnlocked : true ,
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
accounts : await this . getPermittedAccounts ( origin ) ,
2020-12-08 20:48:47 +01:00
} ,
2021-02-04 19:15:23 +01:00
} ;
} ) ;
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
2023-02-02 17:46:22 +01:00
this . unMarkPasswordForgotten ( ) ;
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
// In the current implementation, this handler is triggered by a
// KeyringController event. Other controllers subscribe to the 'unlock'
// event of the MetaMaskController itself.
2021-02-04 19:15:23 +01:00
this . emit ( 'unlock' ) ;
2020-12-08 20:48:47 +01:00
}
/ * *
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
* Handle global application lock .
2020-12-08 20:48:47 +01:00
* Notifies all connections that the extension is locked .
* /
_onLock ( ) {
this . notifyAllConnections ( {
method : NOTIFICATION _NAMES . unlockStateChanged ,
params : {
isUnlocked : false ,
} ,
2021-02-04 19:15:23 +01:00
} ) ;
Permission System 2.0 (#12243)
# Permission System 2.0
## Background
This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.
With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.
Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.
The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.
## Changes in Detail
First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.
- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.
Reviewers should focus their attention on the following files:
- `app/scripts/`
- `metamask-controller.js`
- This is where most of the integration work for the new `PermissionController` occurs.
Some functions that were internal to the original controller were moved here.
- `controllers/permissions/`
- `selectors.js`
- These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
- `specifications.js`
- The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
See the `PermissionController` readme for details.
- `migrations/068.js`
- The new state should be cross-referenced with the controllers that manage it.
The accompanying tests should also be thoroughly reviewed.
Some files may appear new but have just moved and/or been renamed:
- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
- This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
- A truncated version of `test/mocks/permission-controller.js`.
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
// In the current implementation, this handler is triggered by a
// KeyringController event. Other controllers subscribe to the 'lock'
// event of the MetaMaskController itself.
2021-02-04 19:15:23 +01:00
this . emit ( 'lock' ) ;
2020-12-08 20:48:47 +01:00
}
/ * *
* Handle memory state updates .
* - Ensure isClientOpenAndUnlocked is updated
* - Notifies all connections with the new provider network state
* - The external providers handle diffing the state
2022-01-07 16:57:33 +01:00
*
* @ param newState
2020-12-08 20:48:47 +01:00
* /
_onStateUpdate ( newState ) {
2021-02-04 19:15:23 +01:00
this . isClientOpenAndUnlocked = newState . isUnlocked && this . _isClientOpen ;
2020-12-08 20:48:47 +01:00
this . notifyAllConnections ( {
method : NOTIFICATION _NAMES . chainChanged ,
params : this . getProviderNetworkState ( newState ) ,
2021-02-04 19:15:23 +01:00
} ) ;
2020-12-08 20:48:47 +01:00
}
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
// misc
2018-04-20 18:26:24 +02:00
/ * *
2018-04-19 02:54:50 +02:00
* A method for emitting the full MetaMask state to all registered listeners .
2022-01-07 16:57:33 +01:00
*
2018-04-19 02:54:50 +02:00
* @ private
* /
2020-11-03 00:41:28 +01:00
privateSendUpdate ( ) {
2021-02-04 19:15:23 +01:00
this . emit ( 'update' , this . getState ( ) ) ;
2018-03-16 17:37:56 +01:00
}
2020-03-23 17:25:55 +01:00
/ * *
* @ returns { boolean } Whether the extension is unlocked .
* /
2020-11-03 00:41:28 +01:00
isUnlocked ( ) {
2021-02-04 19:15:23 +01:00
return this . keyringController . memStore . getState ( ) . isUnlocked ;
2020-03-23 17:25:55 +01:00
}
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
//=============================================================================
// MISCELLANEOUS
//=============================================================================
2022-02-18 17:48:38 +01:00
getExternalPendingTransactions ( address ) {
return this . smartTransactionsController . getTransactions ( {
addressFrom : address ,
status : 'pending' ,
} ) ;
}
2018-09-21 19:34:21 +02:00
/ * *
* Returns the nonce that will be associated with a transaction once approved
2022-01-07 16:57:33 +01:00
*
2020-01-13 19:36:36 +01:00
* @ param { string } address - The hex string address for the transaction
* @ returns { Promise < number > }
2018-09-21 19:34:21 +02:00
* /
2020-11-03 00:41:28 +01:00
async getPendingNonce ( address ) {
2022-07-31 20:26:40 +02:00
const { nonceDetails , releaseLock } =
await this . txController . nonceTracker . getNonceLock ( address ) ;
2021-02-04 19:15:23 +01:00
const pendingNonce = nonceDetails . params . highestSuggested ;
2018-09-21 19:34:21 +02:00
2021-02-04 19:15:23 +01:00
releaseLock ( ) ;
return pendingNonce ;
2018-09-21 19:34:21 +02:00
}
2019-10-02 20:12:04 +02:00
/ * *
* Returns the next nonce according to the nonce - tracker
2022-01-07 16:57:33 +01:00
*
2020-01-13 19:36:36 +01:00
* @ param { string } address - The hex string address for the transaction
* @ returns { Promise < number > }
2019-10-02 20:12:04 +02:00
* /
2020-11-03 00:41:28 +01:00
async getNextNonce ( address ) {
2021-02-04 19:15:23 +01:00
const nonceLock = await this . txController . nonceTracker . getNonceLock (
address ,
) ;
nonceLock . releaseLock ( ) ;
return nonceLock . nextNonce ;
2019-10-02 20:12:04 +02:00
}
2019-07-31 22:17:11 +02:00
//=============================================================================
// CONFIG
//=============================================================================
2016-06-24 22:05:21 +02:00
2018-04-20 18:26:24 +02:00
/ * *
2023-03-09 22:00:28 +01:00
* Returns the first network configuration object that matches at least one field of the
2021-02-12 16:25:58 +01:00
* provided search criteria . Returns null if no match is found
*
2022-07-27 15:28:05 +02:00
* @ param { object } rpcInfo - The RPC endpoint properties and values to check .
2023-03-09 22:00:28 +01:00
* @ returns { object } rpcInfo found in the network configurations list
2021-02-12 16:25:58 +01:00
* /
2023-03-09 22:00:28 +01:00
findNetworkConfigurationBy ( rpcInfo ) {
const { networkConfigurations } = this . networkController . store . getState ( ) ;
const networkConfiguration = Object . values ( networkConfigurations ) . find (
( configuration ) => {
return Object . keys ( rpcInfo ) . some ( ( key ) => {
return configuration [ key ] === rpcInfo [ key ] ;
} ) ;
} ,
) ;
return networkConfiguration || null ;
2021-02-12 16:25:58 +01:00
}
2021-04-26 20:05:48 +02:00
/ * *
* Sets the Ledger Live preference to use for Ledger hardware wallet support
2022-01-07 16:57:33 +01:00
*
* @ param { string } transportType - The Ledger transport type .
2021-04-26 20:05:48 +02:00
* /
2021-10-21 21:17:03 +02:00
async setLedgerTransportPreference ( transportType ) {
2023-01-25 22:12:08 +01:00
if ( ! this . canUseHardwareWallets ( ) ) {
return undefined ;
}
2022-07-31 20:26:40 +02:00
const currentValue =
this . preferencesController . getLedgerTransportPreference ( ) ;
const newValue =
this . preferencesController . setLedgerTransportPreference ( transportType ) ;
2021-04-26 20:05:48 +02:00
2023-01-20 16:14:40 +01:00
const keyring = await this . getKeyringForDevice ( HardwareDeviceNames . ledger ) ;
2021-04-26 20:05:48 +02:00
if ( keyring ? . updateTransportMethod ) {
2021-10-21 21:17:03 +02:00
return keyring . updateTransportMethod ( newValue ) . catch ( ( e ) => {
2021-04-26 20:05:48 +02:00
// If there was an error updating the transport, we should
// fall back to the original value
2021-10-21 21:17:03 +02:00
this . preferencesController . setLedgerTransportPreference ( currentValue ) ;
2021-04-26 20:05:48 +02:00
throw e ;
} ) ;
}
return undefined ;
}
2018-04-20 18:26:24 +02:00
/ * *
2018-04-19 02:54:50 +02:00
* A method for initializing storage the first time .
2022-01-07 16:57:33 +01:00
*
2022-07-27 15:28:05 +02:00
* @ param { object } initState - The default state to initialize with .
2018-04-19 02:54:50 +02:00
* @ private
* /
2020-11-03 00:41:28 +01:00
recordFirstTimeInfo ( initState ) {
2017-11-28 20:14:57 +01:00
if ( ! ( 'firstTimeInfo' in initState ) ) {
2021-02-04 19:15:23 +01:00
const version = this . platform . getVersion ( ) ;
2017-11-28 20:14:57 +01:00
initState . firstTimeInfo = {
version ,
date : Date . now ( ) ,
2021-02-04 19:15:23 +01:00
} ;
2017-11-28 20:14:57 +01:00
}
}
2018-08-22 21:05:41 +02:00
// TODO: Replace isClientOpen methods with `controllerConnectionChanged` events.
2020-10-22 19:06:44 +02:00
/* eslint-disable accessor-pairs */
2018-04-20 18:26:24 +02:00
/ * *
2018-04-19 02:54:50 +02:00
* A method for recording whether the MetaMask user interface is open or not .
2022-01-07 16:57:33 +01:00
*
2018-04-20 18:26:24 +02:00
* @ param { boolean } open
2018-04-19 02:54:50 +02:00
* /
2020-11-03 00:41:28 +01:00
set isClientOpen ( open ) {
2021-02-04 19:15:23 +01:00
this . _isClientOpen = open ;
this . detectTokensController . isOpen = open ;
2018-04-16 23:45:18 +02:00
}
2020-10-22 19:06:44 +02:00
/* eslint-enable accessor-pairs */
2018-04-16 23:45:18 +02:00
2021-08-04 23:53:13 +02:00
/ * *
* A method that is called by the background when all instances of metamask are closed .
* Currently used to stop polling in the gasFeeController .
* /
onClientClosed ( ) {
try {
this . gasFeeController . stopPolling ( ) ;
this . appStateController . clearPollingTokens ( ) ;
} catch ( error ) {
console . error ( error ) ;
}
}
/ * *
* A method that is called by the background when a particular environment type is closed ( fullscreen , popup , notification ) .
* Currently used to stop polling in the gasFeeController for only that environement type
2022-01-07 16:57:33 +01:00
*
* @ param environmentType
2021-08-04 23:53:13 +02:00
* /
onEnvironmentTypeClosed ( environmentType ) {
const appStatePollingTokenType =
POLLING _TOKEN _ENVIRONMENT _TYPES [ environmentType ] ;
2022-07-31 20:26:40 +02:00
const pollingTokensToDisconnect =
this . appStateController . store . getState ( ) [ appStatePollingTokenType ] ;
2021-08-04 23:53:13 +02:00
pollingTokensToDisconnect . forEach ( ( pollingToken ) => {
this . gasFeeController . disconnectPoller ( pollingToken ) ;
this . appStateController . removePollingToken (
pollingToken ,
appStatePollingTokenType ,
) ;
} ) ;
}
2018-10-02 01:35:57 +02:00
/ * *
2020-06-08 20:06:37 +02:00
* Adds a domain to the PhishingController safelist
2022-01-07 16:57:33 +01:00
*
2020-06-08 20:06:37 +02:00
* @ param { string } hostname - the domain to safelist
2018-10-02 01:35:57 +02:00
* /
2020-11-03 00:41:28 +01:00
safelistPhishingDomain ( hostname ) {
2021-02-04 19:15:23 +01:00
return this . phishingController . bypass ( hostname ) ;
2018-10-02 01:35:57 +02:00
}
2018-10-29 21:55:13 +01:00
2023-03-31 11:00:44 +02:00
async backToSafetyPhishingWarning ( ) {
const extensionURL = this . platform . getExtensionURL ( ) ;
await this . platform . switchToAnotherURL ( undefined , extensionURL ) ;
}
2018-10-29 22:28:59 +01:00
/ * *
* Locks MetaMask
* /
2020-11-03 00:41:28 +01:00
setLocked ( ) {
2021-12-08 18:25:27 +01:00
const [ trezorKeyring ] = this . keyringController . getKeyringsByType (
2023-03-21 15:43:22 +01:00
KeyringType . trezor ,
2021-12-08 18:25:27 +01:00
) ;
if ( trezorKeyring ) {
trezorKeyring . dispose ( ) ;
}
2022-05-12 18:06:14 +02:00
const [ ledgerKeyring ] = this . keyringController . getKeyringsByType (
2023-03-21 15:43:22 +01:00
KeyringType . ledger ,
2022-05-12 18:06:14 +02:00
) ;
ledgerKeyring ? . destroy ? . ( ) ;
2022-11-24 01:49:24 +01:00
if ( isManifestV3 ) {
this . clearLoginArtifacts ( ) ;
}
2021-02-04 19:15:23 +01:00
return this . keyringController . setLocked ( ) ;
2018-10-29 21:55:13 +01:00
}
2022-10-31 06:52:31 +01:00
removePermissionsFor = ( subjects ) => {
try {
this . permissionController . revokePermissions ( subjects ) ;
} catch ( exp ) {
if ( ! ( exp instanceof PermissionsRequestNotFoundError ) ) {
throw exp ;
}
}
} ;
2023-04-25 16:32:51 +02:00
///: BEGIN:ONLY_INCLUDE_IN(snaps)
2023-03-08 19:29:23 +01:00
updateCaveat = ( origin , target , caveatType , caveatValue ) => {
try {
this . controllerMessenger . call (
'PermissionController:updateCaveat' ,
origin ,
target ,
caveatType ,
caveatValue ,
) ;
} catch ( exp ) {
if ( ! ( exp instanceof PermissionsRequestNotFoundError ) ) {
throw exp ;
}
}
} ;
///: END:ONLY_INCLUDE_IN
2022-10-31 06:52:31 +01:00
rejectPermissionsRequest = ( requestId ) => {
try {
this . permissionController . rejectPermissionsRequest ( requestId ) ;
} catch ( exp ) {
if ( ! ( exp instanceof PermissionsRequestNotFoundError ) ) {
throw exp ;
}
}
} ;
acceptPermissionsRequest = ( request ) => {
try {
this . permissionController . acceptPermissionsRequest ( request ) ;
} catch ( exp ) {
if ( ! ( exp instanceof PermissionsRequestNotFoundError ) ) {
throw exp ;
}
}
} ;
resolvePendingApproval = ( id , value ) => {
try {
this . approvalController . accept ( id , value ) ;
} catch ( exp ) {
if ( ! ( exp instanceof ApprovalRequestNotFoundError ) ) {
throw exp ;
}
}
} ;
rejectPendingApproval = ( id , error ) => {
try {
this . approvalController . reject (
id ,
new EthereumRpcError ( error . code , error . message , error . data ) ,
) ;
} catch ( exp ) {
if ( ! ( exp instanceof ApprovalRequestNotFoundError ) ) {
throw exp ;
}
}
} ;
2023-01-23 15:32:01 +01:00
async securityProviderRequest ( requestData , methodName ) {
const { currentLocale , transactionSecurityCheckEnabled } =
this . preferencesController . store . getState ( ) ;
if ( transactionSecurityCheckEnabled ) {
2023-03-23 18:01:51 +01:00
const chainId = Number (
2023-05-02 17:53:20 +02:00
hexToDecimal (
this . networkController . store . getState ( ) . providerConfig . chainId ,
) ,
2023-03-23 18:01:51 +01:00
) ;
2023-01-23 15:32:01 +01:00
try {
const securityProviderResponse = await securityProviderCheck (
requestData ,
methodName ,
chainId ,
currentLocale ,
) ;
return securityProviderResponse ;
} catch ( err ) {
log . error ( err . message ) ;
throw err ;
}
}
return null ;
}
2017-09-22 00:47:25 +02:00
}