@metamask/snaps-execution-environments 3.5.0 → 4.0.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/dist/browserify/iframe/bundle.js +5 -5
  3. package/dist/browserify/iframe/index.html +202 -111
  4. package/dist/browserify/node-process/bundle.js +205 -114
  5. package/dist/browserify/node-thread/bundle.js +205 -114
  6. package/dist/browserify/webview/bundle.js +9 -0
  7. package/dist/browserify/{offscreen → webview}/index.html +202 -111
  8. package/dist/browserify/worker-executor/bundle.js +207 -116
  9. package/dist/browserify/worker-pool/bundle.js +5 -5
  10. package/dist/browserify/worker-pool/index.html +202 -111
  11. package/dist/cjs/common/BaseSnapExecutor.js +2 -2
  12. package/dist/cjs/common/BaseSnapExecutor.js.map +1 -1
  13. package/dist/cjs/common/commands.js +9 -0
  14. package/dist/cjs/common/commands.js.map +1 -1
  15. package/dist/cjs/common/validation.js +14 -0
  16. package/dist/cjs/common/validation.js.map +1 -1
  17. package/dist/cjs/index.js +20 -0
  18. package/dist/cjs/index.js.map +1 -0
  19. package/dist/cjs/proxy/ProxySnapExecutor.js +2 -2
  20. package/dist/cjs/proxy/ProxySnapExecutor.js.map +1 -1
  21. package/dist/cjs/proxy/index.js +20 -0
  22. package/dist/cjs/proxy/index.js.map +1 -0
  23. package/dist/cjs/webview/WebViewExecutorStream.js +121 -0
  24. package/dist/cjs/webview/WebViewExecutorStream.js.map +1 -0
  25. package/dist/cjs/{offscreen → webview}/index.js +4 -4
  26. package/dist/cjs/webview/index.js.map +1 -0
  27. package/dist/esm/common/BaseSnapExecutor.js +1 -1
  28. package/dist/esm/common/BaseSnapExecutor.js.map +1 -1
  29. package/dist/esm/common/commands.js +10 -1
  30. package/dist/esm/common/commands.js.map +1 -1
  31. package/dist/esm/common/validation.js +15 -0
  32. package/dist/esm/common/validation.js.map +1 -1
  33. package/dist/esm/index.js +3 -0
  34. package/dist/esm/index.js.map +1 -0
  35. package/dist/esm/proxy/ProxySnapExecutor.js +2 -2
  36. package/dist/esm/proxy/ProxySnapExecutor.js.map +1 -1
  37. package/dist/esm/proxy/index.js +3 -0
  38. package/dist/esm/proxy/index.js.map +1 -0
  39. package/dist/esm/webview/WebViewExecutorStream.js +111 -0
  40. package/dist/esm/webview/WebViewExecutorStream.js.map +1 -0
  41. package/dist/esm/{offscreen → webview}/index.js +4 -4
  42. package/dist/esm/webview/index.js.map +1 -0
  43. package/dist/types/common/validation.d.ts +31 -0
  44. package/dist/types/index.d.ts +1 -0
  45. package/dist/types/proxy/index.d.ts +1 -0
  46. package/dist/types/webview/WebViewExecutorStream.d.ts +32 -0
  47. package/package.json +9 -9
  48. package/dist/browserify/offscreen/bundle.js +0 -9
  49. package/dist/cjs/offscreen/index.js.map +0 -1
  50. package/dist/esm/offscreen/index.js.map +0 -1
  51. /package/dist/types/{offscreen → webview}/index.d.ts +0 -0
@@ -100,7 +100,7 @@
100
100
  // security options are hard-coded at build time
101
101
  const {
102
102
  scuttleGlobalThis,
103
- } = {"scuttleGlobalThis":{"enabled":true,"exceptions":["postMessage","removeEventListener","isSecureContext"]}}
103
+ } = {"scuttleGlobalThis":{"enabled":true,"exceptions":["postMessage","removeEventListener","isSecureContext","ReactNativeWebView","JSON","String"]}}
104
104
 
