From 21ee99d0824b81a18e65074810d73904acf13832 Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Mon, 16 Dec 2024 12:40:02 +0100 Subject: [PATCH] Add `onSettingsPage` export (#2911) This PR adds a new `onSettingsPage` export that is used to display custom UI. Changes: - Adds a new export `onSettingsPage`: Similar to `onHomePage` this export allows you to show custom UI in MetaMask. Here it's used to display a custom section in MetaMask settings. - Adds a new example snap (`settings-page-example-snap`) to demonstrate how to use this set of features and uses it in `test-snap` Progresses: #2874 --------- Co-authored-by: Frederik Bolding --- packages/examples/README.md | 3 + .../browserify-plugin/snap.manifest.json | 2 +- .../packages/browserify/snap.manifest.json | 2 +- .../packages/settings-page/.depcheckrc.json | 18 ++ .../packages/settings-page/.eslintrc.js | 7 + .../packages/settings-page/CHANGELOG.md | 10 + .../packages/settings-page/LICENSE.APACHE2 | 201 ++++++++++++++++++ .../packages/settings-page/LICENSE.MIT0 | 16 ++ .../examples/packages/settings-page/README.md | 24 +++ .../packages/settings-page/jest.config.js | 36 ++++ .../packages/settings-page/package.json | 86 ++++++++ .../packages/settings-page/snap.config.ts | 17 ++ .../packages/settings-page/snap.manifest.json | 28 +++ .../src/components/SettingsPage.tsx | 56 +++++ .../packages/settings-page/src/index.test.tsx | 44 ++++ .../packages/settings-page/src/index.tsx | 101 +++++++++ .../packages/settings-page/tsconfig.json | 8 + packages/snaps-controllers/coverage.json | 4 +- .../src/snaps/SnapController.test.tsx | 172 ++++++++++++++- .../src/snaps/SnapController.ts | 13 +- .../coverage.json | 2 +- .../common/BaseSnapExecutor.test.browser.ts | 33 +++ .../src/common/commands.ts | 1 + packages/snaps-jest/src/helpers.test.tsx | 26 +++ packages/snaps-jest/src/helpers.ts | 2 + packages/snaps-rpc-methods/jest.config.js | 6 +- .../snaps-rpc-methods/src/endowments/enum.ts | 1 + .../snaps-rpc-methods/src/endowments/index.ts | 4 + .../src/endowments/settings-page.test.ts | 19 ++ .../src/endowments/settings-page.ts | 45 ++++ .../snaps-rpc-methods/src/permissions.test.ts | 9 + .../snaps-sdk/src/types/handlers/index.ts | 1 + .../src/types/handlers/settings-page.ts | 24 +++ packages/snaps-sdk/src/types/permissions.ts | 3 + .../snaps-simulation/src/helpers.test.tsx | 26 +++ packages/snaps-simulation/src/helpers.ts | 27 +++ .../src/methods/specifications.test.ts | 9 + packages/snaps-simulation/src/types.ts | 7 + packages/snaps-utils/coverage.json | 2 +- packages/snaps-utils/src/handler-types.ts | 1 + packages/snaps-utils/src/handlers.ts | 10 + packages/test-snaps/package.json | 1 + .../test-snaps/src/features/snaps/index.ts | 1 + .../src/features/snaps/send-flow/SendFlow.tsx | 7 +- .../snaps/settings-page/SettingsPage.tsx | 46 ++++ .../features/snaps/settings-page/constants.ts | 5 + .../src/features/snaps/settings-page/index.ts | 1 + yarn.lock | 38 ++++ 48 files changed, 1193 insertions(+), 12 deletions(-) create mode 100644 packages/examples/packages/settings-page/.depcheckrc.json create mode 100644 packages/examples/packages/settings-page/.eslintrc.js create mode 100644 packages/examples/packages/settings-page/CHANGELOG.md create mode 100644 packages/examples/packages/settings-page/LICENSE.APACHE2 create mode 100644 packages/examples/packages/settings-page/LICENSE.MIT0 create mode 100644 packages/examples/packages/settings-page/README.md create mode 100644 packages/examples/packages/settings-page/jest.config.js create mode 100644 packages/examples/packages/settings-page/package.json create mode 100644 packages/examples/packages/settings-page/snap.config.ts create mode 100644 packages/examples/packages/settings-page/snap.manifest.json create mode 100644 packages/examples/packages/settings-page/src/components/SettingsPage.tsx create mode 100644 packages/examples/packages/settings-page/src/index.test.tsx create mode 100644 packages/examples/packages/settings-page/src/index.tsx create mode 100644 packages/examples/packages/settings-page/tsconfig.json create mode 100644 packages/snaps-rpc-methods/src/endowments/settings-page.test.ts create mode 100644 packages/snaps-rpc-methods/src/endowments/settings-page.ts create mode 100644 packages/snaps-sdk/src/types/handlers/settings-page.ts create mode 100644 packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx create mode 100644 packages/test-snaps/src/features/snaps/settings-page/constants.ts create mode 100644 packages/test-snaps/src/features/snaps/settings-page/index.ts diff --git a/packages/examples/README.md b/packages/examples/README.md index d2c0dfa004..cee01f973d 100644 --- a/packages/examples/README.md +++ b/packages/examples/README.md @@ -66,6 +66,9 @@ The following is a list of the snaps in this directory. - [**`packages/notifications`**](./packages/notifications): This snap demonstrates how to use the `snap_notify` method to display notifications to the user, either as a MetaMask notification or as a desktop notification. +- [**`packages/settings-page`**](./packages/settings-page): + This snap demonstrates how to use `endowment:page-settings` permission, + showing a settings page to the user. - [**`packages/transaction-insights`**](./packages/transaction-insights): This snap demonstrates how to use `endowment:transaction-insights` permission, and provide transaction insights to the user. diff --git a/packages/examples/packages/browserify-plugin/snap.manifest.json b/packages/examples/packages/browserify-plugin/snap.manifest.json index e9c820531b..d17e6c7427 100644 --- a/packages/examples/packages/browserify-plugin/snap.manifest.json +++ b/packages/examples/packages/browserify-plugin/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/snaps.git" }, "source": { - "shasum": "eug1Oxfxo/X97epSDNuF3elpxJUBNGgPgfvvmVxShxo=", + "shasum": "vr/JCeU5DXN3CeJIeLbZmr44rFnq+BGqQPng7kVxZGY=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/examples/packages/browserify/snap.manifest.json b/packages/examples/packages/browserify/snap.manifest.json index ef628744cf..fe772a5cf5 100644 --- a/packages/examples/packages/browserify/snap.manifest.json +++ b/packages/examples/packages/browserify/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/snaps.git" }, "source": { - "shasum": "Jh7Kcnzc5flRZM4SL8yQnMBj99YrmU91iLLaIxH2o/k=", + "shasum": "4diRqHxV2Sr2wHuyoP1dL/WcSbS6HSVzxkDL+Iv0JNM=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/examples/packages/settings-page/.depcheckrc.json b/packages/examples/packages/settings-page/.depcheckrc.json new file mode 100644 index 0000000000..c437c59cd2 --- /dev/null +++ b/packages/examples/packages/settings-page/.depcheckrc.json @@ -0,0 +1,18 @@ +{ + "ignore-patterns": ["dist", "coverage"], + "ignores": [ + "@lavamoat/allow-scripts", + "@lavamoat/preinstall-always-fail", + "@metamask/auto-changelog", + "@metamask/eslint-*", + "@types/*", + "@typescript-eslint/*", + "eslint-config-*", + "eslint-plugin-*", + "jest-silent-reporter", + "prettier-plugin-packagejson", + "ts-node", + "typedoc", + "typescript" + ] +} diff --git a/packages/examples/packages/settings-page/.eslintrc.js b/packages/examples/packages/settings-page/.eslintrc.js new file mode 100644 index 0000000000..a47fd0b65d --- /dev/null +++ b/packages/examples/packages/settings-page/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + extends: ['../../.eslintrc.js'], + + parserOptions: { + tsconfigRootDir: __dirname, + }, +}; diff --git a/packages/examples/packages/settings-page/CHANGELOG.md b/packages/examples/packages/settings-page/CHANGELOG.md new file mode 100644 index 0000000000..720e00537e --- /dev/null +++ b/packages/examples/packages/settings-page/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +[Unreleased]: https://github.com/MetaMask/snaps/ diff --git a/packages/examples/packages/settings-page/LICENSE.APACHE2 b/packages/examples/packages/settings-page/LICENSE.APACHE2 new file mode 100644 index 0000000000..bf37d0e612 --- /dev/null +++ b/packages/examples/packages/settings-page/LICENSE.APACHE2 @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 ConsenSys Software Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/examples/packages/settings-page/LICENSE.MIT0 b/packages/examples/packages/settings-page/LICENSE.MIT0 new file mode 100644 index 0000000000..3a4d3cb295 --- /dev/null +++ b/packages/examples/packages/settings-page/LICENSE.MIT0 @@ -0,0 +1,16 @@ +MIT No Attribution + +Copyright 2024 Consensys Software Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/examples/packages/settings-page/README.md b/packages/examples/packages/settings-page/README.md new file mode 100644 index 0000000000..faa5015009 --- /dev/null +++ b/packages/examples/packages/settings-page/README.md @@ -0,0 +1,24 @@ +# `@metamask/settings-page-example-snap` + +This snap demonstrates how to use `endowment:page-settings` permission to show +a settings page that leverages custom UI components. + +This endowment is initially restricted to preinstalled snaps only. + +## Snap manifest + +The manifest of this snap includes the `endowment:page-settings` permission: + +```json +{ + "initialPermissions": { + "endowment:page-settings": {} + } +} +``` + +This permission does not require any additional configuration. + +## Snap usage + +This snap exposes an `onSettingsPage` handler, which returns the UI to be shown. diff --git a/packages/examples/packages/settings-page/jest.config.js b/packages/examples/packages/settings-page/jest.config.js new file mode 100644 index 0000000000..f473a91b83 --- /dev/null +++ b/packages/examples/packages/settings-page/jest.config.js @@ -0,0 +1,36 @@ +const deepmerge = require('deepmerge'); + +const baseConfig = require('../../../../jest.config.base'); + +module.exports = deepmerge(baseConfig, { + preset: '@metamask/snaps-jest', + + // Since `@metamask/snaps-jest` runs in the browser, we can't collect + // coverage information. + collectCoverage: false, + + // This is required for the tests to run inside the `MetaMask/snaps` + // repository. You don't need this in your own project. + moduleNameMapper: { + '^@metamask/(.+)/production/jsx-runtime': [ + '/../../../$1/src/jsx/production/jsx-runtime', + '/../../../../node_modules/@metamask/$1/jsx/production/jsx-runtime', + '/node_modules/@metamask/$1/jsx/production/jsx-runtime', + ], + '^@metamask/(.+)/jsx': [ + '/../../../$1/src/jsx', + '/../../../../node_modules/@metamask/$1/jsx', + '/node_modules/@metamask/$1/jsx', + ], + '^@metamask/(.+)/node$': [ + '/../../../$1/src/node', + '/../../../../node_modules/@metamask/$1/node', + '/node_modules/@metamask/$1/node', + ], + '^@metamask/(.+)$': [ + '/../../../$1/src', + '/../../../../node_modules/@metamask/$1', + '/node_modules/@metamask/$1', + ], + }, +}); diff --git a/packages/examples/packages/settings-page/package.json b/packages/examples/packages/settings-page/package.json new file mode 100644 index 0000000000..900c03737f --- /dev/null +++ b/packages/examples/packages/settings-page/package.json @@ -0,0 +1,86 @@ +{ + "name": "@metamask/settings-page-example-snap", + "version": "0.0.0", + "description": "MetaMask example snap demonstrating the use of settings pages", + "keywords": [ + "MetaMask", + "Snaps", + "Ethereum" + ], + "homepage": "https://github.com/MetaMask/snaps/tree/main/packages/examples/packages/settings-page#readme", + "bugs": { + "url": "https://github.com/MetaMask/snaps/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/snaps.git" + }, + "license": "(MIT-0 OR Apache-2.0)", + "sideEffects": false, + "main": "./dist/bundle.js", + "files": [ + "dist", + "snap.manifest.json" + ], + "scripts": { + "build": "mm-snap build", + "build:clean": "yarn clean && yarn build", + "changelog:update": "../../../../scripts/update-changelog.sh @metamask/settings-page-example-snap", + "changelog:validate": "../../../../scripts/validate-changelog.sh @metamask/settings-page-example-snap", + "clean": "rimraf \"dist\"", + "lint": "yarn lint:eslint && yarn lint:misc --check && yarn changelog:validate && yarn lint:dependencies", + "lint:ci": "yarn lint", + "lint:dependencies": "depcheck", + "lint:eslint": "eslint . --cache --ext js,ts,jsx,tsx", + "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write", + "lint:misc": "prettier --no-error-on-unmatched-pattern --loglevel warn \"**/*.json\" \"**/*.md\" \"**/*.html\" \"!CHANGELOG.md\" \"!snap.manifest.json\" --ignore-path ../../../../.gitignore", + "publish:preview": "yarn npm publish --tag preview", + "since-latest-release": "../../../../scripts/since-latest-release.sh", + "start": "mm-snap watch", + "test": "jest --reporters=jest-silent-reporter", + "test:clean": "jest --clearCache", + "test:verbose": "jest --verbose", + "test:watch": "jest --watch" + }, + "dependencies": { + "@metamask/snaps-sdk": "workspace:^" + }, + "devDependencies": { + "@jest/globals": "^29.5.0", + "@lavamoat/allow-scripts": "^3.0.4", + "@metamask/auto-changelog": "^3.4.4", + "@metamask/eslint-config": "^12.1.0", + "@metamask/eslint-config-jest": "^12.1.0", + "@metamask/eslint-config-nodejs": "^12.1.0", + "@metamask/eslint-config-typescript": "^12.1.0", + "@metamask/snaps-cli": "workspace:^", + "@metamask/snaps-jest": "workspace:^", + "@swc/core": "1.3.78", + "@swc/jest": "^0.2.26", + "@typescript-eslint/eslint-plugin": "^5.42.1", + "@typescript-eslint/parser": "^6.21.0", + "deepmerge": "^4.2.2", + "depcheck": "^1.4.7", + "eslint": "^8.27.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-jest": "^27.1.5", + "eslint-plugin-jsdoc": "^41.1.2", + "eslint-plugin-n": "^15.7.0", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-promise": "^6.1.1", + "jest": "^29.0.2", + "jest-silent-reporter": "^0.6.0", + "prettier": "^2.8.8", + "prettier-plugin-packagejson": "^2.5.2", + "ts-node": "^10.9.1", + "typescript": "~5.3.3" + }, + "engines": { + "node": "^18.16 || >=20" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + } +} diff --git a/packages/examples/packages/settings-page/snap.config.ts b/packages/examples/packages/settings-page/snap.config.ts new file mode 100644 index 0000000000..577ddbdd7b --- /dev/null +++ b/packages/examples/packages/settings-page/snap.config.ts @@ -0,0 +1,17 @@ +import type { SnapConfig } from '@metamask/snaps-cli'; +import { resolve } from 'path'; + +const config: SnapConfig = { + input: resolve(__dirname, 'src/index.tsx'), + server: { + port: 8071, + }, + typescript: { + enabled: true, + }, + stats: { + buffer: false, + }, +}; + +export default config; diff --git a/packages/examples/packages/settings-page/snap.manifest.json b/packages/examples/packages/settings-page/snap.manifest.json new file mode 100644 index 0000000000..5c984e9d96 --- /dev/null +++ b/packages/examples/packages/settings-page/snap.manifest.json @@ -0,0 +1,28 @@ +{ + "version": "0.0.0", + "description": "MetaMask example snap demonstrating the use of settings pages.", + "proposedName": "Settings Page Example Snap", + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/snaps.git" + }, + "source": { + "shasum": "zDRgwSzsvtVtFr3F0SzUJCSCBNfix0C4CgTY98F+uDk=", + "location": { + "npm": { + "filePath": "dist/bundle.js", + "packageName": "@metamask/settings-page-example-snap", + "registry": "https://registry.npmjs.org" + } + } + }, + "initialPermissions": { + "endowment:rpc": { + "dapps": true + }, + "endowment:page-settings": {}, + "snap_manageState": {} + }, + "platformVersion": "6.13.0", + "manifestVersion": "0.1" +} diff --git a/packages/examples/packages/settings-page/src/components/SettingsPage.tsx b/packages/examples/packages/settings-page/src/components/SettingsPage.tsx new file mode 100644 index 0000000000..9bcb37c471 --- /dev/null +++ b/packages/examples/packages/settings-page/src/components/SettingsPage.tsx @@ -0,0 +1,56 @@ +import { + Box, + Checkbox, + Dropdown, + Option, + Radio, + RadioGroup, + Section, + Text, + type SnapComponent, +} from '@metamask/snaps-sdk/jsx'; + +export type SettingsPageProps = { + setting1?: boolean; + setting2?: 'option1' | 'option2'; + setting3?: 'option1' | 'option2'; +}; + +/** + * A settings page component that displays three settings. + * + * @param param - The settings page props. + * @param param.setting1 - The first setting. + * @param param.setting2 - The second setting. + * @param param.setting3 - The third setting. + * @returns The settings page component. + */ +export const SettingsPage: SnapComponent = ({ + setting1, + setting2, + setting3, +}) => ( + +
+ Setting 1 + This is the first setting + +
+
+ Setting 2 + This is the second setting + + Option 1 + Option 2 + +
+
+ Setting 3 + This is the third setting + + + + +
+
+); diff --git a/packages/examples/packages/settings-page/src/index.test.tsx b/packages/examples/packages/settings-page/src/index.test.tsx new file mode 100644 index 0000000000..3653e895d8 --- /dev/null +++ b/packages/examples/packages/settings-page/src/index.test.tsx @@ -0,0 +1,44 @@ +import { describe, it } from '@jest/globals'; +import { installSnap } from '@metamask/snaps-jest'; + +import { SettingsPage } from './components/SettingsPage'; + +describe('onSettingsPage', () => { + it('returns custom UI', async () => { + const { onSettingsPage } = await installSnap(); + + const response = await onSettingsPage(); + + const screen = response.getInterface(); + + expect(screen).toRender(); + }); +}); + +describe('onRpcRequest', () => { + describe('getSettings', () => { + it('returns the settings state', async () => { + const { request, onSettingsPage } = await installSnap(); + + const settingPageResponse = await onSettingsPage(); + + const screen = settingPageResponse.getInterface(); + + await screen.clickElement('setting1'); + + await screen.selectFromRadioGroup('setting2', 'option1'); + + await screen.selectInDropdown('setting3', 'option2'); + + expect( + await request({ + method: 'getSettings', + }), + ).toRespondWith({ + setting1: true, + setting2: 'option1', + setting3: 'option2', + }); + }); + }); +}); diff --git a/packages/examples/packages/settings-page/src/index.tsx b/packages/examples/packages/settings-page/src/index.tsx new file mode 100644 index 0000000000..2fc0f3cfa8 --- /dev/null +++ b/packages/examples/packages/settings-page/src/index.tsx @@ -0,0 +1,101 @@ +import type { OnRpcRequestHandler } from '@metamask/snaps-sdk'; +import { + MethodNotFoundError, + UserInputEventType, + type OnSettingsPageHandler, + type OnUserInputHandler, +} from '@metamask/snaps-sdk'; + +import { SettingsPage } from './components/SettingsPage'; + +type SnapState = { + setting1?: boolean; + setting2?: 'option1' | 'option2'; + setting3?: 'option1' | 'option2'; +}; + +/** + * Handle incoming JSON-RPC requests from the dapp, sent through the + * `wallet_invokeSnap` method. This handler handles one method: + * + * - `getSettings`: Get the settings state from the snap state. + * + * @param params - The request parameters. + * @param params.request - The JSON-RPC request object. + * @returns The JSON-RPC response. + * @see https://docs.metamask.io/snaps/reference/exports/#onrpcrequest + * @see https://docs.metamask.io/snaps/reference/rpc-api/#wallet_invokesnap + * @see https://docs.metamask.io/snaps/reference/snaps-api/#snap_managestate + */ +export const onRpcRequest: OnRpcRequestHandler = async ({ request }) => { + switch (request.method) { + case 'getSettings': + return await snap.request({ + method: 'snap_manageState', + params: { + operation: 'get', + encrypted: false, + }, + }); + default: + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw new MethodNotFoundError({ method: request.method }); + } +}; + +/** + * Handle incoming settings page requests from the MetaMask clients. + * + * @returns A static panel rendered with custom UI. + * @see https://docs.metamask.io/snaps/reference/exports/#onsettingspage + */ +export const onSettingsPage: OnSettingsPageHandler = async () => { + const state: SnapState | null = await snap.request({ + method: 'snap_manageState', + params: { + operation: 'get', + encrypted: false, + }, + }); + + return { + content: ( + + ), + }; +}; + +/** + * Handle incoming user events coming from the MetaMask clients open interfaces. + * + * @param params - The event parameters. + * @param params.event - The event object containing the event type, name and value. + * @see https://docs.metamask.io/snaps/reference/exports/#onuserinput + */ +export const onUserInput: OnUserInputHandler = async ({ event }) => { + if (event.type === UserInputEventType.InputChangeEvent) { + const state = await snap.request({ + method: 'snap_manageState', + params: { + operation: 'get', + encrypted: false, + }, + }); + + await snap.request({ + method: 'snap_manageState', + params: { + operation: 'update', + encrypted: false, + newState: { + ...state, + [event.name]: event.value, + }, + }, + }); + } +}; diff --git a/packages/examples/packages/settings-page/tsconfig.json b/packages/examples/packages/settings-page/tsconfig.json new file mode 100644 index 0000000000..17a40a6a74 --- /dev/null +++ b/packages/examples/packages/settings-page/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "composite": false, + "baseUrl": "./" + }, + "include": ["src", "snap.config.ts"] +} diff --git a/packages/snaps-controllers/coverage.json b/packages/snaps-controllers/coverage.json index 28873f6536..74c70ee306 100644 --- a/packages/snaps-controllers/coverage.json +++ b/packages/snaps-controllers/coverage.json @@ -1,6 +1,6 @@ { - "branches": 92.89, + "branches": 92.96, "functions": 96.71, - "lines": 98, + "lines": 98.01, "statements": 97.71 } diff --git a/packages/snaps-controllers/src/snaps/SnapController.test.tsx b/packages/snaps-controllers/src/snaps/SnapController.test.tsx index 4c69531223..b60903fed1 100644 --- a/packages/snaps-controllers/src/snaps/SnapController.test.tsx +++ b/packages/snaps-controllers/src/snaps/SnapController.test.tsx @@ -3514,6 +3514,176 @@ describe('SnapController', () => { snapController.destroy(); }); + it('throws if onSettingsPage handler returns a phishing link', async () => { + const rootMessenger = getControllerMessenger(); + const messenger = getSnapControllerMessenger(rootMessenger); + const snapController = getSnapController( + getSnapControllerOptions({ + messenger, + state: { + snaps: getPersistedSnapsState(), + }, + }), + ); + + rootMessenger.registerActionHandler( + 'PermissionController:getPermissions', + () => ({ + [SnapEndowments.SettingsPage]: { + caveats: null, + date: 1664187844588, + id: 'izn0WGUO8cvq_jqvLQuQP', + invoker: MOCK_SNAP_ID, + parentCapability: SnapEndowments.SettingsPage, + }, + }), + ); + + rootMessenger.registerActionHandler( + 'SubjectMetadataController:getSubjectMetadata', + () => MOCK_SNAP_SUBJECT_METADATA, + ); + + rootMessenger.registerActionHandler( + 'ExecutionService:handleRpcRequest', + async () => + Promise.resolve({ + content: text('[Foo bar](https://foo.bar)'), + }), + ); + + rootMessenger.registerActionHandler( + 'SnapInterfaceController:createInterface', + () => { + throw new Error('Invalid URL: The specified URL is not allowed.'); + }, + ); + + await expect( + snapController.handleRequest({ + snapId: MOCK_SNAP_ID, + origin: 'foo.com', + handler: HandlerType.OnSettingsPage, + request: { + jsonrpc: '2.0', + method: ' ', + params: {}, + id: 1, + }, + }), + ).rejects.toThrow(`Invalid URL: The specified URL is not allowed.`); + + snapController.destroy(); + }); + + it('throws if onSettingsPage return value is an invalid id', async () => { + const rootMessenger = getControllerMessenger(); + const messenger = getSnapControllerMessenger(rootMessenger); + const snapController = getSnapController( + getSnapControllerOptions({ + messenger, + state: { + snaps: getPersistedSnapsState(), + }, + }), + ); + + const handlerResponse = { id: 'bar' }; + + rootMessenger.registerActionHandler( + 'PermissionController:getPermissions', + () => ({ + [SnapEndowments.SettingsPage]: { + caveats: null, + date: 1664187844588, + id: 'izn0WGUO8cvq_jqvLQuQP', + invoker: MOCK_SNAP_ID, + parentCapability: SnapEndowments.SettingsPage, + }, + }), + ); + + rootMessenger.registerActionHandler( + 'SubjectMetadataController:getSubjectMetadata', + () => MOCK_SNAP_SUBJECT_METADATA, + ); + + rootMessenger.registerActionHandler( + 'ExecutionService:handleRpcRequest', + async () => Promise.resolve(handlerResponse), + ); + + await expect( + snapController.handleRequest({ + snapId: MOCK_SNAP_ID, + origin: 'foo.com', + handler: HandlerType.OnSettingsPage, + request: { + jsonrpc: '2.0', + method: ' ', + params: {}, + id: 1, + }, + }), + ).rejects.toThrow("Interface with id 'bar' not found."); + + snapController.destroy(); + }); + + it("doesn't throw if onSettingsPage return value is valid", async () => { + const rootMessenger = getControllerMessenger(); + const messenger = getSnapControllerMessenger(rootMessenger); + const snapController = getSnapController( + getSnapControllerOptions({ + messenger, + state: { + snaps: getPersistedSnapsState(), + }, + }), + ); + + const handlerResponse = { content: text('[foobar](https://foo.bar)') }; + + rootMessenger.registerActionHandler( + 'PermissionController:getPermissions', + () => ({ + [SnapEndowments.SettingsPage]: { + caveats: null, + date: 1664187844588, + id: 'izn0WGUO8cvq_jqvLQuQP', + invoker: MOCK_SNAP_ID, + parentCapability: SnapEndowments.SettingsPage, + }, + }), + ); + + rootMessenger.registerActionHandler( + 'SubjectMetadataController:getSubjectMetadata', + () => MOCK_SNAP_SUBJECT_METADATA, + ); + + rootMessenger.registerActionHandler( + 'ExecutionService:handleRpcRequest', + async () => Promise.resolve(handlerResponse), + ); + + const result = await snapController.handleRequest({ + snapId: MOCK_SNAP_ID, + origin: 'foo.com', + handler: HandlerType.OnSettingsPage, + request: { + jsonrpc: '2.0', + method: ' ', + params: {}, + id: 1, + }, + }); + + expect(result).toStrictEqual({ id: MOCK_INTERFACE_ID }); + + snapController.destroy(); + }); + it('throws if onNameLookup returns an invalid value', async () => { const rootMessenger = getControllerMessenger(); const messenger = getSnapControllerMessenger(rootMessenger); @@ -5442,7 +5612,7 @@ describe('SnapController', () => { [MOCK_SNAP_ID]: {}, }), ).rejects.toThrow( - 'A snap must request at least one of the following permissions: endowment:rpc, endowment:transaction-insight, endowment:cronjob, endowment:name-lookup, endowment:lifecycle-hooks, endowment:keyring, endowment:page-home, endowment:signature-insight.', + 'A snap must request at least one of the following permissions: endowment:rpc, endowment:transaction-insight, endowment:cronjob, endowment:name-lookup, endowment:lifecycle-hooks, endowment:keyring, endowment:page-home, endowment:page-settings, endowment:signature-insight.', ); controller.destroy(); diff --git a/packages/snaps-controllers/src/snaps/SnapController.ts b/packages/snaps-controllers/src/snaps/SnapController.ts index 7b655839d0..173e8ba0d1 100644 --- a/packages/snaps-controllers/src/snaps/SnapController.ts +++ b/packages/snaps-controllers/src/snaps/SnapController.ts @@ -90,6 +90,7 @@ import { OnNameLookupResponseStruct, getLocalizedSnapManifest, MAX_FILE_SIZE, + OnSettingsPageResponseStruct, } from '@metamask/snaps-utils'; import type { Json, NonEmptyArray, SemVerRange } from '@metamask/utils'; import { @@ -3463,7 +3464,8 @@ export class SnapController extends BaseController< switch (handlerType) { case HandlerType.OnTransaction: case HandlerType.OnSignature: - case HandlerType.OnHomePage: { + case HandlerType.OnHomePage: + case HandlerType.OnSettingsPage: { // Since this type has been asserted earlier we can cast const castResult = result as Record | null; @@ -3524,6 +3526,15 @@ export class SnapController extends BaseController< break; } + case HandlerType.OnSettingsPage: { + assertStruct(result, OnSettingsPageResponseStruct); + + if (result && hasProperty(result, 'id')) { + this.#assertInterfaceExists(snapId, result.id as string); + } + + break; + } case HandlerType.OnNameLookup: assertStruct(result, OnNameLookupResponseStruct); break; diff --git a/packages/snaps-execution-environments/coverage.json b/packages/snaps-execution-environments/coverage.json index f958e510ae..1a3193285c 100644 --- a/packages/snaps-execution-environments/coverage.json +++ b/packages/snaps-execution-environments/coverage.json @@ -1,5 +1,5 @@ { - "branches": 80.55, + "branches": 80.68, "functions": 89.26, "lines": 90.67, "statements": 90.06 diff --git a/packages/snaps-execution-environments/src/common/BaseSnapExecutor.test.browser.ts b/packages/snaps-execution-environments/src/common/BaseSnapExecutor.test.browser.ts index 88208997cb..332b50097d 100644 --- a/packages/snaps-execution-environments/src/common/BaseSnapExecutor.test.browser.ts +++ b/packages/snaps-execution-environments/src/common/BaseSnapExecutor.test.browser.ts @@ -1441,6 +1441,39 @@ describe('BaseSnapExecutor', () => { }); }); + it('supports onSettingsPage export', async () => { + const CODE = ` + module.exports.onSettingsPage = () => ({ content: { type: 'panel', children: [] }}); + `; + + const executor = new TestSnapExecutor(); + await executor.executeSnap(1, MOCK_SNAP_ID, CODE, []); + + expect(await executor.readCommand()).toStrictEqual({ + jsonrpc: '2.0', + id: 1, + result: 'OK', + }); + + await executor.writeCommand({ + jsonrpc: '2.0', + id: 2, + method: 'snapRpc', + params: [ + MOCK_SNAP_ID, + HandlerType.OnSettingsPage, + MOCK_ORIGIN, + { jsonrpc: '2.0', method: '' }, + ], + }); + + expect(await executor.readCommand()).toStrictEqual({ + id: 2, + jsonrpc: '2.0', + result: { content: { type: 'panel', children: [] } }, + }); + }); + it('supports onSignature export', async () => { const CODE = ` module.exports.onSignature = ({ signature, signatureOrigin }) => diff --git a/packages/snaps-execution-environments/src/common/commands.ts b/packages/snaps-execution-environments/src/common/commands.ts index 32d073f71f..b03a32d23d 100644 --- a/packages/snaps-execution-environments/src/common/commands.ts +++ b/packages/snaps-execution-environments/src/common/commands.ts @@ -86,6 +86,7 @@ export function getHandlerArguments( return { origin }; case HandlerType.OnHomePage: + case HandlerType.OnSettingsPage: return {}; case HandlerType.OnUserInput: { assertIsOnUserInputRequestArguments(request.params); diff --git a/packages/snaps-jest/src/helpers.test.tsx b/packages/snaps-jest/src/helpers.test.tsx index 684490c54a..6f7ccf69ba 100644 --- a/packages/snaps-jest/src/helpers.test.tsx +++ b/packages/snaps-jest/src/helpers.test.tsx @@ -774,6 +774,32 @@ describe('installSnap', () => { }); }); + describe('getSettingsPage', () => { + it('sends a OnSettingsPage request and returns the result', async () => { + jest.spyOn(console, 'log').mockImplementation(); + + const { snapId, close: closeServer } = await getMockServer({ + sourceCode: ` + module.exports.onSettingsPage = async () => { + return { content: { type: 'text', value: 'Hello, world!' } }; + }; + `, + }); + + const { onSettingsPage, close } = await installSnap(snapId); + const response = await onSettingsPage(); + + expect(response).toStrictEqual( + expect.objectContaining({ + getInterface: expect.any(Function), + }), + ); + + await close(); + await closeServer(); + }); + }); + describe('onKeyringRequest', () => { it('sends a keyring request and returns the result', async () => { jest.spyOn(console, 'log').mockImplementation(); diff --git a/packages/snaps-jest/src/helpers.ts b/packages/snaps-jest/src/helpers.ts index a4d3d38d33..0688084cd6 100644 --- a/packages/snaps-jest/src/helpers.ts +++ b/packages/snaps-jest/src/helpers.ts @@ -178,6 +178,7 @@ export async function installSnap< onCronjob, runCronjob, onHomePage, + onSettingsPage, onKeyringRequest, onInstall, onUpdate, @@ -194,6 +195,7 @@ export async function installSnap< onCronjob, runCronjob, onHomePage, + onSettingsPage, onKeyringRequest, onInstall, onUpdate, diff --git a/packages/snaps-rpc-methods/jest.config.js b/packages/snaps-rpc-methods/jest.config.js index 077ed1c65d..f3813d88c0 100644 --- a/packages/snaps-rpc-methods/jest.config.js +++ b/packages/snaps-rpc-methods/jest.config.js @@ -11,9 +11,9 @@ module.exports = deepmerge(baseConfig, { coverageThreshold: { global: { branches: 92.94, - functions: 97.26, - lines: 97.87, - statements: 97.39, + functions: 97.29, + lines: 97.88, + statements: 97.41, }, }, }); diff --git a/packages/snaps-rpc-methods/src/endowments/enum.ts b/packages/snaps-rpc-methods/src/endowments/enum.ts index f0d1577c6f..cdd13a6746 100644 --- a/packages/snaps-rpc-methods/src/endowments/enum.ts +++ b/packages/snaps-rpc-methods/src/endowments/enum.ts @@ -10,4 +10,5 @@ export enum SnapEndowments { LifecycleHooks = 'endowment:lifecycle-hooks', Keyring = 'endowment:keyring', HomePage = 'endowment:page-home', + SettingsPage = 'endowment:page-settings', } diff --git a/packages/snaps-rpc-methods/src/endowments/index.ts b/packages/snaps-rpc-methods/src/endowments/index.ts index faa0c8fe06..7d82ac72d3 100644 --- a/packages/snaps-rpc-methods/src/endowments/index.ts +++ b/packages/snaps-rpc-methods/src/endowments/index.ts @@ -31,6 +31,7 @@ import { rpcCaveatSpecifications, rpcEndowmentBuilder, } from './rpc'; +import { settingsPageEndowmentBuilder } from './settings-page'; import { getSignatureInsightCaveatMapper, signatureInsightCaveatSpecifications, @@ -55,6 +56,7 @@ export const endowmentPermissionBuilders = { [nameLookupEndowmentBuilder.targetName]: nameLookupEndowmentBuilder, [lifecycleHooksEndowmentBuilder.targetName]: lifecycleHooksEndowmentBuilder, [keyringEndowmentBuilder.targetName]: keyringEndowmentBuilder, + [settingsPageEndowmentBuilder.targetName]: settingsPageEndowmentBuilder, [homePageEndowmentBuilder.targetName]: homePageEndowmentBuilder, [signatureInsightEndowmentBuilder.targetName]: signatureInsightEndowmentBuilder, @@ -93,6 +95,7 @@ export const endowmentCaveatMappers: Record< ), [lifecycleHooksEndowmentBuilder.targetName]: getMaxRequestTimeCaveatMapper, [homePageEndowmentBuilder.targetName]: getMaxRequestTimeCaveatMapper, + [settingsPageEndowmentBuilder.targetName]: getMaxRequestTimeCaveatMapper, }; // We allow null because a permitted handler does not have an endowment @@ -105,6 +108,7 @@ export const handlerEndowments: Record = { [HandlerType.OnUpdate]: lifecycleHooksEndowmentBuilder.targetName, [HandlerType.OnKeyringRequest]: keyringEndowmentBuilder.targetName, [HandlerType.OnHomePage]: homePageEndowmentBuilder.targetName, + [HandlerType.OnSettingsPage]: settingsPageEndowmentBuilder.targetName, [HandlerType.OnSignature]: signatureInsightEndowmentBuilder.targetName, [HandlerType.OnUserInput]: null, }; diff --git a/packages/snaps-rpc-methods/src/endowments/settings-page.test.ts b/packages/snaps-rpc-methods/src/endowments/settings-page.test.ts new file mode 100644 index 0000000000..957b315211 --- /dev/null +++ b/packages/snaps-rpc-methods/src/endowments/settings-page.test.ts @@ -0,0 +1,19 @@ +import { PermissionType, SubjectType } from '@metamask/permission-controller'; + +import { SnapEndowments } from './enum'; +import { settingsPageEndowmentBuilder } from './settings-page'; + +describe('endowment:page-settings', () => { + it('builds the expected permission specification', () => { + const specification = settingsPageEndowmentBuilder.specificationBuilder({}); + expect(specification).toStrictEqual({ + permissionType: PermissionType.Endowment, + targetName: SnapEndowments.SettingsPage, + endowmentGetter: expect.any(Function), + allowedCaveats: null, + subjectTypes: [SubjectType.Snap], + }); + + expect(specification.endowmentGetter()).toBeNull(); + }); +}); diff --git a/packages/snaps-rpc-methods/src/endowments/settings-page.ts b/packages/snaps-rpc-methods/src/endowments/settings-page.ts new file mode 100644 index 0000000000..ec6a1de592 --- /dev/null +++ b/packages/snaps-rpc-methods/src/endowments/settings-page.ts @@ -0,0 +1,45 @@ +import type { + PermissionSpecificationBuilder, + EndowmentGetterParams, + ValidPermissionSpecification, +} from '@metamask/permission-controller'; +import { PermissionType, SubjectType } from '@metamask/permission-controller'; +import type { NonEmptyArray } from '@metamask/utils'; + +import { SnapEndowments } from './enum'; + +const permissionName = SnapEndowments.SettingsPage; + +type SettingsPageEndowmentSpecification = ValidPermissionSpecification<{ + permissionType: PermissionType.Endowment; + targetName: typeof permissionName; + endowmentGetter: (_options?: EndowmentGetterParams) => null; + allowedCaveats: Readonly> | null; +}>; + +/** + * `endowment:settings-page` returns nothing; it is intended to be used as a + * flag by the snap controller to detect whether the snap has the capability to + * use the snap settings page feature. + * + * @param _builderOptions - Optional specification builder options. + * @returns The specification for the `settings-page` endowment. + */ +const specificationBuilder: PermissionSpecificationBuilder< + PermissionType.Endowment, + any, + SettingsPageEndowmentSpecification +> = (_builderOptions?: unknown) => { + return { + permissionType: PermissionType.Endowment, + targetName: permissionName, + allowedCaveats: null, + endowmentGetter: (_getterOptions?: EndowmentGetterParams) => null, + subjectTypes: [SubjectType.Snap], + }; +}; + +export const settingsPageEndowmentBuilder = Object.freeze({ + targetName: permissionName, + specificationBuilder, +} as const); diff --git a/packages/snaps-rpc-methods/src/permissions.test.ts b/packages/snaps-rpc-methods/src/permissions.test.ts index 50f911b100..7725f2cd0e 100644 --- a/packages/snaps-rpc-methods/src/permissions.test.ts +++ b/packages/snaps-rpc-methods/src/permissions.test.ts @@ -82,6 +82,15 @@ describe('buildSnapEndowmentSpecifications', () => { ], "targetName": "endowment:page-home", }, + "endowment:page-settings": { + "allowedCaveats": null, + "endowmentGetter": [Function], + "permissionType": "Endowment", + "subjectTypes": [ + "snap", + ], + "targetName": "endowment:page-settings", + }, "endowment:rpc": { "allowedCaveats": [ "rpcOrigin", diff --git a/packages/snaps-sdk/src/types/handlers/index.ts b/packages/snaps-sdk/src/types/handlers/index.ts index 1e4fc63634..ab6a86d833 100644 --- a/packages/snaps-sdk/src/types/handlers/index.ts +++ b/packages/snaps-sdk/src/types/handlers/index.ts @@ -7,3 +7,4 @@ export * from './rpc-request'; export * from './transaction'; export * from './signature'; export * from './user-input'; +export * from './settings-page'; diff --git a/packages/snaps-sdk/src/types/handlers/settings-page.ts b/packages/snaps-sdk/src/types/handlers/settings-page.ts new file mode 100644 index 0000000000..0dd746f96b --- /dev/null +++ b/packages/snaps-sdk/src/types/handlers/settings-page.ts @@ -0,0 +1,24 @@ +import type { ComponentOrElement } from '..'; + +/** + * The `onSettingsPage` handler. This is called when the user navigates to the + * Snap's settings page in the MetaMask UI. + * + * This function does not receive any arguments. + * + * @returns The content to display on the settings page. See + * {@link OnSettingsPageResponse}. + */ +export type OnSettingsPageHandler = () => Promise; + +/** + * The content to display on the settings page. + * + * @property content - A custom UI component, that will be shown in MetaMask. + * @property id - A custom UI interface ID, that will be shown in MetaMask. + */ +export type OnSettingsPageResponse = + | { + content: ComponentOrElement; + } + | { id: string }; diff --git a/packages/snaps-sdk/src/types/permissions.ts b/packages/snaps-sdk/src/types/permissions.ts index 7caed09815..76fc232dcd 100644 --- a/packages/snaps-sdk/src/types/permissions.ts +++ b/packages/snaps-sdk/src/types/permissions.ts @@ -57,6 +57,9 @@ export type InitialPermissions = Partial<{ 'endowment:page-home'?: { maxRequestTime?: number; }; + 'endowment:page-settings'?: { + maxRequestTime?: number; + }; 'endowment:rpc': { dapps?: boolean; snaps?: boolean; diff --git a/packages/snaps-simulation/src/helpers.test.tsx b/packages/snaps-simulation/src/helpers.test.tsx index e8f83c4646..53368ef92a 100644 --- a/packages/snaps-simulation/src/helpers.test.tsx +++ b/packages/snaps-simulation/src/helpers.test.tsx @@ -548,6 +548,32 @@ describe('helpers', () => { }); }); + describe('getSettingsPage', () => { + it('sends a OnSettingsPage request and returns the result', async () => { + jest.spyOn(console, 'log').mockImplementation(); + + const { snapId, close: closeServer } = await getMockServer({ + sourceCode: ` + module.exports.onSettingsPage = async () => { + return { content: { type: 'text', value: 'Hello, world!' } }; + }; + `, + }); + + const { onSettingsPage, close } = await installSnap(snapId); + const response = await onSettingsPage(); + + expect(response).toStrictEqual( + expect.objectContaining({ + getInterface: expect.any(Function), + }), + ); + + await close(); + await closeServer(); + }); + }); + describe('onKeyringRequest', () => { it('sends a keyring request and returns the result', async () => { jest.spyOn(console, 'log').mockImplementation(); diff --git a/packages/snaps-simulation/src/helpers.ts b/packages/snaps-simulation/src/helpers.ts index 639b119a77..8ec77c2513 100644 --- a/packages/snaps-simulation/src/helpers.ts +++ b/packages/snaps-simulation/src/helpers.ts @@ -118,6 +118,13 @@ export type SnapHelpers = { */ onHomePage(): Promise; + /** + * Get the response from the snap's `onSettingsPage` method. + * + * @returns The response. + */ + onSettingsPage(): Promise; + /** * Send a keyring request to the Snap. * @@ -402,6 +409,26 @@ export function getHelpers({ return response; }, + onSettingsPage: async (): Promise => { + log('Rendering settings page.'); + + const response = await handleRequest({ + snapId, + store, + executionService, + controllerMessenger, + runSaga, + handler: HandlerType.OnSettingsPage, + request: { + method: '', + }, + }); + + assertIsResponseWithInterface(response); + + return response; + }, + mockJsonRpc(mock: JsonRpcMockOptions) { log('Mocking JSON-RPC request %o.', mock); diff --git a/packages/snaps-simulation/src/methods/specifications.test.ts b/packages/snaps-simulation/src/methods/specifications.test.ts index 487eda7235..2c556403e4 100644 --- a/packages/snaps-simulation/src/methods/specifications.test.ts +++ b/packages/snaps-simulation/src/methods/specifications.test.ts @@ -123,6 +123,15 @@ describe('getPermissionSpecifications', () => { ], "targetName": "endowment:page-home", }, + "endowment:page-settings": { + "allowedCaveats": null, + "endowmentGetter": [Function], + "permissionType": "Endowment", + "subjectTypes": [ + "snap", + ], + "targetName": "endowment:page-settings", + }, "endowment:rpc": { "allowedCaveats": [ "rpcOrigin", diff --git a/packages/snaps-simulation/src/types.ts b/packages/snaps-simulation/src/types.ts index 21bc37c7ea..5bb52f557c 100644 --- a/packages/snaps-simulation/src/types.ts +++ b/packages/snaps-simulation/src/types.ts @@ -420,6 +420,13 @@ export type Snap = { */ onHomePage(): Promise; + /** + * Get the response from the snap's `onSettingsPage` method. + * + * @returns The response. + */ + onSettingsPage(): Promise; + /** * Send a keyring to the Snap. * diff --git a/packages/snaps-utils/coverage.json b/packages/snaps-utils/coverage.json index 102bd1c6df..a9248b7438 100644 --- a/packages/snaps-utils/coverage.json +++ b/packages/snaps-utils/coverage.json @@ -2,5 +2,5 @@ "branches": 99.74, "functions": 98.93, "lines": 99.46, - "statements": 96.37 + "statements": 96.31 } diff --git a/packages/snaps-utils/src/handler-types.ts b/packages/snaps-utils/src/handler-types.ts index 642c201fec..230486a95e 100644 --- a/packages/snaps-utils/src/handler-types.ts +++ b/packages/snaps-utils/src/handler-types.ts @@ -8,6 +8,7 @@ export enum HandlerType { OnNameLookup = 'onNameLookup', OnKeyringRequest = 'onKeyringRequest', OnHomePage = 'onHomePage', + OnSettingsPage = 'onSettingsPage', OnUserInput = 'onUserInput', } diff --git a/packages/snaps-utils/src/handlers.ts b/packages/snaps-utils/src/handlers.ts index 6c4e37a9e6..a20a48b842 100644 --- a/packages/snaps-utils/src/handlers.ts +++ b/packages/snaps-utils/src/handlers.ts @@ -5,6 +5,7 @@ import type { OnKeyringRequestHandler, OnNameLookupHandler, OnRpcRequestHandler, + OnSettingsPageHandler, OnSignatureHandler, OnTransactionHandler, OnUpdateHandler, @@ -89,6 +90,13 @@ export const SNAP_EXPORTS = { return typeof snapExport === 'function'; }, }, + [HandlerType.OnSettingsPage]: { + type: HandlerType.OnSettingsPage, + required: true, + validator: (snapExport: unknown): snapExport is OnSettingsPageHandler => { + return typeof snapExport === 'function'; + }, + }, [HandlerType.OnSignature]: { type: HandlerType.OnSignature, required: true, @@ -145,6 +153,8 @@ export const OnHomePageResponseStruct = union([ OnHomePageResponseWithIdStruct, ]); +export const OnSettingsPageResponseStruct = OnHomePageResponseStruct; + export const AddressResolutionStruct = object({ protocol: string(), resolvedDomain: string(), diff --git a/packages/test-snaps/package.json b/packages/test-snaps/package.json index 1077a1ba86..47b175528a 100644 --- a/packages/test-snaps/package.json +++ b/packages/test-snaps/package.json @@ -66,6 +66,7 @@ "@metamask/notification-example-snap": "workspace:^", "@metamask/preinstalled-example-snap": "workspace:^", "@metamask/send-flow-example-snap": "workspace:^", + "@metamask/settings-page-example-snap": "workspace:^", "@metamask/signature-insights-example-snap": "workspace:^", "@metamask/snaps-utils": "workspace:^", "@metamask/utils": "^10.0.0", diff --git a/packages/test-snaps/src/features/snaps/index.ts b/packages/test-snaps/src/features/snaps/index.ts index c80978a40d..91ba2991f4 100644 --- a/packages/test-snaps/src/features/snaps/index.ts +++ b/packages/test-snaps/src/features/snaps/index.ts @@ -27,3 +27,4 @@ export * from './signature-insights'; export * from './updates'; export * from './wasm'; export * from './send-flow'; +export * from './settings-page'; diff --git a/packages/test-snaps/src/features/snaps/send-flow/SendFlow.tsx b/packages/test-snaps/src/features/snaps/send-flow/SendFlow.tsx index f2435cc0f7..82b3a01b2b 100644 --- a/packages/test-snaps/src/features/snaps/send-flow/SendFlow.tsx +++ b/packages/test-snaps/src/features/snaps/send-flow/SendFlow.tsx @@ -30,7 +30,12 @@ export const SendFlow: FunctionComponent = () => { version={SEND_FLOW_VERSION} testId="dialogs" > - diff --git a/packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx b/packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx new file mode 100644 index 0000000000..11c3090bb3 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/settings-page/SettingsPage.tsx @@ -0,0 +1,46 @@ +import { logError } from '@metamask/snaps-utils'; +import type { FunctionComponent } from 'react'; +import { Button } from 'react-bootstrap'; + +import { useInvokeMutation } from '../../../api'; +import { Result, Snap } from '../../../components'; +import { getSnapId } from '../../../utils'; +import { + SETTINGS_PAGE_SNAP_ID, + SETTINGS_PAGE_SNAP_PORT, + SETTINGS_PAGE_VERSION, +} from './constants'; + +export const SettingsPage: FunctionComponent = () => { + const [invokeSnap, { isLoading, data }] = useInvokeMutation(); + const snapId = getSnapId(SETTINGS_PAGE_SNAP_ID, SETTINGS_PAGE_SNAP_PORT); + + const handleSubmit = () => { + invokeSnap({ + snapId, + method: 'getSettings', + }).catch(logError); + }; + return ( + + + + + {JSON.stringify(data, null, 2)} + + + ); +}; diff --git a/packages/test-snaps/src/features/snaps/settings-page/constants.ts b/packages/test-snaps/src/features/snaps/settings-page/constants.ts new file mode 100644 index 0000000000..0b2b4ef5da --- /dev/null +++ b/packages/test-snaps/src/features/snaps/settings-page/constants.ts @@ -0,0 +1,5 @@ +import packageJson from '@metamask/settings-page-example-snap/package.json'; + +export const SETTINGS_PAGE_SNAP_ID = 'npm:@metamask/settings-page-example-snap'; +export const SETTINGS_PAGE_SNAP_PORT = 8071; +export const SETTINGS_PAGE_VERSION = packageJson.version; diff --git a/packages/test-snaps/src/features/snaps/settings-page/index.ts b/packages/test-snaps/src/features/snaps/settings-page/index.ts new file mode 100644 index 0000000000..f533f5abe0 --- /dev/null +++ b/packages/test-snaps/src/features/snaps/settings-page/index.ts @@ -0,0 +1 @@ +export * from './SettingsPage'; diff --git a/yarn.lock b/yarn.lock index 7041b9ad4e..5eb2d26aed 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5517,6 +5517,43 @@ __metadata: languageName: unknown linkType: soft +"@metamask/settings-page-example-snap@workspace:^, @metamask/settings-page-example-snap@workspace:packages/examples/packages/settings-page": + version: 0.0.0-use.local + resolution: "@metamask/settings-page-example-snap@workspace:packages/examples/packages/settings-page" + dependencies: + "@jest/globals": "npm:^29.5.0" + "@lavamoat/allow-scripts": "npm:^3.0.4" + "@metamask/auto-changelog": "npm:^3.4.4" + "@metamask/eslint-config": "npm:^12.1.0" + "@metamask/eslint-config-jest": "npm:^12.1.0" + "@metamask/eslint-config-nodejs": "npm:^12.1.0" + "@metamask/eslint-config-typescript": "npm:^12.1.0" + "@metamask/snaps-cli": "workspace:^" + "@metamask/snaps-jest": "workspace:^" + "@metamask/snaps-sdk": "workspace:^" + "@swc/core": "npm:1.3.78" + "@swc/jest": "npm:^0.2.26" + "@typescript-eslint/eslint-plugin": "npm:^5.42.1" + "@typescript-eslint/parser": "npm:^6.21.0" + deepmerge: "npm:^4.2.2" + depcheck: "npm:^1.4.7" + eslint: "npm:^8.27.0" + eslint-config-prettier: "npm:^8.5.0" + eslint-plugin-import: "npm:^2.26.0" + eslint-plugin-jest: "npm:^27.1.5" + eslint-plugin-jsdoc: "npm:^41.1.2" + eslint-plugin-n: "npm:^15.7.0" + eslint-plugin-prettier: "npm:^4.2.1" + eslint-plugin-promise: "npm:^6.1.1" + jest: "npm:^29.0.2" + jest-silent-reporter: "npm:^0.6.0" + prettier: "npm:^2.8.8" + prettier-plugin-packagejson: "npm:^2.5.2" + ts-node: "npm:^10.9.1" + typescript: "npm:~5.3.3" + languageName: unknown + linkType: soft + "@metamask/signature-insights-example-snap@workspace:^, @metamask/signature-insights-example-snap@workspace:packages/examples/packages/signature-insights": version: 0.0.0-use.local resolution: "@metamask/signature-insights-example-snap@workspace:packages/examples/packages/signature-insights" @@ -6406,6 +6443,7 @@ __metadata: "@metamask/preinstalled-example-snap": "workspace:^" "@metamask/providers": "npm:^18.1.1" "@metamask/send-flow-example-snap": "workspace:^" + "@metamask/settings-page-example-snap": "workspace:^" "@metamask/signature-insights-example-snap": "workspace:^" "@metamask/snaps-utils": "workspace:^" "@metamask/utils": "npm:^10.0.0"