@metamask/snaps-execution-environments 3.2.0 → 3.4.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 (33) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/browserify/iframe/bundle.js +4 -4
  3. package/dist/browserify/node-process/bundle.js +4 -4
  4. package/dist/browserify/node-thread/bundle.js +4 -4
  5. package/dist/browserify/offscreen/bundle.js +4 -4
  6. package/dist/browserify/worker-executor/bundle.js +4 -4
  7. package/dist/browserify/worker-pool/bundle.js +4 -4
  8. package/dist/cjs/common/BaseSnapExecutor.js +25 -6
  9. package/dist/cjs/common/BaseSnapExecutor.js.map +1 -1
  10. package/dist/cjs/common/endowments/commonEndowmentFactory.js.map +1 -1
  11. package/dist/cjs/common/endowments/console.js.map +1 -1
  12. package/dist/cjs/common/endowments/index.js +3 -2
  13. package/dist/cjs/common/endowments/index.js.map +1 -1
  14. package/dist/cjs/common/endowments/network.js +130 -43
  15. package/dist/cjs/common/endowments/network.js.map +1 -1
  16. package/dist/cjs/common/validation.js +1 -1
  17. package/dist/cjs/common/validation.js.map +1 -1
  18. package/dist/esm/common/BaseSnapExecutor.js +25 -6
  19. package/dist/esm/common/BaseSnapExecutor.js.map +1 -1
  20. package/dist/esm/common/endowments/commonEndowmentFactory.js.map +1 -1
  21. package/dist/esm/common/endowments/console.js.map +1 -1
  22. package/dist/esm/common/endowments/index.js +9 -6
  23. package/dist/esm/common/endowments/index.js.map +1 -1
  24. package/dist/esm/common/endowments/network.js +129 -42
  25. package/dist/esm/common/endowments/network.js.map +1 -1
  26. package/dist/esm/common/validation.js +1 -1
  27. package/dist/esm/common/validation.js.map +1 -1
  28. package/dist/types/common/BaseSnapExecutor.d.ts +3 -2
  29. package/dist/types/common/endowments/commonEndowmentFactory.d.ts +3 -2
  30. package/dist/types/common/endowments/index.d.ts +15 -7
  31. package/dist/types/common/endowments/network.d.ts +2 -1
  32. package/dist/types/common/validation.d.ts +6 -6
  33. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/network.ts"],"sourcesContent":["import { withTeardown } from '../utils';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n constructor(ogResponse: Response, teardownRef: { lastTeardown: number }) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return withTeardown<string>(this.#ogResponse.text(), this as any);\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return withTeardown<ArrayBuffer>(\n this.#ogResponse.arrayBuffer(),\n this as any,\n );\n }\n\n async blob(): Promise<Blob> {\n return withTeardown<Blob>(this.#ogResponse.blob(), this as any);\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(newResponse, this.#teardownRef);\n }\n\n async formData(): Promise<FormData> {\n return withTeardown<FormData>(this.#ogResponse.formData(), this as any);\n }\n\n async json(): Promise<any> {\n return withTeardown(this.#ogResponse.json(), this as any);\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = () => {\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n try {\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await withTeardown(fetchPromise, teardownRef),\n teardownRef,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n // Request, Headers and Response are the endowments injected alongside fetch\n // only when 'endowment:network-access' permission is requested,\n // therefore these are hardened as part of fetch dependency injection within its factory.\n // These endowments are not (and should never be) available by default.\n Request: harden(Request),\n Headers: harden(Headers),\n Response: harden(Response),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch', 'Request', 'Headers', 'Response'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"],"names":["ResponseWrapper","body","ogResponse","bodyUsed","headers","ok","redirected","status","statusText","type","url","text","withTeardown","arrayBuffer","blob","clone","newResponse","teardownRef","formData","json","constructor","createNetwork","openConnections","Set","lastTeardown","cleanup","FinalizationRegistry","callback","_fetch","input","init","abortController","AbortController","signal","undefined","originalSignal","addEventListener","abort","reason","once","res","openFetchConnection","fetchPromise","fetch","cancel","add","delete","WeakRef","openBodyConnection","deref","register","harden","teardownFunction","promises","forEach","push","clear","Promise","all","Request","Headers","Response","endowmentModule","names","factory"],"mappings":";;;;+BA0MA;;;eAAA;;;uBA1M6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAOlB,4CAET;AAPF;;;CAGC,GACD,MAAMA;IAUJ,IAAIC,OAA0C;QAC5C,OAAO,yBAAA,IAAI,EAAEC,aAAWD,IAAI;IAC9B;IAEA,IAAIE,WAAW;QACb,OAAO,yBAAA,IAAI,EAAED,aAAWC,QAAQ;IAClC;IAEA,IAAIC,UAAU;QACZ,OAAO,yBAAA,IAAI,EAAEF,aAAWE,OAAO;IACjC;IAEA,IAAIC,KAAK;QACP,OAAO,yBAAA,IAAI,EAAEH,aAAWG,EAAE;IAC5B;IAEA,IAAIC,aAAa;QACf,OAAO,yBAAA,IAAI,EAAEJ,aAAWI,UAAU;IACpC;IAEA,IAAIC,SAAS;QACX,OAAO,yBAAA,IAAI,EAAEL,aAAWK,MAAM;IAChC;IAEA,IAAIC,aAAa;QACf,OAAO,yBAAA,IAAI,EAAEN,aAAWM,UAAU;IACpC;IAEA,IAAIC,OAAO;QACT,OAAO,yBAAA,IAAI,EAAE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AG,CAACL;IACpB;IAEA,OAAO;QACLV,OAAOQ,OAAOvB;QACd,4EAA4E;QAC5E,gEAAgE;QAChE,yFAAyF;QACzF,uEAAuE;QACvE+B,SAASR,OAAOQ;QAChBC,SAAST,OAAOS;QAChBC,UAAUV,OAAOU;QACjBT;IACF;AACF;AAEA,MAAMU,kBAAkB;IACtBC,OAAO;QAAC;QAAS;QAAW;QAAW;KAAW;IAClDC,SAAS3C;AACX;MACA,WAAeyC"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/network.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\n\nimport { withTeardown } from '../utils';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n #onStart: () => Promise<void>;\n\n #onFinish: () => Promise<void>;\n\n constructor(\n ogResponse: Response,\n teardownRef: { lastTeardown: number },\n onStart: () => Promise<void>,\n onFinish: () => Promise<void>,\n ) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n this.#onStart = onStart;\n this.#onFinish = onFinish;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return await withTeardown<string>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.text();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return await withTeardown<ArrayBuffer>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.arrayBuffer();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async blob(): Promise<Blob> {\n return await withTeardown<Blob>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.blob();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(\n newResponse,\n this.#teardownRef,\n this.#onStart,\n this.#onFinish,\n );\n }\n\n async formData(): Promise<FormData> {\n return await withTeardown<FormData>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.formData();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async json(): Promise<any> {\n return await withTeardown(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.json();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @param options - An options bag.\n * @param options.notify - A reference to the notify function of the snap executor.\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = ({ notify }: EndowmentFactoryOptions = {}) => {\n assert(notify, 'Notify must be passed to network endowment factory');\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let started = false;\n const onStart = async () => {\n if (!started) {\n started = true;\n await notify({\n method: 'OutboundRequest',\n params: { source: 'fetch' },\n });\n }\n };\n\n let finished = false;\n const onFinish = async () => {\n if (!finished) {\n finished = true;\n await notify({\n method: 'OutboundResponse',\n params: { source: 'fetch' },\n });\n }\n };\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n return await withTeardown(\n (async () => {\n try {\n await notify({\n method: 'OutboundRequest',\n params: { source: 'fetch' },\n });\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await fetchPromise,\n teardownRef,\n onStart,\n onFinish,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n await notify({\n method: 'OutboundResponse',\n params: { source: 'fetch' },\n });\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n })(),\n teardownRef,\n );\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n // Request, Headers and Response are the endowments injected alongside fetch\n // only when 'endowment:network-access' permission is requested,\n // therefore these are hardened as part of fetch dependency injection within its factory.\n // These endowments are not (and should never be) available by default.\n Request: harden(Request),\n Headers: harden(Headers),\n Response: harden(Response),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch', 'Request', 'Headers', 'Response'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"],"names":["ResponseWrapper","body","ogResponse","bodyUsed","headers","ok","redirected","status","statusText","type","url","text","withTeardown","onStart","onFinish","teardownRef","arrayBuffer","blob","clone","newResponse","formData","json","constructor","createNetwork","notify","assert","openConnections","Set","lastTeardown","cleanup","FinalizationRegistry","callback","_fetch","input","init","abortController","AbortController","signal","undefined","originalSignal","addEventListener","abort","reason","once","started","method","params","source","finished","res","openFetchConnection","fetchPromise","fetch","cancel","add","delete","WeakRef","openBodyConnection","deref","register","harden","teardownFunction","promises","forEach","push","clear","Promise","all","Request","Headers","Response","endowmentModule","names","factory"],"mappings":";;;;+BAoTA;;;eAAA;;;uBApTuB;wBAEM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAQlB,4CAET,2CAEA,wCAEA;AAXF;;;CAGC,GACD,MAAMA;IAqBJ,IAAIC,OAA0C;QAC5C,OAAO,yBAAA,IAAI,EAAEC,aAAWD,IAAI;IAC9B;IAEA,IAAIE,WAAW;QACb,OAAO,yBAAA,IAAI,EAAED,aAAWC,QAAQ;IAClC;IAEA,IAAIC,UAAU;QACZ,OAAO,yBAAA,IAAI,EAAEF,aAAWE,OAAO;IACjC;IAEA,IAAIC,KAAK;QACP,OAAO,yBAAA,IAAI,EAAEH,aAAWG,EAAE;IAC5B;IAEA,IAAIC,aAAa;QACf,OAAO,yBAAA,IAAI,EAAEJ,aAAWI,UAAU;IACpC;IAEA,IAAIC,SAAS;QACX,OAAO,yBAAA,IAAI,EAAEL,aAAWK,MAAM;IAChC;IAEA,IAAIC,aAAa;QACf,OAAO,yBAAA,IAAI,EAAEN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BJ,QACE,+EAA+E,GAC/E;wBACE,IAAI;4BACF,MAAMpD,KAAKyD,KAAK,IAAIL;wBACtB,EAAE,OAAM;wBACN,cAAc,GAChB;oBACF;gBACJ;gBACA3B,gBAAgB4B,GAAG,CAACG;gBACpB5B,QAAQ8B,QAAQ,CACdV,IAAIhD,IAAI,EACR,yFAAyF,GACzF,IAAMyB,gBAAgB6B,MAAM,CAACE;YAEjC;YACA,OAAOG,OAAOX;QAChB,CAAA,KACAlC;IAEJ;IAEA,MAAM8C,mBAAmB;QACvB9C,YAAYa,YAAY,IAAI;QAC5B,MAAMkC,WAA4B,EAAE;QACpCpC,gBAAgBqC,OAAO,CAAC,CAAC,EAAEV,MAAM,EAAE,GAAKS,SAASE,IAAI,CAACX;QACtD3B,gBAAgBuC,KAAK;QACrB,MAAMC,QAAQC,GAAG,CAACL;IACpB;IAEA,OAAO;QACLV,OAAOQ,OAAO5B;QACd,4EAA4E;QAC5E,gEAAgE;QAChE,yFAAyF;QACzF,uEAAuE;QACvEoC,SAASR,OAAOQ;QAChBC,SAAST,OAAOS;QAChBC,UAAUV,OAAOU;QACjBT;IACF;AACF;AAEA,MAAMU,kBAAkB;IACtBC,OAAO;QAAC;QAAS;QAAW;QAAW;KAAW;IAClDC,SAASlD;AACX;MACA,WAAegD"}
@@ -74,7 +74,7 @@ const TerminateRequestArgumentsStruct = (0, _superstruct.union)([
74
74
  const ExecuteSnapRequestArgumentsStruct = (0, _superstruct.tuple)([
75
75
  (0, _superstruct.string)(),
76
76
  (0, _superstruct.string)(),
77
- (0, _superstruct.optional)((0, _superstruct.array)(EndowmentStruct))
77
+ (0, _superstruct.array)(EndowmentStruct)
78
78
  ]);
79
79
  const SnapRpcRequestArgumentsStruct = (0, _superstruct.tuple)([
80
80
  (0, _superstruct.string)(),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n optional(array(EndowmentStruct)),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst OkResponseStruct = assign(\n JsonRpcSuccessStruct,\n object({\n result: OkStruct,\n }),\n);\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["JsonRpcRequestWithoutIdStruct","EndowmentStruct","isEndowment","isEndowmentsArray","PingRequestArgumentsStruct","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","OnTransactionRequestArgumentsStruct","assertIsOnTransactionRequestArguments","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","assign","omit","JsonRpcRequestStruct","object","id","optional","JsonRpcIdStruct","string","value","is","Array","isArray","every","OkStruct","literal","union","undefined","array","tuple","enums","Object","values","HandlerType","params","record","JsonStruct","transaction","chainId","ChainIdStruct","transactionOrigin","nullable","assertStruct","rpcErrors","invalidParams","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OkResponseStruct","JsonRpcSuccessStruct","result","SnapRpcResponse"],"mappings":";;;;;;;;;;;IA2BaA,6BAA6B;eAA7BA;;IAWAC,eAAe;eAAfA;;IASGC,WAAW;eAAXA;;IAUAC,iBAAiB;eAAjBA;;IAMHC,0BAA0B;eAA1BA;;IAIAC,+BAA+B;eAA/BA;;IAKAC,iCAAiC;eAAjCA;;IAMAC,6BAA6B;eAA7BA;;IA+BAC,mCAAmC;eAAnCA;;IAmBGC,qCA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AAC;IACxD,oCAAoC;IACpCuB,aAAaF,IAAAA,mBAAM,EAACjB,IAAAA,mBAAM,KAAIkB,iBAAU;IACxCE,SAASC,yBAAa;IACtBC,mBAAmBC,IAAAA,qBAAQ,EAACvB,IAAAA,mBAAM;AACpC;AAcO,SAASV,sCACdW,KAAc;IAEduB,IAAAA,mBAAY,EACVvB,OACAZ,qCACA,0BACAoC,oBAAS,CAACC,aAAa;AAE3B;AAEA,MAAMC,qBAAqB;IAAEP,SAASC,yBAAa;AAAC;AACpD,MAAMO,sBAAsBhC,IAAAA,mBAAM,EAAC;IACjC,GAAG+B,kBAAkB;IACrBE,SAAS7B,IAAAA,mBAAM;AACjB;AACA,MAAM8B,uBAAuBlC,IAAAA,mBAAM,EAAC;IAClC,GAAG+B,kBAAkB;IACrBI,QAAQ/B,IAAAA,mBAAM;AAChB;AAEO,MAAMT,qCAAqCiB,IAAAA,kBAAK,EAAC;IACtDoB;IACAE;CACD;AAmBM,SAAStC,qCACdS,KAAc;IAEduB,IAAAA,mBAAY,EACVvB,OACAV,oCACA,0BACAkC,oBAAS,CAACC,aAAa;AAE3B;AAEA,MAAMM,mBAAmBvC,IAAAA,mBAAM,EAC7BwC,2BAAoB,EACpBrC,IAAAA,mBAAM,EAAC;IACLsC,QAAQ5B;AACV;AAGF,MAAM6B,kBAAkBF,2BAAoB"}
1
+ {"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n array(EndowmentStruct),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst OkResponseStruct = assign(\n JsonRpcSuccessStruct,\n object({\n result: OkStruct,\n }),\n);\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["JsonRpcRequestWithoutIdStruct","EndowmentStruct","isEndowment","isEndowmentsArray","PingRequestArgumentsStruct","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","OnTransactionRequestArgumentsStruct","assertIsOnTransactionRequestArguments","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","assign","omit","JsonRpcRequestStruct","object","id","optional","JsonRpcIdStruct","string","value","is","Array","isArray","every","OkStruct","literal","union","undefined","array","tuple","enums","Object","values","HandlerType","params","record","JsonStruct","transaction","chainId","ChainIdStruct","transactionOrigin","nullable","assertStruct","rpcErrors","invalidParams","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OkResponseStruct","JsonRpcSuccessStruct","result","SnapRpcResponse"],"mappings":";;;;;;;;;;;IA2BaA,6BAA6B;eAA7BA;;IAWAC,eAAe;eAAfA;;IASGC,WAAW;eAAXA;;IAUAC,iBAAiB;eAAjBA;;IAMHC,0BAA0B;eAA1BA;;IAIAC,+BAA+B;eAA/BA;;IAKAC,iCAAiC;eAAjCA;;IAMAC,6BAA6B;eAA7BA;;IA+BAC,mCAAmC;eAAnCA;;IAmBGC,qCAAqC;eAArCA;;IAqBHC,kCAAkC;eAAlCA;;IAsBGC,oCAAoC;eAApCA;;;2BA3KU;4BACiB;uBAQpC;6BAgBA;AAEA,MAAMX,gCAAgCY,IAAAA,mBAAM,EACjDC,IAAAA,iBAAI,EAACC,2BAAoB,EAAE;IAAC;CAAK,GACjCC,IAAAA,mBAAM,EAAC;IACLC,IAAIC,IAAAA,qBAAQ,EAACC,sBAAe;AAC9B;AAOK,MAAMjB,kBAAkBkB,I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;AACpD,MAAMO,sBAAsBhC,IAAAA,mBAAM,EAAC;IACjC,GAAG+B,kBAAkB;IACrBE,SAAS7B,IAAAA,mBAAM;AACjB;AACA,MAAM8B,uBAAuBlC,IAAAA,mBAAM,EAAC;IAClC,GAAG+B,kBAAkB;IACrBI,QAAQ/B,IAAAA,mBAAM;AAChB;AAEO,MAAMT,qCAAqCiB,IAAAA,kBAAK,EAAC;IACtDoB;IACAE;CACD;AAmBM,SAAStC,qCACdS,KAAc;IAEduB,IAAAA,mBAAY,EACVvB,OACAV,oCACA,0BACAkC,oBAAS,CAACC,aAAa;AAE3B;AAEA,MAAMM,mBAAmBvC,IAAAA,mBAAM,EAC7BwC,2BAAoB,EACpBrC,IAAAA,mBAAM,EAAC;IACLsC,QAAQ5B;AACV;AAGF,MAAM6B,kBAAkBF,2BAAoB"}
@@ -31,7 +31,8 @@ function _define_property(obj, key, value) {
31
31
  import { createIdRemapMiddleware } from '@metamask/json-rpc-engine';
32
32
  import { StreamProvider } from '@metamask/providers';
33
33
  import { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';
34
- import { SNAP_EXPORT_NAMES, logError, SNAP_EXPORTS, WrappedSnapError, getErrorData, unwrapError } from '@metamask/snaps-utils';
34
+ import { getErrorData } from '@metamask/snaps-sdk';
35
+ import { SNAP_EXPORT_NAMES, logError, SNAP_EXPORTS, WrappedSnapError, unwrapError } from '@metamask/snaps-utils';
35
36
  import { isObject, isValidJson, assert, isJsonRpcRequest, hasProperty, getSafeJson } from '@metamask/utils';
36
37
  import { validate } from 'superstruct';
37
38
  import { log } from '../logging';
@@ -188,7 +189,13 @@ export class BaseSnapExecutor {
188
189
  exports: {}
189
190
  };
190
191
  try {
191
- const { endowments, teardown: endowmentTeardown } = createEndowments(snap, ethereum, snapId, _endowments);
192
+ const { endowments, teardown: endowmentTeardown } = createEndowments({
193
+ snap,
194
+ ethereum,
195
+ snapId,
196
+ endowments: _endowments,
197
+ notify: _class_private_method_get(this, _notify, notify).bind(this)
198
+ });
192
199
  // !!! Ensure that this is the only place the data is being set.
193
200
  // Other methods access the object value and mutate its properties.
194
201
  this.snapData.set(snapId, {
@@ -266,13 +273,19 @@ export class BaseSnapExecutor {
266
273
  assertSnapOutboundRequest(sanitizedArgs);
267
274
  return await withTeardown((async ()=>{
268
275
  await _class_private_method_get(this, _notify, notify).call(this, {
269
- method: 'OutboundRequest'
276
+ method: 'OutboundRequest',
277
+ params: {
278
+ source: 'snap.request'
279
+ }
270
280
  });
271
281
  try {
272
282
  return await originalRequest(sanitizedArgs);
273
283
  } finally{
274
284
  await _class_private_method_get(this, _notify, notify).call(this, {
275
- method: 'OutboundResponse'
285
+ method: 'OutboundResponse',
286
+ params: {
287
+ source: 'snap.request'
288
+ }
276
289
  });
277
290
  }
278
291
  })(), this);
@@ -306,13 +319,19 @@ export class BaseSnapExecutor {
306
319
  assertEthereumOutboundRequest(sanitizedArgs);
307
320
  return await withTeardown((async ()=>{
308
321
  await _class_private_method_get(this, _notify, notify).call(this, {
309
- method: 'OutboundRequest'
322
+ method: 'OutboundRequest',
323
+ params: {
324
+ source: 'ethereum.request'
325
+ }
310
326
  });
311
327
  try {
312
328
  return await originalRequest(sanitizedArgs);
313
329
  } finally{
314
330
  await _class_private_method_get(this, _notify, notify).call(this, {
315
- method: 'OutboundResponse'
331
+ method: 'OutboundResponse',
332
+ params: {
333
+ source: 'ethereum.request'
334
+ }
316
335
  });
317
336
  }
318
337
  })(), this);
@@ -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 { SnapsGlobalObject } from '@metamask/snaps-rpc-methods';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n getErrorData,\n unwrapError,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw rpcErrors.invalidRequest({\n message: 'Command stream received a non-JSON-RPC request.',\n data: message,\n });\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n 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,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({ method: 'OutboundRequest' });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({ method: 'OutboundResponse' });\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 SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({ method: 'OutboundRequest' });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({ method: 'OutboundResponse' });\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":["createIdRemapMiddleware","StreamProvider","errorCodes","rpcErrors","serializeError","SNAP_EXPORT_NAMES","logError","SNAP_EXPORTS","WrappedSnapError","getErrorData","unwrapError","isObject","isValidJson","assert","isJsonRpcRequest","hasProperty","getSafeJson","validate","log","getCommandMethodImplementations","createEndowments","addEventListener","removeEventListener","sortParamKeys","assertEthereumOutboundRequest","assertSnapOutboundRequest","sanitizeRequestArguments","proxyStreamProvider","withTeardown","ExecuteSnapRequestArgumentsStruct","PingRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","TerminateRequestArgumentsStruct","fallbackError","code","rpc","internal","message","unhandledError","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","params","executeSnap","terminate","snapRpc","BaseSnapExecutor","errorHandler","error","data","serializedError","shouldIncludeStack","errorData","notify","method","catch","notifyError","onCommandRequest","invalidRequest","id","respond","methodNotFound","methodObject","paramsAsArray","invalidParams","result","methods","rpcError","startSnap","snapId","sourceCode","_endowments","snapPromiseErrorHandler","snapErrorHandler","Error","reason","provider","rpcStream","jsonRpcStreamName","rpcMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","snapData","set","idleTeardown","runningEvaluations","Set","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","cause","onTerminate","forEach","evaluation","stop","clear","get","reduce","acc","exportName","snapExport","validator","originalRequest","request","bind","args","sanitizedArgs","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","streamProviderProxy","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","commandStream","Map","on","target","handlerType","handler","required","methodNotSupported","replace","chunk","resolve","write","requestObject","jsonrpc"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAChE,SAASA,uBAAuB,QAAQ,4BAA4B;AACpE,SAASC,cAAc,QAAQ,sBAAsB;AAErD,SAASC,UAAU,EAAEC,SAAS,EAAEC,cAAc,QAAQ,uBAAuB;AAO7E,SACEC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,EACZC,gBAAgB,EAChBC,YAAY,EACZC,WAAW,QACN,wBAAwB;AAO/B,SACEC,QAAQ,EACRC,WAAW,EACXC,MAAM,EACNC,gBAAgB,EAChBC,WAAW,EACXC,WAAW,QACN,kBAAkB;AAEzB,SAASC,QAAQ,QAAQ,cAAc;AAEvC,SAASC,GAAG,QAAQ,aAAa;AAEjC,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,gBAAgB,QAAQ,eAAe;AAChD,SAASC,gBAAgB,EAAEC,mBAAmB,QAAQ,iBAAiB;AACvE,SAASC,aAAa,QAAQ,eAAe;AAC7C,SACEC,6BAA6B,EAC7BC,yBAAyB,EACzBC,wBAAwB,EACxBC,mBAAmB,EACnBC,YAAY,QACP,UAAU;AACjB,SACEC,iCAAiC,EACjCC,0BAA0B,EAC1BC,6BAA6B,EAC7BC,+BAA+B,QAC1B,eAAe;AAYtB,MAAMC,gBAAgB;IACpBC,MAAMhC,WAAWiC,GAAG,CAACC,QAAQ;I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B,QAAc,CAACkB,SAAShB;QACjC,IAAI,CAACM,aAAa,CAACW,KAAK,CAACF,OAAO,CAACxG;YAC/B,IAAIA,OAAO;gBACTyF,OAAOzF;gBACP;YACF;YACAyG;QACF;IACF;AACF;AAEA,eAAA,OAAcE,aAAmD;IAC/D,IAAI,CAAChJ,YAAYgJ,kBAAkB,CAACjJ,SAASiJ,gBAAgB;QAC3D,MAAMzJ,UAAUiC,QAAQ,CACtB;IAEJ;IAEA,MAAM,0BAAA,IAAI,EAAEuH,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGC,aAAa;QAChBC,SAAS;IACX;AACF;AAEA,eAAA,QAAejG,EAAa,EAAEgG,aAAsC;IAClE,IAAI,CAAChJ,YAAYgJ,kBAAkB,CAACjJ,SAASiJ,gBAAgB;QAC3D,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,0BAAA,IAAI,EAAED,QAAAA,YAAN,IAAI,EAAQ;YAChB1G,OAAO7C,eACLD,UAAUiC,QAAQ,CAChB;YAGJwB;YACAiG,SAAS;QACX;QACA;IACF;IAEA,MAAM,0BAAA,IAAI,EAAEF,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGC,aAAa;QAChBhG;QACAiG,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 { 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} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport 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 throw rpcErrors.invalidRequest({\n message: 'Command stream received a non-JSON-RPC request.',\n data: message,\n });\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n 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":["createIdRemapMiddleware","StreamProvider","errorCodes","rpcErrors","serializeError","getErrorData","SNAP_EXPORT_NAMES","logError","SNAP_EXPORTS","WrappedSnapError","unwrapError","isObject","isValidJson","assert","isJsonRpcRequest","hasProperty","getSafeJson","validate","log","getCommandMethodImplementations","createEndowments","addEventListener","removeEventListener","sortParamKeys","assertEthereumOutboundRequest","assertSnapOutboundRequest","sanitizeRequestArguments","proxyStreamProvider","withTeardown","ExecuteSnapRequestArgumentsStruct","PingRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","TerminateRequestArgumentsStruct","fallbackError","code","rpc","internal","message","unhandledError","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","params","executeSnap","terminate","snapRpc","BaseSnapExecutor","errorHandler","error","data","serializedError","shouldIncludeStack","errorData","notify","method","catch","notifyError","onCommandRequest","invalidRequest","id","respond","methodNotFound","methodObject","paramsAsArray","invalidParams","result","methods","rpcError","startSnap","snapId","sourceCode","_endowments","snapPromiseErrorHandler","snapErrorHandler","Error","reason","provider","rpcStream","jsonRpcStreamName","rpcMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","bind","snapData","set","idleTeardown","runningEvaluations","Set","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","cause","onTerminate","forEach","evaluation","stop","clear","get","reduce","acc","exportName","snapExport","validator","originalRequest","request","args","sanitizedArgs","source","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","streamProviderProxy","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","commandStream","Map","on","target","handlerType","handler","required","methodNotSupported","replace","chunk","resolve","write","requestObject","jsonrpc"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAChE,SAASA,uBAAuB,QAAQ,4BAA4B;AACpE,SAASC,cAAc,QAAQ,sBAAsB;AAErD,SAASC,UAAU,EAAEC,SAAS,EAAEC,cAAc,QAAQ,uBAAuB;AAE7E,SAASC,YAAY,QAAQ,sBAAsB;AAMnD,SACEC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,EACZC,gBAAgB,EAChBC,WAAW,QACN,wBAAwB;AAO/B,SACEC,QAAQ,EACRC,WAAW,EACXC,MAAM,EACNC,gBAAgB,EAChBC,WAAW,EACXC,WAAW,QACN,kBAAkB;AAEzB,SAASC,QAAQ,QAAQ,cAAc;AAEvC,SAASC,GAAG,QAAQ,aAAa;AAEjC,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,gBAAgB,QAAQ,eAAe;AAChD,SAASC,gBAAgB,EAAEC,mBAAmB,QAAQ,iBAAiB;AACvE,SAASC,aAAa,QAAQ,eAAe;AAC7C,SACEC,6BAA6B,EAC7BC,yBAAyB,EACzBC,wBAAwB,EACxBC,mBAAmB,EACnBC,YAAY,QACP,UAAU;AACjB,SACEC,iCAAiC,EACjCC,0BAA0B,EAC1BC,6BAA6B,EAC7BC,+BAA+B,QAC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W;gBACxBjE,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAOlD,YAAYkD;YACrB,EAAE,OAAOjB,OAAO;gBACd,MAAM9C,UAAUiC,QAAQ,CACtB,CAAC,sCAAsC,EAAEa,MAAMZ,OAAO,CAACoH,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAAC5C,WAAW,CAAClB,IAAI,CAAC,IAAI;IAE9B;AA2ZF;AAtUE,eAAA,MAAa+D,KAAW;IACtB,OAAO,IAAIjB,QAAc,CAACkB,SAAShB;QACjC,IAAI,CAACM,aAAa,CAACW,KAAK,CAACF,OAAO,CAACzG;YAC/B,IAAIA,OAAO;gBACT0F,OAAO1F;gBACP;YACF;YACA0G;QACF;IACF;AACF;AAEA,eAAA,OAAcE,aAAmD;IAC/D,IAAI,CAACjJ,YAAYiJ,kBAAkB,CAAClJ,SAASkJ,gBAAgB;QAC3D,MAAM1J,UAAUiC,QAAQ,CACtB;IAEJ;IAEA,MAAM,0BAAA,IAAI,EAAEwH,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGC,aAAa;QAChBC,SAAS;IACX;AACF;AAEA,eAAA,QAAelG,EAAa,EAAEiG,aAAsC;IAClE,IAAI,CAACjJ,YAAYiJ,kBAAkB,CAAClJ,SAASkJ,gBAAgB;QAC3D,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,0BAAA,IAAI,EAAED,QAAAA,YAAN,IAAI,EAAQ;YAChB3G,OAAO7C,eACLD,UAAUiC,QAAQ,CAChB;YAGJwB;YACAkG,SAAS;QACX;QACA;IACF;IAEA,MAAM,0BAAA,IAAI,EAAEF,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGC,aAAa;QAChBjG;QACAkG,SAAS;IACX;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/commonEndowmentFactory.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\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 EndowmentFactoryOptions = {\n snapId?: SnapId;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [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: 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 consoleEndowment,\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"],"names":["rootRealmGlobal","consoleEndowment","crypto","date","interval","math","network","textDecoder","textEncoder","timeout","commonEndowments","endowment","AbortController","name","AbortSignal","ArrayBuffer","atob","bind","BigInt","BigInt64Array","BigUint64Array","btoa","DataView","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","URL","WebAssembly","buildCommonEndowments","endowmentFactories","forEach","endowmentSpecification","names","factory","boundEndowment","harden","push"],"mappings":"AAEA,SAASA,eAAe,QAAQ,kBAAkB;AAClD,OAAOC,sBAAsB,YAAY;AACzC,OAAOC,YAAY,WAAW;AAC9B,OAAOC,UAAU,SAAS;AAC1B,OAAOC,cAAc,aAAa;AAClC,OAAOC,UAAU,SAAS;AAC1B,OAAOC,aAAa,YAAY;AAChC,OAAOC,iBAAiB,gBAAgB;AACxC,OAAOC,iBAAiB,gBAAgB;AACxC,OAAOC,aAAa,YAAY;AAiBhC,6BAA6B;AAC7B,MAAMC,mBAAmD;IACvD;QAAEC,WAAWC;QAAiBC,MAAM;IAAkB;IACtD;QAAEF,WAAWG;QAAaD,MAAM;IAAc;IAC9C;QAAEF,WAAWI;QAAaF,MAAM;IAAc;IAC9C;QAAEF,WAAWK;QAAMH,MAAM;QAAQI,MAAM;IAAK;IAC5C;QAAEN,WAAWO;QAAQL,MAAM;IAAS;IACpC;QAAEF,WAAWQ;QAAeN,MAAM;IAAgB;IAClD;QAAEF,WAAWS;QAAgBP,MAAM;IAAiB;IACpD;QAAEF,WAAWU;QAAMR,MAAM;QAAQI,MAAM;IAAK;IAC5C;QAAEN,WAAWW;QAAUT,MAAM;IAAW;IACxC;QAAEF,WAAWY;QAAcV,MAAM;IAAe;IAChD;QAAEF,WAAWa;QAAcX,MAAM;IAAe;IAChD;QAAEF,WAAWc;QAAWZ,MAAM;IAAY;IAC1C;QAAEF,WAAWe;QAAYb,MAAM;IAAa;IAC5C;QAAEF,WAAWgB;QAAYd,MAAM;IAAa;IAC5C;QAAEF,WAAWiB;QAAYf,MAAM;IAAa;IAC5C;QAAEF,WAAWkB;QAAmBhB,MAAM;IAAoB;IAC1D;QAAEF,WAAWmB;QAAajB,MAAM;IAAc;IAC9C;QAAEF,WAAWoB;QAAalB,MAAM;IAAc;IAC9C;QAAEF,WAAWqB;QAAKnB,MAAM;IAAM;IAC9B;QAAEF,WAAWsB;QAAapB,MAAM;IAAc;CAC/C;AAED;;;;;;CAMC,GACD,MAAMqB,wBAAwB;IAC5B,MAAMC,qBAAyC;QAC7CjC;QACAE;QACAC;QACAC;QACAG;QACAF;QACAC;QACAL;QACAF;KACD;IAEDS,iBAAiB0B,OAAO,CAAC,CAACC;QACxB,MAAM1B,YAAY;YAChB2B,OAAO;gBAACD,uBAAuBxB,IAAI;aAAC;YACpC0B,SAAS;gBACP,MAAMC,iBACJ,OAAOH,uBAAuB1B,SAAS,KAAK,cAC5C0B,uBAAuBpB,IAAI,GACvBoB,uBAAuB1B,SAAS,CAACM,IAAI,CAACjB,mBACtCqC,uBAAuB1B,SAAS;gBACtC,OAAO;oBACL,CAAC0B,uBAAuBxB,IAAI,CAAC,EAAE4B,OAAOD;gBACxC;YACF;QACF;QACAL,mBAAmBO,IAAI,CAAC/B;IAC1B;IAEA,OAAOwB;AACT;AAEA,eAAeD,sBAAsB"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/commonEndowmentFactory.ts"],"sourcesContent":["import type { NotifyFunction } from '../BaseSnapExecutor';\nimport { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\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 EndowmentFactoryOptions = {\n snapId?: string;\n notify?: NotifyFunction;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [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: 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 consoleEndowment,\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"],"names":["rootRealmGlobal","consoleEndowment","crypto","date","interval","math","network","textDecoder","textEncoder","timeout","commonEndowments","endowment","AbortController","name","AbortSignal","ArrayBuffer","atob","bind","BigInt","BigInt64Array","BigUint64Array","btoa","DataView","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","URL","WebAssembly","buildCommonEndowments","endowmentFactories","forEach","endowmentSpecification","names","factory","boundEndowment","harden","push"],"mappings":"AACA,SAASA,eAAe,QAAQ,kBAAkB;AAClD,OAAOC,sBAAsB,YAAY;AACzC,OAAOC,YAAY,WAAW;AAC9B,OAAOC,UAAU,SAAS;AAC1B,OAAOC,cAAc,aAAa;AAClC,OAAOC,UAAU,SAAS;AAC1B,OAAOC,aAAa,YAAY;AAChC,OAAOC,iBAAiB,gBAAgB;AACxC,OAAOC,iBAAiB,gBAAgB;AACxC,OAAOC,aAAa,YAAY;AAkBhC,6BAA6B;AAC7B,MAAMC,mBAAmD;IACvD;QAAEC,WAAWC;QAAiBC,MAAM;IAAkB;IACtD;QAAEF,WAAWG;QAAaD,MAAM;IAAc;IAC9C;QAAEF,WAAWI;QAAaF,MAAM;IAAc;IAC9C;QAAEF,WAAWK;QAAMH,MAAM;QAAQI,MAAM;IAAK;IAC5C;QAAEN,WAAWO;QAAQL,MAAM;IAAS;IACpC;QAAEF,WAAWQ;QAAeN,MAAM;IAAgB;IAClD;QAAEF,WAAWS;QAAgBP,MAAM;IAAiB;IACpD;QAAEF,WAAWU;QAAMR,MAAM;QAAQI,MAAM;IAAK;IAC5C;QAAEN,WAAWW;QAAUT,MAAM;IAAW;IACxC;QAAEF,WAAWY;QAAcV,MAAM;IAAe;IAChD;QAAEF,WAAWa;QAAcX,MAAM;IAAe;IAChD;QAAEF,WAAWc;QAAWZ,MAAM;IAAY;IAC1C;QAAEF,WAAWe;QAAYb,MAAM;IAAa;IAC5C;QAAEF,WAAWgB;QAAYd,MAAM;IAAa;IAC5C;QAAEF,WAAWiB;QAAYf,MAAM;IAAa;IAC5C;QAAEF,WAAWkB;QAAmBhB,MAAM;IAAoB;IAC1D;QAAEF,WAAWmB;QAAajB,MAAM;IAAc;IAC9C;QAAEF,WAAWoB;QAAalB,MAAM;IAAc;IAC9C;QAAEF,WAAWqB;QAAKnB,MAAM;IAAM;IAC9B;QAAEF,WAAWsB;QAAapB,MAAM;IAAc;CAC/C;AAED;;;;;;CAMC,GACD,MAAMqB,wBAAwB;IAC5B,MAAMC,qBAAyC;QAC7CjC;QACAE;QACAC;QACAC;QACAG;QACAF;QACAC;QACAL;QACAF;KACD;IAEDS,iBAAiB0B,OAAO,CAAC,CAACC;QACxB,MAAM1B,YAAY;YAChB2B,OAAO;gBAACD,uBAAuBxB,IAAI;aAAC;YACpC0B,SAAS;gBACP,MAAMC,iBACJ,OAAOH,uBAAuB1B,SAAS,KAAK,cAC5C0B,uBAAuBpB,IAAI,GACvBoB,uBAAuB1B,SAAS,CAACM,IAAI,CAACjB,mBACtCqC,uBAAuB1B,SAAS;gBACtC,OAAO;oBACL,CAAC0B,uBAAuBxB,IAAI,CAAC,EAAE4B,OAAOD;gBACxC;YACF;QACF;QACAL,mBAAmBO,IAAI,CAAC/B;IAC1B;IAEA,OAAOwB;AACT;AAEA,eAAeD,sBAAsB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/console.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\nexport const consoleAttenuatedMethods = new Set([\n 'log',\n 'assert',\n 'error',\n 'debug',\n 'info',\n 'warn',\n]);\n\n/**\n * A set of all the `console` values that will be passed to the snap. This has\n * all the values that are available in both the browser and Node.js.\n */\nexport const consoleMethods = new Set([\n 'debug',\n 'error',\n 'info',\n 'log',\n 'warn',\n 'dir',\n 'dirxml',\n 'table',\n 'trace',\n 'group',\n 'groupCollapsed',\n 'groupEnd',\n 'clear',\n 'count',\n 'countReset',\n 'assert',\n 'profile',\n 'profileEnd',\n 'time',\n 'timeLog',\n 'timeEnd',\n 'timeStamp',\n 'context',\n]);\n\nconst consoleFunctions = ['log', 'error', 'debug', 'info', 'warn'] as const;\n\ntype ConsoleFunctions = {\n [Key in (typeof consoleFunctions)[number]]: (typeof rootRealmGlobal.console)[Key];\n};\n\n/**\n * Gets the appropriate (prepended) message to pass to one of the attenuated\n * method calls.\n *\n * @param snapId - Id of the snap that we're getting a message for.\n * @param message - The id of the snap that will interact with the endowment.\n * @param args - The array of additional arguments.\n * @returns An array of arguments to be passed into an attenuated console method call.\n */\nfunction getMessage(snapId: SnapId, message: unknown, ...args: unknown[]) {\n const prefix = `[Snap: ${snapId}]`;\n\n // If the first argument is a string, prepend the prefix to the message, and keep the\n // rest of the arguments as-is.\n if (typeof message === 'string') {\n return [`${prefix} ${message}`, ...args];\n }\n\n // Otherwise, the `message` is an object, array, etc., so add the prefix as a separate\n // message to the arguments.\n return [prefix, message, ...args];\n}\n\n/**\n * Create a a {@link console} object, with the same properties as the global\n * {@link console} object, but with some methods replaced.\n *\n * @param options - Factory options used in construction of the endowment.\n * @param options.snapId - The id of the snap that will interact with the endowment.\n * @returns The {@link console} object with the replaced methods.\n */\nfunction createConsole({ snapId }: EndowmentFactoryOptions = {}) {\n assert(snapId !== undefined);\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.console,\n ) as (keyof typeof console)[];\n\n const attenuatedConsole = keys.reduce((target, key) => {\n if (consoleMethods.has(key) && !consoleAttenuatedMethods.has(key)) {\n return { ...target, [key]: rootRealmGlobal.console[key] };\n }\n\n return target;\n }, {});\n\n return harden({\n console: {\n ...attenuatedConsole,\n assert: (\n value: any,\n message?: string | undefined,\n ...optionalParams: any[]\n ) => {\n rootRealmGlobal.console.assert(\n value,\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n ...consoleFunctions.reduce<ConsoleFunctions>((target, key) => {\n return {\n ...target,\n [key]: (message?: unknown, ...optionalParams: any[]) => {\n rootRealmGlobal.console[key](\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n };\n }, {} as ConsoleFunctions),\n },\n });\n}\n\nconst endowmentModule = {\n names: ['console'] as const,\n factory: createConsole,\n};\n\nexport default endowmentModule;\n"],"names":["assert","rootRealmGlobal","consoleAttenuatedMethods","Set","consoleMethods","consoleFunctions","getMessage","snapId","message","args","prefix","createConsole","undefined","keys","Object","getOwnPropertyNames","console","attenuatedConsole","reduce","target","key","has","harden","value","optionalParams","endowmentModule","names","factory"],"mappings":"AACA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC,SAASC,eAAe,QAAQ,kBAAkB;AAGlD,OAAO,MAAMC,2BAA2B,IAAIC,IAAI;IAC9C;IACA;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH;;;CAGC,GACD,OAAO,MAAMC,iBAAiB,IAAID,IAAI;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH,MAAME,mBAAmB;IAAC;IAAO;IAAS;IAAS;IAAQ;CAAO;AAMlE;;;;;;;;CAQC,GACD,SAASC,WAAWC,MAAc,EAAEC,OAAgB,EAAE,GAAGC,IAAe;IACtE,MAAMC,SAAS,CAAC,OAAO,EAAEH,OAAO,CAAC,CAAC;IAElC,qFAAqF;IACrF,+BAA+B;IAC/B,IAAI,OAAOC,YAAY,UAAU;QAC/B,OAAO;YAAC,CAAC,EAAEE,OAAO,CAAC,EAAEF,QAAQ,CAAC;eAAKC;SAAK;IAC1C;IAEA,sFAAsF;IACtF,4BAA4B;IAC5B,OAAO;QAACC;QAAQF;WAAYC;KAAK;AACnC;AAEA;;;;;;;CAOC,GACD,SAASE,cAAc,EAAEJ,MAAM,EAA2B,GAAG,CAAC,CAAC;IAC7DP,OAAOO,WAAWK;IAClB,MAAMC,OAAOC,OAAOC,mBAAmB,CACrCd,gBAAgBe,OAAO;IAGzB,MAAMC,oBAAoBJ,KAAKK,MAAM,CAAC,CAACC,QAAQC;QAC7C,IAAIhB,eAAeiB,GAAG,CAACD,QAAQ,CAAClB,yBAAyBmB,GAAG,CAACD,MAAM;YACjE,OAAO;gBAAE,GAAGD,MAAM;gBAAE,CAACC,IAAI,EAAEnB,gBAAgBe,OAAO,CAACI,IAAI;YAAC;QAC1D;QAEA,OAAOD;IACT,GAAG,CAAC;IAEJ,OAAOG,OAAO;QACZN,SAAS;YACP,GAAGC,iBAAiB;YACpBjB,QAAQ,CACNuB,OACAf,SACA,GAAGgB;gBAEHvB,gBAAgBe,OAAO,CAAChB,MAAM,CAC5BuB,UACGjB,WAAWC,QAAQC,YAAYgB;YAEtC;YACA,GAAGnB,iBAAiBa,MAAM,CAAmB,CAACC,QAAQC;gBACpD,OAAO;oBACL,GAAGD,MAAM;oBACT,CAACC,IAAI,EAAE,CAACZ,SAAmB,GAAGgB;wBAC5BvB,gBAAgBe,OAAO,CAACI,IAAI,IACvBd,WAAWC,QAAQC,YAAYgB;oBAEtC;gBACF;YACF,GAAG,CAAC,EAAsB;QAC5B;IACF;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;KAAU;IAClBC,SAAShB;AACX;AAEA,eAAec,gBAAgB"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/console.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\nexport const consoleAttenuatedMethods = new Set([\n 'log',\n 'assert',\n 'error',\n 'debug',\n 'info',\n 'warn',\n]);\n\n/**\n * A set of all the `console` values that will be passed to the snap. This has\n * all the values that are available in both the browser and Node.js.\n */\nexport const consoleMethods = new Set([\n 'debug',\n 'error',\n 'info',\n 'log',\n 'warn',\n 'dir',\n 'dirxml',\n 'table',\n 'trace',\n 'group',\n 'groupCollapsed',\n 'groupEnd',\n 'clear',\n 'count',\n 'countReset',\n 'assert',\n 'profile',\n 'profileEnd',\n 'time',\n 'timeLog',\n 'timeEnd',\n 'timeStamp',\n 'context',\n]);\n\nconst consoleFunctions = ['log', 'error', 'debug', 'info', 'warn'] as const;\n\ntype ConsoleFunctions = {\n [Key in (typeof consoleFunctions)[number]]: (typeof rootRealmGlobal.console)[Key];\n};\n\n/**\n * Gets the appropriate (prepended) message to pass to one of the attenuated\n * method calls.\n *\n * @param snapId - Id of the snap that we're getting a message for.\n * @param message - The id of the snap that will interact with the endowment.\n * @param args - The array of additional arguments.\n * @returns An array of arguments to be passed into an attenuated console method call.\n */\nfunction getMessage(snapId: string, message: unknown, ...args: unknown[]) {\n const prefix = `[Snap: ${snapId}]`;\n\n // If the first argument is a string, prepend the prefix to the message, and keep the\n // rest of the arguments as-is.\n if (typeof message === 'string') {\n return [`${prefix} ${message}`, ...args];\n }\n\n // Otherwise, the `message` is an object, array, etc., so add the prefix as a separate\n // message to the arguments.\n return [prefix, message, ...args];\n}\n\n/**\n * Create a a {@link console} object, with the same properties as the global\n * {@link console} object, but with some methods replaced.\n *\n * @param options - Factory options used in construction of the endowment.\n * @param options.snapId - The id of the snap that will interact with the endowment.\n * @returns The {@link console} object with the replaced methods.\n */\nfunction createConsole({ snapId }: EndowmentFactoryOptions = {}) {\n assert(snapId !== undefined);\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.console,\n ) as (keyof typeof console)[];\n\n const attenuatedConsole = keys.reduce((target, key) => {\n if (consoleMethods.has(key) && !consoleAttenuatedMethods.has(key)) {\n return { ...target, [key]: rootRealmGlobal.console[key] };\n }\n\n return target;\n }, {});\n\n return harden({\n console: {\n ...attenuatedConsole,\n assert: (\n value: any,\n message?: string | undefined,\n ...optionalParams: any[]\n ) => {\n rootRealmGlobal.console.assert(\n value,\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n ...consoleFunctions.reduce<ConsoleFunctions>((target, key) => {\n return {\n ...target,\n [key]: (message?: unknown, ...optionalParams: any[]) => {\n rootRealmGlobal.console[key](\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n };\n }, {} as ConsoleFunctions),\n },\n });\n}\n\nconst endowmentModule = {\n names: ['console'] as const,\n factory: createConsole,\n};\n\nexport default endowmentModule;\n"],"names":["assert","rootRealmGlobal","consoleAttenuatedMethods","Set","consoleMethods","consoleFunctions","getMessage","snapId","message","args","prefix","createConsole","undefined","keys","Object","getOwnPropertyNames","console","attenuatedConsole","reduce","target","key","has","harden","value","optionalParams","endowmentModule","names","factory"],"mappings":"AAAA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC,SAASC,eAAe,QAAQ,kBAAkB;AAGlD,OAAO,MAAMC,2BAA2B,IAAIC,IAAI;IAC9C;IACA;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH;;;CAGC,GACD,OAAO,MAAMC,iBAAiB,IAAID,IAAI;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH,MAAME,mBAAmB;IAAC;IAAO;IAAS;IAAS;IAAQ;CAAO;AAMlE;;;;;;;;CAQC,GACD,SAASC,WAAWC,MAAc,EAAEC,OAAgB,EAAE,GAAGC,IAAe;IACtE,MAAMC,SAAS,CAAC,OAAO,EAAEH,OAAO,CAAC,CAAC;IAElC,qFAAqF;IACrF,+BAA+B;IAC/B,IAAI,OAAOC,YAAY,UAAU;QAC/B,OAAO;YAAC,CAAC,EAAEE,OAAO,CAAC,EAAEF,QAAQ,CAAC;eAAKC;SAAK;IAC1C;IAEA,sFAAsF;IACtF,4BAA4B;IAC5B,OAAO;QAACC;QAAQF;WAAYC;KAAK;AACnC;AAEA;;;;;;;CAOC,GACD,SAASE,cAAc,EAAEJ,MAAM,EAA2B,GAAG,CAAC,CAAC;IAC7DP,OAAOO,WAAWK;IAClB,MAAMC,OAAOC,OAAOC,mBAAmB,CACrCd,gBAAgBe,OAAO;IAGzB,MAAMC,oBAAoBJ,KAAKK,MAAM,CAAC,CAACC,QAAQC;QAC7C,IAAIhB,eAAeiB,GAAG,CAACD,QAAQ,CAAClB,yBAAyBmB,GAAG,CAACD,MAAM;YACjE,OAAO;gBAAE,GAAGD,MAAM;gBAAE,CAACC,IAAI,EAAEnB,gBAAgBe,OAAO,CAACI,IAAI;YAAC;QAC1D;QAEA,OAAOD;IACT,GAAG,CAAC;IAEJ,OAAOG,OAAO;QACZN,SAAS;YACP,GAAGC,iBAAiB;YACpBjB,QAAQ,CACNuB,OACAf,SACA,GAAGgB;gBAEHvB,gBAAgBe,OAAO,CAAChB,MAAM,CAC5BuB,UACGjB,WAAWC,QAAQC,YAAYgB;YAEtC;YACA,GAAGnB,iBAAiBa,MAAM,CAAmB,CAACC,QAAQC;gBACpD,OAAO;oBACL,GAAGD,MAAM;oBACT,CAACC,IAAI,EAAE,CAACZ,SAAmB,GAAGgB;wBAC5BvB,gBAAgBe,OAAO,CAACI,IAAI,IACvBd,WAAWC,QAAQC,YAAYgB;oBAEtC;gBACF;YACF,GAAG,CAAC,EAAsB;QAC5B;IACF;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;KAAU;IAClBC,SAAShB;AACX;AAEA,eAAec,gBAAgB"}
@@ -23,12 +23,14 @@ import buildCommonEndowments from './commonEndowmentFactory';
23
23
  * such attenuated / modified endowments. Otherwise, the value that's on the
24
24
  * root realm global will be used.
25
25
  *
26
- * @param snap - The Snaps global API object.
27
- * @param ethereum - The Snap's EIP-1193 provider object.
28
- * @param snapId - The id of the snap that will use the created endowments.
29
- * @param endowments - The list of endowments to provide to the snap.
26
+ * @param options - An options bag.
27
+ * @param options.snap - The Snaps global API object.
28
+ * @param options.ethereum - The Snap's EIP-1193 provider object.
29
+ * @param options.snapId - The id of the snap that will use the created endowments.
30
+ * @param options.endowments - The list of endowments to provide to the snap.
31
+ * @param options.notify - A reference to the notify function of the snap executor.
30
32
  * @returns An object containing the Snap's endowments.
31
- */ export function createEndowments(snap, ethereum, snapId, endowments = []) {
33
+ */ export function createEndowments({ snap, ethereum, snapId, endowments, notify }) {
32
34
  const attenuatedEndowments = {};
33
35
  // TODO: All endowments should be hardened to prevent covert communication
34
36
  // channels. Hardening the returned objects breaks tests elsewhere in the
@@ -45,7 +47,8 @@ import buildCommonEndowments from './commonEndowmentFactory';
45
47
  // We just confirmed that endowmentFactories has the specified key.
46
48
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
47
49
  const { teardownFunction, ...endowment } = endowmentFactories.get(endowmentName)({
48
- snapId
50
+ snapId,
51
+ notify
49
52
  });
50
53
  Object.assign(attenuatedEndowments, endowment);
51
54
  if (teardownFunction) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { SnapsGlobalObject } from '@metamask/snaps-rpc-methods';\nimport type { SnapId } from '@metamask/snaps-utils';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\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, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param snapId - The id of the snap that will use the created endowments.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsGlobalObject,\n ethereum: StreamProvider,\n snapId: SnapId,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw rpcErrors.internal(`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"],"names":["rpcErrors","logWarning","hasProperty","rootRealmGlobal","buildCommonEndowments","registeredEndowments","endowmentFactories","reduce","factories","builder","names","forEach","name","set","factory","Map","createEndowments","snap","ethereum","snapId","endowments","attenuatedEndowments","result","allEndowments","teardowns","endowmentName","has","teardownFunction","endowment","get","Object","assign","push","globalValue","internal","teardown","Promise","all","map"],"mappings":"AACA,SAASA,SAAS,QAAQ,uBAAuB;AAGjD,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SAASC,WAAW,QAAQ,kBAAkB;AAE9C,SAASC,eAAe,QAAQ,kBAAkB;AAElD,OAAOC,2BAA2B,2BAA2B;AAe7D;;CAEC,GACD,MAAMC,uBAAuBD;AAE7B;;;;CAIC,GACD,MAAME,qBAAqBD,qBAAqBE,MAAM,CAAC,CAACC,WAAWC;IACjEA,QAAQC,KAAK,CAACC,OAAO,CAAC,CAACC;QACrBJ,UAAUK,GAAG,CAACD,MAAMH,QAAQK,OAAO;IACrC;IACA,OAAON;AACT,GAAG,IAAIO;AA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ACf;IAGF,MAAMW,WAAW;QACf,MAAMC,QAAQC,GAAG,CACff,OAAOE,SAAS,CAACc,GAAG,CAAC,CAACX,mBAAqBA;IAE/C;IACA,OAAO;QAAEP,YAAYE,OAAOC,aAAa;QAAEY;IAAS;AACtD"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport type { NotifyFunction } from '../BaseSnapExecutor';\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\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, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param options - An options bag.\n * @param options.snap - The Snaps global API object.\n * @param options.ethereum - The Snap's EIP-1193 provider object.\n * @param options.snapId - The id of the snap that will use the created endowments.\n * @param options.endowments - The list of endowments to provide to the snap.\n * @param options.notify - A reference to the notify function of the snap executor.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments({\n snap,\n ethereum,\n snapId,\n endowments,\n notify,\n}: {\n snap: SnapsProvider;\n ethereum: StreamProvider;\n snapId: string;\n endowments: string[];\n notify: NotifyFunction;\n}): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId, notify });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw rpcErrors.internal(`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"],"names":["rpcErrors","logWarning","hasProperty","rootRealmGlobal","buildCommonEndowments","registeredEndowments","endowmentFactories","reduce","factories","builder","names","forEach","name","set","factory","Map","createEndowments","snap","ethereum","snapId","endowments","notify","attenuatedEndowments","result","allEndowments","teardowns","endowmentName","has","teardownFunction","endowment","get","Object","assign","push","globalValue","internal","teardown","Promise","all","map"],"mappings":"AACA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SAASC,WAAW,QAAQ,kBAAkB;AAG9C,SAASC,eAAe,QAAQ,kBAAkB;AAElD,OAAOC,2BAA2B,2BAA2B;AAe7D;;CAEC,GACD,MAAMC,uBAAuBD;AAE7B;;;;CAIC,GACD,MAAME,qBAAqBD,qBAAqBE,MAAM,CAAC,CAACC,WAAWC;IACjEA,QAAQC,KAAK,CAACC,OAAO,CAAC,CAACC;QACrBJ,UAAUK,GAAG,CAACD,MAAMH,QAAQK,OAAO;IACrC;IACA,OAAON;AACT,GAAG,IAAIO;AAEP;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,iBAAiB,EAC/BC,IAAI,EACJC,QAAQ,EACRC,MAAM,EACNC,UAAU,EACVC,MAAM,EAOP;IACC,MAAMC,uBAAgD,CAAC;IAEvD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAMC,SAASH,WAAWb,MAAM,CAI9B,CAAC,EAAEiB,aAAa,EAAEC,SAAS,EAAE,EAAEC;QAC7B,oEAAoE;QACpE,IAAIpB,mBAAmBqB,GAAG,CAACD,gBAAgB;YACzC,IAAI,CAACxB,YAAYoB,sBAAsBI,gBAAgB;gBACrD,uEAAuE;gBACvE,gEAAgE;gB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