105
105
  function getGlobalRef () {
106
106
  if (typeof globalThis !== 'undefined') {
@@ -12741,8 +12741,207 @@ module.exports = {
12741
12741
  })()
12742
12742
  return module.exports
12743
12743
  })()
12744
+ const { scuttle } = // define scuttle
12745
+ (function(){
12746
+ const global = globalRef
12747
+ const exports = {}
12748
+ const module = { exports }
12749
+ ;(function(){
12750
+ // START of injected code from scuttle
12751
+ /**
12752
+ * @typedef {object} ScuttleOpts
12753
+ * @property {boolean} enabled - Whether scuttling is enabled or not.
12754
+ * @property {Array<string|RegExp>} exceptions - List of properties to exclude from scuttling.
12755
+ * @property {string} scuttlerName - Name of the scuttler function to use which is expected to be found as a
12756
+ * property on the global object (e.g. if scuttlerName is 'x', scuttler function is obtained from globalThis['x']).
12757
+ */
12758
+
12759
+ /**
12760
+ * @typedef {object} GlobalRef
12761
+ * @property {Record<string, any>} [globalThis] - Reference to the global object.
12762
+ */
12763
+
12764
+ const { Object, Array, Error, RegExp, Set, console, Proxy, Reflect } =
12765
+ globalThis
12766
+
12767
+ const {
12768
+ assign,
12769
+ getOwnPropertyNames,
12770
+ getOwnPropertyDescriptor,
12771
+ create,
12772
+ defineProperty,
12773
+ } = Object
12774
+
12775
+ const { isArray, from } = Array
12776
+
12777
+ const { getPrototypeOf } = Reflect
12778
+
12779
+ const { warn } = console
12780
+
12781
+ function generateInvokers(prop) {
12782
+ return { get, set }
12783
+ function set() {
12784
+ warn(
12785
+ `LavaMoat - property "${prop}" of globalThis cannot be set under scuttling mode. ` +
12786
+ 'To learn more visit https://github.com/LavaMoat/LavaMoat/pull/360.'
12787
+ )
12788
+ }
12789
+ function get() {
12790
+ throw new Error(
12791
+ `LavaMoat - property "${prop}" of globalThis is inaccessible under scuttling mode. ` +
12792
+ 'To learn more visit https://github.com/LavaMoat/LavaMoat/pull/360.'
12793
+ )
12794
+ }
12795
+ }
12796
+
12797
+ /**
12798
+ * Applies scuttling, with the default set of options, including using Snow if passed in as scuttlerFunc.
12799
+ * Scuttle globalThis right after we used it to create the root package compartment.
12800
+ *
12801
+ * @param {GlobalRef} globalRef - Reference to the global object.
12802
+ * @param {ScuttleOpts} opts - Scuttling options.
12803
+ */
12804
+ function scuttle(globalRef, opts) {
12805
+ const scuttleOpts = generateScuttleOpts(globalRef, opts)
12806
+
12807
+ if (scuttleOpts.enabled) {
12808
+ if (!isArray(scuttleOpts.exceptions)) {
12809
+ throw new Error(
12810
+ `LavaMoat - exceptions must be an array, got ${typeof scuttleOpts.exceptions}`
12811
+ )
12812
+ }
12813
+ scuttleOpts.scuttlerFunc(globalRef, (realm) =>
12814
+ performScuttleGlobalThis(realm, scuttleOpts.exceptions)
12815
+ )
12816
+ }
12817
+ }
12818
+
12819
+ /**
12820
+ * @param {GlobalRef} globalRef - Reference to the global object.
12821
+ * @param {ScuttleOpts|boolean} originalOpts - Scuttling options. Accepts `true` for backwards compatibility.
12822
+ * @returns {ScuttleOpts} - Final scuttling options.
12823
+ */
12824
+ function generateScuttleOpts(globalRef, originalOpts = create(null)) {
12825
+ const defaultOpts = {
12826
+ enabled: true,
12827
+ exceptions: [],
12828
+ scuttlerName: '',
12829
+ }
12830
+ const opts = assign(
12831
+ create(null),
12832
+ originalOpts === true ? defaultOpts : originalOpts,
12833
+ {
12834
+ scuttlerFunc: (globalRef, scuttle) => scuttle(globalRef),
12835
+ },
12836
+ {
12837
+ exceptions: (originalOpts?.exceptions || defaultOpts.exceptions).map(
12838
+ (e) => toRE(e)
12839
+ ),
12840
+ }
12841
+ )
12842
+ if (opts.scuttlerName) {
12843
+ if (!globalRef[opts.scuttlerName]) {
12844
+ throw new Error(
12845
+ `LavaMoat - 'scuttlerName' function "${opts.scuttlerName}" expected on globalRef.` +
12846
+ 'To learn more visit https://github.com/LavaMoat/LavaMoat/pull/462.'
12847
+ )
12848
+ }
12849
+ opts.scuttlerFunc = globalRef[opts.scuttlerName]
12850
+ }
12851
+ return opts
12852
+
12853
+ /**
12854
+ * @param {string|RegExp} except - Exception to convert to RegExp.
12855
+ * @returns {string|RegExp} - Converted exception.
12856
+ */
12857
+ function toRE(except) {
12858
+ // turn scuttleGlobalThis.exceptions regexes strings to actual regexes
12859
+ if (!except.startsWith('/')) {
12860
+ return except
12861
+ }
12862
+ const parts = except.split('/')
12863
+ const pattern = parts.slice(1, -1).join('/')
12864
+ const flags = parts[parts.length - 1]
12865
+ return new RegExp(pattern, flags)
12866
+ }
12867
+ }
12868
+
12869
+ /**
12870
+ * Runs scuttling on the globalRef. Use applyDefaultScuttling for full scope of options.
12871
+ *
12872
+ * @param {GlobalRef} globalRef - Reference to the global object.
12873
+ * @param {Array<string|RegExp>} extraPropsToAvoid - List of additional properties to exclude from scuttling beyond the default ones.
12874
+ */
12875
+ function performScuttleGlobalThis(globalRef, extraPropsToAvoid = []) {
12876
+ const props = []
12877
+ getPrototypeChain(globalRef).forEach((proto) =>
12878
+ props.push(...getOwnPropertyNames(proto))
12879
+ )
12880
+
12881
+ // support LM,SES exported APIs and polyfills
12882
+ const avoidForLavaMoatCompatibility = ['Compartment', 'Error', 'globalThis']
12883
+ const propsToAvoid = new Set([
12884
+ ...avoidForLavaMoatCompatibility,
12885
+ ...extraPropsToAvoid,
12886
+ ])
12887
+
12888
+ const obj = create(null)
12889
+ props.forEach((prop) => {
12890
+ const { get, set } = generateInvokers(prop)
12891
+ if (shouldAvoidProp(propsToAvoid, prop)) {
12892
+ return
12893
+ }
12894
+ let desc = getOwnPropertyDescriptor(globalRef, prop)
12895
+ if (desc?.configurable === true) {
12896
+ desc = { configurable: false, set, get }
12897
+ } else if (desc?.writable === true) {
12898
+ const p = new Proxy(obj, { getPrototypeOf: get, get, set })
12899
+ desc = { configurable: false, writable: false, value: p }
12900
+ } else {
12901
+ return
12902
+ }
12903
+ defineProperty(globalRef, prop, desc)
12904
+ })
12905
+ }
12906
+
12907
+ /**
12908
+ * @param {Set<string|RegExp>} propsToAvoid - List of properties to exclude from scuttling.
12909
+ * @param {string} prop - Property to check.
12910
+ * @returns {boolean} - Whether the property should be avoided or not.
12911
+ */
12912
+ const shouldAvoidProp = (propsToAvoid, prop) =>
12913
+ from(propsToAvoid).some(
12914
+ (avoid) =>
12915
+ (typeof avoid === 'string' && avoid === prop) ||
12916
+ (avoid instanceof RegExp && avoid.test(prop))
12917
+ )
12918
+
12919
+ /**
12920
+ * @param {object} value - object to get the prototype chain from.
12921
+ * @returns {Array<object>} - Prototype chain as an array.
12922
+ */
12923
+ function getPrototypeChain(value) {
12924
+ const protoChain = []
12925
+ let current = value
12926
+ while (current) {
12927
+ if (typeof current !== 'object' && typeof current !== 'function') {
12928
+ break
12929
+ }
12930
+ protoChain.push(current)
12931
+ current = getPrototypeOf(current)
12932
+ }
12933
+ return protoChain
12934
+ }
12935
+
12936
+ module.exports = {
12937
+ scuttle,
12938
+ }
12939
+
12940
+ // END of injected code from scuttle
12941
+ })()
12942
+ return module.exports
12943
+ })()
12744
12944
 
