@metamask/snaps-execution-environments 0.30.0 → 0.32.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.
Files changed (61) hide show
  1. package/dist/browserify/iframe/bundle.js +6435 -0
  2. package/dist/{webpack → browserify}/iframe/index.html +1411 -178
  3. package/dist/browserify/node-process/bundle.js +15135 -0
  4. package/dist/browserify/node-thread/bundle.js +15135 -0
  5. package/dist/browserify/offscreen/bundle.js +2266 -0
  6. package/dist/{webpack → browserify}/offscreen/index.html +1411 -178
  7. package/dist/common/BaseSnapExecutor.js +32 -16
  8. package/dist/common/BaseSnapExecutor.js.map +1 -1
  9. package/dist/common/commands.js +1 -2
  10. package/dist/common/commands.js.map +1 -1
  11. package/dist/common/endowments/commonEndowmentFactory.d.ts +1 -0
  12. package/dist/common/endowments/commonEndowmentFactory.js +9 -3
  13. package/dist/common/endowments/commonEndowmentFactory.js.map +1 -1
  14. package/dist/common/endowments/crypto.js +2 -2
  15. package/dist/common/endowments/crypto.js.map +1 -1
  16. package/dist/common/endowments/index.d.ts +0 -7
  17. package/dist/common/endowments/index.js +6 -38
  18. package/dist/common/endowments/index.js.map +1 -1
  19. package/dist/common/endowments/interval.js +1 -1
  20. package/dist/common/endowments/interval.js.map +1 -1
  21. package/dist/common/endowments/math.js +6 -3
  22. package/dist/common/endowments/math.js.map +1 -1
  23. package/dist/common/endowments/network.js +8 -6
  24. package/dist/common/endowments/network.js.map +1 -1
  25. package/dist/common/endowments/timeout.js +1 -1
  26. package/dist/common/endowments/timeout.js.map +1 -1
  27. package/dist/common/keyring.js +1 -1
  28. package/dist/common/keyring.js.map +1 -1
  29. package/dist/common/lockdown/lockdown-events.d.ts +4 -0
  30. package/dist/common/lockdown/lockdown-events.js +60 -0
  31. package/dist/common/lockdown/lockdown-events.js.map +1 -0
  32. package/dist/common/sortParams.js +4 -1
  33. package/dist/common/sortParams.js.map +1 -1
  34. package/dist/common/utils.d.ts +13 -0
  35. package/dist/common/utils.js +45 -1
  36. package/dist/common/utils.js.map +1 -1
  37. package/dist/common/validation.js +1 -2
  38. package/dist/common/validation.js.map +1 -1
  39. package/dist/iframe/IFrameSnapExecutor.d.ts +3 -1
  40. package/dist/iframe/IFrameSnapExecutor.js +8 -8
  41. package/dist/iframe/IFrameSnapExecutor.js.map +1 -1
  42. package/dist/iframe/index.js +3 -2
  43. package/dist/iframe/index.js.map +1 -1
  44. package/dist/node-process/index.js +1 -2
  45. package/dist/node-process/index.js.map +1 -1
  46. package/dist/node-thread/index.js +1 -2
  47. package/dist/node-thread/index.js.map +1 -1
  48. package/dist/offscreen/index.js +3 -2
  49. package/dist/offscreen/index.js.map +1 -1
  50. package/package.json +43 -32
  51. package/dist/iframe-test/index.d.ts +0 -1
  52. package/dist/iframe-test/index.js +0 -8
  53. package/dist/iframe-test/index.js.map +0 -1
  54. package/dist/webpack/iframe/bundle.js +0 -2
  55. package/dist/webpack/iframe/bundle.js.LICENSE.txt +0 -14
  56. package/dist/webpack/node-process/bundle.js +0 -106821
  57. package/dist/webpack/node-process/lockdown.umd.min.js +0 -1
  58. package/dist/webpack/node-thread/bundle.js +0 -106821
  59. package/dist/webpack/node-thread/lockdown.umd.min.js +0 -1
  60. package/dist/webpack/offscreen/bundle.js +0 -2
  61. package/dist/webpack/offscreen/bundle.js.LICENSE.txt +0 -12
@@ -64,8 +64,8 @@ class BaseSnapExecutor {
64
64
  const data = this.snapData.get(target);
65
65
  // We're capturing the handler in case someone modifies the data object before the call
66
66
  const handler = handlerName === snaps_utils_1.HandlerType.SnapKeyring
67
- ? (0, keyring_1.wrapKeyring)(this.notify.bind(this), data === null || data === void 0 ? void 0 : data.exports.keyring)
68
- : data === null || data === void 0 ? void 0 : data.exports[handlerName];
67
+ ? (0, keyring_1.wrapKeyring)(this.notify.bind(this), data?.exports.keyring)
68
+ : data?.exports[handlerName];
69
69
  (0, utils_1.assert)(handler !== undefined, `No ${handlerName} handler exported for snap "${target}`);
70
70
  // TODO: fix handler args type cast
71
71
  let result = await this.executeInSnapContext(target, () => handler(args));
@@ -78,18 +78,20 @@ class BaseSnapExecutor {
78
78
  }, this.onTerminate.bind(this));
79
79
  }
80
80
  errorHandler(error, data) {
81
- var _a;
82
81
  const constructedError = (0, utils_2.constructError)(error);
83
82
  const serializedError = (0, eth_rpc_errors_1.serializeError)(constructedError, {
84
83
  fallbackError,
85
84
  shouldIncludeStack: false,
86
85
  });
87
86
  // We're setting it this way to avoid sentData.stack = undefined
88
- const sentData = Object.assign(Object.assign({}, data), { stack: (_a = constructedError === null || constructedError === void 0 ? void 0 : constructedError.stack) !== null && _a !== void 0 ? _a : null });
87
+ const sentData = { ...data, stack: constructedError?.stack ?? null };
89
88
  this.notify({
90
89
  method: 'UnhandledError',
91
90
  params: {
92
- error: Object.assign(Object.assign({}, serializedError), { data: sentData }),
91
+ error: {
92
+ ...serializedError,
93
+ data: sentData,
94
+ },
93
95
  },
94
96
  });
95
97
  }
