@metamask/snaps-execution-environments 2.0.1 → 3.1.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/CHANGELOG.md +16 -1
- package/dist/browserify/iframe/bundle.js +5 -5
- package/dist/browserify/node-process/bundle.js +4 -4
- package/dist/browserify/node-thread/bundle.js +4 -4
- package/dist/browserify/offscreen/bundle.js +4 -4
- package/dist/browserify/worker-executor/bundle.js +5 -5
- package/dist/browserify/worker-pool/bundle.js +4 -4
- package/dist/cjs/common/BaseSnapExecutor.js +37 -27
- package/dist/cjs/common/BaseSnapExecutor.js.map +1 -1
- package/dist/cjs/common/commands.js +1 -0
- package/dist/cjs/common/commands.js.map +1 -1
- package/dist/cjs/common/endowments/console.js.map +1 -1
- package/dist/cjs/common/endowments/index.js +2 -1
- package/dist/cjs/common/endowments/index.js.map +1 -1
- package/dist/cjs/common/endowments/interval.js +2 -1
- package/dist/cjs/common/endowments/interval.js.map +1 -1
- package/dist/cjs/common/endowments/timeout.js +2 -1
- package/dist/cjs/common/endowments/timeout.js.map +1 -1
- package/dist/cjs/common/globalEvents.js +2 -1
- package/dist/cjs/common/globalEvents.js.map +1 -1
- package/dist/cjs/common/globalObject.js.map +1 -1
- package/dist/cjs/common/utils.js +7 -21
- package/dist/cjs/common/utils.js.map +1 -1
- package/dist/cjs/common/validation.js +3 -2
- package/dist/cjs/common/validation.js.map +1 -1
- package/dist/esm/common/BaseSnapExecutor.js +37 -27
- package/dist/esm/common/BaseSnapExecutor.js.map +1 -1
- package/dist/esm/common/commands.js +1 -0
- package/dist/esm/common/commands.js.map +1 -1
- package/dist/esm/common/endowments/console.js.map +1 -1
- package/dist/esm/common/endowments/index.js +2 -1
- package/dist/esm/common/endowments/index.js.map +1 -1
- package/dist/esm/common/endowments/interval.js +2 -1
- package/dist/esm/common/endowments/interval.js.map +1 -1
- package/dist/esm/common/endowments/timeout.js +2 -1
- package/dist/esm/common/endowments/timeout.js.map +1 -1
- package/dist/esm/common/globalEvents.js +2 -1
- package/dist/esm/common/globalEvents.js.map +1 -1
- package/dist/esm/common/globalObject.js.map +1 -1
- package/dist/esm/common/utils.js +7 -25
- package/dist/esm/common/utils.js.map +1 -1
- package/dist/esm/common/validation.js +3 -2
- package/dist/esm/common/validation.js.map +1 -1
- package/dist/types/common/endowments/index.d.ts +1 -1
- package/dist/types/common/utils.d.ts +0 -9
- package/package.json +21 -23
package/dist/cjs/common/utils.js
CHANGED
|
@@ -9,9 +9,6 @@ function _export(target, all) {
|
|
|
9
9
|
});
|
|
10
10
|
}
|
|
11
11
|
_export(exports, {
|
|
12
|
-
constructError: function() {
|
|
13
|
-
return constructError;
|
|
14
|
-
},
|
|
15
12
|
withTeardown: function() {
|
|
16
13
|
return withTeardown;
|
|
17
14
|
},
|
|
@@ -31,20 +28,9 @@ _export(exports, {
|
|
|
31
28
|
return sanitizeRequestArguments;
|
|
32
29
|
}
|
|
33
30
|
});
|
|
31
|
+
const _rpcerrors = require("@metamask/rpc-errors");
|
|
34
32
|
const _utils = require("@metamask/utils");
|
|
35
|
-
const _ethrpcerrors = require("eth-rpc-errors");
|
|
36
33
|
const _logging = require("../logging");
|
|
37
|
-
function constructError(originalError) {
|
|
38
|
-
let _originalError;
|
|
39
|
-
if (originalError instanceof Error) {
|
|
40
|
-
_originalError = originalError;
|
|
41
|
-
} else if (typeof originalError === 'string') {
|
|
42
|
-
_originalError = new Error(originalError);
|
|
43
|
-
// The stack is useless in this case.
|
|
44
|
-
delete _originalError.stack;
|
|
45
|
-
}
|
|
46
|
-
return _originalError;
|
|
47
|
-
}
|
|
48
34
|
async function withTeardown(originalPromise, teardownRef) {
|
|
49
35
|
const myTeardown = teardownRef.lastTeardown;
|
|
50
36
|
return new Promise((resolve, reject)=>{
|
|
@@ -109,27 +95,27 @@ const BLOCKED_RPC_METHODS = Object.freeze([
|
|
|
109
95
|
]);
|
|
110
96
|
function assertSnapOutboundRequest(args) {
|
|
111
97
|
// Disallow any non `wallet_` or `snap_` methods for separation of concerns.
|
|
112
|
-
(0, _utils.assert)(String.prototype.startsWith.call(args.method, 'wallet_') || String.prototype.startsWith.call(args.method, 'snap_'), 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.');
|
|
113
|
-
(0, _utils.assert)(!BLOCKED_RPC_METHODS.includes(args.method),
|
|
98
|
+
(0, _utils.assert)(String.prototype.startsWith.call(args.method, 'wallet_') || String.prototype.startsWith.call(args.method, 'snap_'), 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.', _rpcerrors.rpcErrors.methodNotSupported);
|
|
99
|
+
(0, _utils.assert)(!BLOCKED_RPC_METHODS.includes(args.method), _rpcerrors.rpcErrors.methodNotFound({
|
|
114
100
|
data: {
|
|
115
101
|
method: args.method
|
|
116
102
|
}
|
|
117
103
|
}));
|
|
118
|
-
(0, _utils.assertStruct)(args, _utils.JsonStruct, 'Provided value is not JSON-RPC compatible');
|
|
104
|
+
(0, _utils.assertStruct)(args, _utils.JsonStruct, 'Provided value is not JSON-RPC compatible', _rpcerrors.rpcErrors.invalidParams);
|
|
119
105
|
}
|
|
120
106
|
function assertEthereumOutboundRequest(args) {
|
|
121
107
|
// Disallow snaps methods for separation of concerns.
|
|
122
|
-
(0, _utils.assert)(!String.prototype.startsWith.call(args.method, 'snap_'),
|
|
108
|
+
(0, _utils.assert)(!String.prototype.startsWith.call(args.method, 'snap_'), _rpcerrors.rpcErrors.methodNotFound({
|
|
123
109
|
data: {
|
|
124
110
|
method: args.method
|
|
125
111
|
}
|
|
126
112
|
}));
|
|
127
|
-
(0, _utils.assert)(!BLOCKED_RPC_METHODS.includes(args.method),
|
|
113
|
+
(0, _utils.assert)(!BLOCKED_RPC_METHODS.includes(args.method), _rpcerrors.rpcErrors.methodNotFound({
|
|
128
114
|
data: {
|
|
129
115
|
method: args.method
|
|
130
116
|
}
|
|
131
117
|
}));
|
|
132
|
-
(0, _utils.assertStruct)(args, _utils.JsonStruct, 'Provided value is not JSON-RPC compatible');
|
|
118
|
+
(0, _utils.assertStruct)(args, _utils.JsonStruct, 'Provided value is not JSON-RPC compatible', _rpcerrors.rpcErrors.invalidParams);
|
|
133
119
|
}
|
|
134
120
|
function sanitizeRequestArguments(value) {
|
|
135
121
|
// Before passing to getSafeJson we run the value through JSON serialization.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/utils.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/common/utils.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { assert, assertStruct, getSafeJson, JsonStruct } from '@metamask/utils';\n\nimport { log } from '../logging';\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<Type>(\n originalPromise: Promise<Type>,\n teardownRef: { lastTeardown: number },\n): Promise<Type> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<Type>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that narrows down (attenuates) the fields available on\n * the StreamProvider and replaces the request implementation.\n *\n * @param provider - Instance of a StreamProvider to be limited.\n * @param request - Custom attenuated request object.\n * @returns Proxy to the StreamProvider instance.\n */\nexport function proxyStreamProvider(\n provider: StreamProvider,\n request: unknown,\n): StreamProvider {\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return (\n typeof prop === 'string' &&\n ['request', 'on', 'removeListener'].includes(prop)\n );\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return provider[prop];\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these RPC methods for v1, will revisit later.\nexport const BLOCKED_RPC_METHODS = Object.freeze([\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\n // We disallow all of these confirmations for now, since the screens are not ready for Snaps.\n 'eth_sendRawTransaction',\n 'eth_sendTransaction',\n 'eth_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v1',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'eth_decrypt',\n 'eth_getEncryptionPublicKey',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_watchAsset',\n 'wallet_registerOnboarding',\n 'wallet_scanQRCode',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n rpcErrors.methodNotSupported,\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(\n args,\n JsonStruct,\n 'Provided value is not JSON-RPC compatible',\n rpcErrors.invalidParams,\n );\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(\n args,\n JsonStruct,\n 'Provided value is not JSON-RPC compatible',\n rpcErrors.invalidParams,\n );\n}\n\n/**\n * Gets a sanitized value to be used for passing to the underlying MetaMask provider.\n *\n * @param value - An unsanitized value from a snap.\n * @returns A sanitized value ready to be passed to a MetaMask provider.\n */\nexport function sanitizeRequestArguments(value: unknown): RequestArguments {\n // Before passing to getSafeJson we run the value through JSON serialization.\n // This lets request arguments contain undefined which is normally disallowed.\n const json = JSON.parse(JSON.stringify(value));\n return getSafeJson(json) as RequestArguments;\n}\n"],"names":["withTeardown","proxyStreamProvider","BLOCKED_RPC_METHODS","assertSnapOutboundRequest","assertEthereumOutboundRequest","sanitizeRequestArguments","originalPromise","teardownRef","myTeardown","lastTeardown","Promise","resolve","reject","then","value","log","catch","reason","provider","request","proxy","Proxy","has","_target","prop","includes","get","undefined","Object","freeze","args","assert","String","prototype","startsWith","call","method","rpcErrors","methodNotSupported","methodNotFound","data","assertStruct","JsonStruct","invalidParams","json","JSON","parse","stringify","getSafeJson"],"mappings":";;;;;;;;;;;IAgBsBA,YAAY;eAAZA;;IAoCNC,mBAAmB;eAAnBA;;IA+BHC,mBAAmB;eAAnBA;;IAyBGC,yBAAyB;eAAzBA;;IA6BAC,6BAA6B;eAA7BA;;IAgCAC,wBAAwB;eAAxBA;;;2BAvKU;uBACoC;yBAE1C;AAWb,eAAeL,aACpBM,eAA8B,EAC9BC,WAAqC;IAErC,MAAMC,aAAaD,YAAYE,YAAY;IAC3C,OAAO,IAAIC,QAAc,CAACC,SAASC;QACjCN,gBACGO,IAAI,CAAC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MAAM;QACrB;IACF;IAEFK,IAAAA,mBAAY,EACVX,MACAY,iBAAU,EACV,6CACAL,oBAAS,CAACM,aAAa;AAE3B;AAOO,SAASvC,8BAA8B0B,IAAsB;IAClE,qDAAqD;IACrDC,IAAAA,aAAM,EACJ,CAACC,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACL,KAAKM,MAAM,EAAE,UAC/CC,oBAAS,CAACE,cAAc,CAAC;QACvBC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFL,IAAAA,aAAM,EACJ,CAAC7B,oBAAoBuB,QAAQ,CAACK,KAAKM,MAAM,GACzCC,oBAAS,CAACE,cAAc,CAAC;QACvBC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFK,IAAAA,mBAAY,EACVX,MACAY,iBAAU,EACV,6CACAL,oBAAS,CAACM,aAAa;AAE3B;AAQO,SAAStC,yBAAyBS,KAAc;IACrD,6EAA6E;IAC7E,8EAA8E;IAC9E,MAAM8B,OAAOC,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAACjC;IACvC,OAAOkC,IAAAA,kBAAW,EAACJ;AACrB"}
|
|
@@ -46,6 +46,7 @@ _export(exports, {
|
|
|
46
46
|
return assertIsOnNameLookupRequestArguments;
|
|
47
47
|
}
|
|
48
48
|
});
|
|
49
|
+
const _rpcerrors = require("@metamask/rpc-errors");
|
|
49
50
|
const _snapsutils = require("@metamask/snaps-utils");
|
|
50
51
|
const _utils = require("@metamask/utils");
|
|
51
52
|
const _superstruct = require("superstruct");
|
|
@@ -90,7 +91,7 @@ const OnTransactionRequestArgumentsStruct = (0, _superstruct.object)({
|
|
|
90
91
|
transactionOrigin: (0, _superstruct.nullable)((0, _superstruct.string)())
|
|
91
92
|
});
|
|
92
93
|
function assertIsOnTransactionRequestArguments(value) {
|
|
93
|
-
(0, _utils.assertStruct)(value, OnTransactionRequestArgumentsStruct, 'Invalid request params');
|
|
94
|
+
(0, _utils.assertStruct)(value, OnTransactionRequestArgumentsStruct, 'Invalid request params', _rpcerrors.rpcErrors.invalidParams);
|
|
94
95
|
}
|
|
95
96
|
const baseNameLookupArgs = {
|
|
96
97
|
chainId: _snapsutils.ChainIdStruct
|
|
@@ -108,7 +109,7 @@ const OnNameLookupRequestArgumentsStruct = (0, _superstruct.union)([
|
|
|
108
109
|
addressRequestStruct
|
|
109
110
|
]);
|
|
110
111
|
function assertIsOnNameLookupRequestArguments(value) {
|
|
111
|
-
(0, _utils.assertStruct)(value, OnNameLookupRequestArgumentsStruct, 'Invalid request params');
|
|
112
|
+
(0, _utils.assertStruct)(value, OnNameLookupRequestArgumentsStruct, 'Invalid request params', _rpcerrors.rpcErrors.invalidParams);
|
|
112
113
|
}
|
|
113
114
|
const OkResponseStruct = (0, _superstruct.assign)(_utils.JsonRpcSuccessStruct, (0, _superstruct.object)({
|
|
114
115
|
result: OkStruct
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n optional(array(EndowmentStruct)),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n );\n}\n\nconst OkResponseStruct = assign(\n JsonRpcSuccessStruct,\n object({\n result: OkStruct,\n }),\n);\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["JsonRpcRequestWithoutIdStruct","EndowmentStruct","isEndowment","isEndowmentsArray","PingRequestArgumentsStruct","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","OnTransactionRequestArgumentsStruct","assertIsOnTransactionRequestArguments","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","assign","omit","JsonRpcRequestStruct","object","id","optional","JsonRpcIdStruct","string","value","is","Array","isArray","every","OkStruct","literal","union","undefined","array","tuple","enums","Object","values","HandlerType","params","record","JsonStruct","transaction","chainId","ChainIdStruct","transactionOrigin","nullable","assertStruct","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OkResponseStruct","JsonRpcSuccessStruct","result","SnapRpcResponse"],"mappings":";;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n optional(array(EndowmentStruct)),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst OkResponseStruct = assign(\n JsonRpcSuccessStruct,\n object({\n result: OkStruct,\n }),\n);\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["JsonRpcRequestWithoutIdStruct","EndowmentStruct","isEndowment","isEndowmentsArray","PingRequestArgumentsStruct","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","OnTransactionRequestArgumentsStruct","assertIsOnTransactionRequestArguments","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","assign","omit","JsonRpcRequestStruct","object","id","optional","JsonRpcIdStruct","string","value","is","Array","isArray","every","OkStruct","literal","union","undefined","array","tuple","enums","Object","values","HandlerType","params","record","JsonStruct","transaction","chainId","ChainIdStruct","transactionOrigin","nullable","assertStruct","rpcErrors","invalidParams","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OkResponseStruct","JsonRpcSuccessStruct","result","SnapRpcResponse"],"mappings":";;;;;;;;;;;IA2BaA,6BAA6B;eAA7BA;;IAWAC,eAAe;eAAfA;;IASGC,WAAW;eAAXA;;IAUAC,iBAAiB;eAAjBA;;IAMHC,0BAA0B;eAA1BA;;IAIAC,+BAA+B;eAA/BA;;IAKAC,iCAAiC;eAAjCA;;IAMAC,6BAA6B;eAA7BA;;IA+BAC,mCAAmC;eAAnCA;;IAmBGC,qCAAqC;eAArCA;;IAqBHC,kCAAkC;eAAlCA;;IAsBGC,oCAAoC;eAApCA;;;2BA3KU;4BACiB;uBAQpC;6BAgBA;AAEA,MAAMX,gCAAgCY,IAAAA,mBAAM,EACjDC,IAAAA,iBAAI,EAACC,2BAAoB,EAAE;IAAC;CAAK,GACjCC,IAAAA,mBAAM,EAAC;IACLC,IAAIC,IAAAA,qBAAQ,EAACC,sBAAe;AAC9B;AAOK,MAAMjB,kBAAkBkB,IAAAA,mBAAM;AAS9B,SAASjB,YAAYkB,KAAc;IACxC,OAAOC,IAAAA,eAAE,EAACD,OAAOnB;AACnB;AAQO,SAASE,kBAAkBiB,KAAc;IAC9C,OAAOE,MAAMC,OAAO,CAACH,UAAUA,MAAMI,KAAK,CAACtB;AAC7C;AAEA,MAAMuB,WAAWC,IAAAA,oBAAO,EAAC;AAElB,MAAMtB,6BAA6Ba,IAAAA,qBAAQ,EAChDU,IAAAA,kBAAK,EAAC;IAACD,IAAAA,oBAAO,EAACE;IAAYC,IAAAA,kBAAK;CAAG;AAG9B,MAAMxB,kCAAkCsB,IAAAA,kBAAK,EAAC;IACnDD,IAAAA,oBAAO,EAACE;IACRC,IAAAA,kBAAK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C,2BAAoB,EACpBrC,IAAAA,mBAAM,EAAC;IACLsC,QAAQ5B;AACV;AAGF,MAAM6B,kBAAkBF,2BAAoB"}
|
|
@@ -13,23 +13,26 @@ function _define_property(obj, key, value) {
|
|
|
13
13
|
}
|
|
14
14
|
return obj;
|
|
15
15
|
}
|
|
16
|
+
import { createIdRemapMiddleware } from '@metamask/json-rpc-engine';
|
|
16
17
|
import { StreamProvider } from '@metamask/providers';
|
|
17
|
-
import {
|
|
18
|
+
import { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';
|
|
19
|
+
import { SNAP_EXPORT_NAMES, logError, SNAP_EXPORTS, WrappedSnapError, getErrorData, unwrapError } from '@metamask/snaps-utils';
|
|
18
20
|
import { isObject, isValidJson, assert, isJsonRpcRequest, hasProperty, getSafeJson } from '@metamask/utils';
|
|
19
|
-
import { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';
|
|
20
|
-
import { createIdRemapMiddleware } from 'json-rpc-engine';
|
|
21
21
|
import { validate } from 'superstruct';
|
|
22
22
|
import { log } from '../logging';
|
|
23
23
|
import { getCommandMethodImplementations } from './commands';
|
|
24
24
|
import { createEndowments } from './endowments';
|
|
25
25
|
import { addEventListener, removeEventListener } from './globalEvents';
|
|
26
26
|
import { sortParamKeys } from './sortParams';
|
|
27
|
-
import { assertEthereumOutboundRequest, assertSnapOutboundRequest,
|
|
27
|
+
import { assertEthereumOutboundRequest, assertSnapOutboundRequest, sanitizeRequestArguments, proxyStreamProvider, withTeardown } from './utils';
|
|
28
28
|
import { ExecuteSnapRequestArgumentsStruct, PingRequestArgumentsStruct, SnapRpcRequestArgumentsStruct, TerminateRequestArgumentsStruct } from './validation';
|
|
29
29
|
const fallbackError = {
|
|
30
30
|
code: errorCodes.rpc.internal,
|
|
31
31
|
message: 'Execution Environment Error'
|
|
32
32
|
};
|
|
33
|
+
const unhandledError = rpcErrors.internal({
|
|
34
|
+
message: 'Unhandled Snap Error'
|
|
35
|
+
}).serialize();
|
|
33
36
|
/**
|
|
34
37
|
* The supported methods in the execution environment. The validator checks the
|
|
35
38
|
* incoming JSON-RPC request, and the `params` property is used for sorting the
|
|
@@ -63,34 +66,35 @@ const fallbackError = {
|
|
|
63
66
|
};
|
|
64
67
|
export class BaseSnapExecutor {
|
|
65
68
|
errorHandler(error, data) {
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
fallbackError,
|
|
69
|
+
const serializedError = serializeError(error, {
|
|
70
|
+
fallbackError: unhandledError,
|
|
69
71
|
shouldIncludeStack: false
|
|
70
72
|
});
|
|
71
|
-
|
|
72
|
-
const sentData = {
|
|
73
|
-
...data,
|
|
74
|
-
stack: constructedError?.stack ?? null
|
|
75
|
-
};
|
|
73
|
+
const errorData = getErrorData(serializedError);
|
|
76
74
|
this.notify({
|
|
77
75
|
method: 'UnhandledError',
|
|
78
76
|
params: {
|
|
79
77
|
error: {
|
|
80
78
|
...serializedError,
|
|
81
|
-
data:
|
|
79
|
+
data: {
|
|
80
|
+
...errorData,
|
|
81
|
+
...data
|
|
82
|
+
}
|
|
82
83
|
}
|
|
83
84
|
}
|
|
84
85
|
});
|
|
85
86
|
}
|
|
86
87
|
async onCommandRequest(message) {
|
|
87
88
|
if (!isJsonRpcRequest(message)) {
|
|
88
|
-
throw
|
|
89
|
+
throw rpcErrors.invalidRequest({
|
|
90
|
+
message: 'Command stream received a non-JSON-RPC request.',
|
|
91
|
+
data: message
|
|
92
|
+
});
|
|
89
93
|
}
|
|
90
94
|
const { id, method, params } = message;
|
|
91
95
|
if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {
|
|
92
96
|
this.respond(id, {
|
|
93
|
-
error:
|
|
97
|
+
error: rpcErrors.methodNotFound({
|
|
94
98
|
data: {
|
|
95
99
|
method
|
|
96
100
|
}
|
|
@@ -104,7 +108,7 @@ export class BaseSnapExecutor {
|
|
|
104
108
|
const [error] = validate(paramsAsArray, methodObject.struct);
|
|
105
109
|
if (error) {
|
|
106
110
|
this.respond(id, {
|
|
107
|
-
error:
|
|
111
|
+
error: rpcErrors.invalidParams({
|
|
108
112
|
message: `Invalid parameters for method "${method}": ${error.message}.`,
|
|
109
113
|
data: {
|
|
110
114
|
method,
|
|
@@ -129,7 +133,7 @@ export class BaseSnapExecutor {
|
|
|
129
133
|
}
|
|
130
134
|
notify(requestObject) {
|
|
131
135
|
if (!isValidJson(requestObject) || !isObject(requestObject)) {
|
|
132
|
-
throw
|
|
136
|
+
throw rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects');
|
|
133
137
|
}
|
|
134
138
|
this.commandStream.write({
|
|
135
139
|
...requestObject,
|
|
@@ -141,9 +145,7 @@ export class BaseSnapExecutor {
|
|
|
141
145
|
// Instead of throwing, we directly respond with an error.
|
|
142
146
|
// This prevents an issue where we wouldn't respond when errors were non-serializable
|
|
143
147
|
this.commandStream.write({
|
|
144
|
-
error: serializeError(
|
|
145
|
-
fallbackError
|
|
146
|
-
}),
|
|
148
|
+
error: serializeError(rpcErrors.internal('JSON-RPC responses must be JSON serializable objects.')),
|
|
147
149
|
id,
|
|
148
150
|
jsonrpc: '2.0'
|
|
149
151
|
});
|
|
@@ -223,7 +225,13 @@ export class BaseSnapExecutor {
|
|
|
223
225
|
});
|
|
224
226
|
} catch (error) {
|
|
225
227
|
this.removeSnap(snapId);
|
|
226
|
-
|
|
228
|
+
const [cause] = unwrapError(error);
|
|
229
|
+
throw rpcErrors.internal({
|
|
230
|
+
message: `Error while running snap '${snapId}': ${cause.message}`,
|
|
231
|
+
data: {
|
|
232
|
+
cause: cause.serialize()
|
|
233
|
+
}
|
|
234
|
+
});
|
|
227
235
|
}
|
|
228
236
|
}
|
|
229
237
|
/**
|
|
@@ -336,11 +344,11 @@ export class BaseSnapExecutor {
|
|
|
336
344
|
*/ async executeInSnapContext(snapId, executor) {
|
|
337
345
|
const data = this.snapData.get(snapId);
|
|
338
346
|
if (data === undefined) {
|
|
339
|
-
throw
|
|
347
|
+
throw rpcErrors.internal(`Tried to execute in context of unknown snap: "${snapId}".`);
|
|
340
348
|
}
|
|
341
349
|
let stop;
|
|
342
350
|
const stopPromise = new Promise((_, reject)=>stop = ()=>reject(// TODO(rekmarks): Specify / standardize error code for this case.
|
|
343
|
-
|
|
351
|
+
rpcErrors.internal(`The snap "${snapId}" has been terminated during execution.`)));
|
|
344
352
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
345
353
|
const evaluationData = {
|
|
346
354
|
stop: stop
|
|
@@ -354,6 +362,8 @@ export class BaseSnapExecutor {
|
|
|
354
362
|
executor(),
|
|
355
363
|
stopPromise
|
|
356
364
|
]);
|
|
365
|
+
} catch (error) {
|
|
366
|
+
throw new WrappedSnapError(error);
|
|
357
367
|
} finally{
|
|
358
368
|
data.runningEvaluations.delete(evaluationData);
|
|
359
369
|
if (data.runningEvaluations.size === 0) {
|
|
@@ -385,14 +395,14 @@ export class BaseSnapExecutor {
|
|
|
385
395
|
// before the call.
|
|
386
396
|
const handler = data?.exports[handlerType];
|
|
387
397
|
const { required } = SNAP_EXPORTS[handlerType];
|
|
388
|
-
assert(!required || handler !== undefined, `No ${handlerType} handler exported for snap "${target}
|
|
398
|
+
assert(!required || handler !== undefined, `No ${handlerType} handler exported for snap "${target}`, rpcErrors.methodNotSupported);
|
|
389
399
|
// Certain handlers are not required. If they are not exported, we
|
|
390
400
|
// return null.
|
|
391
401
|
if (!handler) {
|
|
392
402
|
return null;
|
|
393
403
|
}
|
|
394
|
-
|
|
395
|
-
|
|
404
|
+
let result = await this.executeInSnapContext(target, ()=>// TODO: fix handler args type cast
|
|
405
|
+
handler(args));
|
|
396
406
|
// The handler might not return anything, but undefined is not valid JSON.
|
|
397
407
|
if (result === undefined) {
|
|
398
408
|
result = null;
|
|
@@ -401,7 +411,7 @@ export class BaseSnapExecutor {
|
|
|
401
411
|
try {
|
|
402
412
|
return getSafeJson(result);
|
|
403
413
|
} catch (error) {
|
|
404
|
-
throw
|
|
414
|
+
throw rpcErrors.internal(`Received non-JSON-serializable value: ${error.message.replace(/^Assertion failed: /u, '')}`);
|
|
405
415
|
}
|
|
406
416
|
}, this.onTerminate.bind(this));
|
|
407
417
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport type { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n constructError,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n // TODO: fix handler args type cast\n let result = await this.executeInSnapContext(target, () =>\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw new TypeError(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const constructedError = constructError(error);\n const serializedError = serializeError(constructedError, {\n fallbackError,\n shouldIncludeStack: false,\n });\n\n // We're setting it this way to avoid sentData.stack = undefined\n const sentData: Json = { ...data, stack: constructedError?.stack ?? null };\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: sentData,\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw new Error('Command stream received a non-JSON-RPC request.');\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n this.respond(id, {\n error: ethErrors.rpc\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n this.commandStream.write({\n error: serializeError(\n new Error('JSON-RPC responses must be JSON serializable objects.'),\n {\n fallbackError,\n },\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n snapId,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n throw new Error(\n `Error while running snap '${snapId}': ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(sanitizedArgs), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(sanitizedArgs), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n ethErrors.rpc.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["StreamProvider","SNAP_EXPORT_NAMES","logError","SNAP_EXPORTS","isObject","isValidJson","assert","isJsonRpcRequest","hasProperty","getSafeJson","errorCodes","ethErrors","serializeError","createIdRemapMiddleware","validate","log","getCommandMethodImplementations","createEndowments","addEventListener","removeEventListener","sortParamKeys","assertEthereumOutboundRequest","assertSnapOutboundRequest","constructError","sanitizeRequestArguments","proxyStreamProvider","withTeardown","ExecuteSnapRequestArgumentsStruct","PingRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","TerminateRequestArgumentsStruct","fallbackError","code","rpc","internal","message","EXECUTION_ENVIRONMENT_METHODS","ping","struct","params","executeSnap","terminate","snapRpc","BaseSnapExecutor","errorHandler","error","data","constructedError","serializedError","shouldIncludeStack","sentData","stack","notify","method","onCommandRequest","Error","id","respond","methodNotFound","serialize","methodObject","paramsAsArray","invalidParams","result","methods","rpcError","requestObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","snapPromiseErrorHandler","snapErrorHandler","reason","provider","rpcStream","jsonRpcStreamName","rpcMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","snapData","set","idleTeardown","runningEvaluations","Set","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","onTerminate","forEach","evaluation","stop","clear","get","reduce","acc","exportName","snapExport","validator","originalRequest","request","bind","args","sanitizedArgs","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","streamProviderProxy","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","Map","on","catch","target","handlerType","handler","required","TypeError","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;;;;;;;;;;AAChE,SAASA,cAAc,QAAQ,sBAAsB;AAQrD,SACEC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,QACP,wBAAwB;AAO/B,SACEC,QAAQ,EACRC,WAAW,EACXC,MAAM,EACNC,gBAAgB,EAChBC,WAAW,EACXC,WAAW,QACN,kBAAkB;AACzB,SAASC,UAAU,EAAEC,SAAS,EAAEC,cAAc,QAAQ,iBAAiB;AACvE,SAASC,uBAAuB,QAAQ,kBAAkB;AAE1D,SAASC,QAAQ,QAAQ,cAAc;AAEvC,SAASC,GAAG,QAAQ,aAAa;AAEjC,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,gBAAgB,QAAQ,eAAe;AAChD,SAASC,gBAAgB,EAAEC,mBAAmB,QAAQ,iBAAiB;AACvE,SAASC,aAAa,QAAQ,eAAe;AAC7C,SACEC,6BAA6B,EAC7BC,yBAAyB,EACzBC,cAAc,EACdC,wBAAwB,EACxBC,mBAAmB,EACnBC,YAAY,QACP,UAAU;AACjB,SACEC,iCAAiC,EACjCC,0BAA0B,EAC1BC,6BAA6B,EAC7BC,+BAA+B,QAC1B,eAAe;AAYtB,MAAMC,gBAAgB;IACpBC,MAAMtB,WAAWuB,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAUA;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQV;QACRW,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXF,QAAQX;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AACd,OAAO,GAAGhD,gCACb,IAAI,CAACsD,SAAS,CAACkD,IAAI,CAAC,IAAI,GACxB,OAAO0B,QAAQC,aAAa1B;YAC1B,MAAM3E,OAAO,IAAI,CAAC6C,QAAQ,CAACqB,GAAG,CAACkC;YAC/B,uEAAuE;YACvE,mBAAmB;YACnB,MAAME,UAAUtG,MAAMyC,OAAO,CAAC4D,YAAY;YAC1C,MAAM,EAAEE,QAAQ,EAAE,GAAGlJ,YAAY,CAACgJ,YAAY;YAE9C7I,OACE,CAAC+I,YAAYD,YAAYnB,WACzB,CAAC,GAAG,EAAEkB,YAAY,4BAA4B,EAAED,OAAO,CAAC;YAG1D,kEAAkE;YAClE,eAAe;YACf,IAAI,CAACE,SAAS;gBACZ,OAAO;YACT;YAEA,mCAAmC;YACnC,IAAIrF,SAAS,MAAM,IAAI,CAACwC,oBAAoB,CAAC2C,QAAQ,IACnDE,QAAQ3B;YAGV,0EAA0E;YAC1E,IAAI1D,WAAWkE,WAAW;gBACxBlE,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAOtD,YAAYsD;YACrB,EAAE,OAAOlB,OAAO;gBACd,MAAM,IAAIyG,UACR,CAAC,sCAAsC,EAAEzG,MAAMV,OAAO,CAACoH,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAAC5C,WAAW,CAACa,IAAI,CAAC,IAAI;IAE9B;AAwWF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsGlobalObject } from '@metamask/snaps-rpc-methods';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n getErrorData,\n unwrapError,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw rpcErrors.invalidRequest({\n message: 'Command stream received a non-JSON-RPC request.',\n data: message,\n });\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n this.respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n this.commandStream.write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n snapId,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(sanitizedArgs), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(sanitizedArgs), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["createIdRemapMiddleware","StreamProvider","errorCodes","rpcErrors","serializeError","SNAP_EXPORT_NAMES","logError","SNAP_EXPORTS","WrappedSnapError","getErrorData","unwrapError","isObject","isValidJson","assert","isJsonRpcRequest","hasProperty","getSafeJson","validate","log","getCommandMethodImplementations","createEndowments","addEventListener","removeEventListener","sortParamKeys","assertEthereumOutboundRequest","assertSnapOutboundRequest","sanitizeRequestArguments","proxyStreamProvider","withTeardown","ExecuteSnapRequestArgumentsStruct","PingRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","TerminateRequestArgumentsStruct","fallbackError","code","rpc","internal","message","unhandledError","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","params","executeSnap","terminate","snapRpc","BaseSnapExecutor","errorHandler","error","data","serializedError","shouldIncludeStack","errorData","notify","method","onCommandRequest","invalidRequest","id","respond","methodNotFound","methodObject","paramsAsArray","invalidParams","result","methods","rpcError","requestObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","snapPromiseErrorHandler","snapErrorHandler","Error","reason","provider","rpcStream","jsonRpcStreamName","rpcMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","snapData","set","idleTeardown","runningEvaluations","Set","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","cause","onTerminate","forEach","evaluation","stop","clear","get","reduce","acc","exportName","snapExport","validator","originalRequest","request","bind","args","sanitizedArgs","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","streamProviderProxy","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","Map","on","catch","target","handlerType","handler","required","methodNotSupported","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;;;;;;;;;;AAChE,SAASA,uBAAuB,QAAQ,4BAA4B;AACpE,SAASC,cAAc,QAAQ,sBAAsB;AAErD,SAASC,UAAU,EAAEC,SAAS,EAAEC,cAAc,QAAQ,uBAAuB;AAO7E,SACEC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,EACZC,gBAAgB,EAChBC,YAAY,EACZC,WAAW,QACN,wBAAwB;AAO/B,SACEC,QAAQ,EACRC,WAAW,EACXC,MAAM,EACNC,gBAAgB,EAChBC,WAAW,EACXC,WAAW,QACN,kBAAkB;AAEzB,SAASC,QAAQ,QAAQ,cAAc;AAEvC,SAASC,GAAG,QAAQ,aAAa;AAEjC,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,gBAAgB,QAAQ,eAAe;AAChD,SAASC,gBAAgB,EAAEC,mBAAmB,QAAQ,iBAAiB;AACvE,SAASC,aAAa,QAAQ,eAAe;AAC7C,SACEC,6BAA6B,EAC7BC,yBAAyB,EACzBC,wBAAwB,EACxBC,mBAAmB,EACnBC,YAAY,QACP,UAAU;AACjB,SACEC,iCAAiC,EACjCC,0BAA0B,EAC1BC,6BAA6B,EAC7BC,+BAA+B,QAC1B,eAAe;AAYtB,MAAMC,gBAAgB;IACpBC,MAAMhC,WAAWiC,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAEA,MAAMC,iBAAiBnC,UACpBiC,QAAQ,CAAO;IACdC,SAAS;AACX,GACCE,SAAS;AAUZ;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQZ;QACRa,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXF,QAAQb;QACRc,QAAQ;YAAC;YAAU;YAAc;SAAa;IAChD;IACAE,WAAW;QACTH,QAAQV;QACRW,QAAQ,EAAE;IACZ;IACAG,SAAS;QACPJ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AAC+B,SAAS,GAAGA;QAEjB,IAAI,CAACf,OAAO,GAAG9C,gCACb,IAAI,CAACoD,SAAS,CAACoD,IAAI,CAAC,IAAI,GACxB,OAAO0B,QAAQC,aAAa1B;YAC1B,MAAM1E,OAAO,IAAI,CAAC2C,QAAQ,CAACsB,GAAG,CAACkC;YAC/B,uEAAuE;YACvE,mBAAmB;YACnB,MAAME,UAAUrG,MAAMuC,OAAO,CAAC6D,YAAY;YAC1C,MAAM,EAAEE,QAAQ,EAAE,GAAGjJ,YAAY,CAAC+I,YAAY;YAE9CzI,OACE,CAAC2I,YAAYD,YAAYnB,WACzB,CAAC,GAAG,EAAEkB,YAAY,4BAA4B,EAAED,OAAO,CAAC,EACxDlJ,UAAUsJ,kBAAkB;YAG9B,kEAAkE;YAClE,eAAe;YACf,IAAI,CAACF,SAAS;gBACZ,OAAO;YACT;YAEA,IAAIvF,SAAS,MAAM,IAAI,CAACyC,oBAAoB,CAAC4C,QAAQ,IACnD,mCAAmC;gBACnCE,QAAQ3B;YAGV,0EAA0E;YAC1E,IAAI5D,WAAWoE,WAAW;gBACxBpE,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAOhD,YAAYgD;YACrB,EAAE,OAAOf,OAAO;gBACd,MAAM9C,UAAUiC,QAAQ,CACtB,CAAC,sCAAsC,EAAEa,MAAMZ,OAAO,CAACqH,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAAC5C,WAAW,CAACa,IAAI,CAAC,IAAI;IAE9B;AAmXF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["HandlerType","assertExhaustive","assertIsOnTransactionRequestArguments","assertIsOnNameLookupRequestArguments","getHandlerArguments","origin","handler","request","OnTransaction","params","transaction","chainId","transactionOrigin","OnNameLookup","domain","address","OnRpcRequest","OnCronjob","OnInstall","OnUpdate","getCommandMethodImplementations","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":"AAAA,SAASA,WAAW,QAAQ,wBAAwB;AACpD,SAASC,gBAAgB,QAAQ,kBAAkB;AAWnD,SACEC,qCAAqC,EACrCC,oCAAoC,QAC/B,eAAe;AAStB;;;;;;;CAOC,GACD,OAAO,SAASC,oBACdC,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKN,YAAYQ,aAAa;YAAE;gBAC9BN,sCAAsCK,QAAQE,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGL,QAAQE,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKZ,YAAYa,YAAY;YAAE;gBAC7BV,qCAAqCI,QAAQE,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEG,MAAM,EAAEC,OAAO,EAAE,GAChCR,QAAQE,MAAM;gBAEhB,OAAOK,SACH;oBACEH;oBACAG;gBACF,IACA;oBACEH;oBACAI;gBACF;YACN;QACA,KAAKf,YAAYgB,YAAY;
|
|
1
|
+
{"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["HandlerType","assertExhaustive","assertIsOnTransactionRequestArguments","assertIsOnNameLookupRequestArguments","getHandlerArguments","origin","handler","request","OnTransaction","params","transaction","chainId","transactionOrigin","OnNameLookup","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","getCommandMethodImplementations","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":"AAAA,SAASA,WAAW,QAAQ,wBAAwB;AACpD,SAASC,gBAAgB,QAAQ,kBAAkB;AAWnD,SACEC,qCAAqC,EACrCC,oCAAoC,QAC/B,eAAe;AAStB;;;;;;;CAOC,GACD,OAAO,SAASC,oBACdC,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKN,YAAYQ,aAAa;YAAE;gBAC9BN,sCAAsCK,QAAQE,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGL,QAAQE,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKZ,YAAYa,YAAY;YAAE;gBAC7BV,qCAAqCI,QAAQE,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEG,MAAM,EAAEC,OAAO,EAAE,GAChCR,QAAQE,MAAM;gBAEhB,OAAOK,SACH;oBACEH;oBACAG;gBACF,IACA;oBACEH;oBACAI;gBACF;YACN;QACA,KAAKf,YAAYgB,YAAY;QAC7B,KAAKhB,YAAYiB,gBAAgB;YAC/B,OAAO;gBAAEZ;gBAAQE;YAAQ;QAE3B,KAAKP,YAAYkB,SAAS;QAC1B,KAAKlB,YAAYmB,SAAS;QAC1B,KAAKnB,YAAYoB,QAAQ;YACvB,OAAO;gBAAEb;YAAQ;QAEnB;YACE,OAAON,iBAAiBK;IAC5B;AACF;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASe,gCACdC,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQ5B,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMgB,WACLW,QACA5B,SACAF,oBAAoBC,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/common/endowments/console.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\nexport const consoleAttenuatedMethods = new Set([\n 'log',\n 'assert',\n 'error',\n 'debug',\n 'info',\n 'warn',\n]);\n\n/**\n * A set of all the `console` values that will be passed to the snap. This has\n * all the values that are available in both the browser and Node.js.\n */\nexport const consoleMethods = new Set([\n 'debug',\n 'error',\n 'info',\n 'log',\n 'warn',\n 'dir',\n 'dirxml',\n 'table',\n 'trace',\n 'group',\n 'groupCollapsed',\n 'groupEnd',\n 'clear',\n 'count',\n 'countReset',\n 'assert',\n 'profile',\n 'profileEnd',\n 'time',\n 'timeLog',\n 'timeEnd',\n 'timeStamp',\n 'context',\n]);\n\nconst consoleFunctions = ['log', 'error', 'debug', 'info', 'warn'] as const;\n\ntype ConsoleFunctions = {\n [Key in typeof consoleFunctions[number]]: typeof rootRealmGlobal.console[Key];\n};\n\n/**\n * Gets the appropriate (prepended) message to pass to one of the attenuated\n * method calls.\n *\n * @param snapId - Id of the snap that we're getting a message for.\n * @param message - The id of the snap that will interact with the endowment.\n * @param args - The array of additional arguments.\n * @returns An array of arguments to be passed into an attenuated console method call.\n */\nfunction getMessage(snapId: SnapId, message: unknown, ...args: unknown[]) {\n const prefix = `[Snap: ${snapId}]`;\n\n // If the first argument is a string, prepend the prefix to the message, and keep the\n // rest of the arguments as-is.\n if (typeof message === 'string') {\n return [`${prefix} ${message}`, ...args];\n }\n\n // Otherwise, the `message` is an object, array, etc., so add the prefix as a separate\n // message to the arguments.\n return [prefix, message, ...args];\n}\n\n/**\n * Create a a {@link console} object, with the same properties as the global\n * {@link console} object, but with some methods replaced.\n *\n * @param options - Factory options used in construction of the endowment.\n * @param options.snapId - The id of the snap that will interact with the endowment.\n * @returns The {@link console} object with the replaced methods.\n */\nfunction createConsole({ snapId }: EndowmentFactoryOptions = {}) {\n assert(snapId !== undefined);\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.console,\n ) as (keyof typeof console)[];\n\n const attenuatedConsole = keys.reduce((target, key) => {\n if (consoleMethods.has(key) && !consoleAttenuatedMethods.has(key)) {\n return { ...target, [key]: rootRealmGlobal.console[key] };\n }\n\n return target;\n }, {});\n\n return harden({\n console: {\n ...attenuatedConsole,\n assert: (\n value: any,\n message?: string | undefined,\n ...optionalParams: any[]\n ) => {\n rootRealmGlobal.console.assert(\n value,\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n ...consoleFunctions.reduce<ConsoleFunctions>((target, key) => {\n return {\n ...target,\n [key]: (message?: unknown, ...optionalParams: any[]) => {\n rootRealmGlobal.console[key](\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n };\n }, {} as ConsoleFunctions),\n },\n });\n}\n\nconst endowmentModule = {\n names: ['console'] as const,\n factory: createConsole,\n};\n\nexport default endowmentModule;\n"],"names":["assert","rootRealmGlobal","consoleAttenuatedMethods","Set","consoleMethods","consoleFunctions","getMessage","snapId","message","args","prefix","createConsole","undefined","keys","Object","getOwnPropertyNames","console","attenuatedConsole","reduce","target","key","has","harden","value","optionalParams","endowmentModule","names","factory"],"mappings":"AACA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC,SAASC,eAAe,QAAQ,kBAAkB;AAGlD,OAAO,MAAMC,2BAA2B,IAAIC,IAAI;IAC9C;IACA;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH;;;CAGC,GACD,OAAO,MAAMC,iBAAiB,IAAID,IAAI;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH,MAAME,mBAAmB;IAAC;IAAO;IAAS;IAAS;IAAQ;CAAO;AAMlE;;;;;;;;CAQC,GACD,SAASC,WAAWC,MAAc,EAAEC,OAAgB,EAAE,GAAGC,IAAe;IACtE,MAAMC,SAAS,CAAC,OAAO,EAAEH,OAAO,CAAC,CAAC;IAElC,qFAAqF;IACrF,+BAA+B;IAC/B,IAAI,OAAOC,YAAY,UAAU;QAC/B,OAAO;YAAC,CAAC,EAAEE,OAAO,CAAC,EAAEF,QAAQ,CAAC;eAAKC;SAAK;IAC1C;IAEA,sFAAsF;IACtF,4BAA4B;IAC5B,OAAO;QAACC;QAAQF;WAAYC;KAAK;AACnC;AAEA;;;;;;;CAOC,GACD,SAASE,cAAc,EAAEJ,MAAM,EAA2B,GAAG,CAAC,CAAC;IAC7DP,OAAOO,WAAWK;IAClB,MAAMC,OAAOC,OAAOC,mBAAmB,CACrCd,gBAAgBe,OAAO;IAGzB,MAAMC,oBAAoBJ,KAAKK,MAAM,CAAC,CAACC,QAAQC;QAC7C,IAAIhB,eAAeiB,GAAG,CAACD,QAAQ,CAAClB,yBAAyBmB,GAAG,CAACD,MAAM;YACjE,OAAO;gBAAE,GAAGD,MAAM;gBAAE,CAACC,IAAI,EAAEnB,gBAAgBe,OAAO,CAACI,IAAI;YAAC;QAC1D;QAEA,OAAOD;IACT,GAAG,CAAC;IAEJ,OAAOG,OAAO;QACZN,SAAS;YACP,GAAGC,iBAAiB;YACpBjB,QAAQ,CACNuB,OACAf,SACA,GAAGgB;gBAEHvB,gBAAgBe,OAAO,CAAChB,MAAM,CAC5BuB,UACGjB,WAAWC,QAAQC,YAAYgB;YAEtC;YACA,GAAGnB,iBAAiBa,MAAM,CAAmB,CAACC,QAAQC;gBACpD,OAAO;oBACL,GAAGD,MAAM;oBACT,CAACC,IAAI,EAAE,CAACZ,SAAmB,GAAGgB;wBAC5BvB,gBAAgBe,OAAO,CAACI,IAAI,IACvBd,WAAWC,QAAQC,YAAYgB;oBAEtC;gBACF;YACF,GAAG,CAAC,EAAsB;QAC5B;IACF;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;KAAU;IAClBC,SAAShB;AACX;AAEA,eAAec,gBAAgB"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/common/endowments/console.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\nexport const consoleAttenuatedMethods = new Set([\n 'log',\n 'assert',\n 'error',\n 'debug',\n 'info',\n 'warn',\n]);\n\n/**\n * A set of all the `console` values that will be passed to the snap. This has\n * all the values that are available in both the browser and Node.js.\n */\nexport const consoleMethods = new Set([\n 'debug',\n 'error',\n 'info',\n 'log',\n 'warn',\n 'dir',\n 'dirxml',\n 'table',\n 'trace',\n 'group',\n 'groupCollapsed',\n 'groupEnd',\n 'clear',\n 'count',\n 'countReset',\n 'assert',\n 'profile',\n 'profileEnd',\n 'time',\n 'timeLog',\n 'timeEnd',\n 'timeStamp',\n 'context',\n]);\n\nconst consoleFunctions = ['log', 'error', 'debug', 'info', 'warn'] as const;\n\ntype ConsoleFunctions = {\n [Key in (typeof consoleFunctions)[number]]: (typeof rootRealmGlobal.console)[Key];\n};\n\n/**\n * Gets the appropriate (prepended) message to pass to one of the attenuated\n * method calls.\n *\n * @param snapId - Id of the snap that we're getting a message for.\n * @param message - The id of the snap that will interact with the endowment.\n * @param args - The array of additional arguments.\n * @returns An array of arguments to be passed into an attenuated console method call.\n */\nfunction getMessage(snapId: SnapId, message: unknown, ...args: unknown[]) {\n const prefix = `[Snap: ${snapId}]`;\n\n // If the first argument is a string, prepend the prefix to the message, and keep the\n // rest of the arguments as-is.\n if (typeof message === 'string') {\n return [`${prefix} ${message}`, ...args];\n }\n\n // Otherwise, the `message` is an object, array, etc., so add the prefix as a separate\n // message to the arguments.\n return [prefix, message, ...args];\n}\n\n/**\n * Create a a {@link console} object, with the same properties as the global\n * {@link console} object, but with some methods replaced.\n *\n * @param options - Factory options used in construction of the endowment.\n * @param options.snapId - The id of the snap that will interact with the endowment.\n * @returns The {@link console} object with the replaced methods.\n */\nfunction createConsole({ snapId }: EndowmentFactoryOptions = {}) {\n assert(snapId !== undefined);\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.console,\n ) as (keyof typeof console)[];\n\n const attenuatedConsole = keys.reduce((target, key) => {\n if (consoleMethods.has(key) && !consoleAttenuatedMethods.has(key)) {\n return { ...target, [key]: rootRealmGlobal.console[key] };\n }\n\n return target;\n }, {});\n\n return harden({\n console: {\n ...attenuatedConsole,\n assert: (\n value: any,\n message?: string | undefined,\n ...optionalParams: any[]\n ) => {\n rootRealmGlobal.console.assert(\n value,\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n ...consoleFunctions.reduce<ConsoleFunctions>((target, key) => {\n return {\n ...target,\n [key]: (message?: unknown, ...optionalParams: any[]) => {\n rootRealmGlobal.console[key](\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n };\n }, {} as ConsoleFunctions),\n },\n });\n}\n\nconst endowmentModule = {\n names: ['console'] as const,\n factory: createConsole,\n};\n\nexport default endowmentModule;\n"],"names":["assert","rootRealmGlobal","consoleAttenuatedMethods","Set","consoleMethods","consoleFunctions","getMessage","snapId","message","args","prefix","createConsole","undefined","keys","Object","getOwnPropertyNames","console","attenuatedConsole","reduce","target","key","has","harden","value","optionalParams","endowmentModule","names","factory"],"mappings":"AACA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC,SAASC,eAAe,QAAQ,kBAAkB;AAGlD,OAAO,MAAMC,2BAA2B,IAAIC,IAAI;IAC9C;IACA;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH;;;CAGC,GACD,OAAO,MAAMC,iBAAiB,IAAID,IAAI;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH,MAAME,mBAAmB;IAAC;IAAO;IAAS;IAAS;IAAQ;CAAO;AAMlE;;;;;;;;CAQC,GACD,SAASC,WAAWC,MAAc,EAAEC,OAAgB,EAAE,GAAGC,IAAe;IACtE,MAAMC,SAAS,CAAC,OAAO,EAAEH,OAAO,CAAC,CAAC;IAElC,qFAAqF;IACrF,+BAA+B;IAC/B,IAAI,OAAOC,YAAY,UAAU;QAC/B,OAAO;YAAC,CAAC,EAAEE,OAAO,CAAC,EAAEF,QAAQ,CAAC;eAAKC;SAAK;IAC1C;IAEA,sFAAsF;IACtF,4BAA4B;IAC5B,OAAO;QAACC;QAAQF;WAAYC;KAAK;AACnC;AAEA;;;;;;;CAOC,GACD,SAASE,cAAc,EAAEJ,MAAM,EAA2B,GAAG,CAAC,CAAC;IAC7DP,OAAOO,WAAWK;IAClB,MAAMC,OAAOC,OAAOC,mBAAmB,CACrCd,gBAAgBe,OAAO;IAGzB,MAAMC,oBAAoBJ,KAAKK,MAAM,CAAC,CAACC,QAAQC;QAC7C,IAAIhB,eAAeiB,GAAG,CAACD,QAAQ,CAAClB,yBAAyBmB,GAAG,CAACD,MAAM;YACjE,OAAO;gBAAE,GAAGD,MAAM;gBAAE,CAACC,IAAI,EAAEnB,gBAAgBe,OAAO,CAACI,IAAI;YAAC;QAC1D;QAEA,OAAOD;IACT,GAAG,CAAC;IAEJ,OAAOG,OAAO;QACZN,SAAS;YACP,GAAGC,iBAAiB;YACpBjB,QAAQ,CACNuB,OACAf,SACA,GAAGgB;gBAEHvB,gBAAgBe,OAAO,CAAChB,MAAM,CAC5BuB,UACGjB,WAAWC,QAAQC,YAAYgB;YAEtC;YACA,GAAGnB,iBAAiBa,MAAM,CAAmB,CAACC,QAAQC;gBACpD,OAAO;oBACL,GAAGD,MAAM;oBACT,CAACC,IAAI,EAAE,CAACZ,SAAmB,GAAGgB;wBAC5BvB,gBAAgBe,OAAO,CAACI,IAAI,IACvBd,WAAWC,QAAQC,YAAYgB;oBAEtC;gBACF;YACF,GAAG,CAAC,EAAsB;QAC5B;IACF;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;KAAU;IAClBC,SAAShB;AACX;AAEA,eAAec,gBAAgB"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { rpcErrors } from '@metamask/rpc-errors';
|
|
1
2
|
import { logWarning } from '@metamask/snaps-utils';
|
|
2
3
|
import { hasProperty } from '@metamask/utils';
|
|
3
4
|
import { rootRealmGlobal } from '../globalObject';
|
|
@@ -64,7 +65,7 @@ import buildCommonEndowments from './commonEndowmentFactory';
|
|
|
64
65
|
} else {
|
|
65
66
|
// If we get to this point, we've been passed an endowment that doesn't
|
|
66
67
|
// exist in our current environment.
|
|
67
|
-
throw
|
|
68
|
+
throw rpcErrors.internal(`Unknown endowment: "${endowmentName}".`);
|
|
68
69
|
}
|
|
69
70
|
return {
|
|
70
71
|
allEndowments,
|