12745
- const scuttleOpts = generateScuttleOpts(scuttleGlobalThis)
12746
12945
  const moduleCache = new Map()
12747
12946
  const packageCompartmentCache = new Map()
12748
12947
  const globalStore = new Map()
@@ -12750,13 +12949,7 @@ module.exports = {
12750
12949
  const rootPackageName = '$root$'
12751
12950
  const rootPackageCompartment = createRootPackageCompartment(globalRef)
12752
12951
 
12753
- // scuttle globalThis right after we used it to create the root package compartment
12754
- if (scuttleOpts.enabled) {
12755
- if (!Array.isArray(scuttleOpts.exceptions)) {
12756
- throw new Error(`LavaMoat - scuttleGlobalThis.exceptions must be an array, got "${typeof scuttleOpts.exceptions}"`)
12757
- }
12758
- scuttleOpts.scuttlerFunc(globalRef, realm => performScuttleGlobalThis(realm, scuttleOpts.exceptions))
12759
- }
12952
+ scuttle(globalRef, scuttleGlobalThis)
12760
12953
 
12761
12954
  const kernel = {
12762
12955
  internalRequire,
@@ -12768,85 +12961,6 @@ module.exports = {
12768
12961
  Object.freeze(kernel)
12769
12962
  return kernel
12770
12963
 
12771
- // generate final scuttling options (1) by taking default
12772
- // options into consideration, (2) turning RE strings into
12773
- // actual REs and (3) without mutating original opts object
12774
- function generateScuttleOpts(originalOpts) {
12775
- const defaultOpts = {
12776
- enabled: true,
12777
- exceptions: [],
12778
- scuttlerName: '',
12779
- }
12780
- const opts = Object.assign({},
12781
- originalOpts === true ? { ... defaultOpts } : { ...originalOpts },
12782
- { scuttlerFunc: (globalRef, scuttle) => scuttle(globalRef) },
12783
- { exceptions: (originalOpts.exceptions || defaultOpts.exceptions).map(e => toRE(e)) },
12784
- )
12785
- if (opts.scuttlerName) {
12786
- if (!globalRef[opts.scuttlerName]) {
12787
- throw new Error(
12788
- `LavaMoat - 'scuttlerName' function "${opts.scuttlerName}" expected on globalRef.` +
12789
- 'To learn more visit https://github.com/LavaMoat/LavaMoat/pull/462.',
12790
- )
12791
- }
12792
- opts.scuttlerFunc = globalRef[opts.scuttlerName]
12793
- }
12794
- return opts
12795
-
12796
- function toRE(except) {
12797
- // turn scuttleGlobalThis.exceptions regexes strings to actual regexes
12798
- if (!except.startsWith('/')) {
12799
- return except
12800
- }
12801
- const parts = except.split('/')
12802
- const pattern = parts.slice(1, -1).join('/')
12803
- const flags = parts[parts.length - 1]
12804
- return new RegExp(pattern, flags)
12805
- }
12806
- }
12807
-
12808
- function performScuttleGlobalThis (globalRef, extraPropsToAvoid = []) {
12809
- const props = []
12810
- getPrototypeChain(globalRef)
12811
- .forEach(proto =>
12812
- props.push(...Object.getOwnPropertyNames(proto)))
12813
-
12814
- // support LM,SES exported APIs and polyfills
12815
- const avoidForLavaMoatCompatibility = ['Compartment', 'Error', 'globalThis']
12816
- const propsToAvoid = new Set([...avoidForLavaMoatCompatibility, ...extraPropsToAvoid])
12817
-
12818
- const obj = Object.create(null)
12819
- for (const prop of props) {
12820
- // eslint-disable-next-line no-inner-declarations
12821
- function set() {
12822
- console.warn(
12823
- `LavaMoat - property "${prop}" of globalThis cannot be set under scuttling mode. ` +
12824
- 'To learn more visit https://github.com/LavaMoat/LavaMoat/pull/360.',
12825
- )
12826
- }
12827
- // eslint-disable-next-line no-inner-declarations
12828
- function get() {
12829
- throw new Error(
12830
- `LavaMoat - property "${prop}" of globalThis is inaccessible under scuttling mode. ` +
12831
- 'To learn more visit https://github.com/LavaMoat/LavaMoat/pull/360.',
12832
- )
12833
- }
12834
- if (shouldAvoidProp(propsToAvoid, prop)) {
12835
- continue
12836
- }
12837
- let desc = Object.getOwnPropertyDescriptor(globalRef, prop)
12838
- if (desc?.configurable === true) {
12839
- desc = { configurable: false, set, get }
12840
- } else if (desc?.writable === true) {
12841
- const p = new Proxy(obj, { getPrototypeOf: get, get, set } )
12842
- desc = { configurable: false, writable: false, value: p }
12843
- } else {
12844
- continue
12845
- }
12846
- Object.defineProperty(globalRef, prop, desc)
12847
- }
12848
- }
12849
-
12850
12964
  // this function instantiaties a module from a moduleId.
12851
12965
  // 1. loads the module metadata and policy
12852
12966
  // 2. prepares the execution environment
@@ -13131,29 +13245,6 @@ module.exports = {
13131
13245
  return packageConfig
13132
13246
  }
13133
13247
 
13134
- // util for getting the prototype chain as an array
13135
- // includes the provided value in the result
13136
- function getPrototypeChain (value) {
13137
- const protoChain = []
13138
- let current = value
13139
- while (current && (typeof current === 'object' || typeof current === 'function')) {
13140
- protoChain.push(current)
13141
- current = Reflect.getPrototypeOf(current)
13142
- }
13143
- return protoChain
13144
- }
13145
-
13146
- function shouldAvoidProp(propsToAvoid, prop) {
13147
- for (const avoid of propsToAvoid) {
13148
- if (avoid instanceof RegExp && avoid.test(prop)) {
13149
- return true
13150
- }
13151
- if (propsToAvoid.has(prop)) {
13152
- return true
13153
- }
13154
- }
13155
- return false
13156
- }
13157
13248
  }
13158
13249
  })()