@@ -150,13 +152,20 @@ class BaseSnapExecutor {
150
152
  if (!(0, utils_1.isValidJson)(requestObject) || !(0, utils_1.isObject)(requestObject)) {
151
153
  throw new Error('JSON-RPC notifications must be JSON serializable objects');
152
154
  }
153
- this.commandStream.write(Object.assign(Object.assign({}, requestObject), { jsonrpc: '2.0' }));
155
+ this.commandStream.write({
156
+ ...requestObject,
157
+ jsonrpc: '2.0',
158
+ });
154
159
  }
155
160
  respond(id, requestObject) {
156
161
  if (!(0, utils_1.isValidJson)(requestObject) || !(0, utils_1.isObject)(requestObject)) {
157
162
  throw new Error('JSON-RPC responses must be JSON serializable objects.');
158
163
  }
159
- this.commandStream.write(Object.assign(Object.assign({}, requestObject), { id, jsonrpc: '2.0' }));
164
+ this.commandStream.write({
165
+ ...requestObject,
166
+ id,
167
+ jsonrpc: '2.0',
168
+ });
160
169
  }
161
170
  /**
162
171
  * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw
@@ -202,7 +211,19 @@ class BaseSnapExecutor {
202
211
  });
203
212
  (0, globalEvents_1.addEventListener)('unhandledRejection', this.snapPromiseErrorHandler);
204
213
  (0, globalEvents_1.addEventListener)('error', this.snapErrorHandler);
205
- const compartment = new Compartment(Object.assign(Object.assign({}, endowments), { module: snapModule, exports: snapModule.exports, window: Object.assign({}, endowments), self: Object.assign({}, endowments) }));
214
+ const compartment = new Compartment({
215
+ ...endowments,
216
+ module: snapModule,
217
+ exports: snapModule.exports,
218
+ });
219
+ // All of those are JavaScript runtime specific and self referential,
220
+ // but we add them for compatibility sake with external libraries.
221
+ //
222
+ // We can't do that in the injected globals object above
223
+ // because SES creates its own globalThis
224
+ compartment.globalThis.self = compartment.globalThis;
225
+ compartment.globalThis.global = compartment.globalThis;
226
+ compartment.globalThis.window = compartment.globalThis;
206
227
  await this.executeInSnapContext(snapName, () => {
207
228
  compartment.evaluate(sourceCode);
208
229
  this.registerSnapExports(snapName, snapModule);
@@ -233,7 +254,7 @@ class BaseSnapExecutor {
233
254
  data.exports = snaps_utils_1.SNAP_EXPORT_NAMES.reduce((acc, exportName) => {
234
255
  const snapExport = snapModule.exports[exportName];
235
256
  if ((0, validation_1.validateExport)(exportName, snapExport)) {
236
- return Object.assign(Object.assign({}, acc), { [exportName]: snapExport });
257
+ return { ...acc, [exportName]: snapExport };
237
258
  }
238
259
  return acc;
239
260
  }, {});
@@ -247,8 +268,7 @@ class BaseSnapExecutor {
247
268
  createSnapGlobal(provider) {
248
269
  const originalRequest = provider.request.bind(provider);
249
270
  const request = async (args) => {
250
- (0, utils_1.assert)(String.prototype.startsWith.call(args.method, 'wallet_') ||
251
- String.prototype.startsWith.call(args.method, 'snap_'), 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.');
271
+ (0, utils_2.assertSnapOutboundRequest)(args);
252
272
  this.notify({ method: 'OutboundRequest' });
253
273
  try {
254
274
  return await (0, utils_2.withTeardown)(originalRequest(args), this);
@@ -281,11 +301,7 @@ class BaseSnapExecutor {
281
301
  createEIP1193Provider(provider) {
282
302
  const originalRequest = provider.request.bind(provider);
283
303
  const request = async (args) => {
284
- (0, utils_1.assert)(!String.prototype.startsWith.call(args.method, 'snap_'), eth_rpc_errors_1.ethErrors.rpc.methodNotFound({
285
- data: {
286
- method: args.method,
287
- },
288
- }));
304
+ (0, utils_2.assertEthereumOutboundRequest)(args);
289
305
  this.notify({ method: 'OutboundRequest' });
290
306
  try {
291
307
  return await (0, utils_2.withTeardown)(originalRequest(args), this);
@@ -1 +1 @@
1
- {"version":3,"file":"BaseSnapExecutor.js","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,mDAAqD;AAGrD,uDAM+B;AAC/B,2CAUyB;AACzB,mDAAuE;AACvE,qDAA0D;AAE1D,6CAAuC;AAEvC,wCAAiC;AACjC,mEAAgD;AAChD,yCAGoB;AACpB,6CAAgD;AAChD,iDAAuE;AACvE,uCAAwC;AACxC,6CAA6C;AAC7C,mCAA4E;AAC5E,6CAMsB;AAYtB,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE,2BAAU,CAAC,GAAG,CAAC,QAAQ;IAC7B,OAAO,EAAE,6BAA6B;CACvC,CAAC;AAYF;;;;GAIG;AACH,MAAM,6BAA6B,GAAG;IACpC,IAAI,EAAE;QACJ,MAAM,EAAE,uCAA0B;QAClC,MAAM,EAAE,EAAE;KACX;IACD,WAAW,EAAE;QACX,MAAM,EAAE,8CAAiC;QACzC,MAAM,EAAE,CAAC,UAAU,EAAE,YAAY,EAAE,YAAY,CAAC;KACjD;IACD,SAAS,EAAE;QACT,MAAM,EAAE,4CAA+B;QACvC,MAAM,EAAE,EAAE;KACX;IACD,OAAO,EAAE;QACP,MAAM,EAAE,0CAA6B;QACrC,MAAM,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,CAAC;KACnD;CACF,CAAC;AAEF,MAAa,gBAAgB;IAe3B,YAAsB,aAAqB,EAAE,SAAiB;QAFtD,iBAAY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CAAyC,CAC/D,CACF,CAAC,CACP,CAAC;QAEF,oEAAoE;QACpE,MAAM,cAAc,GAAG,EAAE,IAAI,EAAE,IAAK,EAAE,CAAC;QAEvC,IAAI;YACF,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;YAC5C,8CAA8C;YAC9C,oEAAoE;YACpE,uCAAuC;YACvC,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC;SACtD;gBAAS;YACR,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE;gBACtC,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC;gBACvB,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;aAC3B;SACF;IACH,CAAC;CACF;AA/ZD,4CA+ZC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/index.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n SNAP_EXPORT_NAMES,\n logError,\n} from '@metamask/snaps-utils';\nimport {\n isObject,\n isValidJson,\n JsonRpcNotification,\n assert,\n isJsonRpcRequest,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n hasProperty,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport EEOpenRPCDocument from '../openrpc.json';\nimport {\n CommandMethodsMapping,\n getCommandMethodImplementations,\n} from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { wrapKeyring } from './keyring';\nimport { sortParamKeys } from './sortParams';\nimport { constructError, proxyStreamProvider, withTeardown } from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n validateExport,\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\n// TODO: `KeyringParameters` expects a `chainId` for certain methods, but we're\n// not providing it in `getHandlerArguments`, resulting in type errors.\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: ['snapName', '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\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, handlerName, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object before the call\n const handler =\n handlerName === HandlerType.SnapKeyring\n ? wrapKeyring(this.notify.bind(this), data?.exports.keyring)\n : data?.exports[handlerName];\n assert(\n handler !== undefined,\n `No ${handlerName} handler exported for snap \"${target}`,\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 assert(\n isValidJson(result),\n new TypeError('Received non-JSON-serializable value.'),\n );\n return result;\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 if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\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 =\n EXECUTION_ENVIRONMENT_METHODS[\n method as keyof typeof EXECUTION_ENVIRONMENT_METHODS\n ];\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 throw new Error('JSON-RPC responses must be JSON serializable objects.');\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 snapName - The name 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 snapName: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapName}' 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, { snapName });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapName,\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 _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(snapName, {\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 window: { ...endowments },\n self: { ...endowments },\n });\n\n await this.executeInSnapContext(snapName, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapName, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapName);\n throw new Error(\n `Error while running snap '${snapName}': ${(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(snapName: string, snapModule: any) {\n const data = this.snapData.get(snapName);\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 if (validateExport(exportName, 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 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 this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), 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 assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), 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 snapName - The name of the snap to remove.\n */\n private removeSnap(snapName: string): void {\n this.snapData.delete(snapName);\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 snapName - The name 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 snapName: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapName);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapName}\".`,\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 \"${snapName}\" 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"]}
1
+ {"version":3,"file":"BaseSnapExecutor.js","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,mDAAqD;AAGrD,uDAM+B;AAC/B,2CAUyB;AACzB,mDAAuE;AACvE,qDAA0D;AAE1D,6CAAuC;AAEvC,wCAAiC;AACjC,mEAAgD;AAChD,yCAGoB;AACpB,6CAAgD;AAChD,iDAAuE;AACvE,uCAAwC;AACxC,6CAA6C;AAC7C,mCAMiB;AACjB,6CAMsB;AAYtB,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE,2BAAU,CAAC,GAAG,CAAC,QAAQ;IAC7B,OAAO,EAAE,6BAA6B;CACvC,CAAC;AAYF;;;;GAIG;AACH,MAAM,6BAA6B,GAAG;IACpC,IAAI,EAAE;QACJ,MAAM,EAAE,uCAA0B;QAClC,MAAM,EAAE,EAAE;KACX;IACD,WAAW,EAAE;QACX,MAAM,EAAE,8CAAiC;QACzC,MA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O,CAC7B,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CACZ,CAAC,IAAI,GAAG,GAAG,EAAE,CACX,MAAM;QACJ,kEAAkE;QAClE,0BAAS,CAAC,GAAG,CAAC,QAAQ,CACpB,aAAa,QAAQ,yCAAyC,CAC/D,CACF,CAAC,CACP,CAAC;QAEF,oEAAoE;QACpE,MAAM,cAAc,GAAG,EAAE,IAAI,EAAE,IAAK,EAAE,CAAC;QAEvC,IAAI;YACF,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;YAC5C,8CAA8C;YAC9C,oEAAoE;YACpE,uCAAuC;YACvC,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC;SACtD;gBAAS;YACR,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE;gBACtC,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC;gBACvB,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;aAC3B;SACF;IACH,CAAC;CACF;AAvZD,4CAuZC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/index.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n SNAP_EXPORT_NAMES,\n logError,\n} from '@metamask/snaps-utils';\nimport {\n isObject,\n isValidJson,\n JsonRpcNotification,\n assert,\n isJsonRpcRequest,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n hasProperty,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport EEOpenRPCDocument from '../openrpc.json';\nimport {\n CommandMethodsMapping,\n getCommandMethodImplementations,\n} from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { wrapKeyring } from './keyring';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n constructError,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n validateExport,\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\n// TODO: `KeyringParameters` expects a `chainId` for certain methods, but we're\n// not providing it in `getHandlerArguments`, resulting in type errors.\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: ['snapName', '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, handlerName, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object before the call\n const handler =\n handlerName === HandlerType.SnapKeyring\n ? wrapKeyring(this.notify.bind(this), data?.exports.keyring)\n : data?.exports[handlerName];\n assert(\n handler !== undefined,\n `No ${handlerName} handler exported for snap \"${target}`,\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 assert(\n isValidJson(result),\n new TypeError('Received non-JSON-serializable value.'),\n );\n return result;\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 if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\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 throw new Error('JSON-RPC responses must be JSON serializable objects.');\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 snapName - The name 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 snapName: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapName}' 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, { snapName });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapName,\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 _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(snapName, {\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(snapName, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapName, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapName);\n throw new Error(\n `Error while running snap '${snapName}': ${(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(snapName: string, snapModule: any) {\n const data = this.snapData.get(snapName);\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 if (validateExport(exportName, 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 assertSnapOutboundRequest(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), 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 assertEthereumOutboundRequest(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), 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 snapName - The name of the snap to remove.\n */\n private removeSnap(snapName: string): void {\n this.snapData.delete(snapName);\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 snapName - The name 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 snapName: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapName);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapName}\".`,\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 \"${snapName}\" 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"]}
@@ -57,8 +57,7 @@ function getCommandMethodImplementations(startSnap, invokeSnap, onTerminate) {
57
57
  return 'OK';
58
58
  },
