@metamask/snaps-utils 0.33.1-flask.1 → 0.34.0-flask.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -35
- package/dist/handlers.d.ts +4 -4
- package/dist/handlers.js.map +1 -1
- package/dist/icon.d.ts +4 -0
- package/dist/icon.js +17 -0
- package/dist/icon.js.map +1 -0
- package/dist/index.browser.d.ts +1 -0
- package/dist/index.browser.js +1 -0
- package/dist/index.browser.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/manifest/manifest.js +8 -7
- package/dist/manifest/manifest.js.map +1 -1
- package/dist/manifest/validation.d.ts +2 -0
- package/dist/manifest/validation.js +1 -0
- package/dist/manifest/validation.js.map +1 -1
- package/dist/npm.d.ts +0 -2
- package/dist/npm.js +8 -5
- package/dist/npm.js.map +1 -1
- package/dist/snaps.d.ts +9 -2
- package/dist/snaps.js +11 -1
- package/dist/snaps.js.map +1 -1
- package/dist/validation.d.ts +8 -0
- package/dist/validation.js +21 -0
- package/dist/validation.js.map +1 -0
- package/package.json +8 -7
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.34.0-flask.1]
|
|
10
|
+
### Changed
|
|
11
|
+
- Add SVG validation ([#1401](https://github.com/MetaMask/snaps/pull/1401))
|
|
12
|
+
- Make handler types generic, allowing them to be changed ([#1409](https://github.com/MetaMask/snaps/pull/1409))
|
|
13
|
+
- Allow use of `$schema` in manifest files ([#1389](https://github.com/MetaMask/snaps/pull/1389))
|
|
14
|
+
|
|
9
15
|
## [0.33.1-flask.1]
|
|
10
16
|
### Changed
|
|
11
17
|
- No changes this release.
|
|
@@ -197,38 +203,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
197
203
|
### Added
|
|
198
204
|
- Initial release ([#410](https://github.com/MetaMask/snaps-monorepo/pull/410), [#421](https://github.com/MetaMask/snaps-monorepo/pull/421))
|
|
199
205
|
|
|
200
|
-
[Unreleased]: https://github.com/MetaMask/snaps
|
|
201
|
-
[0.
|
|
202
|
-
[0.33.
|
|
203
|
-
[0.
|
|
204
|
-
[0.32.
|
|
205
|
-
[0.32.
|
|
206
|
-
[0.
|
|
207
|
-
[0.
|
|
208
|
-
[0.
|
|
209
|
-
[0.
|
|
210
|
-
[0.
|
|
211
|
-
[0.27.
|
|
212
|
-
[0.
|
|
213
|
-
[0.26.
|
|
214
|
-
[0.26.
|
|
215
|
-
[0.
|
|
216
|
-
[0.
|
|
217
|
-
[0.24.
|
|
218
|
-
[0.
|
|
219
|
-
[0.
|
|
220
|
-
[0.22.
|
|
221
|
-
[0.22.
|
|
222
|
-
[0.22.
|
|
223
|
-
[0.
|
|
224
|
-
[0.
|
|
225
|
-
[0.
|
|
226
|
-
[0.19.
|
|
227
|
-
[0.
|
|
228
|
-
[0.18.
|
|
229
|
-
[0.
|
|
230
|
-
[0.
|
|
231
|
-
[0.
|
|
232
|
-
[0.
|
|
233
|
-
[0.
|
|
234
|
-
[0.
|
|
206
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/v0.34.0-flask.1...HEAD
|
|
207
|
+
[0.34.0-flask.1]: https://github.com/MetaMask/snaps/compare/v0.33.1-flask.1...v0.34.0-flask.1
|
|
208
|
+
[0.33.1-flask.1]: https://github.com/MetaMask/snaps/compare/v0.33.0-flask.1...v0.33.1-flask.1
|
|
209
|
+
[0.33.0-flask.1]: https://github.com/MetaMask/snaps/compare/v0.32.2...v0.33.0-flask.1
|
|
210
|
+
[0.32.2]: https://github.com/MetaMask/snaps/compare/v0.32.1...v0.32.2
|
|
211
|
+
[0.32.1]: https://github.com/MetaMask/snaps/compare/v0.32.0...v0.32.1
|
|
212
|
+
[0.32.0]: https://github.com/MetaMask/snaps/compare/v0.31.0...v0.32.0
|
|
213
|
+
[0.31.0]: https://github.com/MetaMask/snaps/compare/v0.30.0...v0.31.0
|
|
214
|
+
[0.30.0]: https://github.com/MetaMask/snaps/compare/v0.29.0...v0.30.0
|
|
215
|
+
[0.29.0]: https://github.com/MetaMask/snaps/compare/v0.28.0...v0.29.0
|
|
216
|
+
[0.28.0]: https://github.com/MetaMask/snaps/compare/v0.27.1...v0.28.0
|
|
217
|
+
[0.27.1]: https://github.com/MetaMask/snaps/compare/v0.27.0...v0.27.1
|
|
218
|
+
[0.27.0]: https://github.com/MetaMask/snaps/compare/v0.26.2...v0.27.0
|
|
219
|
+
[0.26.2]: https://github.com/MetaMask/snaps/compare/v0.26.1...v0.26.2
|
|
220
|
+
[0.26.1]: https://github.com/MetaMask/snaps/compare/v0.26.0...v0.26.1
|
|
221
|
+
[0.26.0]: https://github.com/MetaMask/snaps/compare/v0.25.0...v0.26.0
|
|
222
|
+
[0.25.0]: https://github.com/MetaMask/snaps/compare/v0.24.1...v0.25.0
|
|
223
|
+
[0.24.1]: https://github.com/MetaMask/snaps/compare/v0.24.0...v0.24.1
|
|
224
|
+
[0.24.0]: https://github.com/MetaMask/snaps/compare/v0.23.0...v0.24.0
|
|
225
|
+
[0.23.0]: https://github.com/MetaMask/snaps/compare/v0.22.3...v0.23.0
|
|
226
|
+
[0.22.3]: https://github.com/MetaMask/snaps/compare/v0.22.2...v0.22.3
|
|
227
|
+
[0.22.2]: https://github.com/MetaMask/snaps/compare/v0.22.1...v0.22.2
|
|
228
|
+
[0.22.1]: https://github.com/MetaMask/snaps/compare/v0.22.0...v0.22.1
|
|
229
|
+
[0.22.0]: https://github.com/MetaMask/snaps/compare/v0.21.0...v0.22.0
|
|
230
|
+
[0.21.0]: https://github.com/MetaMask/snaps/compare/v0.20.0...v0.21.0
|
|
231
|
+
[0.20.0]: https://github.com/MetaMask/snaps/compare/v0.19.1...v0.20.0
|
|
232
|
+
[0.19.1]: https://github.com/MetaMask/snaps/compare/v0.19.0...v0.19.1
|
|
233
|
+
[0.19.0]: https://github.com/MetaMask/snaps/compare/v0.18.1...v0.19.0
|
|
234
|
+
[0.18.1]: https://github.com/MetaMask/snaps/compare/v0.18.0...v0.18.1
|
|
235
|
+
[0.18.0]: https://github.com/MetaMask/snaps/compare/v0.17.0...v0.18.0
|
|
236
|
+
[0.17.0]: https://github.com/MetaMask/snaps/compare/v0.16.0...v0.17.0
|
|
237
|
+
[0.16.0]: https://github.com/MetaMask/snaps/compare/v0.15.0...v0.16.0
|
|
238
|
+
[0.15.0]: https://github.com/MetaMask/snaps/compare/v0.14.0...v0.15.0
|
|
239
|
+
[0.14.0]: https://github.com/MetaMask/snaps/compare/v0.13.0...v0.14.0
|
|
240
|
+
[0.13.0]: https://github.com/MetaMask/snaps/compare/v0.12.0...v0.13.0
|
|
241
|
+
[0.12.0]: https://github.com/MetaMask/snaps/releases/tag/v0.12.0
|
package/dist/handlers.d.ts
CHANGED
|
@@ -11,9 +11,9 @@ import { AccountId, ChainId, RequestArguments } from './namespace';
|
|
|
11
11
|
* @param args.request - The JSON-RPC request sent to the snap.
|
|
12
12
|
* @returns The JSON-RPC response. This must be a JSON-serializable value.
|
|
13
13
|
*/
|
|
14
|
-
export declare type OnRpcRequestHandler = (args: {
|
|
14
|
+
export declare type OnRpcRequestHandler<Params extends Json[] | Record<string, Json> | undefined = Json[] | Record<string, Json> | undefined> = (args: {
|
|
15
15
|
origin: string;
|
|
16
|
-
request: JsonRpcRequest<
|
|
16
|
+
request: JsonRpcRequest<Params>;
|
|
17
17
|
}) => Promise<unknown>;
|
|
18
18
|
/**
|
|
19
19
|
* The response from a snap's `onTransaction` handler.
|
|
@@ -52,8 +52,8 @@ export declare type OnTransactionHandler = (args: {
|
|
|
52
52
|
* @param args - The request arguments.
|
|
53
53
|
* @param args.request - The JSON-RPC request sent to the snap.
|
|
54
54
|
*/
|
|
55
|
-
export declare type OnCronjobHandler = (args: {
|
|
56
|
-
request: JsonRpcRequest<
|
|
55
|
+
export declare type OnCronjobHandler<Params extends Json[] | Record<string, Json> | undefined = Json[] | Record<string, Json> | undefined> = (args: {
|
|
56
|
+
request: JsonRpcRequest<Params>;
|
|
57
57
|
}) => Promise<unknown>;
|
|
58
58
|
/**
|
|
59
59
|
* A request sent to the `handleRequest` handler of a snap keyring.
|
package/dist/handlers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlers.js","sourceRoot":"","sources":["../src/handlers.ts"],"names":[],"mappings":"","sourcesContent":["import { Component } from '@metamask/snaps-ui';\nimport { Json, JsonRpcRequest } from '@metamask/utils';\n\nimport { AccountId, ChainId, RequestArguments } from './namespace';\n\n/**\n * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is\n * made to the snap.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n * @returns The JSON-RPC response. This must be a JSON-serializable value.\n */\nexport type OnRpcRequestHandler = (args: {\n origin: string;\n request: JsonRpcRequest<
|
|
1
|
+
{"version":3,"file":"handlers.js","sourceRoot":"","sources":["../src/handlers.ts"],"names":[],"mappings":"","sourcesContent":["import { Component } from '@metamask/snaps-ui';\nimport { Json, JsonRpcRequest } from '@metamask/utils';\n\nimport { AccountId, ChainId, RequestArguments } from './namespace';\n\n/**\n * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is\n * made to the snap.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n * @returns The JSON-RPC response. This must be a JSON-serializable value.\n */\nexport type OnRpcRequestHandler<\n Params extends Json[] | Record<string, Json> | undefined =\n | Json[]\n | Record<string, Json>\n | undefined,\n> = (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n}) => Promise<unknown>;\n\n/**\n * The response from a snap's `onTransaction` handler.\n *\n * @property content - A custom UI component, that will be shown in MetaMask. Can be created using `@metamask/snaps-ui`.\n *\n * If the snap has no insights about the transaction, this should be `null`.\n */\nexport type OnTransactionResponse = {\n content: Component | null;\n};\n\n/**\n * The `onTransaction` handler. This is called whenever a transaction is\n * submitted to the snap. It can return insights about the transaction, which\n * will be displayed to the user.\n *\n * @param args - The request arguments.\n * @param args.transaction - The transaction object.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.transactionOrigin - The origin of the transaction. This is the\n * URL of the dapp that submitted the transaction.\n * @returns Insights about the transaction. See {@link OnTransactionResponse}.\n */\n// TODO: Improve type.\nexport type OnTransactionHandler = (args: {\n transaction: { [key: string]: Json };\n chainId: string;\n transactionOrigin?: string;\n}) => Promise<OnTransactionResponse>;\n\n/**\n * The `onCronjob` handler. This is called on a regular interval, as defined by\n * the snap's manifest.\n *\n * @param args - The request arguments.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnCronjobHandler<\n Params extends Json[] | Record<string, Json> | undefined =\n | Json[]\n | Record<string, Json>\n | undefined,\n> = (args: { request: JsonRpcRequest<Params> }) => Promise<unknown>;\n\n/**\n * A request sent to the `handleRequest` handler of a snap keyring.\n *\n * @property chainId - The CAIP-2 chain ID of the network the request is being\n * made to.\n * @property origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n */\nexport type KeyringRequest = {\n chainId: ChainId;\n origin: string;\n};\n\n/**\n * A keyring event, which consists of a {@link KeyringRequest}, combined with\n * the name of the event.\n */\nexport type KeyringEvent = KeyringRequest & { eventName: string };\n\n/**\n * A snap keyring object, which can be exported as `keyring` in a snap.\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SnapKeyring {\n getAccounts(): Promise<AccountId[]>;\n handleRequest(\n data: KeyringRequest & {\n request: RequestArguments;\n },\n ): Promise<Json>;\n on(data: KeyringEvent, listener: (...args: Json[]) => void): void;\n off(data: KeyringEvent): void;\n\n addAccount?(chainId: ChainId): Promise<AccountId>;\n removeAccount?(accountId: AccountId): Promise<void>;\n\n importAccount?(chainId: ChainId, data: Json): Promise<AccountId>;\n exportAccount?(accountId: AccountId): Promise<Json>;\n}\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n onRpcRequest?: OnRpcRequestHandler;\n onTransaction?: OnTransactionHandler;\n onCronjob?: OnCronjobHandler;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports & {\n keyring?: SnapKeyring;\n};\n"]}
|
package/dist/icon.d.ts
ADDED
package/dist/icon.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.assertIsSnapIcon = exports.SVG_MAX_BYTE_SIZE_TEXT = exports.SVG_MAX_BYTE_SIZE = void 0;
|
|
7
|
+
const utils_1 = require("@metamask/utils");
|
|
8
|
+
const is_svg_1 = __importDefault(require("is-svg"));
|
|
9
|
+
exports.SVG_MAX_BYTE_SIZE = 100000;
|
|
10
|
+
exports.SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(exports.SVG_MAX_BYTE_SIZE / 1000)}kb`;
|
|
11
|
+
const assertIsSnapIcon = (icon) => {
|
|
12
|
+
(0, utils_1.assert)(icon.path.endsWith('.svg'), 'Expected snap icon to end in ".svg".');
|
|
13
|
+
(0, utils_1.assert)(Buffer.byteLength(icon.value, 'utf8') <= exports.SVG_MAX_BYTE_SIZE, `The specified SVG icon exceeds the maximum size of ${exports.SVG_MAX_BYTE_SIZE_TEXT}.`);
|
|
14
|
+
(0, utils_1.assert)((0, is_svg_1.default)(icon.toString()), 'Snap icon must be a valid SVG.');
|
|
15
|
+
};
|
|
16
|
+
exports.assertIsSnapIcon = assertIsSnapIcon;
|
|
17
|
+
//# sourceMappingURL=icon.js.map
|
package/dist/icon.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"icon.js","sourceRoot":"","sources":["../src/icon.ts"],"names":[],"mappings":";;;;;;AAAA,2CAAyC;AACzC,oDAA2B;AAId,QAAA,iBAAiB,GAAG,MAAO,CAAC;AAC5B,QAAA,sBAAsB,GAAG,GAAG,IAAI,CAAC,KAAK,CACjD,yBAAiB,GAAG,IAAI,CACzB,IAAI,CAAC;AAEC,MAAM,gBAAgB,GAAG,CAAC,IAAiB,EAAE,EAAE;IACpD,IAAA,cAAM,EAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,sCAAsC,CAAC,CAAC;IAE3E,IAAA,cAAM,EACJ,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,yBAAiB,EAC1D,sDAAsD,8BAAsB,GAAG,CAChF,CAAC;IAEF,IAAA,cAAM,EAAC,IAAA,gBAAK,EAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,EAAE,gCAAgC,CAAC,CAAC;AACnE,CAAC,CAAC;AATW,QAAA,gBAAgB,oBAS3B","sourcesContent":["import { assert } from '@metamask/utils';\nimport isSvg from 'is-svg';\n\nimport { VirtualFile } from './virtual-file';\n\nexport const SVG_MAX_BYTE_SIZE = 100_000;\nexport const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(\n SVG_MAX_BYTE_SIZE / 1000,\n)}kb`;\n\nexport const assertIsSnapIcon = (icon: VirtualFile) => {\n assert(icon.path.endsWith('.svg'), 'Expected snap icon to end in \".svg\".');\n\n assert(\n Buffer.byteLength(icon.value, 'utf8') <= SVG_MAX_BYTE_SIZE,\n `The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`,\n );\n\n assert(isSvg(icon.toString()), 'Snap icon must be a valid SVG.');\n};\n"]}
|
package/dist/index.browser.d.ts
CHANGED
package/dist/index.browser.js
CHANGED
|
@@ -30,6 +30,7 @@ __exportStar(require("./notification"), exports);
|
|
|
30
30
|
__exportStar(require("./path"), exports);
|
|
31
31
|
__exportStar(require("./snaps"), exports);
|
|
32
32
|
__exportStar(require("./types"), exports);
|
|
33
|
+
__exportStar(require("./validation"), exports);
|
|
33
34
|
__exportStar(require("./versions"), exports);
|
|
34
35
|
__exportStar(require("./virtual-file/index.browser"), exports);
|
|
35
36
|
//# sourceMappingURL=index.browser.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.browser.js","sourceRoot":"","sources":["../src/index.browser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,6CAA2B;AAC3B,4CAA0B;AAC1B,+CAA6B;AAC7B,uDAAqC;AACrC,4CAA0B;AAC1B,6CAA2B;AAC3B,2CAAyB;AACzB,6CAA2B;AAC3B,4CAA0B;AAC1B,2DAAyC;AACzC,8CAA4B;AAC5B,iDAA+B;AAC/B,yCAAuB;AACvB,0CAAwB;AACxB,0CAAwB;AACxB,6CAA2B;AAC3B,+DAA6C","sourcesContent":["export * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './notification';\nexport * from './path';\nexport * from './snaps';\nexport * from './types';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"]}
|
|
1
|
+
{"version":3,"file":"index.browser.js","sourceRoot":"","sources":["../src/index.browser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,6CAA2B;AAC3B,4CAA0B;AAC1B,+CAA6B;AAC7B,uDAAqC;AACrC,4CAA0B;AAC1B,6CAA2B;AAC3B,2CAAyB;AACzB,6CAA2B;AAC3B,4CAA0B;AAC1B,2DAAyC;AACzC,8CAA4B;AAC5B,iDAA+B;AAC/B,yCAAuB;AACvB,0CAAwB;AACxB,0CAAwB;AACxB,+CAA6B;AAC7B,6CAA2B;AAC3B,+DAA6C","sourcesContent":["export * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './notification';\nexport * from './path';\nexport * from './snaps';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"]}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -35,6 +35,7 @@ __exportStar(require("./path"), exports);
|
|
|
35
35
|
__exportStar(require("./post-process"), exports);
|
|
36
36
|
__exportStar(require("./snaps"), exports);
|
|
37
37
|
__exportStar(require("./types"), exports);
|
|
38
|
+
__exportStar(require("./validation"), exports);
|
|
38
39
|
__exportStar(require("./versions"), exports);
|
|
39
40
|
__exportStar(require("./virtual-file"), exports);
|
|
40
41
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,4CAA0B;AAC1B,6CAA2B;AAC3B,+CAA6B;AAC7B,uDAAqC;AACrC,4CAA0B;AAC1B,yCAAuB;AACvB,uCAAqB;AACrB,6CAA2B;AAC3B,2CAAyB;AACzB,6CAA2B;AAC3B,4CAA0B;AAC1B,6CAA2B;AAC3B,yCAAuB;AACvB,8CAA4B;AAC5B,iDAA+B;AAC/B,wCAAsB;AACtB,yCAAuB;AACvB,iDAA+B;AAC/B,0CAAwB;AACxB,0CAAwB;AACxB,6CAA2B;AAC3B,iDAA+B","sourcesContent":["export * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './eval';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './notification';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './types';\nexport * from './versions';\nexport * from './virtual-file';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,4CAA0B;AAC1B,6CAA2B;AAC3B,+CAA6B;AAC7B,uDAAqC;AACrC,4CAA0B;AAC1B,yCAAuB;AACvB,uCAAqB;AACrB,6CAA2B;AAC3B,2CAAyB;AACzB,6CAA2B;AAC3B,4CAA0B;AAC1B,6CAA2B;AAC3B,yCAAuB;AACvB,8CAA4B;AAC5B,iDAA+B;AAC/B,wCAAsB;AACtB,yCAAuB;AACvB,iDAA+B;AAC/B,0CAAwB;AACxB,0CAAwB;AACxB,+CAA6B;AAC7B,6CAA2B;AAC3B,iDAA+B","sourcesContent":["export * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './eval';\nexport * from './fs';\nexport * from './handlers';\nexport * from './iframe';\nexport * from './json-rpc';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './notification';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"]}
|
|
@@ -15,13 +15,14 @@ const snaps_1 = require("../snaps");
|
|
|
15
15
|
const types_1 = require("../types");
|
|
16
16
|
const virtual_file_1 = require("../virtual-file");
|
|
17
17
|
const MANIFEST_SORT_ORDER = {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
18
|
+
$schema: 1,
|
|
19
|
+
version: 2,
|
|
20
|
+
description: 3,
|
|
21
|
+
proposedName: 4,
|
|
22
|
+
repository: 5,
|
|
23
|
+
source: 6,
|
|
24
|
+
initialPermissions: 7,
|
|
25
|
+
manifestVersion: 8,
|
|
25
26
|
};
|
|
26
27
|
/**
|
|
27
28
|
* Validates a snap.manifest.json file. Attempts to fix the manifest and write
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../src/manifest/manifest.ts"],"names":[],"mappings":";;;;;;AAAA,2CAAgF;AAChF,sEAAwC;AACxC,2BAAoC;AACpC,gDAA6B;AAE7B,8CAA0C;AAC1C,8BAAqC;AACrC,gCAAyC;AACzC,oCAIkB;AAClB,oCAKkB;AAClB,kDAA+D;AAG/D,MAAM,mBAAmB,GAAuC;IAC9D,OAAO,EAAE,CAAC;IACV,WAAW,EAAE,CAAC;IACd,YAAY,EAAE,CAAC;IACf,UAAU,EAAE,CAAC;IACb,MAAM,EAAE,CAAC;IACT,kBAAkB,EAAE,CAAC;IACrB,eAAe,EAAE,CAAC;CACnB,CAAC;AAuBF;;;;;;;;;;GAUG;AACI,KAAK,UAAU,aAAa,CACjC,QAAgB,EAChB,aAAa,GAAG,IAAI,EACpB,UAAmB;IAEnB,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,MAAM,MAAM,GAAa,EAAE,CAAC;IAE5B,IAAI,OAAO,GAAG,KAAK,CAAC;IAEpB,MAAM,YAAY,GAAG,cAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,wBAAgB,CAAC,QAAQ,CAAC,CAAC;IACzE,MAAM,YAAY,GAAG,MAAM,IAAA,iBAAY,EAAC,YAAY,CAAC,CAAC;IACtD,MAAM,mBAAmB,GAAG,YAAY,CAAC,MAAM,CAAC;IAEhD,MAAM,WAAW,GAAG,MAAM,IAAA,iBAAY,EACpC,cAAS,CAAC,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qB,GAAG,WAAW,CAAC,MAAM,CAAC,UAAU,CAAC;IAE5D,MAAM,mBAAmB,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC;IAC5E,MAAM,sBAAsB,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC;IACvD,MAAM,kBAAkB,GAAG,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC;IAEtD,IAAI,eAAe,KAAK,mBAAmB,EAAE;QAC3C,MAAM,IAAI,wCAAgC,CACxC,IAAI,wBAAgB,CAAC,QAAQ,wBAAwB,mBAAmB,0BAA0B,wBAAgB,CAAC,WAAW,oBAAoB,eAAe,KAAK,EACtK,mCAA2B,CAAC,YAAY,CACzC,CAAC;KACH;IAED,IAAI,kBAAkB,KAAK,sBAAsB,EAAE;QACjD,MAAM,IAAI,wCAAgC,CACxC,IAAI,wBAAgB,CAAC,QAAQ,2BAA2B,sBAAsB,0BAA0B,wBAAgB,CAAC,WAAW,uBAAuB,kBAAkB,KAAK,EAClL,mCAA2B,CAAC,eAAe,CAC5C,CAAC;KACH;IAED;IACE,4EAA4E;IAC5E,wDAAwD;IACxD,CAAC,qBAAqB,IAAI,kBAAkB,CAAC;QAC7C,CAAC,IAAA,yBAAS,EAAC,qBAAqB,EAAE,kBAAkB,CAAC,EACrD;QACA,MAAM,IAAI,wCAAgC,CACxC,IAAI,wBAAgB,CAAC,QAAQ,4CAA4C,wBAAgB,CAAC,WAAW,uBAAuB,EAC5H,mCAA2B,CAAC,kBAAkB,CAC/C,CAAC;KACH;IAED,IAAA,0BAAkB,EAChB,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,EACjC,IAAI,wBAAgB,CAAC,QAAQ,kDAAkD,CAChF,CAAC;AACJ,CAAC;AA5CD,0DA4CC","sourcesContent":["import { Json, assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport {\n NpmSnapFileNames,\n SnapFiles,\n SnapValidationFailureReason,\n UnvalidatedSnapFiles,\n} from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n version: 1,\n description: 2,\n proposedName: 3,\n repository: 4,\n source: 5,\n initialPermissions: 6,\n manifestVersion: 7,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await fs.writeFile(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): VirtualFile<SnapManifest> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap bundle file: ${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap icon file: ${error.message}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an npm Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n validateSnapShasum(\n { manifest, sourceCode, svgIcon },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../src/manifest/manifest.ts"],"names":[],"mappings":";;;;;;AAAA,2CAAgF;AAChF,sEAAwC;AACxC,2BAAoC;AACpC,gDAA6B;AAE7B,8CAA0C;AAC1C,8BAAqC;AACrC,gCAAyC;AACzC,oCAIkB;AAClB,oCAKkB;AAClB,kDAA+D;AAG/D,MAAM,mBAAmB,GAAuC;IAC9D,OAAO,EAAE,CAAC;IACV,OAAO,EAAE,CAAC;IACV,WAAW,EAAE,CAAC;IACd,YAAY,EAAE,CAAC;IACf,UAAU,EAAE,CAAC;IACb,MAAM,EAAE,CAAC;IACT,kBAAkB,EAAE,CAAC;IACrB,eAAe,EAAE,CAAC;CACnB,CAAC;AAuBF;;;;;;;;;;GAUG;AACI,KAAK,UAAU,aAAa,CACjC,QAAgB,EAChB,aAAa,GAAG,IAAI,EACpB,UAAmB;IAEnB,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,MAAM,MAAM,GAAa,EAAE,CAAC;IAE5B,IAAI,OAAO,GAAG,KAAK,CAAC;IAEpB,MAAM,YAAY,GAAG,cAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,wBAAgB,CAAC,QAAQ,CAAC,CAAC;IACzE,MAAM,YAAY,GAAG,MAAM,IAAA,iBAAY,EAAC,YAAY,CAAC,CAAC;IACtD,MAAM,mBAAmB,GAAG,YAAY,CAAC,MAAM,CAAC;IAEhD,MAAM,WAAW,GAAG,MAAM,IAAA,iBAAY,EACpC,cAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,wBAAgB,CAAC,WAAW,CAAC,CACvD,CAAC;IAEF,MAAM,SAAS,GAAyB;QACtC,QAAQ,EAAE,YAAY;QACtB,WAAW,EAAE,WAAW;QACxB,UAAU,EAAE,MAAM,iBAAiB,CACjC,QAAQ,EACR,mBAAmB,EACn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OAAO,CAAC;IACvD,MAAM,kBAAkB,GAAG,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC;IAEtD,IAAI,eAAe,KAAK,mBAAmB,EAAE;QAC3C,MAAM,IAAI,wCAAgC,CACxC,IAAI,wBAAgB,CAAC,QAAQ,wBAAwB,mBAAmB,0BAA0B,wBAAgB,CAAC,WAAW,oBAAoB,eAAe,KAAK,EACtK,mCAA2B,CAAC,YAAY,CACzC,CAAC;KACH;IAED,IAAI,kBAAkB,KAAK,sBAAsB,EAAE;QACjD,MAAM,IAAI,wCAAgC,CACxC,IAAI,wBAAgB,CAAC,QAAQ,2BAA2B,sBAAsB,0BAA0B,wBAAgB,CAAC,WAAW,uBAAuB,kBAAkB,KAAK,EAClL,mCAA2B,CAAC,eAAe,CAC5C,CAAC;KACH;IAED;IACE,4EAA4E;IAC5E,wDAAwD;IACxD,CAAC,qBAAqB,IAAI,kBAAkB,CAAC;QAC7C,CAAC,IAAA,yBAAS,EAAC,qBAAqB,EAAE,kBAAkB,CAAC,EACrD;QACA,MAAM,IAAI,wCAAgC,CACxC,IAAI,wBAAgB,CAAC,QAAQ,4CAA4C,wBAAgB,CAAC,WAAW,uBAAuB,EAC5H,mCAA2B,CAAC,kBAAkB,CAC/C,CAAC;KACH;IAED,IAAA,0BAAkB,EAChB,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,EACjC,IAAI,wBAAgB,CAAC,QAAQ,kDAAkD,CAChF,CAAC;AACJ,CAAC;AA5CD,0DA4CC","sourcesContent":["import { Json, assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport {\n NpmSnapFileNames,\n SnapFiles,\n SnapValidationFailureReason,\n UnvalidatedSnapFiles,\n} from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await fs.writeFile(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): VirtualFile<SnapManifest> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap bundle file: ${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap icon file: ${error.message}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an npm Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n validateSnapShasum(\n { manifest, sourceCode, svgIcon },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"]}
|
|
@@ -276,6 +276,7 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
276
276
|
type: string;
|
|
277
277
|
url: string;
|
|
278
278
|
} | undefined;
|
|
279
|
+
$schema?: string | undefined;
|
|
279
280
|
}, {
|
|
280
281
|
version: Struct<import("@metamask/utils").SemVerVersion, null>;
|
|
281
282
|
description: Struct<string, null>;
|
|
@@ -491,6 +492,7 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
491
492
|
}> | undefined, null>;
|
|
492
493
|
}>;
|
|
493
494
|
manifestVersion: Struct<"0.1", "0.1">;
|
|
495
|
+
$schema: Struct<string | undefined, null>;
|
|
494
496
|
}>;
|
|
495
497
|
export declare type SnapManifest = Infer<typeof SnapManifestStruct>;
|
|
496
498
|
/**
|
|
@@ -108,6 +108,7 @@ exports.SnapManifestStruct = (0, superstruct_1.object)({
|
|
|
108
108
|
}),
|
|
109
109
|
initialPermissions: exports.PermissionsStruct,
|
|
110
110
|
manifestVersion: (0, superstruct_1.literal)('0.1'),
|
|
111
|
+
$schema: (0, superstruct_1.optional)((0, superstruct_1.string)()), // enables JSON-Schema linting in VSC and other IDEs
|
|
111
112
|
});
|
|
112
113
|
/**
|
|
113
114
|
* Check if the given value is a valid {@link SnapManifest} object.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/manifest/validation.ts"],"names":[],"mappings":";;;AAAA,2CAKyB;AACzB,6CAmBqB;AAErB,wCAA6D;AAC7D,wCAA6E;AAC7E,0CAA+C;AAC/C,4CAAgD;AAChD,oCAAwC;AACxC,oCAAwD;AAExD,+EAA+E;AAC/E,gCAAgC;AAChC,MAAM,kBAAkB,GAAa;IACnC,2BAAiB;IACjB,sCAA4B;CAC7B,CAAC;AAEF,MAAM,iBAAiB,GAAG,UAAU,CAAC;AACxB,QAAA,eAAe,GAAG,IAAA,oBAAM,EACnC,IAAA,mBAAK,EAAC,IAAA,oBAAM,GAAE,CAAC,EACf,aAAa,EACb,CAAC,IAAI,EAAE,EAAE;IACP,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;QACrB,OAAO,uDAAuD,CAAC;KAChE;IA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/C,qEAAqE;IACrE,OAAO,IAAA,oBAAM,EAAC,KAAK,EAAE,0BAAkB,CAAC,CAAC;AAC3C,CAAC;AAHD,gDAGC","sourcesContent":["import {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport {\n array,\n boolean,\n create,\n enums,\n Infer,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n Struct,\n type,\n union,\n} from 'superstruct';\n\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { RpcOriginsStruct } from '../json-rpc';\nimport { NamespacesStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nconst BIP32_INDEX_REGEX = /^\\d+'?$/u;\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !BIP32_INDEX_REGEX.test(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <T extends { path: string[]; curve: string }, S>(\n struct: Struct<T, S>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:long-running': optional(object({})),\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n 'endowment:keyring': optional(\n object({\n namespaces: NamespacesStruct,\n }),\n ),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u,\n ),\n 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/manifest/validation.ts"],"names":[],"mappings":";;;AAA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H,CAAC;IACF,kBAAkB,EAAE,yBAAiB;IACrC,eAAe,EAAE,IAAA,qBAAO,EAAC,KAAK,CAAC;IAC/B,OAAO,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,GAAE,CAAC,EAAE,oDAAoD;CAClF,CAAC,CAAC;AAIH;;;;;GAKG;AACH,SAAgB,cAAc,CAAC,KAAc;IAC3C,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,0BAAkB,CAAC,CAAC;AACvC,CAAC;AAFD,wCAEC;AAED;;;;;GAKG;AACH,SAAgB,oBAAoB,CAClC,KAAc;IAEd,IAAA,oBAAY,EACV,KAAK,EACL,0BAAkB,EAClB,IAAI,wBAAgB,CAAC,QAAQ,cAAc,CAC5C,CAAC;AACJ,CAAC;AARD,oDAQC;AAED;;;;;;;GAOG;AACH,SAAgB,kBAAkB,CAAC,KAAc;IAC/C,qEAAqE;IACrE,OAAO,IAAA,oBAAM,EAAC,KAAK,EAAE,0BAAkB,CAAC,CAAC;AAC3C,CAAC;AAHD,gDAGC","sourcesContent":["import {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport {\n array,\n boolean,\n create,\n enums,\n Infer,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n Struct,\n type,\n union,\n} from 'superstruct';\n\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { RpcOriginsStruct } from '../json-rpc';\nimport { NamespacesStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nconst BIP32_INDEX_REGEX = /^\\d+'?$/u;\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !BIP32_INDEX_REGEX.test(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <T extends { path: string[]; curve: string }, S>(\n struct: Struct<T, S>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:long-running': optional(object({})),\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n 'endowment:keyring': optional(\n object({\n namespaces: NamespacesStruct,\n }),\n ),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u,\n ),\n 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"]}
|
package/dist/npm.d.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import { NpmSnapFileNames, SnapFiles, UnvalidatedSnapFiles } from './types';
|
|
2
|
-
export declare const SVG_MAX_BYTE_SIZE = 100000;
|
|
3
|
-
export declare const SVG_MAX_BYTE_SIZE_TEXT: string;
|
|
4
2
|
export declare const EXPECTED_SNAP_FILES: readonly ["manifest", "packageJson", "sourceCode"];
|
|
5
3
|
export declare const SnapFileNameFromKey: {
|
|
6
4
|
readonly manifest: NpmSnapFileNames.Manifest;
|
package/dist/npm.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.validateNpmSnap = exports.SnapFileNameFromKey = exports.EXPECTED_SNAP_FILES =
|
|
3
|
+
exports.validateNpmSnap = exports.SnapFileNameFromKey = exports.EXPECTED_SNAP_FILES = void 0;
|
|
4
|
+
const icon_1 = require("./icon");
|
|
4
5
|
const manifest_1 = require("./manifest/manifest");
|
|
5
6
|
const validation_1 = require("./manifest/validation");
|
|
6
7
|
const types_1 = require("./types");
|
|
7
|
-
exports.SVG_MAX_BYTE_SIZE = 100000;
|
|
8
|
-
exports.SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(exports.SVG_MAX_BYTE_SIZE / 1000)}kb`;
|
|
9
8
|
exports.EXPECTED_SNAP_FILES = [
|
|
10
9
|
'manifest',
|
|
11
10
|
'packageJson',
|
|
@@ -16,6 +15,7 @@ exports.SnapFileNameFromKey = {
|
|
|
16
15
|
packageJson: types_1.NpmSnapFileNames.PackageJson,
|
|
17
16
|
sourceCode: 'source code bundle',
|
|
18
17
|
};
|
|
18
|
+
// TODO: Refactor this to be more shared with other validation.
|
|
19
19
|
/**
|
|
20
20
|
* Validates the files extracted from an npm Snap package tarball by ensuring
|
|
21
21
|
* that they're non-empty and that the Json files match their respective schemas
|
|
@@ -59,8 +59,11 @@ function validateNpmSnap(snapFiles, errorPrefix) {
|
|
|
59
59
|
svgIcon,
|
|
60
60
|
});
|
|
61
61
|
if (svgIcon) {
|
|
62
|
-
|
|
63
|
-
|
|
62
|
+
try {
|
|
63
|
+
(0, icon_1.assertIsSnapIcon)(svgIcon);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
throw new Error(`${errorPrefix ?? ''}${error.message}`);
|
|
64
67
|
}
|
|
65
68
|
}
|
|
66
69
|
return {
|
package/dist/npm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm.js","sourceRoot":"","sources":["../src/npm.ts"],"names":[],"mappings":";;;AAAA,kDAA8D;AAC9D,sDAA6D;AAC7D,mCAKiB;AAEJ,QAAA,
|
|
1
|
+
{"version":3,"file":"npm.js","sourceRoot":"","sources":["../src/npm.ts"],"names":[],"mappings":";;;AAAA,iCAA0C;AAC1C,kDAA8D;AAC9D,sDAA6D;AAC7D,mCAKiB;AAEJ,QAAA,mBAAmB,GAAG;IACjC,UAAU;IACV,aAAa;IACb,YAAY;CACJ,CAAC;AAEE,QAAA,mBAAmB,GAAG;IACjC,QAAQ,EAAE,wBAAgB,CAAC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QAAQ,EAAE,iBAAiB;QAC3B,WAAW,EAAE,oBAAoB;QACjC,UAAU;QACV,OAAO;KACR,CAAC,CAAC;IAEH,IAAI,OAAO,EAAE;QACX,IAAI;YACF,IAAA,uBAAgB,EAAC,OAAO,CAAC,CAAC;SAC3B;QAAC,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CAAC,GAAG,WAAW,IAAI,EAAE,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;SACzD;KACF;IAED,OAAO;QACL,QAAQ,EAAE,iBAAiB;QAC3B,WAAW,EAAE,oBAAoB;QACjC,UAAU;QACV,OAAO;KACR,CAAC;AACJ,CAAC;AAtDD,0CAsDC","sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport {\n assertIsNpmSnapPackageJson,\n NpmSnapFileNames,\n SnapFiles,\n UnvalidatedSnapFiles,\n} from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const { manifest, packageJson, sourceCode, svgIcon } = snapFiles as SnapFiles;\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedPackageJson = packageJson;\n\n validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n });\n\n if (svgIcon) {\n try {\n assertIsSnapIcon(svgIcon);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n };\n}\n"]}
|
package/dist/snaps.d.ts
CHANGED
|
@@ -28,7 +28,7 @@ export declare enum SnapStatusEvents {
|
|
|
28
28
|
Update = "UPDATE"
|
|
29
29
|
}
|
|
30
30
|
export declare type StatusContext = {
|
|
31
|
-
snapId:
|
|
31
|
+
snapId: ValidatedSnapId;
|
|
32
32
|
};
|
|
33
33
|
export declare type StatusEvents = {
|
|
34
34
|
type: SnapStatusEvents;
|
|
@@ -60,7 +60,7 @@ export declare type Snap = {
|
|
|
60
60
|
/**
|
|
61
61
|
* The ID of the Snap.
|
|
62
62
|
*/
|
|
63
|
-
id:
|
|
63
|
+
id: ValidatedSnapId;
|
|
64
64
|
/**
|
|
65
65
|
* The initial permissions of the Snap, which will be requested when it is
|
|
66
66
|
* installed.
|
|
@@ -140,6 +140,13 @@ declare const snapIdSymbol: unique symbol;
|
|
|
140
140
|
* @returns The snap prefix from a snap id, e.g. `npm:`.
|
|
141
141
|
*/
|
|
142
142
|
export declare function getSnapPrefix(snapId: string): SnapIdPrefixes;
|
|
143
|
+
/**
|
|
144
|
+
* Strips snap prefix from a full snap ID.
|
|
145
|
+
*
|
|
146
|
+
* @param snapId - The snap ID to strip.
|
|
147
|
+
* @returns The stripped snap ID.
|
|
148
|
+
*/
|
|
149
|
+
export declare function stripSnapPrefix(snapId: string): string;
|
|
143
150
|
/**
|
|
144
151
|
* Assert that the given value is a valid snap ID.
|
|
145
152
|
*
|
package/dist/snaps.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.verifyRequestedSnapPermissions = exports.isSnapPermitted = exports.isCaipChainId = exports.assertIsValidSnapId = exports.getSnapPrefix = exports.SnapIdStruct = exports.HttpSnapIdStruct = exports.NpmSnapIdStruct = exports.LocalSnapIdStruct = exports.BaseSnapIdStruct = exports.LOCALHOST_HOSTNAMES = exports.validateSnapShasum = exports.getSnapChecksum = exports.ProgrammaticallyFixableSnapError = exports.SnapStatusEvents = exports.SnapStatus = exports.PROPOSED_NAME_REGEX = void 0;
|
|
6
|
+
exports.verifyRequestedSnapPermissions = exports.isSnapPermitted = exports.isCaipChainId = exports.assertIsValidSnapId = exports.stripSnapPrefix = exports.getSnapPrefix = exports.SnapIdStruct = exports.HttpSnapIdStruct = exports.NpmSnapIdStruct = exports.LocalSnapIdStruct = exports.BaseSnapIdStruct = exports.LOCALHOST_HOSTNAMES = exports.validateSnapShasum = exports.getSnapChecksum = exports.ProgrammaticallyFixableSnapError = exports.SnapStatusEvents = exports.SnapStatus = exports.PROPOSED_NAME_REGEX = void 0;
|
|
7
7
|
const utils_1 = require("@metamask/utils");
|
|
8
8
|
const base_1 = require("@scure/base");
|
|
9
9
|
const fast_json_stable_stringify_1 = __importDefault(require("fast-json-stable-stringify"));
|
|
@@ -148,6 +148,16 @@ function getSnapPrefix(snapId) {
|
|
|
148
148
|
throw new Error(`Invalid or no prefix found for "${snapId}"`);
|
|
149
149
|
}
|
|
150
150
|
exports.getSnapPrefix = getSnapPrefix;
|
|
151
|
+
/**
|
|
152
|
+
* Strips snap prefix from a full snap ID.
|
|
153
|
+
*
|
|
154
|
+
* @param snapId - The snap ID to strip.
|
|
155
|
+
* @returns The stripped snap ID.
|
|
156
|
+
*/
|
|
157
|
+
function stripSnapPrefix(snapId) {
|
|
158
|
+
return snapId.replace(getSnapPrefix(snapId), '');
|
|
159
|
+
}
|
|
160
|
+
exports.stripSnapPrefix = stripSnapPrefix;
|
|
151
161
|
/**
|
|
152
162
|
* Assert that the given value is a valid snap ID.
|
|
153
163
|
*
|
package/dist/snaps.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.js","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAMA,2CAOyB;AACzB,sCAAqC;AAErC,4FAAyD;AACzD,6CAWqB;AACrB,0FAA2D;AAE3D,uCAA2C;AAC3C,yCAA2C;AAE3C,mCAOiB;AAGjB,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAWrH,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;AACrB,CAAC,EANW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAMrB;AAED,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,mCAAe,CAAA;IACf,iCAAa,CAAA;IACb,mCAAe,CAAA;IACf,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAK3B;AA+FD;;;GAGG;AACH,MAAa,gCAAiC,SAAQ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,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO;QACtC,IAAA,gBAAQ,EAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,wBAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC;AA9BD,wEA8BC","sourcesContent":["import {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { BlockReason } from '@metamask/snaps-registry';\nimport {\n assert,\n Json,\n SemVerVersion,\n isObject,\n Opaque,\n assertStruct,\n} from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n Struct,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport { SnapManifest, SnapPermissions } from './manifest/validation';\nimport {\n SnapFiles,\n SnapId,\n SnapIdPrefixes,\n SnapsPermissionRequest,\n SnapValidationFailureReason,\n uri,\n} from './types';\nimport { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: string };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap & {\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n};\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: SnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"snaps.js","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAMA,2CAOyB;AACzB,sCAAqC;AAErC,4FAAyD;AACzD,6CAWqB;AACrB,0FAA2D;AAE3D,uCAA2C;AAC3C,yCAA2C;AAE3C,mCAOiB;AAGjB,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAWrH,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;AACrB,CAAC,EANW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAMrB;AAED,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,mCAAe,CAAA;IACf,iCAAa,CAAA;IACb,mCAAe,CAAA;IACf,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAK3B;AA+FD;;;GAGG;AACH,MAAa,gCAAiC,SAAQ,KAAK;IAGzD,YAAY,OAAe,EAAE,MAAmC;QAC9D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAPD,4EAOC;AAED;;;;;GAKG;AACH,SAAS,wBAAwB,CAC/B,QAAmC;IAEnC,MAAM,YAAY,GAAG,QAAQ,CAAC,KAAK,EAAsB,CAAC;IAC1D,OAAO,YAAY,CAA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iD,wBAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC;AA9BD,wEA8BC","sourcesContent":["import {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { BlockReason } from '@metamask/snaps-registry';\nimport {\n assert,\n Json,\n SemVerVersion,\n isObject,\n Opaque,\n assertStruct,\n} from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n Struct,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport { SnapManifest, SnapPermissions } from './manifest/validation';\nimport {\n SnapFiles,\n SnapId,\n SnapIdPrefixes,\n SnapsPermissionRequest,\n SnapValidationFailureReason,\n uri,\n} from './types';\nimport { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap & {\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n};\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { SnapFiles } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Validates the files contained in a fetched snap.
|
|
4
|
+
*
|
|
5
|
+
* @param files - All potentially included files in a fetched snap.
|
|
6
|
+
* @throws If any of the files are considered invalid.
|
|
7
|
+
*/
|
|
8
|
+
export declare function validateFetchedSnap(files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>): void;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateFetchedSnap = void 0;
|
|
4
|
+
const icon_1 = require("./icon");
|
|
5
|
+
const validation_1 = require("./manifest/validation");
|
|
6
|
+
const snaps_1 = require("./snaps");
|
|
7
|
+
/**
|
|
8
|
+
* Validates the files contained in a fetched snap.
|
|
9
|
+
*
|
|
10
|
+
* @param files - All potentially included files in a fetched snap.
|
|
11
|
+
* @throws If any of the files are considered invalid.
|
|
12
|
+
*/
|
|
13
|
+
function validateFetchedSnap(files) {
|
|
14
|
+
(0, validation_1.assertIsSnapManifest)(files.manifest.result);
|
|
15
|
+
(0, snaps_1.validateSnapShasum)(files);
|
|
16
|
+
if (files.svgIcon) {
|
|
17
|
+
(0, icon_1.assertIsSnapIcon)(files.svgIcon);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
exports.validateFetchedSnap = validateFetchedSnap;
|
|
21
|
+
//# sourceMappingURL=validation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation.js","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":";;;AAAA,iCAA0C;AAC1C,sDAA6D;AAC7D,mCAA6C;AAG7C;;;;;GAKG;AACH,SAAgB,mBAAmB,CACjC,KAA6D;IAE7D,IAAA,iCAAoB,EAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC5C,IAAA,0BAAkB,EAAC,KAAK,CAAC,CAAC;IAE1B,IAAI,KAAK,CAAC,OAAO,EAAE;QACjB,IAAA,uBAAgB,EAAC,KAAK,CAAC,OAAO,CAAC,CAAC;KACjC;AACH,CAAC;AATD,kDASC","sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport { SnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport function validateFetchedSnap(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): void {\n assertIsSnapManifest(files.manifest.result);\n validateSnapShasum(files);\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-utils",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.34.0-flask.1",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
|
-
"url": "https://github.com/MetaMask/snaps
|
|
6
|
+
"url": "https://github.com/MetaMask/snaps.git"
|
|
7
7
|
},
|
|
8
8
|
"exports": {
|
|
9
9
|
".": {
|
|
@@ -54,18 +54,19 @@
|
|
|
54
54
|
"dependencies": {
|
|
55
55
|
"@babel/core": "^7.20.12",
|
|
56
56
|
"@babel/types": "^7.18.7",
|
|
57
|
-
"@metamask/base-controller": "^
|
|
58
|
-
"@metamask/permission-controller": "^
|
|
57
|
+
"@metamask/base-controller": "^3.0.0",
|
|
58
|
+
"@metamask/permission-controller": "^4.0.0",
|
|
59
59
|
"@metamask/providers": "^10.2.1",
|
|
60
|
-
"@metamask/snaps-registry": "^1.2.
|
|
61
|
-
"@metamask/snaps-ui": "^0.
|
|
62
|
-
"@metamask/utils": "^
|
|
60
|
+
"@metamask/snaps-registry": "^1.2.1",
|
|
61
|
+
"@metamask/snaps-ui": "^0.34.0-flask.1",
|
|
62
|
+
"@metamask/utils": "^6.0.0",
|
|
63
63
|
"@noble/hashes": "^1.1.3",
|
|
64
64
|
"@scure/base": "^1.1.1",
|
|
65
65
|
"cron-parser": "^4.5.0",
|
|
66
66
|
"eth-rpc-errors": "^4.0.3",
|
|
67
67
|
"fast-deep-equal": "^3.1.3",
|
|
68
68
|
"fast-json-stable-stringify": "^2.1.0",
|
|
69
|
+
"is-svg": "^4.4.0",
|
|
69
70
|
"rfdc": "^1.3.0",
|
|
70
71
|
"semver": "^7.3.7",
|
|
71
72
|
"ses": "^0.18.1",
|