13159
13250
 
@@ -11,7 +11,7 @@ Object.defineProperty(exports, "BaseSnapExecutor", {
11
11
  }
12
12
  });
13
13
  const _jsonrpcengine = require("@metamask/json-rpc-engine");
14
- const _providers = require("@metamask/providers");
14
+ const _StreamProvider = require("@metamask/providers/dist/StreamProvider");
15
15
  const _rpcerrors = require("@metamask/rpc-errors");
16
16
  const _snapssdk = require("@metamask/snaps-sdk");
17
17
  const _snapsutils = require("@metamask/snaps-utils");
@@ -193,7 +193,7 @@ class BaseSnapExecutor {
193
193
  snapId
194
194
  });
195
195
  };
196
- const provider = new _providers.StreamProvider(this.rpcStream, {
196
+ const provider = new _StreamProvider.StreamProvider(this.rpcStream, {
197
197
  jsonRpcStreamName: 'metamask-provider',
198
198
  rpcMiddleware: [
199
199
  (0, _jsonrpcengine.createIdRemapMiddleware)()
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { validate, is } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n await this.#write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments({\n snap,\n ethereum,\n snapId,\n endowments: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\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 SnapsProvider;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","unhandledError","rpcErrors","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","serializedError","serializeError","shouldIncludeStack","errorData","getErrorData","notify","method","catch","notifyError","logError","onCommandRequest","isJsonRpcRequest","hasProperty","is","id","JsonRpcIdStruct","write","jsonrpc","logInfo","respond","methodNotFound","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","result","methods","rpcError","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","Error","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","bind","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","cause","unwrapError","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validator","SNAP_EXPORTS","originalRequest","request","args","sanitizedArgs","sanitizeRequestArguments","assertSnapOutboundRequest","withTeardown","source","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","WrappedSnapError","size","lastTeardown","commandStream","Map","on","getCommandMethodImplementations","target","handlerType","handler","required","assert","methodNotSupported","getSafeJson","replace","chunk","resolve","requestObject","isValidJson","isObject"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BAqHnDA;;;eAAAA;;;+BApH2B;2BACT;2BAEuB;0BAEzB;4BAatB;uBAeA;6BAEsB;yBAET;0BAE4B;4BACf;8BACqB;4BACxB;wBAOvB;4BAMA;;;;;;;;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;QACF;IACF;AACF;AAEA,eAAA,OAAcC,aAAmD;IAC/D,IAAI,CAACC,IAAAA,kBAAW,EAACD,kBAAkB,CAACE,IAAAA,eAAQ,EAACF,gBAAgB;QAC3D,MAAMtJ,oBAAS,CAACH,QAAQ,CACtB;IAEJ;IAEA,MAAM,0BAAA,IAAI,EAAEmC,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGsH,aAAa;QAChBrH,SAAS;IACX;AACF;AAEA,eAAA,QAAeH,EAAa,EAAEwH,aAAsC;IAClE,IAAI,CAACC,IAAAA,kBAAW,EAACD,kBAAkB,CAACE,IAAAA,eAAQ,EAACF,gBAAgB;QAC3D,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,0BAAA,IAAI,EAAEtH,QAAAA,YAAN,IAAI,EAAQ;YAChBlB,OAAOG,IAAAA,yBAAc,EACnBjB,oBAAS,CAACH,QAAQ,CAChB;YAGJiC;YACAG,SAAS;QACX;QACA;IACF;IAEA,MAAM,0BAAA,IAAI,EAAED,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGsH,aAAa;QAChBxH;QACAG,SAAS;IACX;AACF"}
1
+ {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { StreamProvider } from '@metamask/providers/dist/StreamProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { validate, is } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n await this.#write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments({\n snap,\n ethereum,\n snapId,\n endowments: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\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 SnapsProvider;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","unhandledError","rpcErrors","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","serializedError","serializeError","shouldIncludeStack","errorData","getErrorData","notify","method","catch","notifyError","logError","onCommandRequest","isJsonRpcRequest","hasProperty","is","id","JsonRpcIdStruct","write","jsonrpc","logInfo","respond","methodNotFound","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","result","methods","rpcError","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","Error","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","bind","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","cause","unwrapError","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validator","SNAP_EXPORTS","originalRequest","request","args","sanitizedArgs","sanitizeRequestArguments","assertSnapOutboundRequest","withTeardown","source","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","WrappedSnapError","size","lastTeardown","commandStream","Map","on","getCommandMethodImplementations","target","handlerType","handler","required","assert","methodNotSupported","getSafeJson","replace","chunk","resolve","requestObject","isValidJson","isObject"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BAqHnDA;;;eAAAA;;;+BApH2B;gCAET;2BACuB;0BAEzB;4BAatB;uBAeA;6BAEsB;yBAET;0BAE4B;4BACf;8BACqB;4BACxB;wBAOvB;4BAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYP,MAAMC,gBAAgB;IACpBC,MAAMC,qBAAU,CAACC,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAEA,MAAMC,iBAAiBC,oBAAS,CAC7BH,QAAQ,CAAO;IACdC,SAAS;AACX,GACCG,SAAS;AAUZ;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQC,sCAA0B;QAClCC,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXH,QAAQI,6CAAiC;QACzCF,QAAQ;YAAC;YAAU;YAAc;SAAa;IAChD;IACAG,WAAW;QACTL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,EAACF,gBAAgB;QAC3D,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,0BAAA,IAAI,EAAEtH,QAAAA,YAAN,IAAI,EAAQ;YAChBlB,OAAOG,IAAAA,yBAAc,EACnBjB,oBAAS,CAACH,QAAQ,CAChB;YAGJiC;YACAG,SAAS;QACX;QACA;IACF;IAEA,MAAM,0BAAA,IAAI,EAAED,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGsH,aAAa;QAChBxH;QACAG,SAAS;IACX;AACF"}
@@ -69,6 +69,15 @@ function getHandlerArguments(origin, handler, request) {
69
69
  };
70
70
  case _snapsutils.HandlerType.OnHomePage:
71
71
  return {};
72
+ case _snapsutils.HandlerType.OnUserInput:
73
+ {
74
+ (0, _validation.assertIsOnUserInputRequestArguments)(request.params);
75
+ const { id, event } = request.params;
76
+ return {
77
+ id,
78
+ event
79
+ };
80
+ }
72
81
  default:
73
82
  return (0, _utils.assertExhaustive)(handler);
74
83
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnSignatureRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnSignature: {\n assertIsOnSignatureRequestArguments(request.params);\n\n const { signature, signatureOrigin } = request.params;\n return { signature, signatureOrigin };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n case HandlerType.OnHomePage:\n return {};\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnSignature","assertIsOnSignatureRequestArguments","signature","signatureOrigin","OnNameLookup","assertIsOnNameLookupRequestArguments","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","OnHomePage","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IAiCgBA,mBAAmB;eAAnBA;;IAsEAC,+BAA+B;eAA/BA;;;4BAvGY;uBACK;4BAe1B;AAiBA,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKN,uBAAW,CAACO,WAAW;YAAE;gBAC5BC,IAAAA,+CAAmC,EAACT,QAAQI,MAAM;gBAElD,MAAM,EAAEM,SAAS,EAAEC,eAAe,EAAE,GAAGX,QAAQI,MAAM;gBACrD,OAAO;oBAAEM;oBAAWC;gBAAgB;YACtC;QACA,KAAKV,uBAAW,CAACW,YAAY;YAAE;gBAC7BC,IAAAA,gDAAoC,EAACb,QAAQI,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEQ,MAAM,EAAEC,OAAO,EAAE,GAChCf,QAAQI,MAAM;gBAEhB,OAAOU,SACH;oBACER;oBACAQ;gBACF,IACA;oBACER;oBACAS;gBACF;YACN;QACA,KAAKd,uBAAW,CAACe,YAAY;QAC7B,KAAKf,uBAAW,CAACgB,gBAAgB;YAC/B,OAAO;gBAAEnB;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACiB,SAAS;QAC1B,KAAKjB,uBAAW,CAACkB,SAAS;QAC1B,KAAKlB,uBAAW,CAACmB,QAAQ;YACvB,OAAO;gBAAEpB;YAAQ;QAEnB,KAAKC,uBAAW,CAACoB,UAAU;YACzB,OAAO,CAAC;QAEV;YACE,OAAOC,IAAAA,uBAAgB,EAACvB;IAC5B;AACF;AAaO,SAASF,gCACd0B,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQpC,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMwB,WACLW,QACApC,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnSignatureRequestArguments,\n assertIsOnNameLookupRequestArguments,\n assertIsOnUserInputRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnSignature: {\n assertIsOnSignatureRequestArguments(request.params);\n\n const { signature, signatureOrigin } = request.params;\n return { signature, signatureOrigin };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n case HandlerType.OnHomePage:\n return {};\n case HandlerType.OnUserInput: {\n assertIsOnUserInputRequestArguments(request.params);\n\n const { id, event } = request.params;\n return { id, event };\n }\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnSignature","assertIsOnSignatureRequestArguments","signature","signatureOrigin","OnNameLookup","assertIsOnNameLookupRequestArguments","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","OnHomePage","OnUserInput","assertIsOnUserInputRequestArguments","id","event","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IAkCgBA,mBAAmB;eAAnBA;;IA4EAC,+BAA+B;eAA/BA;;;4BA9GY;uBACK;4BAgB1B;AAiBA,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKN,uBAAW,CAACO,WAAW;YAAE;gBAC5BC,IAAAA,+CAAmC,EAACT,QAAQI,MAAM;gBAElD,MAAM,EAAEM,SAAS,EAAEC,eAAe,EAAE,GAAGX,QAAQI,MAAM;gBACrD,OAAO;oBAAEM;oBAAWC;gBAAgB;YACtC;QACA,KAAKV,uBAAW,CAACW,YAAY;YAAE;gBAC7BC,IAAAA,gDAAoC,EAACb,QAAQI,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEQ,MAAM,EAAEC,OAAO,EAAE,GAChCf,QAAQI,MAAM;gBAEhB,OAAOU,SACH;oBACER;oBACAQ;gBACF,IACA;oBACER;oBACAS;gBACF;YACN;QACA,KAAKd,uBAAW,CAACe,YAAY;QAC7B,KAAKf,uBAAW,CAACgB,gBAAgB;YAC/B,OAAO;gBAAEnB;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACiB,SAAS;QAC1B,KAAKjB,uBAAW,CAACkB,SAAS;QAC1B,KAAKlB,uBAAW,CAACmB,QAAQ;YACvB,OAAO;gBAAEpB;YAAQ;QAEnB,KAAKC,uBAAW,CAACoB,UAAU;YACzB,OAAO,CAAC;QACV,KAAKpB,uBAAW,CAACqB,WAAW;YAAE;gBAC5BC,IAAAA,+CAAmC,EAACvB,QAAQI,MAAM;gBAElD,MAAM,EAAEoB,EAAE,EAAEC,KAAK,EAAE,GAAGzB,QAAQI,MAAM;gBACpC,OAAO;oBAAEoB;oBAAIC;gBAAM;YACrB;QAEA;YACE,OAAOC,IAAAA,uBAAgB,EAAC3B;IAC5B;AACF;AAaO,SAASF,gCACd8B,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQxC,SAASD,QAAQE;YACvC,OACE,AAAC,MAAM4B,WACLW,QACAxC,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
@@ -50,9 +50,16 @@ _export(exports, {
50
50
  },
51
51
  assertIsOnNameLookupRequestArguments: function() {
52
52
  return assertIsOnNameLookupRequestArguments;
53
+ },
54
+ OnUserInputArgumentsStruct: function() {
55
+ return OnUserInputArgumentsStruct;
56
+ },
57
+ assertIsOnUserInputRequestArguments: function() {
58
+ return assertIsOnUserInputRequestArguments;
53
59
  }
54
60
  });
55
61
  const _rpcerrors = require("@metamask/rpc-errors");
62
+ const _snapssdk = require("@metamask/snaps-sdk");
56
63
  const _snapsutils = require("@metamask/snaps-utils");
57
64
  const _utils = require("@metamask/utils");
58
65
  const _superstruct = require("superstruct");
@@ -125,6 +132,13 @@ const OnNameLookupRequestArgumentsStruct = (0, _superstruct.union)([
125
132
  function assertIsOnNameLookupRequestArguments(value) {
126
133
  (0, _utils.assertStruct)(value, OnNameLookupRequestArgumentsStruct, 'Invalid request params', _rpcerrors.rpcErrors.invalidParams);
127
134
  }
135
+ const OnUserInputArgumentsStruct = (0, _superstruct.object)({
136
+ id: (0, _superstruct.string)(),
137
+ event: _snapssdk.UserInputEventStruct
138
+ });
139
+ function assertIsOnUserInputRequestArguments(value) {
140
+ (0, _utils.assertStruct)(value, OnUserInputArgumentsStruct, 'Invalid request params', _rpcerrors.rpcErrors.invalidParams);
141
+ }
128
142
  const OkResponseStruct = (0, _superstruct.object)({
129
143
  id: _utils.JsonRpcIdStruct,
130
144
  jsonrpc: _utils.JsonRpcVersionStruct,