59
59
  snapRpc: async (target, handler, origin, request) => {
60
- var _a;
61
- return ((_a = (await invokeSnap(target, handler, getHandlerArguments(origin, handler, request)))) !== null && _a !== void 0 ? _a : null);
60
+ return ((await invokeSnap(target, handler, getHandlerArguments(origin, handler, request))) ?? null);
62
61
  },
63
62
  };
64
63
  }
@@ -1 +1 @@
1
- {"version":3,"file":"commands.js","sourceRoot":"","sources":["../../src/common/commands.ts"],"names":[],"mappings":";;;AAAA,uDAAoD;AACpD,2CAAmD;AAGnD,6CAOsB;AAStB;;;;;;;GAOG;AACH,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AM,EACN,OAAO,EACP,mBAAmB,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAC9C,CAAC,mCAAI,IAAI,CACX,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AA3BD,0EA2BC","sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport {\n assertIsOnTransactionRequestArguments,\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n SnapRpc,\n Terminate,\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\n case HandlerType.OnRpcRequest:\n case HandlerType.SnapKeyring:\n return { origin, request };\n\n case HandlerType.OnCronjob:\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 (snapName, sourceCode, endowments) => {\n await startSnap(snapName, 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"]}
1
+ {"version":3,"file":"commands.js","sourceRoot":"","sources":["../../src/common/commands.ts"],"names":[],"mappings":";;;AAAA,uDAAoD;AACpD,2CAAmD;AAGnD,6CAOsB;AAStB;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CACjC,MAAc,EACd,OAAoB,EACpB,OAAgC;IAEhC,sEAAsE;IAEtE,QAAQ,OAAO,EAAE;QACf,KAAK,yBAAW,CAAC,aAAa,CAAC,CAAC;YAC9B,IAAA,kDAAqC,EAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAEtD,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,iBAAiB,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;YACnE,OAAO;gBACL,WAAW;gBACX,OAAO;gBACP,iBAAiB;aAClB,CAAC;SACH;QAED,KAAK,yBAAW,CAAC,YAAY,CAAC;QAC9B,KAAK,yBAAW,CAAC,WAAW;YAC1B,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QAE7B,KAAK,yBAAW,CAAC,SAAS;YACxB,OAAO,EAAE,OAAO,EAAE,CAAC;QAErB;YACE,OAAO,IAAA,wBAAgB,EAAC,OAAO,CAAC,CAAC;KACpC;AACH,CAAC;AA7BD,kDA6BC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,+BAA+B,CAC7C,SAA8D,EAC9D,UAAsB,EACtB,WAAuB;IAEvB,OAAO;QACL,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC;QACvC,SAAS,EAAE,KAAK,IAAI,EAAE;YACpB,WAAW,EAAE,CAAC;YACd,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QAED,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAE,EAAE;YACtD,MAAM,SAAS,CAAC,QAAQ,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC;YAClD,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE;YAClD,OAAO,CACL,CAAC,MAAM,UAAU,CACf,MAAM,EACN,OAAO,EACP,mBAAmB,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAC9C,CAAC,IAAI,IAAI,CACX,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AA3BD,0EA2BC","sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport {\n assertIsOnTransactionRequestArguments,\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n SnapRpc,\n Terminate,\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\n case HandlerType.OnRpcRequest:\n case HandlerType.SnapKeyring:\n return { origin, request };\n\n case HandlerType.OnCronjob:\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 (snapName, sourceCode, endowments) => {\n await startSnap(snapName, 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"]}
@@ -7,6 +7,7 @@ export declare type EndowmentFactory = {
7
7
  export declare type CommonEndowmentSpecification = {
8
8
  endowment: unknown;
9
9
  name: string;
10
+ bind?: boolean;
10
11
  };
11
12
  /**
12
13
  * Creates a consolidated collection of common endowments.
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ const globalObject_1 = require("../globalObject");
6
7
  const crypto_1 = __importDefault(require("./crypto"));
7
8
  const date_1 = __importDefault(require("./date"));
8
9
  const interval_1 = __importDefault(require("./interval"));
@@ -16,11 +17,12 @@ const commonEndowments = [
16
17
  { endowment: AbortController, name: 'AbortController' },
17
18
  { endowment: AbortSignal, name: 'AbortSignal' },
18
19
  { endowment: ArrayBuffer, name: 'ArrayBuffer' },
19
- { endowment: atob, name: 'atob' },
20
+ { endowment: atob, name: 'atob', bind: true },
20
21
  { endowment: BigInt, name: 'BigInt' },
21
22
  { endowment: BigInt64Array, name: 'BigInt64Array' },
22
23
  { endowment: BigUint64Array, name: 'BigUint64Array' },
23
- { endowment: btoa, name: 'btoa' },
24
+ { endowment: btoa, name: 'btoa', bind: true },
25
+ { endowment: console, name: 'console' },
24
26
  { endowment: DataView, name: 'DataView' },
25
27
  { endowment: Float32Array, name: 'Float32Array' },
26
28
  { endowment: Float64Array, name: 'Float64Array' },
@@ -56,8 +58,12 @@ const buildCommonEndowments = () => {
56
58
  const endowment = {
57
59
  names: [endowmentSpecification.name],
58
60
  factory: () => {
61
+ const boundEndowment = typeof endowmentSpecification.endowment === 'function' &&
62
+ endowmentSpecification.bind
63
+ ? endowmentSpecification.endowment.bind(globalObject_1.rootRealmGlobal)
64
+ : endowmentSpecification.endowment;
59
65
  return {
60
- [endowmentSpecification.name]: harden(endowmentSpecification.endowment),
66
+ [endowmentSpecification.name]: harden(boundEndowment),
61
67
  };
62
68
  },
63
69
  };
@@ -1 +1 @@
1
- {"version":3,"file":"commonEndowmentFactory.js","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":";;;;;AAAA,sDAA8B;AAC9B,kDAA0B;AAC1B,0DAAkC;AAClC,kDAA0B;AAC1B,wDAAgC;AAChC,gEAAwC;AACxC,gEAAwC;AACxC,wDAAgC;AAYhC,6BAA6B;AAC7B,MAAM,gBAAgB,GAAmC;IACvD,EAAE,SAAS,EAAE,eAAe,EAAE,IAAI,EAAE,iBAAiB,EAAE;IACvD,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE;IACjC,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE;IACrC,EAAE,SAAS,EAAE,aAAa,EAAE,IAAI,EAAE,eAAe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EAAE;gBACZ,OAAO;oBACL,CAAC,sBAAsB,CAAC,IAAI,CAAC,EAAE,MAAM,CACnC,sBAAsB,CAAC,SAAS,CACjC;iBACO,CAAC;YACb,CAAC;SACF,CAAC;QACF,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;IAEH,OAAO,kBAAkB,CAAC;AAC5B,CAAC,CAAC;AAEF,kBAAe,qBAAqB,CAAC","sourcesContent":["import crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: () => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob' },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa' },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n return {\n [endowmentSpecification.name]: harden(\n endowmentSpecification.endowment,\n ),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"]}
1
+ {"version":3,"file":"commonEndowmentFactory.js","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":";;;;;AAAA,kDAAkD;AAClD,sDAA8B;AAC9B,kDAA0B;AAC1B,0DAAkC;AAClC,kDAA0B;AAC1B,wDAAgC;AAChC,gEAAwC;AACxC,gEAAwC;AACxC,wDAAgC;AAahC,6BAA6B;AAC7B,MAAM,gBAAgB,GAAmC;IACvD,EAAE,SAAS,EAAE,eAAe,EAAE,IAAI,EAAE,iBAAiB,EAAE;IACvD,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE;IAC7C,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE;IACrC,EAAE,SAAS,EAAE,aAAa,EAAE,IAAI,EAAE,eAAe,EAAE;IACnD,EAAE,SAAS,EAAE,cAAc,EAAE,IAAI,EAAE,gBAAgB,EAAE;IACrD,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE;IAC7C,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE;IACvC,EAAE,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,IAAI,CAAC,8BAAe,CAAC;oBACxD,CAAC,CAAC,sBAAsB,CAAC,SAAS,CAAC;gBACvC,OAAO;oBACL,CAAC,sBAAsB,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,cAAc,CAAC;iBAC7C,CAAC;YACb,CAAC;SACF,CAAC;QACF,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;IAEH,OAAO,kBAAkB,CAAC;AAC5B,CAAC,CAAC;AAEF,kBAAe,qBAAqB,CAAC","sourcesContent":["import { rootRealmGlobal } from '../globalObject';\nimport crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: () => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n bind?: boolean;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob', bind: true },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa', bind: true },\n { endowment: console, name: 'console' },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n const boundEndowment =\n typeof endowmentSpecification.endowment === 'function' &&\n endowmentSpecification.bind\n ? endowmentSpecification.endowment.bind(rootRealmGlobal)\n : endowmentSpecification.endowment;\n return {\n [endowmentSpecification.name]: harden(boundEndowment),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"]}
@@ -7,8 +7,8 @@ const createCrypto = () => {
7
7
  'SubtleCrypto' in globalObject_1.rootRealmGlobal &&
8
8
  typeof globalObject_1.rootRealmGlobal.SubtleCrypto === 'function') {
9
9
  return {
10
- crypto: globalObject_1.rootRealmGlobal.crypto,
11
- SubtleCrypto: globalObject_1.rootRealmGlobal.SubtleCrypto,
10
+ crypto: harden(globalObject_1.rootRealmGlobal.crypto),
11
+ SubtleCrypto: harden(globalObject_1.rootRealmGlobal.SubtleCrypto),
12
12
  };
13
13
  }
14
14
  // For now, we expose the experimental webcrypto API for Node.js execution environments
@@ -1 +1 @@
1
- {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../../src/common/endowments/crypto.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD,MAAM,YAAY,GAAG,GAAG,EAAE;IACxB,IACE,QAAQ,IAAI,8BAAe;QAC3B,OAAO,8BAAe,CAAC,MAAM,KAAK,QAAQ;QAC1C,cAAc,IAAI,8BAAe;QACjC,OAAO,8BAAe,CAAC,YAAY,KAAK,UAAU,EAClD;QACA,OAAO;YACL,MAAM,EAAE,8BAAe,CAAC,MAAM;YAC9B,YAAY,EAAE,8BAAe,CAAC,YAAY;SAC3C,CAAC;KACH;IACD,uFAAuF;IACvF,+EAA+E;IAC/E,6HAA6H;IAC7H,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC;IAC3C,OAAO;QACL,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC;QACtB,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC;KACvC,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,QAAQ,EAAE,cAAc,CAAU;IAC1C,OAAO,EAAE,YAAY;CACtB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["import { rootRealmGlobal } from '../globalObject';\n\nconst createCrypto = () => {\n if (\n 'crypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.crypto === 'object' &&\n 'SubtleCrypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.SubtleCrypto === 'function'\n ) {\n return {\n crypto: rootRealmGlobal.crypto,\n SubtleCrypto: rootRealmGlobal.SubtleCrypto,\n };\n }\n // For now, we expose the experimental webcrypto API for Node.js execution environments\n // TODO: Figure out if this is enough long-term or if we should use a polyfill.\n /* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */\n const crypto = require('crypto').webcrypto;\n return {\n crypto: harden(crypto),\n SubtleCrypto: harden(crypto.subtle.constructor),\n } as const;\n};\n\nconst endowmentModule = {\n names: ['crypto', 'SubtleCrypto'] as const,\n factory: createCrypto,\n};\nexport default endowmentModule;\n"]}
1
+ {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../../src/common/endowments/crypto.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD,MAAM,YAAY,GAAG,GAAG,EAAE;IACxB,IACE,QAAQ,IAAI,8BAAe;QAC3B,OAAO,8BAAe,CAAC,MAAM,KAAK,QAAQ;QAC1C,cAAc,IAAI,8BAAe;QACjC,OAAO,8BAAe,CAAC,YAAY,KAAK,UAAU,EAClD;QACA,OAAO;YACL,MAAM,EAAE,MAAM,CAAC,8BAAe,CAAC,MAAM,CAAC;YACtC,YAAY,EAAE,MAAM,CAAC,8BAAe,CAAC,YAAY,CAAC;SACnD,CAAC;KACH;IACD,uFAAuF;IACvF,+EAA+E;IAC/E,6HAA6H;IAC7H,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC;IAC3C,OAAO;QACL,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC;QACtB,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC;KACvC,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,QAAQ,EAAE,cAAc,CAAU;IAC1C,OAAO,EAAE,YAAY;CACtB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["import { rootRealmGlobal } from '../globalObject';\n\nconst createCrypto = () => {\n if (\n 'crypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.crypto === 'object' &&\n 'SubtleCrypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.SubtleCrypto === 'function'\n ) {\n return {\n crypto: harden(rootRealmGlobal.crypto),\n SubtleCrypto: harden(rootRealmGlobal.SubtleCrypto),\n };\n }\n // For now, we expose the experimental webcrypto API for Node.js execution environments\n // TODO: Figure out if this is enough long-term or if we should use a polyfill.\n /* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */\n const crypto = require('crypto').webcrypto;\n return {\n crypto: harden(crypto),\n SubtleCrypto: harden(crypto.subtle.constructor),\n } as const;\n};\n\nconst endowmentModule = {\n names: ['crypto', 'SubtleCrypto'] as const,\n factory: createCrypto,\n};\nexport default endowmentModule;\n"]}
@@ -16,10 +16,3 @@ export declare function createEndowments(snap: SnapsGlobalObject, ethereum: Stre
16
16
  endowments: Record<string, unknown>;
17
17
  teardown: () => Promise<void>;
18
18
  };
