@metamask/snaps-execution-environments 0.32.1 → 0.33.0-flask.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +298 -0
- package/dist/browserify/iframe/bundle.js +453 -665
- package/dist/browserify/iframe/index.html +2 -2
- package/dist/browserify/node-process/bundle.js +276 -488
- package/dist/browserify/node-thread/bundle.js +276 -488
- package/dist/browserify/offscreen/bundle.js +162 -416
- package/dist/browserify/offscreen/index.html +2 -2
- package/dist/browserify/worker-executor/bundle.js +17874 -0
- package/dist/browserify/worker-pool/bundle.js +2026 -0
- package/dist/browserify/worker-pool/index.html +11660 -0
- package/dist/common/BaseSnapExecutor.d.ts +4 -4
- package/dist/common/BaseSnapExecutor.js +22 -22
- package/dist/common/BaseSnapExecutor.js.map +1 -1
- package/dist/common/commands.js +2 -2
- package/dist/common/commands.js.map +1 -1
- package/dist/common/endowments/commonEndowmentFactory.d.ts +5 -1
- package/dist/common/endowments/commonEndowmentFactory.js +2 -1
- package/dist/common/endowments/commonEndowmentFactory.js.map +1 -1
- package/dist/common/endowments/console.d.ts +45 -0
- package/dist/common/endowments/console.js +103 -0
- package/dist/common/endowments/console.js.map +1 -0
- package/dist/common/endowments/crypto.d.ts +4 -0
- package/dist/common/endowments/crypto.js +3 -1
- package/dist/common/endowments/crypto.js.map +1 -1
- package/dist/common/endowments/index.d.ts +3 -1
- package/dist/common/endowments/index.js +3 -3
- package/dist/common/endowments/index.js.map +1 -1
- package/dist/common/endowments/math.js +4 -1
- package/dist/common/endowments/math.js.map +1 -1
- package/dist/common/utils.js +2 -1
- package/dist/common/utils.js.map +1 -1
- package/dist/offscreen/OffscreenSnapExecutor.js +1 -1
- package/dist/offscreen/OffscreenSnapExecutor.js.map +1 -1
- package/dist/openrpc.json +2 -2
- package/dist/webworker/executor/WebWorkerSnapExecutor.d.ts +13 -0
- package/dist/webworker/executor/WebWorkerSnapExecutor.js +37 -0
- package/dist/webworker/executor/WebWorkerSnapExecutor.js.map +1 -0
- package/dist/webworker/executor/index.d.ts +1 -0
- package/dist/webworker/executor/index.js +10 -0
- package/dist/webworker/executor/index.js.map +1 -0
- package/dist/webworker/pool/WebWorkerPool.d.ts +22 -0
- package/dist/webworker/pool/WebWorkerPool.js +168 -0
- package/dist/webworker/pool/WebWorkerPool.js.map +1 -0
- package/dist/webworker/pool/index.d.ts +1 -0
- package/dist/webworker/pool/index.js +10 -0
- package/dist/webworker/pool/index.js.map +1 -0
- package/package.json +21 -20
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":";;;;;;AAEA,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":";;;;;;AAEA,uDAA2D;AAC3D,2CAA8C;AAE9C,kDAAkD;AAClD,sFAEkC;AAelC;;GAEG;AACH,MAAM,oBAAoB,GAAG,IAAA,gCAAqB,GAAE,CAAC;AAErD;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE;IAC5E,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC7B,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC,CAAC,CAAC;IACH,OAAO,SAAS,CAAC;AACnB,CAAC,EAAE,IAAI,GAAG,EAAyE,CAAC,CAAC;AAErF;;;;;;;;;;;;GAYG;AACH,SAAgB,gBAAgB,CAC9B,IAAuB,EACvB,QAAwB,EACxB,MAAc,EACd,aAAuB,EAAE;IAEzB,MAAM,oBAAoB,GAA4B,EAAE,CAAC;IAEzD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAI9B,CAAC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,EAAE;KACd,CACF,CAAC;IAEF,MAAM,QAAQ,GAAG,KAAK,IAAI,EAAE;QAC1B,MAAM,OAAO,CAAC,GAAG,CACf,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,gBAAgB,EAAE,EAAE,CAAC,gBAAgB,EAAE,CAAC,CAC/D,CAAC;IACJ,CAAC,CAAC;IACF,OAAO,EAAE,UAAU,EAAE,MAAM,CAAC,aAAa,EAAE,QAAQ,EAAE,CAAC;AACxD,CAAC;AAlED,4CAkEC","sourcesContent":["import { StreamProvider } from '@metamask/providers';\nimport { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport { SnapId, logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport buildCommonEndowments, {\n EndowmentFactoryOptions,\n} from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param snapId - The id of the snap that will use the created endowments.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsGlobalObject,\n ethereum: StreamProvider,\n snapId: SnapId,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw new Error(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
const globalObject_1 = require("../globalObject");
|
|
4
|
+
const crypto_1 = require("./crypto");
|
|
4
5
|
/**
|
|
5
6
|
* Create a {@link Math} object, with the same properties as the global
|
|
6
7
|
* {@link Math} object, but with the {@link Math.random} method replaced.
|
|
@@ -18,6 +19,8 @@ function createMath() {
|
|
|
18
19
|
}
|
|
19
20
|
return { ...target, [key]: globalObject_1.rootRealmGlobal.Math[key] };
|
|
20
21
|
}, {});
|
|
22
|
+
// Since the math endowment requires crypto, we can leverage the crypto endowment factory to get a hardened and platform agnostic instance of webcrypto
|
|
23
|
+
const { crypto: hardenedCrypto } = (0, crypto_1.createCrypto)();
|
|
21
24
|
return harden({
|
|
22
25
|
Math: {
|
|
23
26
|
...math,
|
|
@@ -38,7 +41,7 @@ function createMath() {
|
|
|
38
41
|
//
|
|
39
42
|
// - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey
|
|
40
43
|
// - https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
|
|
41
|
-
return
|
|
44
|
+
return hardenedCrypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;
|
|
42
45
|
},
|
|
43
46
|
},
|
|
44
47
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"math.js","sourceRoot":"","sources":["../../../src/common/endowments/math.ts"],"names":[],"mappings":";;AAAA,kDAAkD;
|
|
1
|
+
{"version":3,"file":"math.js","sourceRoot":"","sources":["../../../src/common/endowments/math.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAClD,qCAAwC;AAExC;;;;;;GAMG;AACH,SAAS,UAAU;IACjB,yEAAyE;IACzE,wDAAwD;IACxD,MAAM,IAAI,GAAG,MAAM,CAAC,mBAAmB,CACrC,8BAAe,CAAC,IAAI,CACI,CAAC;IAE3B,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAgB,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE;QACtD,IAAI,GAAG,KAAK,QAAQ,EAAE;YACpB,OAAO,MAAM,CAAC;SACf;QAED,OAAO,EAAE,GAAG,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,8BAAe,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;IACzD,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,uJAAuJ;IACvJ,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,IAAA,qBAAY,GAAE,CAAC;IAElD,OAAO,MAAM,CAAC;QACZ,IAAI,EAAE;YACJ,GAAG,IAAI;YACP,MAAM,EAAE,GAAG,EAAE;gBACX,qEAAqE;gBACrE,wEAAwE;gBACxE,wEAAwE;gBACxE,gEAAgE;gBAChE,WAAW;gBACX,EAAE;gBACF,mEAAmE;gBACnE,qEAAqE;gBACrE,0BAA0B;gBAC1B,EAAE;gBACF,sEAAsE;gBACtE,sEAAsE;gBACtE,OAAO;gBACP,EAAE;gBACF,8EAA8E;gBAC9E,4EAA4E;gBAC5E,OAAO,cAAc,CAAC,eAAe,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;YACzE,CAAC;SACF;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,MAAM,CAAU;IACxB,OAAO,EAAE,UAAU;CACpB,CAAC;AAEF,kBAAe,eAAe,CAAC","sourcesContent":["import { rootRealmGlobal } from '../globalObject';\nimport { createCrypto } from './crypto';\n\n/**\n * Create a {@link Math} object, with the same properties as the global\n * {@link Math} object, but with the {@link Math.random} method replaced.\n *\n * @returns The {@link Math} object with the {@link Math.random} method\n * replaced.\n */\nfunction createMath() {\n // `Math` does not work with `Object.keys`, `Object.entries`, etc., so we\n // need to create a new object with the same properties.\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.Math,\n ) as (keyof typeof Math)[];\n\n const math = keys.reduce<Partial<Math>>((target, key) => {\n if (key === 'random') {\n return target;\n }\n\n return { ...target, [key]: rootRealmGlobal.Math[key] };\n }, {});\n\n // Since the math endowment requires crypto, we can leverage the crypto endowment factory to get a hardened and platform agnostic instance of webcrypto\n const { crypto: hardenedCrypto } = createCrypto();\n\n return harden({\n Math: {\n ...math,\n random: () => {\n // NOTE: This is not intended to be a secure replacement for the weak\n // random number generator used by `Math.random`. It is only intended to\n // prevent side channel attacks of `Math.random` by replacing it with an\n // alternative implementation that is not vulnerable to the same\n // attacks.\n //\n // This does not mean that this implementation is secure. It is not\n // intended to be used in a security context, and this implementation\n // may change at any time.\n //\n // To securely generate random numbers, use a cryptographically secure\n // random number generator, such as the one provided by the Web Crypto\n // API:\n //\n // - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey\n // - https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\n return hardenedCrypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;\n },\n },\n });\n}\n\nconst endowmentModule = {\n names: ['Math'] as const,\n factory: createMath,\n};\n\nexport default endowmentModule;\n"]}
|
package/dist/common/utils.js
CHANGED
|
@@ -87,10 +87,11 @@ function proxyStreamProvider(provider, request) {
|
|
|
87
87
|
return proxy;
|
|
88
88
|
}
|
|
89
89
|
exports.proxyStreamProvider = proxyStreamProvider;
|
|
90
|
-
// We're blocking these
|
|
90
|
+
// We're blocking these RPC methods for v1, will revisit later.
|
|
91
91
|
const BLOCKED_RPC_METHODS = Object.freeze([
|
|
92
92
|
'eth_requestAccounts',
|
|
93
93
|
'wallet_requestSnaps',
|
|
94
|
+
'wallet_requestPermissions',
|
|
94
95
|
]);
|
|
95
96
|
/**
|
|
96
97
|
* Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.
|
package/dist/common/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/common/utils.ts"],"names":[],"mappings":";;;AAEA,2CAAmE;AACnE,mDAA2C;AAE3C,wCAAiC;AAEjC;;;;;;;GAOG;AACH,SAAgB,cAAc,CAAC,aAAsB;IACnD,IAAI,cAAiC,CAAC;IACtC,IAAI,aAAa,YAAY,KAAK,EAAE;QAClC,cAAc,GAAG,aAAa,CAAC;KAChC;SAAM,IAAI,OAAO,aAAa,KAAK,QAAQ,EAAE;QAC5C,cAAc,GAAG,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;QAC1C,qCAAqC;QACrC,OAAO,cAAc,CAAC,KAAK,CAAC;KAC7B;IACD,OAAO,cAAc,CAAC;AACxB,CAAC;AAVD,wCAUC;AAED;;;;;;;;;GASG;AACI,KAAK,UAAU,YAAY,CAChC,eAA2B,EAC3B,WAAqC;IAErC,MAAM,UAAU,GAAG,WAAW,CAAC,YAAY,CAAC;IAC5C,OAAO,IAAI,OAAO,CAAI,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACxC,eAAe;aACZ,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE;YACd,IAAI,WAAW,CAAC,YAAY,KAAK,UAAU,EAAE;gBAC3C,OAAO,CAAC,KAAK,CAAC,CAAC;aAChB;iBAAM;gBACL,IAAA,aAAG,EACD,+EAA+E,CAChF,CAAC;aACH;QACH,CAAC,CAAC;aACD,KAAK,CAAC,CAAC,MAAM,EAAE,EAAE;YAChB,IAAI,WAAW,CAAC,YAAY,KAAK,UAAU,EAAE;gBAC3C,MAAM,CAAC,MAAM,CAAC,CAAC;aAChB;iBAAM;gBACL,IAAA,aAAG,EACD,+EAA+E,CAChF,CAAC;aACH;QACH,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACL,CAAC;AA1BD,oCA0BC;AAED;;;;;;;GAOG;AACH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,CACH,CAAC;IACF,IAAA,oBAAY,EAAC,IAAI,EAAE,kBAAU,EAAE,2CAA2C,CAAC,CAAC;AAC9E,CAAC;AAnBD,sEAmBC","sourcesContent":["import { StreamProvider } from '@metamask/providers';\nimport { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { assert, assertStruct, JsonStruct } from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { log } from '../logging';\n\n/**\n * Takes an error that was thrown, determines if it is\n * an error object. If it is then it will return that. Otherwise,\n * an error object is created with the original error message.\n *\n * @param originalError - The error that was originally thrown.\n * @returns An error object.\n */\nexport function constructError(originalError: unknown) {\n let _originalError: Error | undefined;\n if (originalError instanceof Error) {\n _originalError = originalError;\n } else if (typeof originalError === 'string') {\n _originalError = new Error(originalError);\n // The stack is useless in this case.\n delete _originalError.stack;\n }\n return _originalError;\n}\n\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<T>(\n originalPromise: Promise<T>,\n teardownRef: { lastTeardown: number },\n): Promise<T> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<T>((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.\nconst BLOCKED_RPC_METHODS = Object.freeze([\n 'eth_requestAccounts',\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\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 );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\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 ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n"]}
|
|
@@ -51,7 +51,7 @@ class OffscreenSnapExecutor {
|
|
|
51
51
|
}
|
|
52
52
|
exports.OffscreenSnapExecutor = OffscreenSnapExecutor;
|
|
53
53
|
_OffscreenSnapExecutor_stream = new WeakMap(), _OffscreenSnapExecutor_instances = new WeakSet(), _OffscreenSnapExecutor_onData = function _OffscreenSnapExecutor_onData(data) {
|
|
54
|
-
const { jobId, frameUrl, data: request } = data;
|
|
54
|
+
const { jobId, extra: { frameUrl }, data: request, } = data;
|
|
55
55
|
if (!this.jobs[jobId]) {
|
|
56
56
|
// This ensures that a job is initialized before it is used. To avoid
|
|
57
57
|
// code duplication, we call the `#onData` method again, which will
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OffscreenSnapExecutor.js","sourceRoot":"","sources":["../../src/offscreen/OffscreenSnapExecutor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,uEAGuC;AACvC,uDAA+D;AAC/D,2CAAyD;AAQzD;;;;;;;;;;;;;GAaG;AACH,MAAa,qBAAqB;IAgBhC,YAAY,MAA6B;;QAfzC,gDAAwC;QAE/B,SAAI,GAAgC,EAAE,CAAC;QAc9C,uBAAA,IAAI,iCAAW,MAAM,MAAA,CAAC;QACtB,uBAAA,IAAI,qCAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,uBAAA,IAAI,uEAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACnD,CAAC;IAdD;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CAAC,MAA6B;QAC7C,OAAO,IAAI,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC3C,CAAC;
|
|
1
|
+
{"version":3,"file":"OffscreenSnapExecutor.js","sourceRoot":"","sources":["../../src/offscreen/OffscreenSnapExecutor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,uEAGuC;AACvC,uDAA+D;AAC/D,2CAAyD;AAQzD;;;;;;;;;;;;;GAaG;AACH,MAAa,qBAAqB;IAgBhC,YAAY,M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AgB;IAClD,MAAM,MAAM,GAAG,MAAM,IAAA,0BAAY,EAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IACnD,MAAM,SAAS,GAAG,IAAI,6CAAuB,CAAC;QAC5C,IAAI,EAAE,QAAQ;QACd,MAAM,EAAE,OAAO;QACf,YAAY,EAAE,MAAM;QACpB,YAAY,EAAE,GAAG;KAClB,CAAC,CAAC;IAEH,yEAAyE;IACzE,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE;QAC5B,uBAAA,IAAI,qCAAQ,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;IAC5D,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC1B,CAAC,qFAQa,KAAa;IACzB,IAAA,cAAM,EAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,QAAQ,KAAK,cAAc,CAAC,CAAC;IAEtD,MAAM,MAAM,GAAG,QAAQ,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC9C,IAAA,cAAM,EAAC,MAAM,EAAE,mBAAmB,KAAK,cAAc,CAAC,CAAC;IAEvD,MAAM,CAAC,MAAM,EAAE,CAAC;IAChB,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;IAClC,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import {\n BasePostMessageStream,\n WindowPostMessageStream,\n} from '@metamask/post-message-stream';\nimport { createWindow, logError } from '@metamask/snaps-utils';\nimport { JsonRpcRequest, assert } from '@metamask/utils';\n\ntype ExecutorJob = {\n id: string;\n window: Window;\n stream: WindowPostMessageStream;\n};\n\n/**\n * A snap executor using the Offscreen Documents API.\n *\n * This is not a traditional snap executor, as it does not execute snaps itself.\n * Instead, it creates an iframe window for each snap execution, and sends the\n * snap execution request to the iframe window. The iframe window is responsible\n * for executing the snap.\n *\n * Extensions can only have a single offscreen document, so this executor is\n * persisted between snap executions. The offscreen snap executor essentially\n * acts as a proxy between the extension and the iframe execution environment.\n *\n * @see https://developer.chrome.com/docs/extensions/reference/offscreen/\n */\nexport class OffscreenSnapExecutor {\n readonly #stream: BasePostMessageStream;\n\n readonly jobs: Record<string, ExecutorJob> = {};\n\n /**\n * Initialize the executor with the given stream. This is a wrapper around the\n * constructor.\n *\n * @param stream - The stream to use for communication.\n * @returns The initialized executor.\n */\n static initialize(stream: BasePostMessageStream) {\n return new OffscreenSnapExecutor(stream);\n }\n\n constructor(stream: BasePostMessageStream) {\n this.#stream = stream;\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle an incoming message from the `OffscreenExecutionService`. This\n * assumes that the message contains a `jobId` property, and a JSON-RPC\n * request in the `data` property.\n *\n * @param data - The message data.\n * @param data.data - The JSON-RPC request.\n * @param data.jobId - The job ID.\n * @param data.extra - Extra data.\n * @param data.extra.frameUrl - The URL to load in the iframe.\n */\n #onData(data: {\n data: JsonRpcRequest;\n jobId: string;\n extra: { frameUrl: string };\n }) {\n const {\n jobId,\n extra: { frameUrl },\n data: request,\n } = data;\n\n if (!this.jobs[jobId]) {\n // This ensures that a job is initialized before it is used. To avoid\n // code duplication, we call the `#onData` method again, which will\n // run the rest of the logic after initialization.\n this.#initializeJob(jobId, frameUrl)\n .then(() => {\n this.#onData(data);\n })\n .catch((error) => {\n logError('[Worker] Error initializing job:', error);\n });\n\n return;\n }\n\n // This is a method specific to the `OffscreenSnapExecutor`, as the service\n // itself does not have access to the iframes directly.\n if (request.method === 'terminateJob') {\n this.#terminateJob(jobId);\n return;\n }\n\n this.jobs[jobId].stream.write(request);\n }\n\n /**\n * Create a new iframe and set up a stream to communicate with it.\n *\n * @param jobId - The job ID.\n * @param frameUrl - The URL to load in the iframe.\n */\n async #initializeJob(jobId: string, frameUrl: string): Promise<ExecutorJob> {\n const window = await createWindow(frameUrl, jobId);\n const jobStream = new WindowPostMessageStream({\n name: 'parent',\n target: 'child',\n targetWindow: window,\n targetOrigin: '*',\n });\n\n // Write messages from the iframe to the parent, wrapped with the job ID.\n jobStream.on('data', (data) => {\n this.#stream.write({ data, jobId });\n });\n\n this.jobs[jobId] = { id: jobId, window, stream: jobStream };\n return this.jobs[jobId];\n }\n\n /**\n * Terminate the job with the given ID. This will close the iframe and delete\n * the job from the internal job map.\n *\n * @param jobId - The job ID.\n */\n #terminateJob(jobId: string) {\n assert(this.jobs[jobId], `Job \"${jobId}\" not found.`);\n\n const iframe = document.getElementById(jobId);\n assert(iframe, `Iframe with ID \"${jobId}\" not found.`);\n\n iframe.remove();\n this.jobs[jobId].stream.destroy();\n delete this.jobs[jobId];\n }\n}\n"]}
|
package/dist/openrpc.json
CHANGED
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"description": "executes a snap in the environment. The snap can then be interacted with via `snapRpc`",
|
|
33
33
|
"params": [
|
|
34
34
|
{
|
|
35
|
-
"name": "
|
|
35
|
+
"name": "snapId",
|
|
36
36
|
"required": true,
|
|
37
37
|
"description": "the name of the snap",
|
|
38
38
|
"schema": {
|
|
@@ -75,7 +75,7 @@
|
|
|
75
75
|
"name": "BasicTestSnapExecuteExample",
|
|
76
76
|
"params": [
|
|
77
77
|
{
|
|
78
|
-
"name": "
|
|
78
|
+
"name": "snapId",
|
|
79
79
|
"value": "TestSnap"
|
|
80
80
|
},
|
|
81
81
|
{
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { BasePostMessageStream } from '@metamask/post-message-stream';
|
|
2
|
+
import { BaseSnapExecutor } from '../../common/BaseSnapExecutor';
|
|
3
|
+
export declare class WebWorkerSnapExecutor extends BaseSnapExecutor {
|
|
4
|
+
/**
|
|
5
|
+
* Initialize the WebWorkerSnapExecutor. This creates a post message stream
|
|
6
|
+
* from and to the parent window, for two-way communication with the iframe.
|
|
7
|
+
*
|
|
8
|
+
* @param stream - The stream to use for communication.
|
|
9
|
+
* @returns An instance of `WebWorkerSnapExecutor`, with the initialized post
|
|
10
|
+
* message streams.
|
|
11
|
+
*/
|
|
12
|
+
static initialize(stream?: BasePostMessageStream): WebWorkerSnapExecutor;
|
|
13
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.WebWorkerSnapExecutor = void 0;
|
|
7
|
+
const object_multiplex_1 = __importDefault(require("@metamask/object-multiplex"));
|
|
8
|
+
const post_message_stream_1 = require("@metamask/post-message-stream");
|
|
9
|
+
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
10
|
+
const pump_1 = __importDefault(require("pump"));
|
|
11
|
+
const BaseSnapExecutor_1 = require("../../common/BaseSnapExecutor");
|
|
12
|
+
const logging_1 = require("../../logging");
|
|
13
|
+
class WebWorkerSnapExecutor extends BaseSnapExecutor_1.BaseSnapExecutor {
|
|
14
|
+
/**
|
|
15
|
+
* Initialize the WebWorkerSnapExecutor. This creates a post message stream
|
|
16
|
+
* from and to the parent window, for two-way communication with the iframe.
|
|
17
|
+
*
|
|
18
|
+
* @param stream - The stream to use for communication.
|
|
19
|
+
* @returns An instance of `WebWorkerSnapExecutor`, with the initialized post
|
|
20
|
+
* message streams.
|
|
21
|
+
*/
|
|
22
|
+
static initialize(stream = new post_message_stream_1.WebWorkerPostMessageStream()) {
|
|
23
|
+
(0, logging_1.log)('Worker: Connecting to parent.');
|
|
24
|
+
const mux = new object_multiplex_1.default();
|
|
25
|
+
(0, pump_1.default)(stream, mux, stream, (error) => {
|
|
26
|
+
if (error) {
|
|
27
|
+
(0, snaps_utils_1.logError)(`Parent stream failure, closing worker.`, error);
|
|
28
|
+
}
|
|
29
|
+
self.close();
|
|
30
|
+
});
|
|
31
|
+
const commandStream = mux.createStream(snaps_utils_1.SNAP_STREAM_NAMES.COMMAND);
|
|
32
|
+
const rpcStream = mux.createStream(snaps_utils_1.SNAP_STREAM_NAMES.JSON_RPC);
|
|
33
|
+
return new WebWorkerSnapExecutor(commandStream, rpcStream);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
exports.WebWorkerSnapExecutor = WebWorkerSnapExecutor;
|
|
37
|
+
//# sourceMappingURL=WebWorkerSnapExecutor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"WebWorkerSnapExecutor.js","sourceRoot":"","sources":["../../../src/webworker/executor/WebWorkerSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,kFAAyD;AACzD,uEAGuC;AACvC,uDAAoE;AACpE,gDAAwB;AAExB,oEAAiE;AACjE,2CAAoC;AAEpC,MAAa,qBAAsB,SAAQ,mCAAgB;IACzD;;;;;;;OAOG;IACH,MAAM,CAAC,UAAU,CACf,SAAgC,IAAI,gDAA0B,EAAE;QAEhE,IAAA,aAAG,EAAC,+BAA+B,CAAC,CAAC;QAErC,MAAM,GAAG,GAAG,IAAI,0BAAe,EAAE,CAAC;QAClC,IAAA,cAAI,EAAC,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;YAClC,IAAI,KAAK,EAAE;gBACT,IAAA,sBAAQ,EAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;aAC3D;YACD,IAAI,CAAC,KAAK,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;QAEH,MAAM,aAAa,GAAG,GAAG,CAAC,YAAY,CAAC,+BAAiB,CAAC,OAAO,CAAC,CAAC;QAClE,MAAM,SAAS,GAAG,GAAG,CAAC,YAAY,CAAC,+BAAiB,CAAC,QAAQ,CAAC,CAAC;QAE/D,OAAO,IAAI,qBAAqB,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;IAC7D,CAAC;CACF;AA3BD,sDA2BC","sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport {\n BasePostMessageStream,\n WebWorkerPostMessageStream,\n} from '@metamask/post-message-stream';\nimport { logError, SNAP_STREAM_NAMES } from '@metamask/snaps-utils';\nimport pump from 'pump';\n\nimport { BaseSnapExecutor } from '../../common/BaseSnapExecutor';\nimport { log } from '../../logging';\n\nexport class WebWorkerSnapExecutor extends BaseSnapExecutor {\n /**\n * Initialize the WebWorkerSnapExecutor. This creates a post message stream\n * from and to the parent window, for two-way communication with the iframe.\n *\n * @param stream - The stream to use for communication.\n * @returns An instance of `WebWorkerSnapExecutor`, with the initialized post\n * message streams.\n */\n static initialize(\n stream: BasePostMessageStream = new WebWorkerPostMessageStream(),\n ) {\n log('Worker: Connecting to parent.');\n\n const mux = new ObjectMultiplex();\n pump(stream, mux, stream, (error) => {\n if (error) {\n logError(`Parent stream failure, closing worker.`, error);\n }\n self.close();\n });\n\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n return new WebWorkerSnapExecutor(commandStream, rpcStream);\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const lockdown_events_1 = require("../../common/lockdown/lockdown-events");
|
|
4
|
+
const lockdown_more_1 = require("../../common/lockdown/lockdown-more");
|
|
5
|
+
const WebWorkerSnapExecutor_1 = require("./WebWorkerSnapExecutor");
|
|
6
|
+
// Lockdown is already applied in LavaMoat
|
|
7
|
+
(0, lockdown_more_1.executeLockdownMore)();
|
|
8
|
+
(0, lockdown_events_1.executeLockdownEvents)();
|
|
9
|
+
WebWorkerSnapExecutor_1.WebWorkerSnapExecutor.initialize();
|
|
10
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/webworker/executor/index.ts"],"names":[],"mappings":";;AAAA,2EAA8E;AAC9E,uEAA0E;AAC1E,mEAAgE;AAEhE,0CAA0C;AAC1C,IAAA,mCAAmB,GAAE,CAAC;AACtB,IAAA,uCAAqB,GAAE,CAAC;AAExB,6CAAqB,CAAC,UAAU,EAAE,CAAC","sourcesContent":["import { executeLockdownEvents } from '../../common/lockdown/lockdown-events';\nimport { executeLockdownMore } from '../../common/lockdown/lockdown-more';\nimport { WebWorkerSnapExecutor } from './WebWorkerSnapExecutor';\n\n// Lockdown is already applied in LavaMoat\nexecuteLockdownMore();\nexecuteLockdownEvents();\n\nWebWorkerSnapExecutor.initialize();\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { BasePostMessageStream, WebWorkerParentPostMessageStream } from '@metamask/post-message-stream';
|
|
2
|
+
declare type ExecutorJob = {
|
|
3
|
+
id: string;
|
|
4
|
+
worker: Worker;
|
|
5
|
+
stream: WebWorkerParentPostMessageStream;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* A snap executor using the WebWorker API.
|
|
9
|
+
*
|
|
10
|
+
* This is not a traditional snap executor, as it does not execute snaps itself.
|
|
11
|
+
* Instead, it creates a pool of webworkers for each snap execution, and sends
|
|
12
|
+
* the snap execution request to the webworker. The webworker is responsible for
|
|
13
|
+
* executing the snap.
|
|
14
|
+
*/
|
|
15
|
+
export declare class WebWorkerPool {
|
|
16
|
+
#private;
|
|
17
|
+
readonly pool: Worker[];
|
|
18
|
+
readonly jobs: Map<string, ExecutorJob>;
|
|
19
|
+
static initialize(stream?: BasePostMessageStream, url?: string, poolSize?: number): WebWorkerPool;
|
|
20
|
+
constructor(stream: BasePostMessageStream, url: string, poolSize?: number);
|
|
21
|
+
}
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var _WebWorkerPool_instances, _WebWorkerPool_poolSize, _WebWorkerPool_stream, _WebWorkerPool_url, _WebWorkerPool_workerSourceURL, _WebWorkerPool_onData, _WebWorkerPool_initializeJob, _WebWorkerPool_terminateJob, _WebWorkerPool_getWorker, _WebWorkerPool_updatePool, _WebWorkerPool_createWorker, _WebWorkerPool_getWorkerURL;
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.WebWorkerPool = void 0;
|
|
16
|
+
const post_message_stream_1 = require("@metamask/post-message-stream");
|
|
17
|
+
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
18
|
+
const utils_1 = require("@metamask/utils");
|
|
19
|
+
const non_secure_1 = require("nanoid/non-secure");
|
|
20
|
+
/**
|
|
21
|
+
* A snap executor using the WebWorker API.
|
|
22
|
+
*
|
|
23
|
+
* This is not a traditional snap executor, as it does not execute snaps itself.
|
|
24
|
+
* Instead, it creates a pool of webworkers for each snap execution, and sends
|
|
25
|
+
* the snap execution request to the webworker. The webworker is responsible for
|
|
26
|
+
* executing the snap.
|
|
27
|
+
*/
|
|
28
|
+
class WebWorkerPool {
|
|
29
|
+
constructor(stream, url, poolSize = 3) {
|
|
30
|
+
_WebWorkerPool_instances.add(this);
|
|
31
|
+
_WebWorkerPool_poolSize.set(this, void 0);
|
|
32
|
+
_WebWorkerPool_stream.set(this, void 0);
|
|
33
|
+
_WebWorkerPool_url.set(this, void 0);
|
|
34
|
+
this.pool = [];
|
|
35
|
+
this.jobs = new Map();
|
|
36
|
+
_WebWorkerPool_workerSourceURL.set(this, void 0);
|
|
37
|
+
__classPrivateFieldSet(this, _WebWorkerPool_stream, stream, "f");
|
|
38
|
+
__classPrivateFieldSet(this, _WebWorkerPool_url, url, "f");
|
|
39
|
+
__classPrivateFieldSet(this, _WebWorkerPool_poolSize, poolSize, "f");
|
|
40
|
+
__classPrivateFieldGet(this, _WebWorkerPool_stream, "f").on('data', __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_onData).bind(this));
|
|
41
|
+
}
|
|
42
|
+
/* istanbul ignore next - Constructor arguments. */
|
|
43
|
+
static initialize(stream = new post_message_stream_1.WindowPostMessageStream({
|
|
44
|
+
name: 'child',
|
|
45
|
+
target: 'parent',
|
|
46
|
+
targetWindow: self.parent,
|
|
47
|
+
targetOrigin: '*',
|
|
48
|
+
}), url = '../executor/bundle.js', poolSize) {
|
|
49
|
+
return new WebWorkerPool(stream, url, poolSize);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
exports.WebWorkerPool = WebWorkerPool;
|
|
53
|
+
_WebWorkerPool_poolSize = new WeakMap(), _WebWorkerPool_stream = new WeakMap(), _WebWorkerPool_url = new WeakMap(), _WebWorkerPool_workerSourceURL = new WeakMap(), _WebWorkerPool_instances = new WeakSet(), _WebWorkerPool_onData = function _WebWorkerPool_onData(data) {
|
|
54
|
+
const { jobId, data: request } = data;
|
|
55
|
+
const job = this.jobs.get(jobId);
|
|
56
|
+
if (!job) {
|
|
57
|
+
// This ensures that a job is initialized before it is used. To avoid
|
|
58
|
+
// code duplication, we call the `#onData` method again, which will
|
|
59
|
+
// run the rest of the logic after initialization.
|
|
60
|
+
__classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_initializeJob).call(this, jobId)
|
|
61
|
+
.then(() => {
|
|
62
|
+
__classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_onData).call(this, data);
|
|
63
|
+
})
|
|
64
|
+
.catch((error) => {
|
|
65
|
+
(0, snaps_utils_1.logError)('[Worker] Error initializing job:', error.toString());
|
|
66
|
+
__classPrivateFieldGet(this, _WebWorkerPool_stream, "f").write({
|
|
67
|
+
jobId,
|
|
68
|
+
data: {
|
|
69
|
+
name: 'command',
|
|
70
|
+
data: {
|
|
71
|
+
jsonrpc: '2.0',
|
|
72
|
+
id: request.id ?? null,
|
|
73
|
+
error: {
|
|
74
|
+
code: -32000,
|
|
75
|
+
message: 'Internal error',
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
// This is a method specific to the `WebWorkerPool`, as the service itself
|
|
84
|
+
// does not have access to the workers directly.
|
|
85
|
+
if (request.method === 'terminateJob') {
|
|
86
|
+
__classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_terminateJob).call(this, jobId);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
job.stream.write(request);
|
|
90
|
+
}, _WebWorkerPool_initializeJob =
|
|
91
|
+
/**
|
|
92
|
+
* Create a new worker and set up a stream to communicate with it.
|
|
93
|
+
*
|
|
94
|
+
* @param jobId - The job ID.
|
|
95
|
+
* @returns The job.
|
|
96
|
+
*/
|
|
97
|
+
async function _WebWorkerPool_initializeJob(jobId) {
|
|
98
|
+
const worker = await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_getWorker).call(this);
|
|
99
|
+
const jobStream = new post_message_stream_1.WebWorkerParentPostMessageStream({
|
|
100
|
+
worker,
|
|
101
|
+
});
|
|
102
|
+
// Write messages from the worker to the parent, wrapped with the job ID.
|
|
103
|
+
jobStream.on('data', (data) => {
|
|
104
|
+
__classPrivateFieldGet(this, _WebWorkerPool_stream, "f").write({ data, jobId });
|
|
105
|
+
});
|
|
106
|
+
const job = { id: jobId, worker, stream: jobStream };
|
|
107
|
+
this.jobs.set(jobId, job);
|
|
108
|
+
return job;
|
|
109
|
+
}, _WebWorkerPool_terminateJob = function _WebWorkerPool_terminateJob(jobId) {
|
|
110
|
+
const job = this.jobs.get(jobId);
|
|
111
|
+
(0, utils_1.assert)(job, `Job "${jobId}" not found.`);
|
|
112
|
+
job.stream.destroy();
|
|
113
|
+
job.worker.terminate();
|
|
114
|
+
this.jobs.delete(jobId);
|
|
115
|
+
}, _WebWorkerPool_getWorker =
|
|
116
|
+
/**
|
|
117
|
+
* Get a worker from the pool. A new worker will be created automatically.
|
|
118
|
+
*
|
|
119
|
+
* @returns The worker.
|
|
120
|
+
*/
|
|
121
|
+
async function _WebWorkerPool_getWorker() {
|
|
122
|
+
// Lazily create the pool of workers.
|
|
123
|
+
if (this.pool.length === 0) {
|
|
124
|
+
await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_updatePool).call(this);
|
|
125
|
+
}
|
|
126
|
+
const worker = this.pool.shift();
|
|
127
|
+
(0, utils_1.assert)(worker, 'Worker not found.');
|
|
128
|
+
await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_updatePool).call(this);
|
|
129
|
+
return worker;
|
|
130
|
+
}, _WebWorkerPool_updatePool =
|
|
131
|
+
/**
|
|
132
|
+
* Update the pool of workers. This will create new workers if the pool is
|
|
133
|
+
* below the minimum size.
|
|
134
|
+
*/
|
|
135
|
+
async function _WebWorkerPool_updatePool() {
|
|
136
|
+
while (this.pool.length < __classPrivateFieldGet(this, _WebWorkerPool_poolSize, "f")) {
|
|
137
|
+
const worker = await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_createWorker).call(this);
|
|
138
|
+
this.pool.push(worker);
|
|
139
|
+
}
|
|
140
|
+
}, _WebWorkerPool_createWorker =
|
|
141
|
+
/**
|
|
142
|
+
* Create a new worker. This will fetch the worker source if it has not
|
|
143
|
+
* already been fetched.
|
|
144
|
+
*
|
|
145
|
+
* @returns The worker.
|
|
146
|
+
*/
|
|
147
|
+
async function _WebWorkerPool_createWorker() {
|
|
148
|
+
return new Worker(await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_getWorkerURL).call(this), {
|
|
149
|
+
name: `worker-${(0, non_secure_1.nanoid)()}`,
|
|
150
|
+
});
|
|
151
|
+
}, _WebWorkerPool_getWorkerURL =
|
|
152
|
+
/**
|
|
153
|
+
* Get the URL of the worker source. This will fetch the worker source if it
|
|
154
|
+
* has not already been fetched.
|
|
155
|
+
*
|
|
156
|
+
* @returns The worker source URL, as a `blob:` URL.
|
|
157
|
+
*/
|
|
158
|
+
async function _WebWorkerPool_getWorkerURL() {
|
|
159
|
+
if (__classPrivateFieldGet(this, _WebWorkerPool_workerSourceURL, "f")) {
|
|
160
|
+
return __classPrivateFieldGet(this, _WebWorkerPool_workerSourceURL, "f");
|
|
161
|
+
}
|
|
162
|
+
const blob = await fetch(__classPrivateFieldGet(this, _WebWorkerPool_url, "f"))
|
|
163
|
+
.then(async (response) => response.blob())
|
|
164
|
+
.then(URL.createObjectURL.bind(URL));
|
|
165
|
+
__classPrivateFieldSet(this, _WebWorkerPool_workerSourceURL, blob, "f");
|
|
166
|
+
return blob;
|
|
167
|
+
};
|
|
168
|
+
//# sourceMappingURL=WebWorkerPool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"WebWorkerPool.js","sourceRoot":"","sources":["../../../src/webworker/p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Ac,MAAlB,IAAI,CAAgB,EAAE;QAC5C,IAAI,EAAE,UAAU,IAAA,mBAAM,GAAE,EAAE;KAC3B,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,IAAI,uBAAA,IAAI,sCAAiB,EAAE;QACzB,OAAO,uBAAA,IAAI,sCAAiB,CAAC;KAC9B;IAED,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC,uBAAA,IAAI,0BAAK,CAAC;SAChC,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;SACzC,IAAI,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAEvC,uBAAA,IAAI,kCAAoB,IAAI,MAAA,CAAC;IAC7B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import {\n BasePostMessageStream,\n WebWorkerParentPostMessageStream,\n WindowPostMessageStream,\n} from '@metamask/post-message-stream';\nimport { logError } from '@metamask/snaps-utils';\nimport { JsonRpcRequest, assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid/non-secure';\n\ntype ExecutorJob = {\n id: string;\n worker: Worker;\n stream: WebWorkerParentPostMessageStream;\n};\n\n/**\n * A snap executor using the WebWorker API.\n *\n * This is not a traditional snap executor, as it does not execute snaps itself.\n * Instead, it creates a pool of webworkers for each snap execution, and sends\n * the snap execution request to the webworker. The webworker is responsible for\n * executing the snap.\n */\nexport class WebWorkerPool {\n readonly #poolSize;\n\n readonly #stream: BasePostMessageStream;\n\n readonly #url: string;\n\n readonly pool: Worker[] = [];\n\n readonly jobs: Map<string, ExecutorJob> = new Map();\n\n #workerSourceURL?: string;\n\n /* istanbul ignore next - Constructor arguments. */\n static initialize(\n stream: BasePostMessageStream = new WindowPostMessageStream({\n name: 'child',\n target: 'parent',\n targetWindow: self.parent,\n targetOrigin: '*',\n }),\n url = '../executor/bundle.js',\n poolSize?: number,\n ) {\n return new WebWorkerPool(stream, url, poolSize);\n }\n\n constructor(stream: BasePostMessageStream, url: string, poolSize = 3) {\n this.#stream = stream;\n this.#url = url;\n this.#poolSize = poolSize;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle an incoming message from the `WebWorkerExecutionService`. This\n * assumes that the message contains a `jobId` property, and a JSON-RPC\n * request in the `data` property.\n *\n * @param data - The message data.\n * @param data.data - The JSON-RPC request.\n * @param data.jobId - The job ID.\n */\n #onData(data: { data: JsonRpcRequest; jobId: string }) {\n const { jobId, data: request } = data;\n\n const job = this.jobs.get(jobId);\n if (!job) {\n // This ensures that a job is initialized before it is used. To avoid\n // code duplication, we call the `#onData` method again, which will\n // run the rest of the logic after initialization.\n this.#initializeJob(jobId)\n .then(() => {\n this.#onData(data);\n })\n .catch((error) => {\n logError('[Worker] Error initializing job:', error.toString());\n\n this.#stream.write({\n jobId,\n data: {\n name: 'command',\n data: {\n jsonrpc: '2.0',\n id: request.id ?? null,\n error: {\n code: -32000,\n message: 'Internal error',\n },\n },\n },\n });\n });\n\n return;\n }\n\n // This is a method specific to the `WebWorkerPool`, as the service itself\n // does not have access to the workers directly.\n if (request.method === 'terminateJob') {\n this.#terminateJob(jobId);\n return;\n }\n\n job.stream.write(request);\n }\n\n /**\n * Create a new worker and set up a stream to communicate with it.\n *\n * @param jobId - The job ID.\n * @returns The job.\n */\n async #initializeJob(jobId: string): Promise<ExecutorJob> {\n const worker = await this.#getWorker();\n const jobStream = new WebWorkerParentPostMessageStream({\n worker,\n });\n\n // Write messages from the worker to the parent, wrapped with the job ID.\n jobStream.on('data', (data) => {\n this.#stream.write({ data, jobId });\n });\n\n const job = { id: jobId, worker, stream: jobStream };\n this.jobs.set(jobId, job);\n return job;\n }\n\n /**\n * Terminate the job with the given ID. This will close the worker and delete\n * the job from the internal job map.\n *\n * @param jobId - The job ID.\n */\n #terminateJob(jobId: string) {\n const job = this.jobs.get(jobId);\n assert(job, `Job \"${jobId}\" not found.`);\n\n job.stream.destroy();\n job.worker.terminate();\n\n this.jobs.delete(jobId);\n }\n\n /**\n * Get a worker from the pool. A new worker will be created automatically.\n *\n * @returns The worker.\n */\n async #getWorker() {\n // Lazily create the pool of workers.\n if (this.pool.length === 0) {\n await this.#updatePool();\n }\n\n const worker = this.pool.shift();\n assert(worker, 'Worker not found.');\n\n await this.#updatePool();\n\n return worker;\n }\n\n /**\n * Update the pool of workers. This will create new workers if the pool is\n * below the minimum size.\n */\n async #updatePool() {\n while (this.pool.length < this.#poolSize) {\n const worker = await this.#createWorker();\n this.pool.push(worker);\n }\n }\n\n /**\n * Create a new worker. This will fetch the worker source if it has not\n * already been fetched.\n *\n * @returns The worker.\n */\n async #createWorker() {\n return new Worker(await this.#getWorkerURL(), {\n name: `worker-${nanoid()}`,\n });\n }\n\n /**\n * Get the URL of the worker source. This will fetch the worker source if it\n * has not already been fetched.\n *\n * @returns The worker source URL, as a `blob:` URL.\n */\n async #getWorkerURL() {\n if (this.#workerSourceURL) {\n return this.#workerSourceURL;\n }\n\n const blob = await fetch(this.#url)\n .then(async (response) => response.blob())\n .then(URL.createObjectURL.bind(URL));\n\n this.#workerSourceURL = blob;\n return blob;\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const lockdown_events_1 = require("../../common/lockdown/lockdown-events");
|
|
4
|
+
const lockdown_more_1 = require("../../common/lockdown/lockdown-more");
|
|
5
|
+
const WebWorkerPool_1 = require("./WebWorkerPool");
|
|
6
|
+
// Lockdown is already applied in LavaMoat
|
|
7
|
+
(0, lockdown_more_1.executeLockdownMore)();
|
|
8
|
+
(0, lockdown_events_1.executeLockdownEvents)();
|
|
9
|
+
WebWorkerPool_1.WebWorkerPool.initialize();
|
|
10
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/webworker/pool/index.ts"],"names":[],"mappings":";;AAAA,2EAA8E;AAC9E,uEAA0E;AAC1E,mDAAgD;AAEhD,0CAA0C;AAC1C,IAAA,mCAAmB,GAAE,CAAC;AACtB,IAAA,uCAAqB,GAAE,CAAC;AAExB,6BAAa,CAAC,UAAU,EAAE,CAAC","sourcesContent":["import { executeLockdownEvents } from '../../common/lockdown/lockdown-events';\nimport { executeLockdownMore } from '../../common/lockdown/lockdown-more';\nimport { WebWorkerPool } from './WebWorkerPool';\n\n// Lockdown is already applied in LavaMoat\nexecuteLockdownMore();\nexecuteLockdownEvents();\n\nWebWorkerPool.initialize();\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-execution-environments",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.33.0-flask.1",
|
|
4
4
|
"description": "Snap sandbox environments for executing SES javascript",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -32,18 +32,18 @@
|
|
|
32
32
|
"build:lavamoat:policy": "yarn build:lavamoat --writeAutoPolicy && node scripts/build.js --writeAutoPolicy",
|
|
33
33
|
"auto-changelog-init": "auto-changelog init",
|
|
34
34
|
"prepare-manifest:preview": "../../scripts/prepare-preview-manifest.sh",
|
|
35
|
-
"publish:preview": "yarn npm publish --tag preview"
|
|
36
|
-
"publish:package": "../../scripts/publish-package.sh"
|
|
35
|
+
"publish:preview": "yarn npm publish --tag preview"
|
|
37
36
|
},
|
|
38
37
|
"dependencies": {
|
|
39
38
|
"@metamask/object-multiplex": "^1.2.0",
|
|
40
|
-
"@metamask/post-message-stream": "^6.1.
|
|
41
|
-
"@metamask/providers": "^10.2.
|
|
42
|
-
"@metamask/rpc-methods": "^0.
|
|
43
|
-
"@metamask/snaps-utils": "^0.
|
|
39
|
+
"@metamask/post-message-stream": "^6.1.2",
|
|
40
|
+
"@metamask/providers": "^10.2.1",
|
|
41
|
+
"@metamask/rpc-methods": "^0.33.0-flask.1",
|
|
42
|
+
"@metamask/snaps-utils": "^0.33.0-flask.1",
|
|
44
43
|
"@metamask/utils": "^5.0.0",
|
|
45
44
|
"eth-rpc-errors": "^4.0.3",
|
|
46
45
|
"json-rpc-engine": "^6.1.0",
|
|
46
|
+
"nanoid": "^3.1.31",
|
|
47
47
|
"pump": "^3.0.0",
|
|
48
48
|
"ses": "^0.18.1",
|
|
49
49
|
"stream-browserify": "^3.0.0",
|
|
@@ -51,12 +51,12 @@
|
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@babel/core": "^7.20.12",
|
|
54
|
-
"@babel/preset-env": "^7.20.
|
|
55
|
-
"@babel/preset-typescript": "^7.
|
|
54
|
+
"@babel/preset-env": "^7.20.12",
|
|
55
|
+
"@babel/preset-typescript": "^7.20.12",
|
|
56
56
|
"@browserify/uglifyify": "^6.0.0",
|
|
57
57
|
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
|
|
58
58
|
"@esbuild-plugins/node-modules-polyfill": "^0.2.2",
|
|
59
|
-
"@lavamoat/allow-scripts": "^2.
|
|
59
|
+
"@lavamoat/allow-scripts": "^2.3.1",
|
|
60
60
|
"@lavamoat/lavapack": "^3.3.0",
|
|
61
61
|
"@lavamoat/lavatube": "^0.0.1",
|
|
62
62
|
"@metamask/auto-changelog": "^3.1.0",
|
|
@@ -64,23 +64,24 @@
|
|
|
64
64
|
"@metamask/eslint-config-jest": "^11.0.0",
|
|
65
65
|
"@metamask/eslint-config-nodejs": "^11.0.1",
|
|
66
66
|
"@metamask/eslint-config-typescript": "^11.0.0",
|
|
67
|
+
"@types/express": "^4.17.17",
|
|
67
68
|
"@types/jest": "^27.5.1",
|
|
68
69
|
"@types/node": "^17.0.36",
|
|
69
70
|
"@typescript-eslint/eslint-plugin": "^5.42.1",
|
|
70
71
|
"@typescript-eslint/parser": "^5.42.1",
|
|
71
|
-
"@wdio/browser-runner": "^8.
|
|
72
|
-
"@wdio/cli": "^8.
|
|
73
|
-
"@wdio/globals": "^8.
|
|
74
|
-
"@wdio/mocha-framework": "^8.
|
|
75
|
-
"@wdio/spec-reporter": "^8.
|
|
76
|
-
"@wdio/static-server-service": "^8.
|
|
77
|
-
"babel-loader": "^9.1.2",
|
|
72
|
+
"@wdio/browser-runner": "^8.5.2",
|
|
73
|
+
"@wdio/cli": "^8.5.2",
|
|
74
|
+
"@wdio/globals": "^8.5.2",
|
|
75
|
+
"@wdio/mocha-framework": "^8.5.2",
|
|
76
|
+
"@wdio/spec-reporter": "^8.5.2",
|
|
77
|
+
"@wdio/static-server-service": "^8.5.2",
|
|
78
78
|
"babel-plugin-tsconfig-paths-module-resolver": "^1.0.4",
|
|
79
79
|
"babelify": "^10.0.0",
|
|
80
80
|
"browserify": "^17.0.0",
|
|
81
81
|
"buffer": "^6.0.3",
|
|
82
82
|
"common-shakeify": "^1.1.2",
|
|
83
83
|
"deepmerge": "^4.2.2",
|
|
84
|
+
"esbuild": "^0.17.15",
|
|
84
85
|
"eslint": "^8.27.0",
|
|
85
86
|
"eslint-config-prettier": "^8.5.0",
|
|
86
87
|
"eslint-plugin-import": "^2.26.0",
|
|
@@ -101,7 +102,7 @@
|
|
|
101
102
|
"prettier-plugin-packagejson": "^2.2.11",
|
|
102
103
|
"process": "^0.11.10",
|
|
103
104
|
"rimraf": "^4.1.2",
|
|
104
|
-
"ts-jest": "^29.0.
|
|
105
|
+
"ts-jest": "^29.0.2",
|
|
105
106
|
"ts-node": "^10.9.1",
|
|
106
107
|
"tsconfig-paths": "^4.1.2",
|
|
107
108
|
"typescript": "~4.8.4",
|
|
@@ -109,7 +110,7 @@
|
|
|
109
110
|
"vite-tsconfig-paths": "^4.0.5",
|
|
110
111
|
"wdio-chromedriver-service": "^8.1.1",
|
|
111
112
|
"wdio-geckodriver-service": "^4.1.0",
|
|
112
|
-
"webdriverio": "^8.
|
|
113
|
+
"webdriverio": "^8.5.2",
|
|
113
114
|
"yargs": "^17.7.1"
|
|
114
115
|
},
|
|
115
116
|
"engines": {
|
|
@@ -119,4 +120,4 @@
|
|
|
119
120
|
"access": "public",
|
|
120
121
|
"registry": "https://registry.npmjs.org/"
|
|
121
122
|
}
|
|
122
|
-
}
|
|
123
|
+
}
|