@metamask/snaps-utils 0.24.0 → 0.25.0
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/dist/caveats.d.ts +5 -1
- package/dist/caveats.js +4 -0
- package/dist/caveats.js.map +1 -1
- package/dist/eval-worker.js.map +1 -1
- package/dist/eval.js +1 -1
- package/dist/eval.js.map +1 -1
- package/dist/fs.js.map +1 -1
- package/dist/json-rpc.d.ts +19 -1
- package/dist/json-rpc.js +25 -1
- package/dist/json-rpc.js.map +1 -1
- package/dist/manifest/manifest.js +6 -6
- package/dist/manifest/manifest.js.map +1 -1
- package/dist/manifest/validation.d.ts +52 -32
- package/dist/manifest/validation.js +15 -14
- package/dist/manifest/validation.js.map +1 -1
- package/dist/mock.js +4 -1
- package/dist/mock.js.map +1 -1
- package/dist/namespace.d.ts +1 -1
- package/dist/namespace.js +4 -2
- package/dist/namespace.js.map +1 -1
- package/dist/notification.js +1 -1
- package/dist/notification.js.map +1 -1
- package/dist/npm.js.map +1 -1
- package/dist/object.js.map +1 -1
- package/dist/post-process.js +3 -2
- package/dist/post-process.js.map +1 -1
- package/dist/snaps.d.ts +2 -1
- package/dist/snaps.js +2 -2
- package/dist/snaps.js.map +1 -1
- package/dist/types.d.ts +6 -6
- package/dist/types.js +6 -9
- package/dist/types.js.map +1 -1
- package/dist/versions.d.ts +81 -12
- package/dist/versions.js +61 -17
- package/dist/versions.js.map +1 -1
- package/package.json +17 -15
package/dist/caveats.d.ts
CHANGED
|
@@ -18,5 +18,9 @@ export declare enum SnapCaveatType {
|
|
|
18
18
|
/**
|
|
19
19
|
* Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.
|
|
20
20
|
*/
|
|
21
|
-
TransactionOrigin = "transactionOrigin"
|
|
21
|
+
TransactionOrigin = "transactionOrigin",
|
|
22
|
+
/**
|
|
23
|
+
* The origins that a Snap can receive JSON-RPC messages from.
|
|
24
|
+
*/
|
|
25
|
+
RpcOrigin = "rpcOrigin"
|
|
22
26
|
}
|
package/dist/caveats.js
CHANGED
|
@@ -23,5 +23,9 @@ var SnapCaveatType;
|
|
|
23
23
|
* Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.
|
|
24
24
|
*/
|
|
25
25
|
SnapCaveatType["TransactionOrigin"] = "transactionOrigin";
|
|
26
|
+
/**
|
|
27
|
+
* The origins that a Snap can receive JSON-RPC messages from.
|
|
28
|
+
*/
|
|
29
|
+
SnapCaveatType["RpcOrigin"] = "rpcOrigin";
|
|
26
30
|
})(SnapCaveatType = exports.SnapCaveatType || (exports.SnapCaveatType = {}));
|
|
27
31
|
//# sourceMappingURL=caveats.js.map
|
package/dist/caveats.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"caveats.js","sourceRoot":"","sources":["../src/caveats.ts"],"names":[],"mappings":";;;AAAA,IAAY,
|
|
1
|
+
{"version":3,"file":"caveats.js","sourceRoot":"","sources":["../src/caveats.ts"],"names":[],"mappings":";;;AAAA,IAAY,cA8BX;AA9BD,WAAY,cAAc;IACxB;;OAEG;IACH,uEAAqD,CAAA;IAErD;;OAEG;IACH,2DAAyC,CAAA;IAEzC;;OAEG;IACH,6CAA2B,CAAA;IAE3B;;OAEG;IACH,6CAA2B,CAAA;IAE3B;;OAEG;IACH,yDAAuC,CAAA;IAEvC;;OAEG;IACH,yCAAuB,CAAA;AACzB,CAAC,EA9BW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QA8BzB","sourcesContent":["export enum SnapCaveatType {\n /**\n * Permitted derivation paths, used by `snap_getBip32Entropy`.\n */\n PermittedDerivationPaths = 'permittedDerivationPaths',\n\n /**\n * Permitted coin types, used by `snap_getBip44Entropy`.\n */\n PermittedCoinTypes = 'permittedCoinTypes',\n\n /**\n * Permission to use the Snap keyring API.\n */\n SnapKeyring = 'snapKeyring',\n\n /**\n * Caveat specifying a snap cronjob.\n */\n SnapCronjob = 'snapCronjob',\n\n /**\n * Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.\n */\n TransactionOrigin = 'transactionOrigin',\n\n /**\n * The origins that a Snap can receive JSON-RPC messages from.\n */\n RpcOrigin = 'rpcOrigin',\n}\n"]}
|
package/dist/eval-worker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eval-worker.js","sourceRoot":"","sources":["../src/eval-worker.ts"],"names":[],"mappings":";;AAAA,uDAAuD;AACvD,wBAAsB;AAEtB,2BAAkC;
|
|
1
|
+
{"version":3,"file":"eval-worker.js","sourceRoot":"","sources":["../src/eval-worker.ts"],"names":[],"mappings":";;AAAA,uDAAuD;AACvD,wBAAsB;AAEtB,2BAAkC;AAElC,iCAAgD;AAChD,mCAAyD;AAIzD,QAAQ,iBACN,aAAa,EAAE,QAAQ,EACvB,WAAW,EAAE,QAAQ,EACrB,UAAU,EAAE,QAAQ,EACpB,UAAU,EAAE,QAAQ,EACpB,cAAc,EAAE,QAAQ,IAIrB,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,MAAM;IACjC,CAAC,CAAC;QACE,YAAY,EAAE,QAAQ;KACvB;IACH,CAAC,CAAC,EAAE,CAAC,EACP,CAAC;AAEH;;;;;;GAMG;AACH,SAAS,iBAAiB;IACxB,MAAM,UAAU,GAAG,IAAA,6BAAsB,GAAE,CAAC;IAC5C,uCACK,UAAU,KACb,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,UAAU,IAChB;AACJ,CAAC;AAED,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAErC,MAAM,UAAU,GAAsB,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;AAEtD,IAAI,WAAW,iCACV,iBAAiB,EAAE,KACtB,MAAM,EAAE,UAAU,EAClB,OAAO,EAAE,UAAU,CAAC,OAAO,IAC3B,CAAC,QAAQ,CAAC,IAAA,iBAAY,EAAC,YAAY,EAAE,MAAM,CAAC,CAAC,CAAC;AAEhD,MAAM,cAAc,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,CAC3D,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,yBAAiB,CAAC,QAAQ,CAAC,UAAyB,CAAC,CACvE,CAAC;AAEF,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE;IAC7B,OAAO,CAAC,IAAI,CAAC,mCAAmC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;CAC9E;AAED,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,8BAA8B","sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport { generateMockEndowments } from './mock';\nimport { HandlerType, SNAP_EXPORT_NAMES } from './types';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // TODO: See if there's an easier way to do this. This file is ran in a\n // separate process, so we can't mock SES with Jest.\n ...(process.env.NODE_ENV === 'test'\n ? {\n domainTaming: 'unsafe',\n }\n : {}),\n});\n\n/**\n * Get mock endowments that don't do anything. This is useful for running the\n * eval, for snaps that try to communicate with the extension on initialisation,\n * for example.\n *\n * @returns The mock endowments.\n */\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nnew Compartment({\n ...getMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n}).evaluate(readFileSync(snapFilePath, 'utf8'));\n\nconst invalidExports = Object.keys(snapModule.exports).filter(\n (snapExport) => !SNAP_EXPORT_NAMES.includes(snapExport as HandlerType),\n);\n\nif (invalidExports.length > 0) {\n console.warn(`Invalid snap exports detected:\\n${invalidExports.join('\\n')}`);\n}\n\nsetTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n"]}
|
package/dist/eval.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.evalBundle = void 0;
|
|
4
|
-
const path_1 = require("path");
|
|
5
4
|
const child_process_1 = require("child_process");
|
|
5
|
+
const path_1 = require("path");
|
|
6
6
|
const fs_1 = require("./fs");
|
|
7
7
|
const WORKER_PATH = (0, path_1.join)(__dirname, 'eval-worker.js');
|
|
8
8
|
/**
|
package/dist/eval.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eval.js","sourceRoot":"","sources":["../src/eval.ts"],"names":[],"mappings":";;;AAAA
|
|
1
|
+
{"version":3,"file":"eval.js","sourceRoot":"","sources":["../src/eval.ts"],"names":[],"mappings":";;;AAAA,iDAAqC;AACrC,+BAA4B;AAE5B,6BAAwC;AAExC,MAAM,WAAW,GAAG,IAAA,WAAI,EAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;AAEtD;;;;;;GAMG;AACI,KAAK,UAAU,UAAU,CAAC,UAAkB;IACjD,MAAM,IAAA,qBAAgB,EAAC,UAAU,CAAC,CAAC;IAEnC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,MAAM,GAAG,IAAA,oBAAI,EAAC,WAAW,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;QAE/C,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,QAAgB,EAAE,EAAE;YACrC,IAAI,QAAQ,KAAK,CAAC,EAAE;gBAClB,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;aACtB;YAED,OAAO,MAAM,CACX,IAAI,KAAK,CAAC,2CAA2C,QAAQ,EAAE,CAAC,CACjE,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAhBD,gCAgBC","sourcesContent":["import { fork } from 'child_process';\nimport { join } from 'path';\n\nimport { validateFilePath } from './fs';\n\nconst WORKER_PATH = join(__dirname, 'eval-worker.js');\n\n/**\n * Spawn a new process to run the provided bundle in.\n *\n * @param bundlePath - The path to the bundle to run.\n * @returns `null` if the worker ran successfully.\n * @throws If the worker failed to run successfully.\n */\nexport async function evalBundle(bundlePath: string): Promise<null> {\n await validateFilePath(bundlePath);\n\n return new Promise((resolve, reject) => {\n const worker = fork(WORKER_PATH, [bundlePath]);\n\n worker.on('exit', (exitCode: number) => {\n if (exitCode === 0) {\n return resolve(null);\n }\n\n return reject(\n new Error(`Process exited with non-zero exit code: ${exitCode}`),\n );\n });\n });\n}\n"]}
|
package/dist/fs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fs.js","sourceRoot":"","sources":["../src/fs.ts"],"names":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"fs.js","sourceRoot":"","sources":["../src/fs.ts"],"names":[],"mappings":";;;;;;AACA,2BAAoC;AACpC,gDAA6B;AAI7B;;;;;;;GAOG;AACI,KAAK,UAAU,WAAW,CAC/B,UAAkB,EAClB,SAAkB;IAElB,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,aAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACxC,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;KAC5B;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE;YAC3B,IAAI,CAAC,SAAS,EAAE;gBACd,OAAO,KAAK,CAAC;aACd;YAED,MAAM,aAAE,CAAC,KAAK,CAAC,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YAChD,OAAO,IAAI,CAAC;SACb;QAED,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAnBD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AQ,CAAC,KAAK,CAAC;QACzB,QAAQ,KAAK,KAAK;QAClB,cAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,KAAK,QAAQ,EACzC;QACA,MAAM,IAAI,KAAK,CAAC,yBAAyB,QAAQ,sBAAsB,CAAC,CAAC;KAC1E;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AATD,kDASC;AAED;;;;;;GAMG;AACI,KAAK,UAAU,gBAAgB,CAAC,QAAgB;IACrD,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,QAAQ,CAAC,CAAC;IACtC,IAAI,CAAC,MAAM,EAAE;QACX,MAAM,IAAI,KAAK,CACb,oBAAoB,QAAQ,oCAAoC,CACjE,CAAC;KACH;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AARD,4CAQC;AAED;;;;;;;GAOG;AACI,KAAK,UAAU,eAAe,CACnC,OAAe,EACf,SAAkB;IAElB,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IACrD,IAAI,CAAC,MAAM,EAAE;QACX,MAAM,IAAI,KAAK,CACb,oBAAoB,OAAO,+CAA+C,CAC3E,CAAC;KACH;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAXD,0CAWC","sourcesContent":["import { Json } from '@metamask/utils';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { NpmSnapFileNames } from './types';\n\n/**\n * Checks whether the given path string resolves to an existing directory, and\n * optionally creates the directory if it doesn't exist.\n *\n * @param pathString - The path string to check.\n * @param createDir - Whether to create the directory if it doesn't exist.\n * @returns Whether the given path is an existing directory.\n */\nexport async function isDirectory(\n pathString: string,\n createDir: boolean,\n): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isDirectory();\n } catch (error) {\n if (error.code === 'ENOENT') {\n if (!createDir) {\n return false;\n }\n\n await fs.mkdir(pathString, { recursive: true });\n return true;\n }\n\n return false;\n }\n}\n\n/**\n * Checks whether the given path string resolves to an existing file.\n *\n * @param pathString - The path string to check.\n * @returns Whether the given path is an existing file.\n */\nexport async function isFile(pathString: string): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isFile();\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Reads a `.json` file, parses its contents, and returns them.\n *\n * @param pathString - The path to the JSON file.\n * @returns The parsed contents of the JSON file.\n */\nexport async function readJsonFile<Type = Json>(\n pathString: string,\n): Promise<Type> {\n if (!pathString.endsWith('.json')) {\n throw new Error('The specified file must be a \".json\" file.');\n }\n\n return JSON.parse(await fs.readFile(pathString, 'utf8'));\n}\n\n/**\n * Utility function for reading `package.json` or the Snap manifest file.\n * These are assumed to be in the current working directory.\n *\n * @param pathString - The base path of the file to read.\n * @param snapJsonFileName - The name of the file to read.\n * @returns The parsed JSON file.\n */\nexport async function readSnapJsonFile(\n pathString: string,\n snapJsonFileName: NpmSnapFileNames,\n): Promise<Json> {\n const path = pathUtils.join(pathString, snapJsonFileName);\n\n try {\n return await readJsonFile(path);\n } catch (error) {\n if (error.code === 'ENOENT') {\n throw new Error(\n `Could not find '${path}'. Please ensure that the file exists.`,\n );\n }\n\n throw error;\n }\n}\n\n/**\n * Gets the complete out file path from an output file name and parent\n * directory path.\n *\n * @param outDir - The path to the out file's parent directory.\n * @param outFileName - The out file's name.\n * @returns The complete path to the out file.\n */\nexport function getOutfilePath(outDir: string, outFileName: string): string {\n return pathUtils.join(outDir, outFileName || 'bundle.js');\n}\n\n/**\n * Ensures that the outfile name is just a `.js` file name.\n * Throws on validation failure.\n *\n * @param filename - The file name to validate.\n * @returns `true` if validation succeeded.\n * @throws If the file name is invalid.\n */\nexport function validateOutfileName(filename: string): boolean {\n if (\n !filename.endsWith('.js') ||\n filename === '.js' ||\n pathUtils.basename(filename) !== filename\n ) {\n throw new Error(`Invalid outfile name: ${filename}. Must be a .js file`);\n }\n return true;\n}\n\n/**\n * Validates a file path. Throws on validation failure.\n *\n * @param filePath - The file path to validate.\n * @returns `true` if validation succeeded.\n * @throws If the path does not resolve to a file.\n */\nexport async function validateFilePath(filePath: string): Promise<boolean> {\n const exists = await isFile(filePath);\n if (!exists) {\n throw new Error(\n `Invalid params: '${filePath}' is not a file or does not exist.`,\n );\n }\n return true;\n}\n\n/**\n * Validates a directory path. Throws on validation failure.\n *\n * @param dirPath - The directory path to validate.\n * @param createDir - Whether to create the directory if it doesn't exist.\n * @returns `true` if validation succeeded or the directory was created.\n * @throws If the directory does not exist or could not be created.\n */\nexport async function validateDirPath(\n dirPath: string,\n createDir: boolean,\n): Promise<boolean> {\n const exists = await isDirectory(dirPath, createDir);\n if (!exists) {\n throw new Error(\n `Invalid params: '${dirPath}' is not a directory or could not be created.`,\n );\n }\n return true;\n}\n"]}
|
package/dist/json-rpc.d.ts
CHANGED
|
@@ -1,4 +1,22 @@
|
|
|
1
|
-
import { Json, JsonRpcSuccess } from '@metamask/utils';
|
|
1
|
+
import { Json, JsonRpcSuccess, AssertionErrorConstructor } from '@metamask/utils';
|
|
2
|
+
import { Infer } from 'superstruct';
|
|
3
|
+
export declare const RpcOriginsStruct: import("superstruct").Struct<{
|
|
4
|
+
dapps?: boolean | undefined;
|
|
5
|
+
snaps?: boolean | undefined;
|
|
6
|
+
}, {
|
|
7
|
+
dapps: import("superstruct").Struct<boolean | undefined, null>;
|
|
8
|
+
snaps: import("superstruct").Struct<boolean | undefined, null>;
|
|
9
|
+
}>;
|
|
10
|
+
export declare type RpcOrigins = Infer<typeof RpcOriginsStruct>;
|
|
11
|
+
/**
|
|
12
|
+
* Asserts that the given value is a valid {@link RpcOrigins} object.
|
|
13
|
+
*
|
|
14
|
+
* @param value - The value to assert.
|
|
15
|
+
* @param ErrorWrapper - An optional error wrapper to use. Defaults to
|
|
16
|
+
* {@link AssertionError}.
|
|
17
|
+
* @throws If the value is not a valid {@link RpcOrigins} object.
|
|
18
|
+
*/
|
|
19
|
+
export declare function assertIsRpcOrigins(value: unknown, ErrorWrapper?: AssertionErrorConstructor): asserts value is RpcOrigins;
|
|
2
20
|
/**
|
|
3
21
|
* Assert that the given value is a successful JSON-RPC response. If the value
|
|
4
22
|
* is not a success response, an error is thrown. If the value is an JSON-RPC
|
package/dist/json-rpc.js
CHANGED
|
@@ -1,7 +1,31 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.assertIsJsonRpcSuccess = void 0;
|
|
3
|
+
exports.assertIsJsonRpcSuccess = exports.assertIsRpcOrigins = exports.RpcOriginsStruct = void 0;
|
|
4
4
|
const utils_1 = require("@metamask/utils");
|
|
5
|
+
const superstruct_1 = require("superstruct");
|
|
6
|
+
exports.RpcOriginsStruct = (0, superstruct_1.refine)((0, superstruct_1.object)({
|
|
7
|
+
dapps: (0, superstruct_1.optional)((0, superstruct_1.boolean)()),
|
|
8
|
+
snaps: (0, superstruct_1.optional)((0, superstruct_1.boolean)()),
|
|
9
|
+
}), 'RPC origins', (value) => {
|
|
10
|
+
if (!Object.values(value).some(Boolean)) {
|
|
11
|
+
throw new Error('Must specify at least one JSON-RPC origin');
|
|
12
|
+
}
|
|
13
|
+
return true;
|
|
14
|
+
});
|
|
15
|
+
/**
|
|
16
|
+
* Asserts that the given value is a valid {@link RpcOrigins} object.
|
|
17
|
+
*
|
|
18
|
+
* @param value - The value to assert.
|
|
19
|
+
* @param ErrorWrapper - An optional error wrapper to use. Defaults to
|
|
20
|
+
* {@link AssertionError}.
|
|
21
|
+
* @throws If the value is not a valid {@link RpcOrigins} object.
|
|
22
|
+
*/
|
|
23
|
+
function assertIsRpcOrigins(value,
|
|
24
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
25
|
+
ErrorWrapper) {
|
|
26
|
+
(0, utils_1.assertStruct)(value, exports.RpcOriginsStruct, 'Invalid JSON-RPC origins', ErrorWrapper);
|
|
27
|
+
}
|
|
28
|
+
exports.assertIsRpcOrigins = assertIsRpcOrigins;
|
|
5
29
|
/**
|
|
6
30
|
* Assert that the given value is a successful JSON-RPC response. If the value
|
|
7
31
|
* is not a success response, an error is thrown. If the value is an JSON-RPC
|
package/dist/json-rpc.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-rpc.js","sourceRoot":"","sources":["../src/json-rpc.ts"],"names":[],"mappings":";;;AAAA,
|
|
1
|
+
{"version":3,"file":"json-rpc.js","sourceRoot":"","sources":["../src/json-rpc.ts"],"names":[],"mappings":";;;AAAA,2CAOyB;AACzB,6CAAuE;AAE1D,QAAA,gBAAgB,GAAG,IAAA,oBAAM,EACpC,IAAA,oBAAM,EAAC;IACL,KAAK,EAAE,IAAA,sBAAQ,EAAC,IAAA,qBAAO,GAAE,CAAC;IAC1B,KAAK,EAAE,IAAA,sBAAQ,EAAC,IAAA,qBAAO,GAAE,CAAC;CAC3B,CAAC,EACF,aAAa,EACb,CAAC,KAAK,EAAE,EAAE;IACR,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;QACvC,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;KAC9D;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CACF,CAAC;AAIF;;;;;;;GAOG;AACH,SAAgB,kBAAkB,CAChC,KAAc;AACd,gEAAgE;AAChE,YAAwC;IAExC,IAAA,oBAAY,EACV,KAAK,EACL,wBAAgB,EAChB,0BAA0B,EAC1B,YAAY,CACb,CAAC;AACJ,CAAC;AAXD,gDAWC;AAED;;;;;;;GAOG;AACH,SAAgB,sBAAsB,CACpC,KAAc;IAEd,IAAI,CAAC,IAAA,wBAAgB,EAAC,KAAK,CAAC,EAAE;QAC5B,IAAI,IAAA,wBAAgB,EAAC,KAAK,CAAC,EAAE;YAC3B,MAAM,IAAI,KAAK,CAAC,4BAA4B,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;SACpE;QAED,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;KAC/C;AACH,CAAC;AAVD,wDAUC","sourcesContent":["import {\n isJsonRpcFailure,\n isJsonRpcSuccess,\n Json,\n JsonRpcSuccess,\n AssertionErrorConstructor,\n assertStruct,\n} from '@metamask/utils';\nimport { boolean, Infer, object, optional, refine } from 'superstruct';\n\nexport const RpcOriginsStruct = refine(\n object({\n dapps: optional(boolean()),\n snaps: optional(boolean()),\n }),\n 'RPC origins',\n (value) => {\n if (!Object.values(value).some(Boolean)) {\n throw new Error('Must specify at least one JSON-RPC origin');\n }\n\n return true;\n },\n);\n\nexport type RpcOrigins = Infer<typeof RpcOriginsStruct>;\n\n/**\n * Asserts that the given value is a valid {@link RpcOrigins} object.\n *\n * @param value - The value to assert.\n * @param ErrorWrapper - An optional error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link RpcOrigins} object.\n */\nexport function assertIsRpcOrigins(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is RpcOrigins {\n assertStruct(\n value,\n RpcOriginsStruct,\n 'Invalid JSON-RPC origins',\n ErrorWrapper,\n );\n}\n\n/**\n * Assert that the given value is a successful JSON-RPC response. If the value\n * is not a success response, an error is thrown. If the value is an JSON-RPC\n * error, the error message is included in the thrown error.\n *\n * @param value - The value to check.\n * @throws If the value is not a JSON-RPC success response.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n): asserts value is JsonRpcSuccess<Json> {\n if (!isJsonRpcSuccess(value)) {\n if (isJsonRpcFailure(value)) {\n throw new Error(`JSON-RPC request failed: ${value.error.message}`);\n }\n\n throw new Error('Invalid JSON-RPC response.');\n }\n}\n"]}
|
|
@@ -15,9 +15,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
exports.validateNpmSnapManifest = exports.getWritableManifest = exports.getSnapSourceCode = exports.fixManifest = exports.checkManifest = void 0;
|
|
18
|
+
const utils_1 = require("@metamask/utils");
|
|
19
|
+
const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
|
|
18
20
|
const fs_1 = require("fs");
|
|
19
21
|
const path_1 = __importDefault(require("path"));
|
|
20
|
-
const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
|
|
21
22
|
const deep_clone_1 = require("../deep-clone");
|
|
22
23
|
const fs_2 = require("../fs");
|
|
23
24
|
const npm_1 = require("../npm");
|
|
@@ -152,10 +153,8 @@ function fixManifest(snapFiles, error) {
|
|
|
152
153
|
manifestCopy.source.shasum = (0, snaps_1.getSnapSourceShasum)(sourceCode);
|
|
153
154
|
break;
|
|
154
155
|
/* istanbul ignore next */
|
|
155
|
-
default:
|
|
156
|
-
|
|
157
|
-
throw new Error(`Unrecognized validation failure reason: '${failureReason}'`);
|
|
158
|
-
}
|
|
156
|
+
default:
|
|
157
|
+
(0, utils_1.assertExhaustive)(error.reason);
|
|
159
158
|
}
|
|
160
159
|
return manifestCopy;
|
|
161
160
|
}
|
|
@@ -194,9 +193,10 @@ exports.getSnapSourceCode = getSnapSourceCode;
|
|
|
194
193
|
function getWritableManifest(manifest) {
|
|
195
194
|
const { repository } = manifest, remaining = __rest(manifest, ["repository"]);
|
|
196
195
|
const keys = Object.keys(repository ? Object.assign(Object.assign({}, remaining), { repository }) : remaining);
|
|
197
|
-
|
|
196
|
+
const writableManifest = keys
|
|
198
197
|
.sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])
|
|
199
198
|
.reduce((result, key) => (Object.assign(Object.assign({}, result), { [key]: manifest[key] })), {});
|
|
199
|
+
return writableManifest;
|
|
200
200
|
}
|
|
201
201
|
exports.getWritableManifest = getWritableManifest;
|
|
202
202
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../src/manifest/manifest.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,2BAAoC;AACp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M,kBAAkB,GAAG,QAAQ,CAAC,UAAU,CAAC;IAE/C,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,QAAQ,EACR,UAAU,EACV,IAAI,wBAAgB,CAAC,QAAQ,kDAAkD,CAChF,CAAC;IACF,OAAO,CAAC,QAAQ,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;AAC7C,CAAC;AA7CD,0DA6CC","sourcesContent":["import { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { Json } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { deepClone } from '../deep-clone';\nimport { readSnapJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapSourceShasum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport {\n NpmSnapFileNames,\n NpmSnapPackageJson,\n SnapFiles,\n SnapValidationFailureReason,\n UnvalidatedSnapFiles,\n} from '../types';\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 unvalidatedManifest = await readSnapJsonFile(\n basePath,\n NpmSnapFileNames.Manifest,\n );\n\n const iconPath =\n unvalidatedManifest && typeof unvalidatedManifest === 'object'\n ? /* istanbul ignore next */\n (unvalidatedManifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath\n : /* istanbul ignore next */\n undefined;\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: unvalidatedManifest,\n packageJson: await readSnapJsonFile(basePath, NpmSnapFileNames.PackageJson),\n sourceCode:\n sourceCode ?? (await getSnapSourceCode(basePath, unvalidatedManifest)),\n svgIcon:\n iconPath &&\n (await fs.readFile(pathUtils.join(basePath, iconPath), 'utf8')),\n };\n\n let manifest: 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 doesn't see that the 'manifest' variable must be of type\n // SnapManifest at this point, so we cast it.\n const validatedManifest = manifest as SnapManifest;\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 await fs.writeFile(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\\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): SnapManifest {\n const { manifest, packageJson, sourceCode } = snapFiles;\n const manifestCopy = deepClone(manifest);\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.repository\n ? deepClone(packageJson.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapSourceShasum(sourceCode);\n break;\n\n /* istanbul ignore next */\n default: {\n const failureReason: never = error.reason;\n throw new Error(\n `Unrecognized validation failure reason: '${failureReason}'`,\n );\n }\n }\n\n return manifestCopy;\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 * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n): Promise<string | undefined> {\n if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n try {\n return sourceFilePath\n ? await fs.readFile(pathUtils.join(basePath, sourceFilePath), 'utf8')\n : undefined;\n } catch (error) {\n throw new Error(`Failed to read Snap bundle file: ${error.message}`);\n }\n }\n\n return undefined;\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 return keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {} as SnapManifest,\n );\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 * @returns A tuple containing the validated snap manifest, snap source code,\n * and `package.json`.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n}: SnapFiles): [SnapManifest, string, NpmSnapPackageJson] {\n const packageJsonName = packageJson.name;\n const packageJsonVersion = packageJson.version;\n const packageJsonRepository = packageJson.repository;\n\n const manifestPackageName = manifest.source.location.npm.packageName;\n const manifestPackageVersion = manifest.version;\n const manifestRepository = manifest.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,\n sourceCode,\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n return [manifest, sourceCode, packageJson];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../src/manifest/manifest.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,2CAAyD;AACzD,sEAAwC;AACxC,2BAAoC;AACpC,gDAA6B;AAE7B,8CAA0C;AAC1C,8BAAyC;AACzC,gCAAyC;AACzC,oCAIkB;AAClB,oCAMkB;AAGlB,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,mBAAmB,GAAG,MAAM,IAAA,qBAAgB,EAChD,QAAQ,EACR,wBAAgB,CAAC,QAAQ,CAC1B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,wBAAgB,CAAC,QAAQ,4CAA4C,wBAAgB,CAAC,WAAW,uBAAuB,EAC5H,mCAA2B,CAAC,kBAAkB,CAC/C,CAAC;KACH;IAED,IAAA,0BAAkB,EAChB,QAAQ,EACR,UAAU,EACV,IAAI,wBAAgB,CAAC,QAAQ,kDAAkD,CAChF,CAAC;IACF,OAAO,CAAC,QAAQ,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;AAC7C,CAAC;AA7CD,0DA6CC","sourcesContent":["import { Json, assertExhaustive } 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 { readSnapJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapSourceShasum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport {\n NpmSnapFileNames,\n NpmSnapPackageJson,\n SnapFiles,\n SnapValidationFailureReason,\n UnvalidatedSnapFiles,\n} from '../types';\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 unvalidatedManifest = await readSnapJsonFile(\n basePath,\n NpmSnapFileNames.Manifest,\n );\n\n const iconPath =\n unvalidatedManifest && typeof unvalidatedManifest === 'object'\n ? /* istanbul ignore next */\n (unvalidatedManifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath\n : /* istanbul ignore next */\n undefined;\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: unvalidatedManifest,\n packageJson: await readSnapJsonFile(basePath, NpmSnapFileNames.PackageJson),\n sourceCode:\n sourceCode ?? (await getSnapSourceCode(basePath, unvalidatedManifest)),\n svgIcon:\n iconPath &&\n (await fs.readFile(pathUtils.join(basePath, iconPath), 'utf8')),\n };\n\n let manifest: 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 doesn't see that the 'manifest' variable must be of type\n // SnapManifest at this point, so we cast it.\n const validatedManifest = manifest as SnapManifest;\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 await fs.writeFile(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\\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): SnapManifest {\n const { manifest, packageJson, sourceCode } = snapFiles;\n const manifestCopy = deepClone(manifest);\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.repository\n ? deepClone(packageJson.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapSourceShasum(sourceCode);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n return manifestCopy;\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 * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n): Promise<string | undefined> {\n if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n try {\n return sourceFilePath\n ? await fs.readFile(pathUtils.join(basePath, sourceFilePath), 'utf8')\n : undefined;\n } catch (error) {\n throw new Error(`Failed to read Snap bundle file: ${error.message}`);\n }\n }\n\n return undefined;\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 * @returns A tuple containing the validated snap manifest, snap source code,\n * and `package.json`.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n}: SnapFiles): [SnapManifest, string, NpmSnapPackageJson] {\n const packageJsonName = packageJson.name;\n const packageJsonVersion = packageJson.version;\n const packageJsonRepository = packageJson.repository;\n\n const manifestPackageName = manifest.source.location.npm.packageName;\n const manifestPackageVersion = manifest.version;\n const manifestRepository = manifest.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,\n sourceCode,\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n return [manifest, sourceCode, packageJson];\n}\n"]}
|
|
@@ -24,6 +24,10 @@ export declare type Base64Opts = {
|
|
|
24
24
|
*/
|
|
25
25
|
export declare const base64: <T extends string, S>(struct: Struct<T, S>, opts?: Base64Opts) => Struct<T, S>;
|
|
26
26
|
export declare const Bip32PathStruct: Struct<string[], Struct<string, null>>;
|
|
27
|
+
export declare const bip32entropy: <T extends {
|
|
28
|
+
path: string[];
|
|
29
|
+
curve: string;
|
|
30
|
+
}, S>(struct: Struct<T, S>) => Struct<T, S>;
|
|
27
31
|
export declare const Bip32EntropyStruct: Struct<{
|
|
28
32
|
path: string[];
|
|
29
33
|
curve: "ed25519" | "secp256k1";
|
|
@@ -35,20 +39,20 @@ export declare const Bip32EntropyStruct: Struct<{
|
|
|
35
39
|
}>;
|
|
36
40
|
}>;
|
|
37
41
|
export declare type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;
|
|
38
|
-
export declare const
|
|
42
|
+
export declare const SnapGetBip32EntropyPermissionsStruct: Struct<{
|
|
43
|
+
path: string[];
|
|
44
|
+
curve: "ed25519" | "secp256k1";
|
|
45
|
+
}[], Struct<{
|
|
39
46
|
path: string[];
|
|
40
|
-
curve: "
|
|
41
|
-
compressed?: boolean | undefined;
|
|
47
|
+
curve: "ed25519" | "secp256k1";
|
|
42
48
|
}, {
|
|
43
49
|
path: Struct<string[], Struct<string, null>>;
|
|
44
|
-
curve: Struct<"
|
|
50
|
+
curve: Struct<"ed25519" | "secp256k1", {
|
|
51
|
+
ed25519: "ed25519";
|
|
45
52
|
secp256k1: "secp256k1";
|
|
46
|
-
ed225519: "ed225519";
|
|
47
53
|
}>;
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
export declare type Bip32PublicKey = Infer<typeof Bip32PublicKeyStruct>;
|
|
51
|
-
declare const PermissionsStruct: Struct<{
|
|
54
|
+
}>>;
|
|
55
|
+
export declare const PermissionsStruct: Struct<{
|
|
52
56
|
'endowment:long-running'?: {} | undefined;
|
|
53
57
|
'endowment:network-access'?: {} | undefined;
|
|
54
58
|
'endowment:transaction-insight'?: {
|
|
@@ -65,6 +69,10 @@ declare const PermissionsStruct: Struct<{
|
|
|
65
69
|
};
|
|
66
70
|
}[];
|
|
67
71
|
} | undefined;
|
|
72
|
+
'endowment:rpc'?: {
|
|
73
|
+
dapps?: boolean | undefined;
|
|
74
|
+
snaps?: boolean | undefined;
|
|
75
|
+
} | undefined;
|
|
68
76
|
snap_confirm?: {} | undefined;
|
|
69
77
|
snap_manageState?: {} | undefined;
|
|
70
78
|
snap_notify?: {} | undefined;
|
|
@@ -74,8 +82,7 @@ declare const PermissionsStruct: Struct<{
|
|
|
74
82
|
}[] | undefined;
|
|
75
83
|
snap_getBip32PublicKey?: {
|
|
76
84
|
path: string[];
|
|
77
|
-
curve: "
|
|
78
|
-
compressed?: boolean | undefined;
|
|
85
|
+
curve: "ed25519" | "secp256k1";
|
|
79
86
|
}[] | undefined;
|
|
80
87
|
snap_getBip44Entropy?: {
|
|
81
88
|
coinType: number;
|
|
@@ -141,6 +148,13 @@ declare const PermissionsStruct: Struct<{
|
|
|
141
148
|
}>;
|
|
142
149
|
}>>;
|
|
143
150
|
}>;
|
|
151
|
+
'endowment:rpc': Struct<{
|
|
152
|
+
dapps?: boolean | undefined;
|
|
153
|
+
snaps?: boolean | undefined;
|
|
154
|
+
} | undefined, {
|
|
155
|
+
dapps: Struct<boolean | undefined, null>;
|
|
156
|
+
snaps: Struct<boolean | undefined, null>;
|
|
157
|
+
}>;
|
|
144
158
|
snap_confirm: Struct<{} | undefined, {}>;
|
|
145
159
|
snap_manageState: Struct<{} | undefined, {}>;
|
|
146
160
|
snap_notify: Struct<{} | undefined, {}>;
|
|
@@ -159,19 +173,16 @@ declare const PermissionsStruct: Struct<{
|
|
|
159
173
|
}>>;
|
|
160
174
|
snap_getBip32PublicKey: Struct<{
|
|
161
175
|
path: string[];
|
|
162
|
-
curve: "
|
|
163
|
-
compressed?: boolean | undefined;
|
|
176
|
+
curve: "ed25519" | "secp256k1";
|
|
164
177
|
}[] | undefined, Struct<{
|
|
165
178
|
path: string[];
|
|
166
|
-
curve: "
|
|
167
|
-
compressed?: boolean | undefined;
|
|
179
|
+
curve: "ed25519" | "secp256k1";
|
|
168
180
|
}, {
|
|
169
181
|
path: Struct<string[], Struct<string, null>>;
|
|
170
|
-
curve: Struct<"
|
|
182
|
+
curve: Struct<"ed25519" | "secp256k1", {
|
|
183
|
+
ed25519: "ed25519";
|
|
171
184
|
secp256k1: "secp256k1";
|
|
172
|
-
ed225519: "ed225519";
|
|
173
185
|
}>;
|
|
174
|
-
compressed: Struct<boolean | undefined, null>;
|
|
175
186
|
}>>;
|
|
176
187
|
snap_getBip44Entropy: Struct<{
|
|
177
188
|
coinType: number;
|
|
@@ -203,7 +214,7 @@ declare const PermissionsStruct: Struct<{
|
|
|
203
214
|
}>;
|
|
204
215
|
export declare type SnapPermissions = Infer<typeof PermissionsStruct>;
|
|
205
216
|
export declare const SnapManifestStruct: Struct<{
|
|
206
|
-
version:
|
|
217
|
+
version: import("../versions").SemVerVersion;
|
|
207
218
|
description: string;
|
|
208
219
|
proposedName: string;
|
|
209
220
|
source: {
|
|
@@ -234,6 +245,10 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
234
245
|
};
|
|
235
246
|
}[];
|
|
236
247
|
} | undefined;
|
|
248
|
+
'endowment:rpc'?: {
|
|
249
|
+
dapps?: boolean | undefined;
|
|
250
|
+
snaps?: boolean | undefined;
|
|
251
|
+
} | undefined;
|
|
237
252
|
snap_confirm?: {} | undefined;
|
|
238
253
|
snap_manageState?: {} | undefined;
|
|
239
254
|
snap_notify?: {} | undefined;
|
|
@@ -243,8 +258,7 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
243
258
|
}[] | undefined;
|
|
244
259
|
snap_getBip32PublicKey?: {
|
|
245
260
|
path: string[];
|
|
246
|
-
curve: "
|
|
247
|
-
compressed?: boolean | undefined;
|
|
261
|
+
curve: "ed25519" | "secp256k1";
|
|
248
262
|
}[] | undefined;
|
|
249
263
|
snap_getBip44Entropy?: {
|
|
250
264
|
coinType: number;
|
|
@@ -267,7 +281,7 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
267
281
|
url: string;
|
|
268
282
|
} | undefined;
|
|
269
283
|
}, {
|
|
270
|
-
version: Struct<
|
|
284
|
+
version: Struct<import("../versions").SemVerVersion, null>;
|
|
271
285
|
description: Struct<string, null>;
|
|
272
286
|
proposedName: Struct<string, null>;
|
|
273
287
|
repository: Struct<{
|
|
@@ -327,6 +341,10 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
327
341
|
};
|
|
328
342
|
}[];
|
|
329
343
|
} | undefined;
|
|
344
|
+
'endowment:rpc'?: {
|
|
345
|
+
dapps?: boolean | undefined;
|
|
346
|
+
snaps?: boolean | undefined;
|
|
347
|
+
} | undefined;
|
|
330
348
|
snap_confirm?: {} | undefined;
|
|
331
349
|
snap_manageState?: {} | undefined;
|
|
332
350
|
snap_notify?: {} | undefined;
|
|
@@ -336,8 +354,7 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
336
354
|
}[] | undefined;
|
|
337
355
|
snap_getBip32PublicKey?: {
|
|
338
356
|
path: string[];
|
|
339
|
-
curve: "
|
|
340
|
-
compressed?: boolean | undefined;
|
|
357
|
+
curve: "ed25519" | "secp256k1";
|
|
341
358
|
}[] | undefined;
|
|
342
359
|
snap_getBip44Entropy?: {
|
|
343
360
|
coinType: number;
|
|
@@ -403,6 +420,13 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
403
420
|
}>;
|
|
404
421
|
}>>;
|
|
405
422
|
}>;
|
|
423
|
+
'endowment:rpc': Struct<{
|
|
424
|
+
dapps?: boolean | undefined;
|
|
425
|
+
snaps?: boolean | undefined;
|
|
426
|
+
} | undefined, {
|
|
427
|
+
dapps: Struct<boolean | undefined, null>;
|
|
428
|
+
snaps: Struct<boolean | undefined, null>;
|
|
429
|
+
}>;
|
|
406
430
|
snap_confirm: Struct<{} | undefined, {}>;
|
|
407
431
|
snap_manageState: Struct<{} | undefined, {}>;
|
|
408
432
|
snap_notify: Struct<{} | undefined, {}>;
|
|
@@ -421,19 +445,16 @@ export declare const SnapManifestStruct: Struct<{
|
|
|
421
445
|
}>>;
|
|
422
446
|
snap_getBip32PublicKey: Struct<{
|
|
423
447
|
path: string[];
|
|
424
|
-
curve: "
|
|
425
|
-
compressed?: boolean | undefined;
|
|
448
|
+
curve: "ed25519" | "secp256k1";
|
|
426
449
|
}[] | undefined, Struct<{
|
|
427
450
|
path: string[];
|
|
428
|
-
curve: "
|
|
429
|
-
compressed?: boolean | undefined;
|
|
451
|
+
curve: "ed25519" | "secp256k1";
|
|
430
452
|
}, {
|
|
431
453
|
path: Struct<string[], Struct<string, null>>;
|
|
432
|
-
curve: Struct<"
|
|
454
|
+
curve: Struct<"ed25519" | "secp256k1", {
|
|
455
|
+
ed25519: "ed25519";
|
|
433
456
|
secp256k1: "secp256k1";
|
|
434
|
-
ed225519: "ed225519";
|
|
435
457
|
}>;
|
|
436
|
-
compressed: Struct<boolean | undefined, null>;
|
|
437
458
|
}>>;
|
|
438
459
|
snap_getBip44Entropy: Struct<{
|
|
439
460
|
coinType: number;
|
|
@@ -480,4 +501,3 @@ export declare function isSnapManifest(value: unknown): value is SnapManifest;
|
|
|
480
501
|
* @throws If the value is not a valid {@link SnapManifest} object.
|
|
481
502
|
*/
|
|
482
503
|
export declare function assertIsSnapManifest(value: unknown): asserts value is SnapManifest;
|
|
483
|
-
export {};
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.assertIsSnapManifest = exports.isSnapManifest = exports.SnapManifestStruct = exports.
|
|
3
|
+
exports.assertIsSnapManifest = exports.isSnapManifest = exports.SnapManifestStruct = exports.PermissionsStruct = exports.SnapGetBip32EntropyPermissionsStruct = exports.Bip32EntropyStruct = exports.bip32entropy = exports.Bip32PathStruct = exports.base64 = exports.SIP_6_MAGIC_VALUE = void 0;
|
|
4
4
|
const utils_1 = require("@metamask/utils");
|
|
5
5
|
const superstruct_1 = require("superstruct");
|
|
6
6
|
const cronjob_1 = require("../cronjob");
|
|
7
|
+
const json_rpc_1 = require("../json-rpc");
|
|
7
8
|
const namespace_1 = require("../namespace");
|
|
8
9
|
const types_1 = require("../types");
|
|
10
|
+
const versions_1 = require("../versions");
|
|
9
11
|
// 0xd36e6170 - 0x80000000
|
|
10
12
|
exports.SIP_6_MAGIC_VALUE = `1399742832'`;
|
|
11
13
|
// BIP-43 purposes that cannot be used for entropy derivation. These are in the
|
|
@@ -51,7 +53,7 @@ exports.Bip32PathStruct = (0, superstruct_1.refine)((0, superstruct_1.array)((0,
|
|
|
51
53
|
if (path.length < 3) {
|
|
52
54
|
return 'Paths must have a length of at least three.';
|
|
53
55
|
}
|
|
54
|
-
if (path.slice(1).some((
|
|
56
|
+
if (path.slice(1).some((part) => !BIP32_INDEX_REGEX.test(part))) {
|
|
55
57
|
return 'Path must be a valid BIP-32 derivation path array.';
|
|
56
58
|
}
|
|
57
59
|
if (FORBIDDEN_PURPOSES.includes(path[1])) {
|
|
@@ -61,33 +63,32 @@ exports.Bip32PathStruct = (0, superstruct_1.refine)((0, superstruct_1.array)((0,
|
|
|
61
63
|
});
|
|
62
64
|
const bip32entropy = (struct) => (0, superstruct_1.refine)(struct, 'BIP-32 entropy', (value) => {
|
|
63
65
|
if (value.curve === 'ed25519' &&
|
|
64
|
-
value.path.slice(1).some((
|
|
66
|
+
value.path.slice(1).some((part) => !part.endsWith("'"))) {
|
|
65
67
|
return 'Ed25519 does not support unhardened paths.';
|
|
66
68
|
}
|
|
67
69
|
return true;
|
|
68
70
|
});
|
|
71
|
+
exports.bip32entropy = bip32entropy;
|
|
69
72
|
// Used outside @metamask/snap-utils
|
|
70
|
-
exports.Bip32EntropyStruct = bip32entropy((0, superstruct_1.
|
|
73
|
+
exports.Bip32EntropyStruct = (0, exports.bip32entropy)((0, superstruct_1.type)({
|
|
71
74
|
path: exports.Bip32PathStruct,
|
|
72
75
|
curve: (0, superstruct_1.enums)(['ed25519', 'secp256k1']),
|
|
73
76
|
}));
|
|
74
|
-
exports.
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
compressed: (0, superstruct_1.optional)((0, superstruct_1.boolean)()),
|
|
78
|
-
}));
|
|
79
|
-
const PermissionsStruct = (0, superstruct_1.type)({
|
|
77
|
+
exports.SnapGetBip32EntropyPermissionsStruct = (0, superstruct_1.size)((0, superstruct_1.array)(exports.Bip32EntropyStruct), 1, Infinity);
|
|
78
|
+
/* eslint-disable @typescript-eslint/naming-convention */
|
|
79
|
+
exports.PermissionsStruct = (0, superstruct_1.type)({
|
|
80
80
|
'endowment:long-running': (0, superstruct_1.optional)((0, superstruct_1.object)({})),
|
|
81
81
|
'endowment:network-access': (0, superstruct_1.optional)((0, superstruct_1.object)({})),
|
|
82
82
|
'endowment:transaction-insight': (0, superstruct_1.optional)((0, superstruct_1.object)({
|
|
83
83
|
allowTransactionOrigin: (0, superstruct_1.optional)((0, superstruct_1.boolean)()),
|
|
84
84
|
})),
|
|
85
85
|
'endowment:cronjob': (0, superstruct_1.optional)((0, superstruct_1.object)({ jobs: cronjob_1.CronjobSpecificationArrayStruct })),
|
|
86
|
+
'endowment:rpc': (0, superstruct_1.optional)(json_rpc_1.RpcOriginsStruct),
|
|
86
87
|
snap_confirm: (0, superstruct_1.optional)((0, superstruct_1.object)({})),
|
|
87
88
|
snap_manageState: (0, superstruct_1.optional)((0, superstruct_1.object)({})),
|
|
88
89
|
snap_notify: (0, superstruct_1.optional)((0, superstruct_1.object)({})),
|
|
89
|
-
snap_getBip32Entropy: (0, superstruct_1.optional)(
|
|
90
|
-
snap_getBip32PublicKey: (0, superstruct_1.optional)(
|
|
90
|
+
snap_getBip32Entropy: (0, superstruct_1.optional)(exports.SnapGetBip32EntropyPermissionsStruct),
|
|
91
|
+
snap_getBip32PublicKey: (0, superstruct_1.optional)(exports.SnapGetBip32EntropyPermissionsStruct),
|
|
91
92
|
snap_getBip44Entropy: (0, superstruct_1.optional)((0, superstruct_1.size)((0, superstruct_1.array)((0, superstruct_1.object)({ coinType: (0, superstruct_1.size)((0, superstruct_1.integer)(), 0, 2 ** 32 - 1) })), 1, Infinity)),
|
|
92
93
|
snap_getEntropy: (0, superstruct_1.optional)((0, superstruct_1.object)({})),
|
|
93
94
|
'endowment:keyring': (0, superstruct_1.optional)((0, superstruct_1.object)({
|
|
@@ -95,7 +96,7 @@ const PermissionsStruct = (0, superstruct_1.type)({
|
|
|
95
96
|
})),
|
|
96
97
|
});
|
|
97
98
|
exports.SnapManifestStruct = (0, superstruct_1.object)({
|
|
98
|
-
version:
|
|
99
|
+
version: versions_1.VersionStruct,
|
|
99
100
|
description: (0, superstruct_1.size)((0, superstruct_1.string)(), 1, 280),
|
|
100
101
|
proposedName: (0, superstruct_1.size)((0, superstruct_1.pattern)((0, superstruct_1.string)(), /^(?:[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), 1, 214),
|
|
101
102
|
repository: (0, superstruct_1.optional)((0, superstruct_1.object)({
|
|
@@ -116,7 +117,7 @@ exports.SnapManifestStruct = (0, superstruct_1.object)({
|
|
|
116
117
|
}),
|
|
117
118
|
}),
|
|
118
119
|
}),
|
|
119
|
-
initialPermissions: PermissionsStruct,
|
|
120
|
+
initialPermissions: exports.PermissionsStruct,
|
|
120
121
|
manifestVersion: (0, superstruct_1.literal)('0.1'),
|
|
121
122
|
});
|
|
122
123
|
/**
|