19
- /**
20
- * Checks whether the specified function is a constructor.
21
- *
22
- * @param value - Any function value.
23
- * @returns Whether the specified function is a constructor.
24
- */
25
- export declare function isConstructor<T extends Function>(value: T): boolean;
@@ -1,20 +1,10 @@
1
1
  "use strict";
2
- var __rest = (this && this.__rest) || function (s, e) {
3
- var t = {};
4
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
- t[p] = s[p];
6
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
- t[p[i]] = s[p[i]];
10
- }
11
- return t;
12
- };
13
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
14
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
4
  };
16
5
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.isConstructor = exports.createEndowments = void 0;
6
+ exports.createEndowments = void 0;
7
+ const snaps_utils_1 = require("@metamask/snaps-utils");
18
8
  const utils_1 = require("@metamask/utils");
19
9
  const globalObject_1 = require("../globalObject");
20
10
  const commonEndowmentFactory_1 = __importDefault(require("./commonEndowmentFactory"));
@@ -60,9 +50,9 @@ function createEndowments(snap, ethereum, endowments = []) {
60
50
  // if explicitly listed among its endowment.
61
51
  // This may not have an actual use case, but, safety first.
62
52
  // We just confirmed that endowmentFactories has the specified key.
63
- const _a =
53
+ const { teardownFunction, ...endowment } =
64
54
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
65
- endowmentFactories.get(endowmentName)(), { teardownFunction } = _a, endowment = __rest(_a, ["teardownFunction"]);
55
+ endowmentFactories.get(endowmentName)();
66
56
  Object.assign(attenuatedEndowments, endowment);
67
57
  if (teardownFunction) {
68
58
  teardowns.push(teardownFunction);
@@ -75,13 +65,11 @@ function createEndowments(snap, ethereum, endowments = []) {
75
65
  allEndowments[endowmentName] = ethereum;
76
66
  }
77
67
  else if (endowmentName in globalObject_1.rootRealmGlobal) {
68
+ (0, snaps_utils_1.logWarning)(`Access to unhardened global ${endowmentName}.`);
78
69
  // If the endowment doesn't have a factory, just use whatever is on the
79
70
  // global object.
80
71
  const globalValue = globalObject_1.rootRealmGlobal[endowmentName];
81
- allEndowments[endowmentName] =
82
- typeof globalValue === 'function' && !isConstructor(globalValue)
83
- ? globalValue.bind(globalObject_1.rootRealmGlobal)
84
- : globalValue;
72
+ allEndowments[endowmentName] = globalValue;
85
73
  }
86
74
  else {
87
75
  // If we get to this point, we've been passed an endowment that doesn't
@@ -99,24 +87,4 @@ function createEndowments(snap, ethereum, endowments = []) {
99
87
  return { endowments: result.allEndowments, teardown };
100
88
  }
101
89
  exports.createEndowments = createEndowments;
102
- /**
103
- * Checks whether the specified function is a constructor.
104
- *
105
- * @param value - Any function value.
106
- * @returns Whether the specified function is a constructor.
107
- */
108
- // `Function` is exactly what we want here.
109
- // eslint-disable-next-line @typescript-eslint/ban-types
110
- function isConstructor(value) {
111
- var _a, _b;
112
- // In our current usage, the string `prototype.constructor.name` should never
113
- // be empty, because you can't create a class with no name, and the
114
- // `prototype.constructor.name` property is configurable but not writable.
115
- // Nevertheless, that property was the empty string for `Date` in the iframe
116
- // execution environment during local testing. We have no idea why, but we
117
- // have to handle that case.
118
- // TODO: Does the `prototype` object always have a `constructor` property?
119
- return Boolean(typeof ((_b = (_a = value.prototype) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) === 'string');
120
- }
121
- exports.isConstructor = isConstructor;
122
90
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAEA,2CAA8C;AAE9C,kDAAkD;AAClD,sFAA6D;AAe7D;;GAEG;AACH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,CAAC,OAAO,CAAA,MAAA,MAAA,KAAK,CAAC,SAAS,0CAAE,WAAW,0CAAE,IAAI,CAAA,KAAK,QAAQ,CAAC,CAAC;AACzE,CAAC;AATD,sCASC","sourcesContent":["import { StreamProvider } from '@metamask/providers';\nimport { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport buildCommonEndowments 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, () => 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 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 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 const { teardownFunction, ...endowment } =\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n endowmentFactories.get(endowmentName)!();\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\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 // 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] =\n typeof globalValue === 'function' && !isConstructor(globalValue)\n ? globalValue.bind(rootRealmGlobal)\n : 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\n/**\n * Checks whether the specified function is a constructor.\n *\n * @param value - Any function value.\n * @returns Whether the specified function is a constructor.\n */\n// `Function` is exactly what we want here.\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isConstructor<T extends Function>(value: T): boolean {\n // In our current usage, the string `prototype.constructor.name` should never\n // be empty, because you can't create a class with no name, and the\n // `prototype.constructor.name` property is configurable but not writable.\n // Nevertheless, that property was the empty string for `Date` in the iframe\n // execution environment during local testing. We have no idea why, but we\n // have to handle that case.\n // TODO: Does the `prototype` object always have a `constructor` property?\n return Boolean(typeof value.prototype?.constructor?.name === 'string');\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":";;;;;;AAEA,uDAAmD;AACnD,2CAA8C;AAE9C,kDAAkD;AAClD,sFAA6D;AAe7D;;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,EAAwC,CAAC,CAAC;AAEpD;;;;;;;;;;;GAWG;AACH,SAAgB,gBAAgB,CAC9B,IAAuB,EACvB,QAAwB,EACxB,aAAuB,EAAE;IAEzB,MAAM,oBAAoB,GAA4B,EAAE,CAAC;IAEzD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAI9B,CAAC,EAAE,aAAa,EAAE,SAAS,EAAE,EAAE,aAAa,EAAE,EAAE;QAC9C,oEAAoE;QACpE,IAAI,kBAAkB,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE;YACzC,IAAI,CAAC,IAAA,mBAAW,EAAC,oBAAoB,EAAE,aAAa,CAAC,EAAE;gBACrD,uEAAuE;gBACvE,gEAAgE;gBAChE,wEAAwE;gBACxE,4CAA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AAQ,EAAE,CAAC;AACxD,CAAC;AAjED,4CAiEC","sourcesContent":["import { StreamProvider } from '@metamask/providers';\nimport { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport buildCommonEndowments 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, () => 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 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 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 const { teardownFunction, ...endowment } =\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n endowmentFactories.get(endowmentName)!();\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\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"]}
@@ -19,7 +19,7 @@ const createInterval = () => {
19
19
  }
20
20
  harden(handler);
21
21
  const handle = Object.freeze(Object.create(null));
22
- const platformHandle = setInterval(handler, Math.max(MINIMUM_INTERVAL, timeout !== null && timeout !== void 0 ? timeout : 0));
22
+ const platformHandle = setInterval(handler, Math.max(MINIMUM_INTERVAL, timeout ?? 0));
23
23
  registeredHandles.set(handle, platformHandle);
24
24
  return handle;
25
25
  };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AC;SACxB;IACH,CAAC,CAAC;IAEF,OAAO;QACL,WAAW,EAAE,MAAM,CAAC,YAAY,CAAC;QACjC,aAAa,EAAE,MAAM,CAAC,cAAc,CAAC;QACrC,gBAAgB;KACR,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,aAAa,EAAE,eAAe,CAAU;IAChD,OAAO,EAAE,cAAc;CACxB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["const MINIMUM_INTERVAL = 10;\n\n/**\n * Creates a pair of `setInterval` and `clearInterval` functions attenuated such\n * that:\n * - `setInterval` throws if its \"handler\" parameter is not a function.\n * - `clearInterval` only clears timeouts created by its sibling `setInterval`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setInterval` and `clearInterval`\n * functions.\n */\nconst createInterval = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setInterval = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The interval handler must be a function. Received: ${typeof handler}`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setInterval(\n handler,\n Math.max(MINIMUM_INTERVAL, timeout ?? 0),\n );\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearInterval = (handle: unknown): void => {\n harden(handle);\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearInterval(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearInterval(handle);\n }\n };\n\n return {\n setInterval: harden(_setInterval),\n clearInterval: harden(_clearInterval),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setInterval', 'clearInterval'] as const,\n factory: createInterval,\n};\nexport default endowmentModule;\n"]}
1
+ {"version":3,"file":"interval.js","sourceRoot":"","sources":["../../../src/common/endowments/interval.ts"],"names":[],"mappings":";;AAAA,MAAM,gBAAgB,GA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KACR,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,aAAa,EAAE,eAAe,CAAU;IAChD,OAAO,EAAE,cAAc;CACxB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["const MINIMUM_INTERVAL = 10;\n\n/**\n * Creates a pair of `setInterval` and `clearInterval` functions attenuated such\n * that:\n * - `setInterval` throws if its \"handler\" parameter is not a function.\n * - `clearInterval` only clears timeouts created by its sibling `setInterval`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setInterval` and `clearInterval`\n * functions.\n */\nconst createInterval = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setInterval = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The interval handler must be a function. Received: ${typeof handler}`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setInterval(\n handler,\n Math.max(MINIMUM_INTERVAL, timeout ?? 0),\n );\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearInterval = (handle: unknown): void => {\n harden(handle);\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearInterval(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearInterval(handle);\n }\n };\n\n return {\n setInterval: harden(_setInterval),\n clearInterval: harden(_clearInterval),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setInterval', 'clearInterval'] as const,\n factory: createInterval,\n};\nexport default endowmentModule;\n"]}
@@ -16,10 +16,12 @@ function createMath() {
16
16
  if (key === 'random') {
17
17
  return target;
18
18
  }
19
- return Object.assign(Object.assign({}, target), { [key]: globalObject_1.rootRealmGlobal.Math[key] });
19
+ return { ...target, [key]: globalObject_1.rootRealmGlobal.Math[key] };
20
20
  }, {});
21
21
  return harden({
22
- Math: Object.assign(Object.assign({}, math), { random: () => {
22
+ Math: {
23
+ ...math,
24
+ random: () => {
23
25
  // NOTE: This is not intended to be a secure replacement for the weak
24
26
  // random number generator used by `Math.random`. It is only intended to
25
27
  // prevent side channel attacks of `Math.random` by replacing it with an
@@ -37,7 +39,8 @@ function createMath() {
37
39
  // - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey
38
40
  // - https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
39
41
  return crypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;
40
- } }),
42
+ },
43
+ },
41
44
  });
42
45
  }
43
46
  const endowmentModule = {
@@ -1 +1 @@
1
- {"version":3,"file":"math.js","sourceRoot":"","sources":["../../../src/common/endowments/math.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD;;;;;;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,uCAAY,MAAM,KAAE,CAAC,GAAG,CAAC,EAAE,8BAAe,CAAC,IAAI,CAAC,GAAG,CAAC,IAAG;IACzD,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO,MAAM,CAAC;QACZ,IAAI,kCACC,IAAI,KACP,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,MAAM,CAAC,eAAe,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;YACjE,CAAC,GACF;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';\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 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 crypto.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"]}
1
+ {"version":3,"file":"math.js","sourceRoot":"","sources":["../../../src/common/endowments/math.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD;;;;;;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,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,MAAM,CAAC,eAAe,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;YACjE,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';\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 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 crypto.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"]}
@@ -96,7 +96,7 @@ const createNetwork = () => {
96
96
  (callback) => callback());
97
97
  const _fetch = async (input, init) => {
98
98
  const abortController = new AbortController();
99
- if ((init === null || init === void 0 ? void 0 : init.signal) !== null && (init === null || init === void 0 ? void 0 : init.signal) !== undefined) {
99
+ if (init?.signal !== null && init?.signal !== undefined) {
100
100
  const originalSignal = init.signal;
101
101
  // Merge abort controllers
102
102
  originalSignal.addEventListener('abort', () => {
@@ -106,14 +106,17 @@ const createNetwork = () => {
106
106
  let res;
107
107
  let openFetchConnection;
108
108
  try {
109
- const fetchPromise = fetch(input, Object.assign(Object.assign({}, init), { signal: abortController.signal }));
109
+ const fetchPromise = fetch(input, {
110
+ ...init,
111
+ signal: abortController.signal,
112
+ });
110
113
  openFetchConnection = {
111
114
  cancel: async () => {
112
115
  abortController.abort();
113
116
  try {
114
117
  await fetchPromise;
115
118
  }
116
- catch (_a) {
119
+ catch {
117
120
  /* do nothing */
118
121
  }
119
122
  },
@@ -132,11 +135,10 @@ const createNetwork = () => {
132
135
  cancel:
133
136
  /* istanbul ignore next: see it.todo('can be torn down during body read') test */
134
137
  async () => {
135
- var _a;
136
138
  try {
137
- await ((_a = body.deref()) === null || _a === void 0 ? void 0 : _a.cancel());
139
+ await body.deref()?.cancel();
138
140
  }
139
- catch (_b) {
141
+ catch {
140
142
  /* do nothing */
141
143
  }
142
144
  },