@metamask/snaps-execution-environments 0.29.0 → 0.31.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 (46) hide show
  1. package/dist/common/BaseSnapExecutor.js +48 -29
  2. package/dist/common/BaseSnapExecutor.js.map +1 -1
  3. package/dist/common/commands.js +1 -2
  4. package/dist/common/commands.js.map +1 -1
  5. package/dist/common/endowments/crypto.js +2 -2
  6. package/dist/common/endowments/crypto.js.map +1 -1
  7. package/dist/common/endowments/index.js +3 -15
  8. package/dist/common/endowments/index.js.map +1 -1
  9. package/dist/common/endowments/interval.js +1 -1
  10. package/dist/common/endowments/interval.js.map +1 -1
  11. package/dist/common/endowments/math.js +6 -3
  12. package/dist/common/endowments/math.js.map +1 -1
  13. package/dist/common/endowments/network.js +8 -6
  14. package/dist/common/endowments/network.js.map +1 -1
  15. package/dist/common/endowments/timeout.js +1 -1
  16. package/dist/common/endowments/timeout.js.map +1 -1
  17. package/dist/common/keyring.js +1 -1
  18. package/dist/common/keyring.js.map +1 -1
  19. package/dist/common/sortParams.js +4 -1
  20. package/dist/common/sortParams.js.map +1 -1
  21. package/dist/common/utils.d.ts +23 -0
  22. package/dist/common/utils.js +74 -1
  23. package/dist/common/utils.js.map +1 -1
  24. package/dist/common/validation.js +1 -2
  25. package/dist/common/validation.js.map +1 -1
  26. package/dist/iframe/IFrameSnapExecutor.d.ts +3 -1
  27. package/dist/iframe/IFrameSnapExecutor.js +8 -8
  28. package/dist/iframe/IFrameSnapExecutor.js.map +1 -1
  29. package/dist/webpack/iframe/bundle.js +1 -1750
  30. package/dist/webpack/iframe/bundle.js.LICENSE.txt +2 -13
  31. package/dist/webpack/iframe/index.html +10424 -7
  32. package/dist/webpack/node-process/bundle.js +111298 -1471
  33. package/dist/webpack/node-process/lockdown.umd.min.js +1 -1
  34. package/dist/webpack/node-thread/bundle.js +111298 -1471
  35. package/dist/webpack/node-thread/lockdown.umd.min.js +1 -1
  36. package/dist/webpack/offscreen/bundle.js +1 -1750
  37. package/dist/webpack/offscreen/bundle.js.LICENSE.txt +1 -14
  38. package/dist/webpack/offscreen/index.html +10423 -7
  39. package/package.json +40 -21
  40. package/dist/iframe-test/index.d.ts +0 -1
  41. package/dist/iframe-test/index.js +0 -8
  42. package/dist/iframe-test/index.js.map +0 -1
  43. package/dist/webpack/iframe/lockdown.umd.min.js +0 -1
  44. package/dist/webpack/node-process/bundle.js.LICENSE.txt +0 -1
  45. package/dist/webpack/node-thread/bundle.js.LICENSE.txt +0 -1
  46. package/dist/webpack/offscreen/lockdown.umd.min.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"timeout.js","sourceRoot":"","sources":["../../../src/common/endowments/timeout.ts"],"names":[],"mappings":";;AAAA,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B;;;;;;;;;GASG;AACH,MAAM,aAAa,GAAG,GAAG,EAAE;IACzB,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAoB,CAAC;IAEtD,MAAM,WAAW,GAAG,CAAC,OAAqB,EAAE,OAAgB,EAAW,EAAE;QACvE,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;YACjC,MAAM,IAAI,KAAK,CACb,qDAAqD,OAAO,OAAO,EAAE,CACtE,CAAC;SACH;QACD,MAAM,CAAC,OAAO,CAAC,CAAC;QAChB,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAClD,MAAM,cAAc,GAAG,UAAU,CAAC,GAAG,EAAE;YACrC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACjC,OAAO,EAAE,CAAC;QACZ,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,eAAe,EAAE,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,CAAC,CAAC,CAAC,CAAC;QAE5C,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;QAC9C,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,CAAC,MAAe,EAAQ,EAAE;QAC9C,MAAM,cAAc,GAAG,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACrD,IAAI,cAAc,KAAK,SAAS,EAAE;YAChC,YAAY,CAAC,cAAqB,CAAC,CAAC;YACpC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;SAClC;IACH,CAAC,CAAC;IAEF,MAAM,gBAAgB,GAAG,GAAS,EAAE;QAClC,KAAK,MAAM,MAAM,IAAI,iBAAiB,CAAC,IAAI,EAAE,EAAE;YAC7C,aAAa,CAAC,MAAM,CAAC,CAAC;SACvB;IACH,CAAC,CAAC;IAEF,OAAO;QACL,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC;QAC/B,YAAY,EAAE,MAAM,CAAC,aAAa,CAAC;QACnC,gBAAgB;KACR,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,YAAY,EAAE,cAAc,CAAU;IAC9C,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["const MINIMUM_TIMEOUT = 10;\n\n/**\n * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such\n * that:\n * - `setTimeout` throws if its \"handler\" parameter is not a function.\n * - `clearTimeout` only clears timeouts created by its sibling `setTimeout`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setTimeout` and `clearTimeout`\n * functions.\n */\nconst createTimeout = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setTimeout = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The timeout handler must be a function. Received: ${typeof handler}`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setTimeout(() => {\n registeredHandles.delete(handle);\n handler();\n }, Math.max(MINIMUM_TIMEOUT, timeout ?? 0));\n\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearTimeout = (handle: unknown): void => {\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearTimeout(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearTimeout(handle);\n }\n };\n\n return {\n setTimeout: harden(_setTimeout),\n clearTimeout: harden(_clearTimeout),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setTimeout', 'clearTimeout'] as const,\n factory: createTimeout,\n};\nexport default endowmentModule;\n"]}
1
+ {"version":3,"file":"timeout.js","sourceRoot":"","sources":["../../../src/common/endowments/timeout.ts"],"names":[],"mappings":";;AAAA,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B;;;;;;;;;GASG;AACH,MAAM,aAAa,GAAG,GAAG,EAAE;IACzB,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAoB,CAAC;IACtD,MAAM,WAAW,GAAG,CAAC,OAAqB,EAAE,OAAgB,EAAW,EAAE;QACvE,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;YACjC,MAAM,IAAI,KAAK,CACb,qDAAqD,OAAO,OAAO,EAAE,CACtE,CAAC;SACH;QACD,MAAM,CAAC,OAAO,CAAC,CAAC;QAChB,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAClD,MAAM,cAAc,GAAG,UAAU,CAAC,GAAG,EAAE;YACrC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACjC,OAAO,EAAE,CAAC;QACZ,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,eAAe,EAAE,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC;QAE5C,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;QAC9C,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,CAAC,MAAe,EAAQ,EAAE;QAC9C,MAAM,cAAc,GAAG,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACrD,IAAI,cAAc,KAAK,SAAS,EAAE;YAChC,YAAY,CAAC,cAAqB,CAAC,CAAC;YACpC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;SAClC;IACH,CAAC,CAAC;IAEF,MAAM,gBAAgB,GAAG,GAAS,EAAE;QAClC,KAAK,MAAM,MAAM,IAAI,iBAAiB,CAAC,IAAI,EAAE,EAAE;YAC7C,aAAa,CAAC,MAAM,CAAC,CAAC;SACvB;IACH,CAAC,CAAC;IAEF,OAAO;QACL,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC;QAC/B,YAAY,EAAE,MAAM,CAAC,aAAa,CAAC;QACnC,gBAAgB;KACR,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,YAAY,EAAE,cAAc,CAAU;IAC9C,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["const MINIMUM_TIMEOUT = 10;\n\n/**\n * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such\n * that:\n * - `setTimeout` throws if its \"handler\" parameter is not a function.\n * - `clearTimeout` only clears timeouts created by its sibling `setTimeout`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setTimeout` and `clearTimeout`\n * functions.\n */\nconst createTimeout = () => {\n const registeredHandles = new Map<unknown, unknown>();\n const _setTimeout = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The timeout handler must be a function. Received: ${typeof handler}`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setTimeout(() => {\n registeredHandles.delete(handle);\n handler();\n }, Math.max(MINIMUM_TIMEOUT, timeout ?? 0));\n\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearTimeout = (handle: unknown): void => {\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearTimeout(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearTimeout(handle);\n }\n };\n\n return {\n setTimeout: harden(_setTimeout),\n clearTimeout: harden(_clearTimeout),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setTimeout', 'clearTimeout'] as const,\n factory: createTimeout,\n};\nexport default endowmentModule;\n"]}
@@ -18,7 +18,7 @@ function wrapKeyring(notify, keyring) {
18
18
  if (!(method in keyring)) {
19
19
  throw new Error(`Keyring does not expose ${method}`);
20
20
  }
21
- let args = (params !== null && params !== void 0 ? params : []);
21
+ let args = (params ?? []);
22
22
  const keyringMethod = keyring[method];
23
23
  (0, utils_1.assert)(keyringMethod !== undefined);
24
24
  const func = keyringMethod.bind(keyring);
@@ -1 +1 @@
1
- {"version":3,"file":"keyring.js","sourceRoot":"","sources":["../../src/common/keyring.ts"],"names":[],"mappings":";;;AACA,2CAMyB;AAEzB;;;;;;GAMG;AACH,SAAgB,WAAW,CACzB,MAKS,EACT,OAAqB;IAErB,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;KACzC;IAED,MAAM,cAAc,GAAG,CAAC,EAAE,OAAO,EAAuC,EAAE,EAAE;QAC1E,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;QACnC,IAAI,CAAC,CAAC,MAAM,IAAI,OAAO,CAAC,EAAE;YACxB,MAAM,IAAI,KAAK,CAAC,2BAA2B,MAAM,EAAE,CAAC,CAAC;SACtD;QACD,IAAI,IAAI,GAAG,CAAC,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,EAAE,CAAc,CAAC;QACvC,MAAM,aAAa,GAAG,OAAO,CAAC,MAA2B,CAAC,CAAC;QAC3D,IAAA,cAAM,EAAC,aAAa,KAAK,SAAS,CAAC,CAAC;QACpC,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACzC,sCAAsC;QACtC,IAAI,MAAM,KAAK,IAAI,EAAE;YACnB,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAS,CAAC;YAC7B,MAAM,QAAQ,GAAG,CAAC,GAAG,YAAuB,EAAE,EAAE;gBAC9C,IAAA,cAAM,EACJ,IAAA,mBAAW,EAAC,YAAY,CAAC,EACzB,IAAI,SAAS,CACX,6DAA6D,CAC9D,CACF,CAAC;gBACF,OAAO,MAAM,CAAC;oBACZ,MAAM,EAAE,kBAAkB;oBAC1B,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE;iBACrC,CAAC,CAAC;YACL,CAAC,CAAC;YACF,IAAI,GAAG,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;SACzB;QACD,OAAQ,IAAqC,CAAC,GAAG,IAAI,CAAC,CAAC;IACzD,CAAC,CAAC;IACF,OAAO,cAAc,CAAC;AACxB,CAAC;AA1CD,kCA0CC","sourcesContent":["import { SnapKeyring } from '@metamask/snaps-utils';\nimport {\n assert,\n isValidJson,\n Json,\n JsonRpcNotification,\n JsonRpcRequest,\n} from '@metamask/utils';\n\n/**\n * Wraps a SnapKeyring class, returning a handler that can route requests to the exposed functions by the class.\n *\n * @param notify - The BaseSnapExecutor notify function, used for event communication.\n * @param keyring - The SnapKeyring instance.\n * @returns A handler function.\n */\nexport function wrapKeyring(\n notify: (\n requestObject: Omit<\n JsonRpcNotification<Record<string, Json> | Json[]>,\n 'jsonrpc'\n >,\n ) => void,\n keyring?: SnapKeyring,\n) {\n if (!keyring) {\n throw new Error('Keyring not exported');\n }\n\n const keyringHandler = ({ request }: { request: JsonRpcRequest<Json[]> }) => {\n const { method, params } = request;\n if (!(method in keyring)) {\n throw new Error(`Keyring does not expose ${method}`);\n }\n let args = (params ?? []) as unknown[];\n const keyringMethod = keyring[method as keyof SnapKeyring];\n assert(keyringMethod !== undefined);\n const func = keyringMethod.bind(keyring);\n // Special case for registering events\n if (method === 'on') {\n const data = args[0] as Json;\n const listener = (...listenerArgs: unknown[]) => {\n assert(\n isValidJson(listenerArgs),\n new TypeError(\n 'Keyrings .on listener received non-JSON-serializable value.',\n ),\n );\n return notify({\n method: 'SnapKeyringEvent',\n params: { data, args: listenerArgs },\n });\n };\n args = [data, listener];\n }\n return (func as (..._: unknown[]) => unknown)(...args);\n };\n return keyringHandler;\n}\n"]}
1
+ {"version":3,"file":"keyring.js","sourceRoot":"","sources":["../../src/common/keyring.ts"],"names":[],"mappings":";;;AACA,2CAMyB;AAEzB;;;;;;GAMG;AACH,SAAgB,WAAW,CACzB,MAKS,EACT,OAAqB;IAErB,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;KACzC;IAED,MAAM,cAAc,GAAG,CAAC,EAAE,OAAO,EAAuC,EAAE,EAAE;QAC1E,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;QACnC,IAAI,CAAC,CAAC,MAAM,IAAI,OAAO,CAAC,EAAE;YACxB,MAAM,IAAI,KAAK,CAAC,2BAA2B,MAAM,EAAE,CAAC,CAAC;SACtD;QACD,IAAI,IAAI,GAAG,CAAC,MAAM,IAAI,EAAE,CAAc,CAAC;QACvC,MAAM,aAAa,GAAG,OAAO,CAAC,MAA2B,CAAC,CAAC;QAC3D,IAAA,cAAM,EAAC,aAAa,KAAK,SAAS,CAAC,CAAC;QACpC,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACzC,sCAAsC;QACtC,IAAI,MAAM,KAAK,IAAI,EAAE;YACnB,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAS,CAAC;YAC7B,MAAM,QAAQ,GAAG,CAAC,GAAG,YAAuB,EAAE,EAAE;gBAC9C,IAAA,cAAM,EACJ,IAAA,mBAAW,EAAC,YAAY,CAAC,EACzB,IAAI,SAAS,CACX,6DAA6D,CAC9D,CACF,CAAC;gBACF,OAAO,MAAM,CAAC;oBACZ,MAAM,EAAE,kBAAkB;oBAC1B,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE;iBACrC,CAAC,CAAC;YACL,CAAC,CAAC;YACF,IAAI,GAAG,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;SACzB;QACD,OAAQ,IAAqC,CAAC,GAAG,IAAI,CAAC,CAAC;IACzD,CAAC,CAAC;IACF,OAAO,cAAc,CAAC;AACxB,CAAC;AA1CD,kCA0CC","sourcesContent":["import { SnapKeyring } from '@metamask/snaps-utils';\nimport {\n assert,\n isValidJson,\n Json,\n JsonRpcNotification,\n JsonRpcRequest,\n} from '@metamask/utils';\n\n/**\n * Wraps a SnapKeyring class, returning a handler that can route requests to the exposed functions by the class.\n *\n * @param notify - The BaseSnapExecutor notify function, used for event communication.\n * @param keyring - The SnapKeyring instance.\n * @returns A handler function.\n */\nexport function wrapKeyring(\n notify: (\n requestObject: Omit<\n JsonRpcNotification<Record<string, Json> | Json[]>,\n 'jsonrpc'\n >,\n ) => void,\n keyring?: SnapKeyring,\n) {\n if (!keyring) {\n throw new Error('Keyring not exported');\n }\n\n const keyringHandler = ({ request }: { request: JsonRpcRequest<Json[]> }) => {\n const { method, params } = request;\n if (!(method in keyring)) {\n throw new Error(`Keyring does not expose ${method}`);\n }\n let args = (params ?? []) as unknown[];\n const keyringMethod = keyring[method as keyof SnapKeyring];\n assert(keyringMethod !== undefined);\n const func = keyringMethod.bind(keyring);\n // Special case for registering events\n if (method === 'on') {\n const data = args[0] as Json;\n const listener = (...listenerArgs: unknown[]) => {\n assert(\n isValidJson(listenerArgs),\n new TypeError(\n 'Keyrings .on listener received non-JSON-serializable value.',\n ),\n );\n return notify({\n method: 'SnapKeyringEvent',\n params: { data, args: listenerArgs },\n });\n };\n args = [data, listener];\n }\n return (func as (..._: unknown[]) => unknown)(...args);\n };\n return keyringHandler;\n}\n"]}
@@ -23,7 +23,10 @@ const sortParamKeys = (methodParams, params) => {
23
23
  if (params instanceof Array) {
24
24
  return params;
25
25
  }
26
- const methodParamsOrder = methodParams.reduce((paramsOrderObj, paramsName, i) => (Object.assign(Object.assign({}, paramsOrderObj), { [paramsName]: i })), {});
26
+ const methodParamsOrder = methodParams.reduce((paramsOrderObj, paramsName, i) => ({
27
+ ...paramsOrderObj,
28
+ [paramsName]: i,
29
+ }), {});
27
30
  return Object.entries(params)
28
31
  .sort(([name1, _1], [name2, _2]) => methodParamsOrder[name1] - methodParamsOrder[name2])
29
32
  .map(([_, val]) => val);
@@ -1 +1 @@
1
- {"version":3,"file":"sortParams.js","sourceRoot":"","sources":["../../src/common/sortParams.ts"],"names":[],"mappings":";AAAA,8IAA8I;;;AAI9I;;;;;;;;;;;;;GAaG;AACI,MAAM,aAAa,GAAG,CAC3B,YAAsB,EACtB,MAAsB,EACtB,EAAE;IACF,IAAI,CAAC,MAAM,EAAE;QACX,OAAO,EAAE,CAAC;KACX;IAED,IAAI,MAAM,YAAY,KAAK,EAAE;QAC3B,OAAO,MAAM,CAAC;KACf;IAED,MAAM,iBAAiB,GAA4B,YAAY,CAAC,MAAM,CACpE,CAAC,cAAc,EAAE,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC,iCAC9B,cAAc,KACjB,CAAC,UAAU,CAAC,EAAE,CAAC,IACf,EACF,EAAE,CACH,CAAC;IAEF,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;SAC1B,IAAI,CACH,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,EAAE,CAC3B,iBAAiB,CAAC,KAAK,CAAC,GAAG,iBAAiB,CAAC,KAAK,CAAC,CACtD;SACA,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;AAC5B,CAAC,CAAC;AA1BW,QAAA,aAAa,iBA0BxB","sourcesContent":["// original source sortParamKeys from: https://github.com/etclabscore/sig.tools/blob/master/src/postMessageServer/postMessageServer.ts#L75-L77\n\nimport { JsonRpcParams } from '@metamask/utils';\n\n/**\n * Deterministically sort JSON-RPC parameter keys. This makes it possible to\n * support both arrays and objects as parameters. Objects are sorted and turned\n * into arrays, for easier consumption by the snap.\n *\n * The order is defined by the `method` parameter.\n *\n * @param methodParams - The parameters of the JSON-RPC method, which\n * determines the ordering for the parameters.\n * @param params - JSON-RPC parameters as object or array.\n * @returns The values for the sorted keys. If `params` is not provided, this\n * returns an empty array. If `params` is an array, this returns the same\n * `params`.\n */\nexport const sortParamKeys = (\n methodParams: string[],\n params?: JsonRpcParams,\n) => {\n if (!params) {\n return [];\n }\n\n if (params instanceof Array) {\n return params;\n }\n\n const methodParamsOrder: { [k: string]: number } = methodParams.reduce(\n (paramsOrderObj, paramsName, i) => ({\n ...paramsOrderObj,\n [paramsName]: i,\n }),\n {},\n );\n\n return Object.entries(params)\n .sort(\n ([name1, _1], [name2, _2]) =>\n methodParamsOrder[name1] - methodParamsOrder[name2],\n )\n .map(([_, val]) => val);\n};\n"]}
1
+ {"version":3,"file":"sortParams.js","sourceRoot":"","sources":["../../src/common/sortParams.ts"],"names":[],"mappings":";AAAA,8IAA8I;;;AAI9I;;;;;;;;;;;;;GAaG;AACI,MAAM,aAAa,GAAG,CAC3B,YAAsB,EACtB,MAAsB,EACtB,EAAE;IACF,IAAI,CAAC,MAAM,EAAE;QACX,OAAO,EAAE,CAAC;KACX;IAED,IAAI,MAAM,YAAY,KAAK,EAAE;QAC3B,OAAO,MAAM,CAAC;KACf;IAED,MAAM,iBAAiB,GAA4B,YAAY,CAAC,MAAM,CACpE,CAAC,cAAc,EAAE,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAClC,GAAG,cAAc;QACjB,CAAC,UAAU,CAAC,EAAE,CAAC;KAChB,CAAC,EACF,EAAE,CACH,CAAC;IAEF,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;SAC1B,IAAI,CACH,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,EAAE,CAC3B,iBAAiB,CAAC,KAAK,CAAC,GAAG,iBAAiB,CAAC,KAAK,CAAC,CACtD;SACA,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;AAC5B,CAAC,CAAC;AA1BW,QAAA,aAAa,iBA0BxB","sourcesContent":["// original source sortParamKeys from: https://github.com/etclabscore/sig.tools/blob/master/src/postMessageServer/postMessageServer.ts#L75-L77\n\nimport { JsonRpcParams } from '@metamask/utils';\n\n/**\n * Deterministically sort JSON-RPC parameter keys. This makes it possible to\n * support both arrays and objects as parameters. Objects are sorted and turned\n * into arrays, for easier consumption by the snap.\n *\n * The order is defined by the `method` parameter.\n *\n * @param methodParams - The parameters of the JSON-RPC method, which\n * determines the ordering for the parameters.\n * @param params - JSON-RPC parameters as object or array.\n * @returns The values for the sorted keys. If `params` is not provided, this\n * returns an empty array. If `params` is an array, this returns the same\n * `params`.\n */\nexport const sortParamKeys = (\n methodParams: string[],\n params?: JsonRpcParams,\n) => {\n if (!params) {\n return [];\n }\n\n if (params instanceof Array) {\n return params;\n }\n\n const methodParamsOrder: { [k: string]: number } = methodParams.reduce(\n (paramsOrderObj, paramsName, i) => ({\n ...paramsOrderObj,\n [paramsName]: i,\n }),\n {},\n );\n\n return Object.entries(params)\n .sort(\n ([name1, _1], [name2, _2]) =>\n methodParamsOrder[name1] - methodParamsOrder[name2],\n )\n .map(([_, val]) => val);\n};\n"]}
@@ -1,3 +1,5 @@
1
+ import { StreamProvider } from '@metamask/providers';
2
+ import { RequestArguments } from '@metamask/providers/dist/BaseProvider';
1
3
  /**
2
4
  * Takes an error that was thrown, determines if it is
3
5
  * an error object. If it is then it will return that. Otherwise,
@@ -20,3 +22,24 @@ export declare function constructError(originalError: unknown): Error | undefine
20
22
  export declare function withTeardown<T>(originalPromise: Promise<T>, teardownRef: {
21
23
  lastTeardown: number;
22
24
  }): Promise<T>;
25
+ /**
26
+ * Returns a Proxy that narrows down (attenuates) the fields available on
27
+ * the StreamProvider and replaces the request implementation.
28
+ *
29
+ * @param provider - Instance of a StreamProvider to be limited.
30
+ * @param request - Custom attenuated request object.
31
+ * @returns Proxy to the StreamProvider instance.
32
+ */
33
+ export declare function proxyStreamProvider(provider: StreamProvider, request: unknown): StreamProvider;
34
+ /**
35
+ * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.
36
+ *
37
+ * @param args - The arguments to validate.
38
+ */
39
+ export declare function assertSnapOutboundRequest(args: RequestArguments): void;
40
+ /**
41
+ * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.
42
+ *
43
+ * @param args - The arguments to validate.
44
+ */
45
+ export declare function assertEthereumOutboundRequest(args: RequestArguments): void;
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.withTeardown = exports.constructError = void 0;
3
+ exports.assertEthereumOutboundRequest = exports.assertSnapOutboundRequest = exports.proxyStreamProvider = exports.withTeardown = exports.constructError = void 0;
4
+ const utils_1 = require("@metamask/utils");
5
+ const eth_rpc_errors_1 = require("eth-rpc-errors");
4
6
  const logging_1 = require("../logging");
5
7
  /**
6
8
  * Takes an error that was thrown, determines if it is
@@ -56,4 +58,75 @@ async function withTeardown(originalPromise, teardownRef) {
56
58
  });
57
59
  }
58
60
  exports.withTeardown = withTeardown;
61
+ /**
62
+ * Returns a Proxy that narrows down (attenuates) the fields available on
63
+ * the StreamProvider and replaces the request implementation.
64
+ *
65
+ * @param provider - Instance of a StreamProvider to be limited.
66
+ * @param request - Custom attenuated request object.
67
+ * @returns Proxy to the StreamProvider instance.
68
+ */
69
+ function proxyStreamProvider(provider, request) {
70
+ // Proxy target is intentionally set to be an empty object, to ensure
71
+ // that access to the prototype chain is not possible.
72
+ const proxy = new Proxy({}, {
73
+ has(_target, prop) {
74
+ return (typeof prop === 'string' &&
75
+ ['request', 'on', 'removeListener'].includes(prop));
76
+ },
77
+ get(_target, prop) {
78
+ if (prop === 'request') {
79
+ return request;
80
+ }
81
+ else if (['on', 'removeListener'].includes(prop)) {
82
+ return provider[prop];
83
+ }
84
+ return undefined;
85
+ },
86
+ });
87
+ return proxy;
88
+ }
89
+ exports.proxyStreamProvider = proxyStreamProvider;
90
+ // We're blocking these two RPC methods for v1, will revisit later.
91
+ const BLOCKED_RPC_METHODS = Object.freeze([
92
+ 'eth_requestAccounts',
93
+ 'wallet_requestSnaps',
94
+ ]);
95
+ /**
96
+ * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.
97
+ *
98
+ * @param args - The arguments to validate.
99
+ */
100
+ function assertSnapOutboundRequest(args) {
101
+ // Disallow any non `wallet_` or `snap_` methods for separation of concerns.
102
+ (0, utils_1.assert)(String.prototype.startsWith.call(args.method, 'wallet_') ||
103
+ String.prototype.startsWith.call(args.method, 'snap_'), 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.');
104
+ (0, utils_1.assert)(!BLOCKED_RPC_METHODS.includes(args.method), eth_rpc_errors_1.ethErrors.rpc.methodNotFound({
105
+ data: {
106
+ method: args.method,
107
+ },
108
+ }));
109
+ (0, utils_1.assertStruct)(args, utils_1.JsonStruct, 'Provided value is not JSON-RPC compatible');
110
+ }
111
+ exports.assertSnapOutboundRequest = assertSnapOutboundRequest;
112
+ /**
113
+ * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.
114
+ *
115
+ * @param args - The arguments to validate.
116
+ */
117
+ function assertEthereumOutboundRequest(args) {
118
+ // Disallow snaps methods for separation of concerns.
119
+ (0, utils_1.assert)(!String.prototype.startsWith.call(args.method, 'snap_'), eth_rpc_errors_1.ethErrors.rpc.methodNotFound({
120
+ data: {
121
+ method: args.method,
122
+ },
123
+ }));
124
+ (0, utils_1.assert)(!BLOCKED_RPC_METHODS.includes(args.method), eth_rpc_errors_1.ethErrors.rpc.methodNotFound({
125
+ data: {
126
+ method: args.method,
127
+ },
128
+ }));
129
+ (0, utils_1.assertStruct)(args, utils_1.JsonStruct, 'Provided value is not JSON-RPC compatible');
130
+ }
131
+ exports.assertEthereumOutboundRequest = assertEthereumOutboundRequest;
59
132
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/common/utils.ts"],"names":[],"mappings":";;;AAAA,wCAAiC;AAEjC;;;;;;;GAOG;AACH,SAAgB,cAAc,CAAC,aAAsB;IACnD,IAAI,cAAiC,CAAC;IACtC,IAAI,aAAa,YAAY,KAAK,EAAE;QAClC,cAAc,GAAG,aAAa,CAAC;KAChC;SAAM,IAAI,OAAO,aAAa,KAAK,QAAQ,EAAE;QAC5C,cAAc,GAAG,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;QAC1C,qCAAqC;QACrC,OAAO,cAAc,CAAC,KAAK,CAAC;KAC7B;IACD,OAAO,cAAc,CAAC;AACxB,CAAC;AAVD,wCAUC;AAED;;;;;;;;;GASG;AACI,KAAK,UAAU,YAAY,CAChC,eAA2B,EAC3B,WAAqC;IAErC,MAAM,UAAU,GAAG,WAAW,CAAC,YAAY,CAAC;IAC5C,OAAO,IAAI,OAAO,CAAI,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACxC,eAAe;aACZ,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE;YACd,IAAI,WAAW,CAAC,YAAY,KAAK,UAAU,EAAE;gBAC3C,OAAO,CAAC,KAAK,CAAC,CAAC;aAChB;iBAAM;gBACL,IAAA,aAAG,EACD,+EAA+E,CAChF,CAAC;aACH;QACH,CAAC,CAAC;aACD,KAAK,CAAC,CAAC,MAAM,EAAE,EAAE;YAChB,IAAI,WAAW,CAAC,YAAY,KAAK,UAAU,EAAE;gBAC3C,MAAM,CAAC,MAAM,CAAC,CAAC;aAChB;iBAAM;gBACL,IAAA,aAAG,EACD,+EAA+E,CAChF,CAAC;aACH;QACH,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACL,CAAC;AA1BD,oCA0BC","sourcesContent":["import { log } from '../logging';\n\n/**\n * Takes an error that was thrown, determines if it is\n * an error object. If it is then it will return that. Otherwise,\n * an error object is created with the original error message.\n *\n * @param originalError - The error that was originally thrown.\n * @returns An error object.\n */\nexport function constructError(originalError: unknown) {\n let _originalError: Error | undefined;\n if (originalError instanceof Error) {\n _originalError = originalError;\n } else if (typeof originalError === 'string') {\n _originalError = new Error(originalError);\n // The stack is useless in this case.\n delete _originalError.stack;\n }\n return _originalError;\n}\n\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<T>(\n originalPromise: Promise<T>,\n teardownRef: { lastTeardown: number },\n): Promise<T> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<T>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/common/utils.ts"],"names":[],"mappings":";;;AAEA,2CAAmE;AACnE,mDAA2C;AAE3C,wCAAiC;AAEjC;;;;;;;GAOG;AACH,SAAgB,cAAc,CAAC,aAAsB;IACnD,IAAI,cAAiC,CAAC;IACtC,IAAI,aAAa,YAAY,KAAK,EAAE;QA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ACvD,0BAAS,CAAC,GAAG,CAAC,cAAc,CAAC;QAC3B,IAAI,EAAE;YACJ,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB;KACF,CAAC,CACH,CAAC;IACF,IAAA,cAAM,EACJ,CAAC,mBAAmB,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAC1C,0BAAS,CAAC,GAAG,CAAC,cAAc,CAAC;QAC3B,IAAI,EAAE;YACJ,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB;KACF,CAAC,CACH,CAAC;IACF,IAAA,oBAAY,EAAC,IAAI,EAAE,kBAAU,EAAE,2CAA2C,CAAC,CAAC;AAC9E,CAAC;AAnBD,sEAmBC","sourcesContent":["import { StreamProvider } from '@metamask/providers';\nimport { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { assert, assertStruct, JsonStruct } from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { log } from '../logging';\n\n/**\n * Takes an error that was thrown, determines if it is\n * an error object. If it is then it will return that. Otherwise,\n * an error object is created with the original error message.\n *\n * @param originalError - The error that was originally thrown.\n * @returns An error object.\n */\nexport function constructError(originalError: unknown) {\n let _originalError: Error | undefined;\n if (originalError instanceof Error) {\n _originalError = originalError;\n } else if (typeof originalError === 'string') {\n _originalError = new Error(originalError);\n // The stack is useless in this case.\n delete _originalError.stack;\n }\n return _originalError;\n}\n\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<T>(\n originalPromise: Promise<T>,\n teardownRef: { lastTeardown: number },\n): Promise<T> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<T>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that narrows down (attenuates) the fields available on\n * the StreamProvider and replaces the request implementation.\n *\n * @param provider - Instance of a StreamProvider to be limited.\n * @param request - Custom attenuated request object.\n * @returns Proxy to the StreamProvider instance.\n */\nexport function proxyStreamProvider(\n provider: StreamProvider,\n request: unknown,\n): StreamProvider {\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return (\n typeof prop === 'string' &&\n ['request', 'on', 'removeListener'].includes(prop)\n );\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return provider[prop];\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these two RPC methods for v1, will revisit later.\nconst BLOCKED_RPC_METHODS = Object.freeze([\n 'eth_requestAccounts',\n 'wallet_requestSnaps',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n"]}
@@ -37,9 +37,8 @@ function validateKeyringExport(snapExport) {
37
37
  * @returns True if the export matches the expected shape, false otherwise.
38
38
  */
39
39
  function validateExport(type, snapExport) {
40
- var _a;
41
40
  const validationFunction = VALIDATION_FUNCTIONS[type];
42
- return (_a = validationFunction === null || validationFunction === void 0 ? void 0 : validationFunction(snapExport)) !== null && _a !== void 0 ? _a : false;
41
+ return validationFunction?.(snapExport) ?? false;
43
42
  }
44
43
  exports.validateExport = validateExport;
45
44
  exports.JsonRpcRequestWithoutIdStruct = (0, superstruct_1.assign)((0, superstruct_1.omit)(utils_1.JsonRpcRequestStruct, ['id']), (0, superstruct_1.object)({
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/common/validation.ts"],"names":[],"mappings":";;;AAAA,uDAAgF;AAChF,2CAQyB;AACzB,6CAeqB;AAErB,MAAM,oBAAoB,GAAG;IAC3B,CAAC,yBAAW,CAAC,YAAY,CAAC,EAAE,sBAAsB;IAClD,CAAC,yBAAW,CAAC,aAAa,CAAC,EAAE,sBAAsB;IACnD,CAAC,yBAAW,CAAC,WAAW,CAAC,EAAE,qBAAqB;IAChD,CAAC,yBAAW,CAAC,SAAS,CAAC,EAAE,sBAAsB;CAChD,CAAC;AAEF;;;;;GAKG;AACH,SAAS,sBAAsB,CAC7B,UAAmB;IAEnB,OAAO,OAAO,UAAU,KAAK,UAAU,CAAC;AAC1C,CAAC;AAED;;;;;GAKG;AACH,SAAS,qBAAqB,CAAC,UAAmB;IAChD,8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,IAAA,mBAAK,EAAC;IACrD,IAAA,oBAAM,GAAE;IACR,IAAA,oBAAM,GAAE;IACR,IAAA,sBAAQ,EAAC,IAAA,mBAAK,EAAC,uBAAe,CAAC,CAAC;CACjC,CAAC,CAAC;AAEU,QAAA,6BAA6B,GAAG,IAAA,mBAAK,EAAC;IACjD,IAAA,oBAAM,GAAE;IACR,IAAA,mBAAK,EAAC,MAAM,CAAC,MAAM,CAAC,yBAAW,CAAC,CAAC;IACjC,IAAA,oBAAM,GAAE;IACR,IAAA,oBAAM,EACJ,qCAA6B,EAC7B,IAAA,oBAAM,EAAC;QACL,MAAM,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,kBAAU,CAAC,CAAC;KAC/C,CAAC,CACH;CACF,CAAC,CAAC;AAqBU,QAAA,mCAAmC,GAAG,IAAA,oBAAM,EAAC;IACxD,oCAAoC;IACpC,WAAW,EAAE,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,kBAAU,CAAC;IACzC,OAAO,EAAE,2BAAa;IACtB,iBAAiB,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,GAAE,CAAC;CACtC,CAAC,CAAC;AAMH;;;;;;;GAOG;AACH,SAAgB,qCAAqC,CACnD,KAAc;IAEd,IAAA,oBAAY,EACV,KAAK,EACL,2CAAmC,EACnC,wBAAwB,CACzB,CAAC;AACJ,CAAC;AARD,sFAQC;AAED,MAAM,gBAAgB,GAAG,IAAA,oBAAM,EAC7B,4BAAoB,EACpB,IAAA,oBAAM,EAAC;IACL,MAAM,EAAE,QAAQ;CACjB,CAAC,CACH,CAAC;AAEF,MAAM,eAAe,GAAG,4BAAoB,CAAC","sourcesContent":["import { SnapKeyring, ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport {\n assertStruct,\n Json,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccess,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport {\n array,\n assign,\n enums,\n Infer,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nconst VALIDATION_FUNCTIONS = {\n [HandlerType.OnRpcRequest]: validateFunctionExport,\n [HandlerType.OnTransaction]: validateFunctionExport,\n [HandlerType.SnapKeyring]: validateKeyringExport,\n [HandlerType.OnCronjob]: validateFunctionExport,\n};\n\n/**\n * Validates a function export.\n *\n * @param snapExport - The export itself.\n * @returns True if the export matches the expected shape, false otherwise.\n */\nfunction validateFunctionExport(\n snapExport: unknown,\n): snapExport is (...args: unknown[]) => unknown {\n return typeof snapExport === 'function';\n}\n\n/**\n * Validates a keyring export.\n *\n * @param snapExport - The export itself.\n * @returns True if the export matches the expected shape, false otherwise.\n */\nfunction validateKeyringExport(snapExport: unknown): snapExport is SnapKeyring {\n // TODO Decide whether we want more validation\n return typeof snapExport === 'object';\n}\n\n/**\n * Validates a given snap export.\n *\n * @param type - The type of export expected.\n * @param snapExport - The export itself.\n * @returns True if the export matches the expected shape, false otherwise.\n */\nexport function validateExport(type: HandlerType, snapExport: unknown) {\n const validationFunction = VALIDATION_FUNCTIONS[type];\n return validationFunction?.(snapExport) ?? false;\n}\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n optional(array(EndowmentStruct)),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n );\n}\n\nconst 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"]}
1
+ {"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/common/validation.ts"],"names":[],"mappings":";;;AAAA,uDAAgF;AAChF,2CAQyB;AACzB,6CAeqB;AAErB,MAAM,oBAAoB,GAAG;IAC3B,CAAC,yBAAW,CAAC,YAAY,CAAC,EAAE,sBAAsB;IAClD,CAAC,yBAAW,CAAC,aAAa,CAAC,EAAE,sBAAsB;IACnD,CAAC,yBAAW,CAAC,WAAW,CAAC,EAAE,qBAAqB;IAChD,CAAC,yBAAW,CAAC,SAAS,CAAC,EAAE,sBAAsB;CAChD,CAAC;AAEF;;;;;GAKG;AACH,SAAS,sBAAsB,CAC7B,UAAmB;IAEnB,OAAO,OAAO,UAAU,KAAK,UAAU,CAAC;AAC1C,CAAC;AAED;;;;;GAKG;AACH,SAAS,qBAAqB,CAAC,UAAmB;IAChD,8CAA8C;IAC9C,OAAO,OAAO,UAAU,KAAK,QAAQ,CAAC;AACxC,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,cAAc,CAAC,IAAiB,EAAE,UAAmB;IACnE,MAAM,kBAAkB,GAAG,oBAAoB,CAAC,IAAI,CAAC,CAAC;IACtD,OAAO,kBAAkB,EAAE,CAAC,UAAU,CAAC,IAAI,KAAK,CAAC;AACnD,CAAC;AAHD,wCAGC;AAEY,QAAA,6BAA6B,GAAG,IAAA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,qCAA6B,EAC7B,IAAA,oBAAM,EAAC;QACL,MAAM,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,kBAAU,CAAC,CAAC;KAC/C,CAAC,CACH;CACF,CAAC,CAAC;AAqBU,QAAA,mCAAmC,GAAG,IAAA,oBAAM,EAAC;IACxD,oCAAoC;IACpC,WAAW,EAAE,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,kBAAU,CAAC;IACzC,OAAO,EAAE,2BAAa;IACtB,iBAAiB,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,GAAE,CAAC;CACtC,CAAC,CAAC;AAMH;;;;;;;GAOG;AACH,SAAgB,qCAAqC,CACnD,KAAc;IAEd,IAAA,oBAAY,EACV,KAAK,EACL,2CAAmC,EACnC,wBAAwB,CACzB,CAAC;AACJ,CAAC;AARD,sFAQC;AAED,MAAM,gBAAgB,GAAG,IAAA,oBAAM,EAC7B,4BAAoB,EACpB,IAAA,oBAAM,EAAC;IACL,MAAM,EAAE,QAAQ;CACjB,CAAC,CACH,CAAC;AAEF,MAAM,eAAe,GAAG,4BAAoB,CAAC","sourcesContent":["import { SnapKeyring, ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport {\n assertStruct,\n Json,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccess,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport {\n array,\n assign,\n enums,\n Infer,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nconst VALIDATION_FUNCTIONS = {\n [HandlerType.OnRpcRequest]: validateFunctionExport,\n [HandlerType.OnTransaction]: validateFunctionExport,\n [HandlerType.SnapKeyring]: validateKeyringExport,\n [HandlerType.OnCronjob]: validateFunctionExport,\n};\n\n/**\n * Validates a function export.\n *\n * @param snapExport - The export itself.\n * @returns True if the export matches the expected shape, false otherwise.\n */\nfunction validateFunctionExport(\n snapExport: unknown,\n): snapExport is (...args: unknown[]) => unknown {\n return typeof snapExport === 'function';\n}\n\n/**\n * Validates a keyring export.\n *\n * @param snapExport - The export itself.\n * @returns True if the export matches the expected shape, false otherwise.\n */\nfunction validateKeyringExport(snapExport: unknown): snapExport is SnapKeyring {\n // TODO Decide whether we want more validation\n return typeof snapExport === 'object';\n}\n\n/**\n * Validates a given snap export.\n *\n * @param type - The type of export expected.\n * @param snapExport - The export itself.\n * @returns True if the export matches the expected shape, false otherwise.\n */\nexport function validateExport(type: HandlerType, snapExport: unknown) {\n const validationFunction = VALIDATION_FUNCTIONS[type];\n return validationFunction?.(snapExport) ?? false;\n}\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n optional(array(EndowmentStruct)),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n );\n}\n\nconst 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"]}
@@ -1,11 +1,13 @@
1
+ import { BasePostMessageStream } from '@metamask/post-message-stream';
1
2
  import { BaseSnapExecutor } from '../common/BaseSnapExecutor';
2
3
  export declare class IFrameSnapExecutor extends BaseSnapExecutor {
3
4
  /**
4
5
  * Initialize the IFrameSnapExecutor. This creates a post message stream from
5
6
  * and to the parent window, for two-way communication with the iframe.
6
7
  *
8
+ * @param stream - The stream to use for communication.
7
9
  * @returns An instance of `IFrameSnapExecutor`, with the initialized post
8
10
  * message streams.
9
11
  */
10
- static initialize(): IFrameSnapExecutor;
12
+ static initialize(stream?: BasePostMessageStream): IFrameSnapExecutor;
11
13
  }
@@ -15,19 +15,19 @@ class IFrameSnapExecutor extends BaseSnapExecutor_1.BaseSnapExecutor {
15
15
  * Initialize the IFrameSnapExecutor. This creates a post message stream from
16
16
  * and to the parent window, for two-way communication with the iframe.
17
17
  *
18
+ * @param stream - The stream to use for communication.
18
19
  * @returns An instance of `IFrameSnapExecutor`, with the initialized post
19
20
  * message streams.
20
21
  */
21
- static initialize() {
22
+ static initialize(stream = new post_message_stream_1.WindowPostMessageStream({
23
+ name: 'child',
24
+ target: 'parent',
25
+ targetWindow: self.parent,
26
+ targetOrigin: '*',
27
+ })) {
22
28
  (0, logging_1.log)('Worker: Connecting to parent.');
23
- const parentStream = new post_message_stream_1.WindowPostMessageStream({
24
- name: 'child',
25
- target: 'parent',
26
- targetWindow: self.parent,
27
- targetOrigin: '*',
28
- });
29
29
  const mux = new object_multiplex_1.default();
30
- (0, pump_1.default)(parentStream, mux, parentStream, (error) => {
30
+ (0, pump_1.default)(stream, mux, stream, (error) => {
31
31
  if (error) {
32
32
  (0, snaps_utils_1.logError)(`Parent stream failure, closing worker.`, error);
33
33
  }
@@ -1 +1 @@
1
- {"version":3,"file":"IFrameSnapExecutor.js","sourceRoot":"","sources":["../../src/iframe/IFrameSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,kFAAyD;AACzD,uEAAwE;AACxE,uDAAoE;AACpE,gDAAwB;AAExB,iEAA8D;AAC9D,wCAAiC;AAEjC,MAAa,kBAAmB,SAAQ,mCAAgB;IACtD;;;;;;OAMG;IACH,MAAM,CAAC,UAAU;QACf,IAAA,aAAG,EAAC,+BAA+B,CAAC,CAAC;QAErC,MAAM,YAAY,GAAG,IAAI,6CAAuB,CAAC;YAC/C,IAAI,EAAE,OAAO;YACb,MAAM,EAAE,QAAQ;YAChB,YAAY,EAAE,IAAI,CAAC,MAAM;YACzB,YAAY,EAAE,GAAG;SAClB,CAAC,CAAC;QAEH,MAAM,GAAG,GAAG,IAAI,0BAAe,EAAE,CAAC;QAClC,IAAA,cAAI,EAAC,YAAY,EAAE,GAAG,EAAE,YAAY,EAAE,CAAC,KAAK,EAAE,EAAE;YAC9C,IAAI,KAAK,EAAE;gBACT,IAAA,sBAAQ,EAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;aAC3D;YACD,IAAI,CAAC,KAAK,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;QAEH,MAAM,aAAa,GAAG,GAAG,CAAC,YAAY,CAAC,+BAAiB,CAAC,OAAO,CAAC,CAAC;QAClE,MAAM,SAAS,GAAG,GAAG,CAAC,YAAY,CAAC,+BAAiB,CAAC,QAAQ,CAAC,CAAC;QAE/D,OAAO,IAAI,kBAAkB,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;IAC1D,CAAC;CACF;AA/BD,gDA+BC","sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport { WindowPostMessageStream } from '@metamask/post-message-stream';\nimport { logError, SNAP_STREAM_NAMES } from '@metamask/snaps-utils';\nimport pump from 'pump';\n\nimport { BaseSnapExecutor } from '../common/BaseSnapExecutor';\nimport { log } from '../logging';\n\nexport class IFrameSnapExecutor extends BaseSnapExecutor {\n /**\n * Initialize the IFrameSnapExecutor. This creates a post message stream from\n * and to the parent window, for two-way communication with the iframe.\n *\n * @returns An instance of `IFrameSnapExecutor`, with the initialized post\n * message streams.\n */\n static initialize() {\n log('Worker: Connecting to parent.');\n\n const parentStream = new WindowPostMessageStream({\n name: 'child',\n target: 'parent',\n targetWindow: self.parent,\n targetOrigin: '*',\n });\n\n const mux = new ObjectMultiplex();\n pump(parentStream, mux, parentStream, (error) => {\n if (error) {\n logError(`Parent stream failure, closing worker.`, error);\n }\n self.close();\n });\n\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n return new IFrameSnapExecutor(commandStream, rpcStream);\n }\n}\n"]}
1
+ {"version":3,"file":"IFrameSnapExecutor.js","sourceRoot":"","sources":["../../src/iframe/IFrameSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,kFAAyD;AACzD,uEAGuC;AACvC,uDAAoE;AACpE,gDAAwB;AAExB,iEAA8D;AAC9D,wCAAiC;AAEjC,MAAa,kBAAmB,SAAQ,mCAAgB;IACtD;;;;;;;OAOG;IACH,MAAM,CAAC,UAAU,CACf,SAAgC,IAAI,6CAAuB,CAAC;QAC1D,IAAI,EAAE,OAAO;QACb,MAAM,EAAE,QAAQ;QAChB,YAAY,EAAE,IAAI,CAAC,MAAM;QACzB,YAAY,EAAE,GAAG;KAClB,CAAC;QAEF,IAAA,aAAG,EAAC,+BAA+B,CAAC,CAAC;QAErC,MAAM,GAAG,GAAG,IAAI,0BAAe,EAAE,CAAC;QAClC,IAAA,cAAI,EAAC,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;YAClC,IAAI,KAAK,EAAE;gBACT,IAAA,sBAAQ,EAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;aAC3D;YACD,IAAI,CAAC,KAAK,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;QAEH,MAAM,aAAa,GAAG,GAAG,CAAC,YAAY,CAAC,+BAAiB,CAAC,OAAO,CAAC,CAAC;QAClE,MAAM,SAAS,GAAG,GAAG,CAAC,YAAY,CAAC,+BAAiB,CAAC,QAAQ,CAAC,CAAC;QAE/D,OAAO,IAAI,kBAAkB,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;IAC1D,CAAC;CACF;AAhCD,gDAgCC","sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport {\n BasePostMessageStream,\n WindowPostMessageStream,\n} from '@metamask/post-message-stream';\nimport { logError, SNAP_STREAM_NAMES } from '@metamask/snaps-utils';\nimport pump from 'pump';\n\nimport { BaseSnapExecutor } from '../common/BaseSnapExecutor';\nimport { log } from '../logging';\n\nexport class IFrameSnapExecutor extends BaseSnapExecutor {\n /**\n * Initialize the IFrameSnapExecutor. This creates a post message stream from\n * and to the parent window, for two-way communication with the iframe.\n *\n * @param stream - The stream to use for communication.\n * @returns An instance of `IFrameSnapExecutor`, with the initialized post\n * message streams.\n */\n static initialize(\n stream: BasePostMessageStream = new WindowPostMessageStream({\n name: 'child',\n target: 'parent',\n targetWindow: self.parent,\n targetOrigin: '*',\n }),\n ) {\n log('Worker: Connecting to parent.');\n\n const mux = new ObjectMultiplex();\n pump(stream, mux, stream, (error) => {\n if (error) {\n logError(`Parent stream failure, closing worker.`, error);\n }\n self.close();\n });\n\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n return new IFrameSnapExecutor(commandStream, rpcStream);\n }\n}\n"]}