@metamask/snaps-execution-environments 0.24.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 (83) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +3 -0
  3. package/dist/common/BaseSnapExecutor.d.ts +68 -0
  4. package/dist/common/BaseSnapExecutor.js +324 -0
  5. package/dist/common/BaseSnapExecutor.js.map +1 -0
  6. package/dist/common/commands.d.ts +30 -0
  7. package/dist/common/commands.js +68 -0
  8. package/dist/common/commands.js.map +1 -0
  9. package/dist/common/endowments/crypto.d.ts +8 -0
  10. package/dist/common/endowments/crypto.js +25 -0
  11. package/dist/common/endowments/crypto.js.map +1 -0
  12. package/dist/common/endowments/index.d.ts +25 -0
  13. package/dist/common/endowments/index.js +122 -0
  14. package/dist/common/endowments/index.js.map +1 -0
  15. package/dist/common/endowments/interval.d.ts +9 -0
  16. package/dist/common/endowments/interval.js +47 -0
  17. package/dist/common/endowments/interval.js.map +1 -0
  18. package/dist/common/endowments/math.d.ts +60 -0
  19. package/dist/common/endowments/math.js +48 -0
  20. package/dist/common/endowments/math.js.map +1 -0
  21. package/dist/common/endowments/network.d.ts +48 -0
  22. package/dist/common/endowments/network.js +362 -0
  23. package/dist/common/endowments/network.js.map +1 -0
  24. package/dist/common/endowments/timeout.d.ts +9 -0
  25. package/dist/common/endowments/timeout.js +50 -0
  26. package/dist/common/endowments/timeout.js.map +1 -0
  27. package/dist/common/globalEvents.d.ts +19 -0
  28. package/dist/common/globalEvents.js +47 -0
  29. package/dist/common/globalEvents.js.map +1 -0
  30. package/dist/common/globalObject.d.ts +9 -0
  31. package/dist/common/globalObject.js +48 -0
  32. package/dist/common/globalObject.js.map +1 -0
  33. package/dist/common/keyring.d.ts +12 -0
  34. package/dist/common/keyring.js +42 -0
  35. package/dist/common/keyring.js.map +1 -0
  36. package/dist/common/lockdown/lockdown-more.d.ts +22 -0
  37. package/dist/common/lockdown/lockdown-more.js +88 -0
  38. package/dist/common/lockdown/lockdown-more.js.map +1 -0
  39. package/dist/common/lockdown/lockdown.d.ts +7 -0
  40. package/dist/common/lockdown/lockdown.js +28 -0
  41. package/dist/common/lockdown/lockdown.js.map +1 -0
  42. package/dist/common/sortParams.d.ts +16 -0
  43. package/dist/common/sortParams.js +32 -0
  44. package/dist/common/sortParams.js.map +1 -0
  45. package/dist/common/utils.d.ts +38 -0
  46. package/dist/common/utils.js +98 -0
  47. package/dist/common/utils.js.map +1 -0
  48. package/dist/common/validation.d.ts +100 -0
  49. package/dist/common/validation.js +110 -0
  50. package/dist/common/validation.js.map +1 -0
  51. package/dist/iframe/IFrameSnapExecutor.d.ts +11 -0
  52. package/dist/iframe/IFrameSnapExecutor.js +41 -0
  53. package/dist/iframe/IFrameSnapExecutor.js.map +1 -0
  54. package/dist/iframe/index.d.ts +1 -0
  55. package/dist/iframe/index.js +9 -0
  56. package/dist/iframe/index.js.map +1 -0
  57. package/dist/iframe-test/index.d.ts +1 -0
  58. package/dist/iframe-test/index.js +8 -0
  59. package/dist/iframe-test/index.js.map +1 -0
  60. package/dist/node-process/ChildProcessSnapExecutor.d.ts +4 -0
  61. package/dist/node-process/ChildProcessSnapExecutor.js +29 -0
  62. package/dist/node-process/ChildProcessSnapExecutor.js.map +1 -0
  63. package/dist/node-process/index.d.ts +1 -0
  64. package/dist/node-process/index.js +9 -0
  65. package/dist/node-process/index.js.map +1 -0
  66. package/dist/node-thread/ThreadSnapExecutor.d.ts +4 -0
  67. package/dist/node-thread/ThreadSnapExecutor.js +29 -0
  68. package/dist/node-thread/ThreadSnapExecutor.js.map +1 -0
  69. package/dist/node-thread/index.d.ts +1 -0
  70. package/dist/node-thread/index.js +9 -0
  71. package/dist/node-thread/index.js.map +1 -0
  72. package/dist/openrpc.json +210 -0
  73. package/dist/webpack/iframe/bundle.js +2 -0
  74. package/dist/webpack/iframe/bundle.js.LICENSE.txt +21 -0
  75. package/dist/webpack/iframe/index.html +10 -0
  76. package/dist/webpack/iframe/lockdown.umd.min.js +1 -0
  77. package/dist/webpack/node-process/bundle.js +1784 -0
  78. package/dist/webpack/node-process/bundle.js.LICENSE.txt +3 -0
  79. package/dist/webpack/node-process/lockdown.umd.min.js +1 -0
  80. package/dist/webpack/node-thread/bundle.js +1784 -0
  81. package/dist/webpack/node-thread/bundle.js.LICENSE.txt +3 -0
  82. package/dist/webpack/node-thread/lockdown.umd.min.js +1 -0
  83. package/package.json +88 -0
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.wrapKeyring = void 0;
4
+ const utils_1 = require("@metamask/utils");
5
+ /**
6
+ * Wraps a SnapKeyring class, returning a handler that can route requests to the exposed functions by the class.
7
+ *
8
+ * @param notify - The BaseSnapExecutor notify function, used for event communication.
9
+ * @param keyring - The SnapKeyring instance.
10
+ * @returns A handler function.
11
+ */
12
+ function wrapKeyring(notify, keyring) {
13
+ if (!keyring) {
14
+ throw new Error('Keyring not exported');
15
+ }
16
+ const keyringHandler = ({ request }) => {
17
+ const { method, params } = request;
18
+ if (!(method in keyring)) {
19
+ throw new Error(`Keyring does not expose ${method}`);
20
+ }
21
+ let args = (params !== null && params !== void 0 ? params : []);
22
+ const keyringMethod = keyring[method];
23
+ (0, utils_1.assert)(keyringMethod !== undefined);
24
+ const func = keyringMethod.bind(keyring);
25
+ // Special case for registering events
26
+ if (method === 'on') {
27
+ const data = args[0];
28
+ const listener = (...listenerArgs) => {
29
+ (0, utils_1.assert)((0, utils_1.isValidJson)(listenerArgs), new TypeError('Keyrings .on listener received non-JSON-serializable value.'));
30
+ return notify({
31
+ method: 'SnapKeyringEvent',
32
+ params: { data, args: listenerArgs },
33
+ });
34
+ };
35
+ args = [data, listener];
36
+ }
37
+ return func(...args);
38
+ };
39
+ return keyringHandler;
40
+ }
41
+ exports.wrapKeyring = wrapKeyring;
42
+ //# sourceMappingURL=keyring.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyring.js","sourceRoot":"","sources":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D,CAAC,CAAC;IACF,OAAO,cAAc,CAAC;AACxB,CAAC;AA1CD,kCA0CC","sourcesContent":["import { SnapKeyring } from '@metamask/snaps-types';\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"]}
@@ -0,0 +1,22 @@
1
+ /// <reference types="ses" />
2
+ /**
3
+ * The SES `lockdown` function only hardens the properties enumerated by the
4
+ * universalPropertyNames constant specified in 'ses/src/whitelist'. This
5
+ * function makes all function and object properties on the start compartment
6
+ * global non-configurable and non-writable, unless they are already
7
+ * non-configurable.
8
+ *
9
+ * It is critical that this function runs at the right time during
10
+ * initialization, which should always be immediately after `lockdown` has been
11
+ * called. At the time of writing, the modifications this function makes to the
12
+ * runtime environment appear to be non-breaking, but that could change with
13
+ * the addition of dependencies, or the order of our scripts in our HTML files.
14
+ * Exercise caution.
15
+ *
16
+ * See inline comments for implementation details.
17
+ *
18
+ * We write this function in IIFE format to avoid polluting global scope.
19
+ *
20
+ * @throws If the lockdown failed.
21
+ */
22
+ export declare function executeLockdownMore(): void;
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ // eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment
3
+ /// <reference path="../../../../../node_modules/ses/index.d.ts" />
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.executeLockdownMore = void 0;
6
+ /**
7
+ * The SES `lockdown` function only hardens the properties enumerated by the
8
+ * universalPropertyNames constant specified in 'ses/src/whitelist'. This
9
+ * function makes all function and object properties on the start compartment
10
+ * global non-configurable and non-writable, unless they are already
11
+ * non-configurable.
12
+ *
13
+ * It is critical that this function runs at the right time during
14
+ * initialization, which should always be immediately after `lockdown` has been
15
+ * called. At the time of writing, the modifications this function makes to the
16
+ * runtime environment appear to be non-breaking, but that could change with
17
+ * the addition of dependencies, or the order of our scripts in our HTML files.
18
+ * Exercise caution.
19
+ *
20
+ * See inline comments for implementation details.
21
+ *
22
+ * We write this function in IIFE format to avoid polluting global scope.
23
+ *
24
+ * @throws If the lockdown failed.
25
+ */
26
+ function executeLockdownMore() {
27
+ // Make all "object" and "function" own properties of globalThis
28
+ // non-configurable and non-writable, when possible.
29
+ // We call a property that is non-configurable and non-writable,
30
+ // "non-modifiable".
31
+ try {
32
+ const namedIntrinsics = Reflect.ownKeys(new Compartment().globalThis);
33
+ // These named intrinsics are not automatically hardened by `lockdown`
34
+ const shouldHardenManually = new Set(['eval', 'Function']);
35
+ const globalProperties = new Set([
36
+ // universalPropertyNames is a constant added by lockdown to global scope
37
+ // at the time of writing, it is initialized in 'ses/src/whitelist'.
38
+ // These properties tend to be non-enumerable.
39
+ ...namedIntrinsics,
40
+ // TODO: Also include the named platform globals
41
+ // This grabs every enumerable property on globalThis.
42
+ // ...Object.keys(globalThis),
43
+ ]);
44
+ globalProperties.forEach((propertyName) => {
45
+ const descriptor = Reflect.getOwnPropertyDescriptor(globalThis, propertyName);
46
+ if (descriptor) {
47
+ if (descriptor.configurable) {
48
+ // If the property on globalThis is configurable, make it
49
+ // non-configurable. If it has no accessor properties, also make it
50
+ // non-writable.
51
+ if (hasAccessor(descriptor)) {
52
+ Object.defineProperty(globalThis, propertyName, {
53
+ configurable: false,
54
+ });
55
+ }
56
+ else {
57
+ Object.defineProperty(globalThis, propertyName, {
58
+ configurable: false,
59
+ writable: false,
60
+ });
61
+ }
62
+ }
63
+ if (shouldHardenManually.has(propertyName)) {
64
+ harden(globalThis[propertyName]);
65
+ }
66
+ }
67
+ });
68
+ }
69
+ catch (error) {
70
+ console.error('Protecting intrinsics failed:', error);
71
+ throw error;
72
+ }
73
+ }
74
+ exports.executeLockdownMore = executeLockdownMore;
75
+ /**
76
+ * Checks whether the given propertyName descriptor has any accessors, i.e. the
77
+ * properties `get` or `set`.
78
+ *
79
+ * We want to make globals non-writable, and we can't set the `writable`
80
+ * property and accessor properties at the same time.
81
+ *
82
+ * @param descriptor - The propertyName descriptor to check.
83
+ * @returns Whether the propertyName descriptor has any accessors.
84
+ */
85
+ function hasAccessor(descriptor) {
86
+ return 'set' in descriptor || 'get' in descriptor;
87
+ }
88
+ //# sourceMappingURL=lockdown-more.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lockdown-more.js","sourceRoot":"","sources":["../../../src/common/lockdown/lockdown-more.ts"],"names":[],"mappings":";AAAA,qFAAqF;AACrF,mEAAmE;;;AAEnE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAgB,mBAAmB;IACjC,gEAAgE;IAChE,oDAAoD;IACpD,gEAAgE;IAChE,oBAAoB;IACpB,IAAI;QACF,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,WAAW,EAAE,CAAC,UAAU,CAAC,CAAC;QAEtE,sEAAsE;QACtE,MAAM,oBA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-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/index.d.ts\" />\n\n/**\n * The SES `lockdown` function only hardens the properties enumerated by the\n * universalPropertyNames constant specified in 'ses/src/whitelist'. This\n * function makes all function and object properties on the start compartment\n * global non-configurable and non-writable, unless they are already\n * non-configurable.\n *\n * It is critical that this function runs at the right time during\n * initialization, which should always be immediately after `lockdown` has been\n * called. At the time of writing, the modifications this function makes to the\n * runtime environment appear to be non-breaking, but that could change with\n * the addition of dependencies, or the order of our scripts in our HTML files.\n * Exercise caution.\n *\n * See inline comments for implementation details.\n *\n * We write this function in IIFE format to avoid polluting global scope.\n *\n * @throws If the lockdown failed.\n */\nexport function executeLockdownMore() {\n // Make all \"object\" and \"function\" own properties of globalThis\n // non-configurable and non-writable, when possible.\n // We call a property that is non-configurable and non-writable,\n // \"non-modifiable\".\n try {\n const namedIntrinsics = Reflect.ownKeys(new Compartment().globalThis);\n\n // These named intrinsics are not automatically hardened by `lockdown`\n const shouldHardenManually = new Set<symbol | string>(['eval', 'Function']);\n\n const globalProperties = new Set([\n // universalPropertyNames is a constant added by lockdown to global scope\n // at the time of writing, it is initialized in 'ses/src/whitelist'.\n // These properties tend to be non-enumerable.\n ...namedIntrinsics,\n\n // TODO: Also include the named platform globals\n // This grabs every enumerable property on globalThis.\n // ...Object.keys(globalThis),\n ]);\n\n globalProperties.forEach((propertyName) => {\n const descriptor = Reflect.getOwnPropertyDescriptor(\n globalThis,\n propertyName,\n );\n\n if (descriptor) {\n if (descriptor.configurable) {\n // If the property on globalThis is configurable, make it\n // non-configurable. If it has no accessor properties, also make it\n // non-writable.\n if (hasAccessor(descriptor)) {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n });\n } else {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n writable: false,\n });\n }\n }\n\n if (shouldHardenManually.has(propertyName)) {\n harden((globalThis as any)[propertyName]);\n }\n }\n });\n } catch (error) {\n console.error('Protecting intrinsics failed:', error);\n throw error;\n }\n}\n\n/**\n * Checks whether the given propertyName descriptor has any accessors, i.e. the\n * properties `get` or `set`.\n *\n * We want to make globals non-writable, and we can't set the `writable`\n * property and accessor properties at the same time.\n *\n * @param descriptor - The propertyName descriptor to check.\n * @returns Whether the propertyName descriptor has any accessors.\n */\nfunction hasAccessor(descriptor: any): boolean {\n return 'set' in descriptor || 'get' in descriptor;\n}\n"]}
@@ -0,0 +1,7 @@
1
+ /// <reference types="ses" />
2
+ /**
3
+ * Execute SES lockdown in the current context, i.e., the current iframe.
4
+ *
5
+ * @throws If the SES lockdown failed.
6
+ */
7
+ export declare function executeLockdown(): void;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ // eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment
3
+ /// <reference path="../../../../../node_modules/ses/index.d.ts" />
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.executeLockdown = void 0;
6
+ /**
7
+ * Execute SES lockdown in the current context, i.e., the current iframe.
8
+ *
9
+ * @throws If the SES lockdown failed.
10
+ */
11
+ function executeLockdown() {
12
+ try {
13
+ lockdown({
14
+ consoleTaming: 'unsafe',
15
+ errorTaming: 'unsafe',
16
+ mathTaming: 'unsafe',
17
+ dateTaming: 'unsafe',
18
+ overrideTaming: 'severe',
19
+ });
20
+ }
21
+ catch (error) {
22
+ // If the `lockdown` call throws an exception, it should not be able to continue
23
+ console.error('Lockdown failed:', error);
24
+ throw error;
25
+ }
26
+ }
27
+ exports.executeLockdown = executeLockdown;
28
+ //# sourceMappingURL=lockdown.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lockdown.js","sourceRoot":"","sources":["../../../src/common/lockdown/lockdown.ts"],"names":[],"mappings":";AAAA,qFAAqF;AACrF,mEAAmE;;;AAEnE;;;;GAIG;AACH,SAAgB,eAAe;IAC7B,IAAI;QACF,QAAQ,CAAC;YACP,aAAa,EAAE,QAAQ;YACvB,WAAW,EAAE,QAAQ;YACrB,UAAU,EAAE,QAAQ;YACpB,UAAU,EAAE,QAAQ;YACpB,cAAc,EAAE,QAAQ;SACzB,CAAC,CAAC;KACJ;IAAC,OAAO,KAAK,EAAE;QACd,gFAAgF;QAChF,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;QACzC,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AAdD,0CAcC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/index.d.ts\" />\n\n/**\n * Execute SES lockdown in the current context, i.e., the current iframe.\n *\n * @throws If the SES lockdown failed.\n */\nexport function executeLockdown() {\n try {\n lockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n });\n } catch (error) {\n // If the `lockdown` call throws an exception, it should not be able to continue\n console.error('Lockdown failed:', error);\n throw error;\n }\n}\n"]}
@@ -0,0 +1,16 @@
1
+ import { JsonRpcParams } from '@metamask/utils';
2
+ /**
3
+ * Deterministically sort JSON-RPC parameter keys. This makes it possible to
4
+ * support both arrays and objects as parameters. Objects are sorted and turned
5
+ * into arrays, for easier consumption by the snap.
6
+ *
7
+ * The order is defined by the `method` parameter.
8
+ *
9
+ * @param methodParams - The parameters of the JSON-RPC method, which
10
+ * determines the ordering for the parameters.
11
+ * @param params - JSON-RPC parameters as object or array.
12
+ * @returns The values for the sorted keys. If `params` is not provided, this
13
+ * returns an empty array. If `params` is an array, this returns the same
14
+ * `params`.
15
+ */
16
+ export declare const sortParamKeys: (methodParams: string[], params?: JsonRpcParams) => import("@metamask/utils").Json[];
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ // original source sortParamKeys from: https://github.com/etclabscore/sig.tools/blob/master/src/postMessageServer/postMessageServer.ts#L75-L77
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.sortParamKeys = void 0;
5
+ /**
6
+ * Deterministically sort JSON-RPC parameter keys. This makes it possible to
7
+ * support both arrays and objects as parameters. Objects are sorted and turned
8
+ * into arrays, for easier consumption by the snap.
9
+ *
10
+ * The order is defined by the `method` parameter.
11
+ *
12
+ * @param methodParams - The parameters of the JSON-RPC method, which
13
+ * determines the ordering for the parameters.
14
+ * @param params - JSON-RPC parameters as object or array.
15
+ * @returns The values for the sorted keys. If `params` is not provided, this
16
+ * returns an empty array. If `params` is an array, this returns the same
17
+ * `params`.
18
+ */
19
+ const sortParamKeys = (methodParams, params) => {
20
+ if (!params) {
21
+ return [];
22
+ }
23
+ if (params instanceof Array) {
24
+ return params;
25
+ }
26
+ const methodParamsOrder = methodParams.reduce((paramsOrderObj, paramsName, i) => (Object.assign(Object.assign({}, paramsOrderObj), { [paramsName]: i })), {});
27
+ return Object.entries(params)
28
+ .sort(([name1, _], [name2, __]) => methodParamsOrder[name1] - methodParamsOrder[name2])
29
+ .map(([_, val]) => val);
30
+ };
31
+ exports.sortParamKeys = sortParamKeys;
32
+ //# sourceMappingURL=sortParams.js.map
@@ -0,0 +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,CAAC,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,EAAE,CAC1B,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, _], [name2, __]) =>\n methodParamsOrder[name1] - methodParamsOrder[name2],\n )\n .map(([_, val]) => val);\n};\n"]}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Takes an error that was thrown, determines if it is
3
+ * an error object. If it is then it will return that. Otherwise,
4
+ * an error object is created with the original error message.
5
+ *
6
+ * @param originalError - The error that was originally thrown.
7
+ * @returns An error object.
8
+ */
9
+ export declare function constructError(originalError: unknown): Error | undefined;
10
+ /**
11
+ * Get all properties of an object, including its prototype chain.
12
+ *
13
+ * @param obj - The object to get all properties for.
14
+ * @returns All properties of `obj` as a tuple set, containing the property name
15
+ * and value.
16
+ */
17
+ export declare function allProperties(obj: any): Set<[object, string | symbol]>;
18
+ /**
19
+ * Get all functions of an object, including its prototype chain. This does not
20
+ * include constructor functions.
21
+ *
22
+ * @param obj - The object to get all functions for.
23
+ * @returns An array with all functions of `obj` as string or symbol.
24
+ */
25
+ export declare function allFunctions(obj: any): (string | symbol)[];
26
+ /**
27
+ * Make proxy for Promise and handle the teardown process properly.
28
+ * If the teardown is called in the meanwhile, Promise result will not be
29
+ * exposed to the snap anymore and warning will be logged to the console.
30
+ *
31
+ * @param originalPromise - Original promise.
32
+ * @param teardownRef - Reference containing teardown count.
33
+ * @param teardownRef.lastTeardown - Number of the last teardown.
34
+ * @returns New proxy promise.
35
+ */
36
+ export declare function withTeardown<T>(originalPromise: Promise<T>, teardownRef: {
37
+ lastTeardown: number;
38
+ }): Promise<T>;
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withTeardown = exports.allFunctions = exports.allProperties = exports.constructError = void 0;
4
+ /**
5
+ * Takes an error that was thrown, determines if it is
6
+ * an error object. If it is then it will return that. Otherwise,
7
+ * an error object is created with the original error message.
8
+ *
9
+ * @param originalError - The error that was originally thrown.
10
+ * @returns An error object.
11
+ */
12
+ function constructError(originalError) {
13
+ let _originalError;
14
+ if (originalError instanceof Error) {
15
+ _originalError = originalError;
16
+ }
17
+ else if (typeof originalError === 'string') {
18
+ _originalError = new Error(originalError);
19
+ // The stack is useless in this case.
20
+ delete _originalError.stack;
21
+ }
22
+ return _originalError;
23
+ }
24
+ exports.constructError = constructError;
25
+ /**
26
+ * Get all properties of an object, including its prototype chain.
27
+ *
28
+ * @param obj - The object to get all properties for.
29
+ * @returns All properties of `obj` as a tuple set, containing the property name
30
+ * and value.
31
+ */
32
+ function allProperties(obj) {
33
+ const properties = new Set();
34
+ let current = obj;
35
+ do {
36
+ for (const key of Reflect.ownKeys(current)) {
37
+ properties.add([current, key]);
38
+ }
39
+ } while ((current = Reflect.getPrototypeOf(current)) &&
40
+ current !== Object.prototype);
41
+ return properties;
42
+ }
43
+ exports.allProperties = allProperties;
44
+ /**
45
+ * Get all functions of an object, including its prototype chain. This does not
46
+ * include constructor functions.
47
+ *
48
+ * @param obj - The object to get all functions for.
49
+ * @returns An array with all functions of `obj` as string or symbol.
50
+ */
51
+ function allFunctions(obj) {
52
+ const result = [];
53
+ for (const [object, key] of allProperties(obj)) {
54
+ if (key === 'constructor') {
55
+ continue;
56
+ }
57
+ const descriptor = Reflect.getOwnPropertyDescriptor(object, key);
58
+ if (descriptor !== undefined && typeof descriptor.value === 'function') {
59
+ result.push(key);
60
+ }
61
+ }
62
+ return result;
63
+ }
64
+ exports.allFunctions = allFunctions;
65
+ /**
66
+ * Make proxy for Promise and handle the teardown process properly.
67
+ * If the teardown is called in the meanwhile, Promise result will not be
68
+ * exposed to the snap anymore and warning will be logged to the console.
69
+ *
70
+ * @param originalPromise - Original promise.
71
+ * @param teardownRef - Reference containing teardown count.
72
+ * @param teardownRef.lastTeardown - Number of the last teardown.
73
+ * @returns New proxy promise.
74
+ */
75
+ function withTeardown(originalPromise, teardownRef) {
76
+ const myTeardown = teardownRef.lastTeardown;
77
+ return new Promise((resolve, reject) => {
78
+ originalPromise
79
+ .then((value) => {
80
+ if (teardownRef.lastTeardown === myTeardown) {
81
+ resolve(value);
82
+ }
83
+ else {
84
+ console.warn('Late promise received after Snap finished execution. Promise will be dropped.');
85
+ }
86
+ })
87
+ .catch((reason) => {
88
+ if (teardownRef.lastTeardown === myTeardown) {
89
+ reject(reason);
90
+ }
91
+ else {
92
+ console.warn('Late promise received after Snap finished execution. Promise will be dropped.');
93
+ }
94
+ });
95
+ });
96
+ }
97
+ exports.withTeardown = withTeardown;
98
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/common/utils.ts"],"names":[],"mappings":";;;AAAA;;;;;;;GAO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;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAZD,oCAYC;AAED;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,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,OAAO,CAAC,IAAI,CACV,+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,OAAO,CAAC,IAAI,CACV,+EAA+E,CAChF,CAAC;aACH;QACH,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACL,CAAC;AA1BD,oCA0BC","sourcesContent":["/**\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 * Get all properties of an object, including its prototype chain.\n *\n * @param obj - The object to get all properties for.\n * @returns All properties of `obj` as a tuple set, containing the property name\n * and value.\n */\nexport function allProperties(obj: any): Set<[object, string | symbol]> {\n const properties = new Set<[any, any]>();\n let current = obj;\n do {\n for (const key of Reflect.ownKeys(current)) {\n properties.add([current, key]);\n }\n } while (\n (current = Reflect.getPrototypeOf(current)) &&\n current !== Object.prototype\n );\n return properties;\n}\n\n/**\n * Get all functions of an object, including its prototype chain. This does not\n * include constructor functions.\n *\n * @param obj - The object to get all functions for.\n * @returns An array with all functions of `obj` as string or symbol.\n */\nexport function allFunctions(obj: any): (string | symbol)[] {\n const result = [];\n for (const [object, key] of allProperties(obj)) {\n if (key === 'constructor') {\n continue;\n }\n const descriptor = Reflect.getOwnPropertyDescriptor(object, key);\n if (descriptor !== undefined && typeof descriptor.value === 'function') {\n result.push(key);\n }\n }\n return result;\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 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 console.warn(\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 console.warn(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n"]}
@@ -0,0 +1,100 @@
1
+ import { HandlerType } from '@metamask/snaps-utils';
2
+ import { Json, JsonRpcSuccess } from '@metamask/utils';
3
+ import { Infer } from 'superstruct';
4
+ /**
5
+ * Validates a given snap export.
6
+ *
7
+ * @param type - The type of export expected.
8
+ * @param snapExport - The export itself.
9
+ * @returns True if the export matches the expected shape, false otherwise.
10
+ */
11
+ export declare function validateExport(type: HandlerType, snapExport: unknown): boolean;
12
+ export declare const JsonRpcRequestWithoutIdStruct: import("superstruct").Struct<{
13
+ jsonrpc: "2.0";
14
+ method: string;
15
+ id?: string | number | null | undefined;
16
+ params?: Record<string, Json> | Json[] | undefined;
17
+ }, {
18
+ id: import("superstruct").Struct<string | number | null | undefined, null>;
19
+ jsonrpc: import("superstruct").Struct<"2.0", "2.0">;
20
+ method: import("superstruct").Struct<string, null>;
21
+ params: import("superstruct").Struct<Record<string, Json> | Json[] | undefined, null>;
22
+ }>;
23
+ export declare type JsonRpcRequestWithoutId = Infer<typeof JsonRpcRequestWithoutIdStruct>;
24
+ export declare const EndowmentStruct: import("superstruct").Struct<string, null>;
25
+ export declare type Endowment = Infer<typeof EndowmentStruct>;
26
+ /**
27
+ * Check if the given value is an endowment.
28
+ *
29
+ * @param value - The value to check.
30
+ * @returns Whether the value is an endowment.
31
+ */
32
+ export declare function isEndowment(value: unknown): value is Endowment;
33
+ /**
34
+ * Check if the given value is an array of endowments.
35
+ *
36
+ * @param value - The value to check.
37
+ * @returns Whether the value is an array of endowments.
38
+ */
39
+ export declare function isEndowmentsArray(value: unknown): value is Endowment[];
40
+ export declare const PingRequestArgumentsStruct: import("superstruct").Struct<unknown[] | undefined, null>;
41
+ export declare const TerminateRequestArgumentsStruct: import("superstruct").Struct<unknown[] | undefined, null>;
42
+ export declare const ExecuteSnapRequestArgumentsStruct: import("superstruct").Struct<[string, string, string[] | undefined], null>;
43
+ export declare const SnapRpcRequestArgumentsStruct: import("superstruct").Struct<[string, HandlerType, string, {
44
+ jsonrpc: "2.0";
45
+ method: string;
46
+ id?: string | number | null | undefined;
47
+ params?: Record<string, Json> | undefined;
48
+ }], null>;
49
+ export declare type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;
50
+ export declare type TerminateRequestArguments = Infer<typeof TerminateRequestArgumentsStruct>;
51
+ export declare type ExecuteSnapRequestArguments = Infer<typeof ExecuteSnapRequestArgumentsStruct>;
52
+ export declare type SnapRpcRequestArguments = Infer<typeof SnapRpcRequestArgumentsStruct>;
53
+ export declare type RequestArguments = PingRequestArguments | TerminateRequestArguments | ExecuteSnapRequestArguments | SnapRpcRequestArguments;
54
+ export declare const OnTransactionRequestArgumentsStruct: import("superstruct").Struct<{
55
+ chainId: string;
56
+ transaction: Record<string, Json>;
57
+ transactionOrigin: string | null;
58
+ }, {
59
+ transaction: import("superstruct").Struct<Record<string, Json>, null>;
60
+ chainId: import("superstruct").Struct<string, null>;
61
+ transactionOrigin: import("superstruct").Struct<string | null, null>;
62
+ }>;
63
+ export declare type OnTransactionRequestArguments = Infer<typeof OnTransactionRequestArgumentsStruct>;
64
+ /**
65
+ * Asserts that the given value is a valid {@link OnTransactionRequestArguments}
66
+ * object.
67
+ *
68
+ * @param value - The value to validate.
69
+ * @throws If the value is not a valid {@link OnTransactionRequestArguments}
70
+ * object.
71
+ */
72
+ export declare function assertIsOnTransactionRequestArguments(value: unknown): asserts value is OnTransactionRequestArguments;
73
+ declare const OkResponseStruct: import("superstruct").Struct<{
74
+ jsonrpc: "2.0";
75
+ id: string | number | null;
76
+ result: "OK";
77
+ }, {
78
+ result: import("superstruct").Struct<"OK", "OK">;
79
+ jsonrpc: import("superstruct").Struct<"2.0", "2.0">;
80
+ id: import("superstruct").Struct<string | number | null, null>;
81
+ }>;
82
+ declare const SnapRpcResponse: import("superstruct").Struct<{
83
+ id: string | number | null;
84
+ jsonrpc: "2.0";
85
+ result: Json;
86
+ }, {
87
+ id: import("superstruct").Struct<string | number | null, null>;
88
+ jsonrpc: import("superstruct").Struct<"2.0", "2.0">;
89
+ result: import("superstruct").Struct<Json, null>;
90
+ }>;
91
+ export declare type OkResponse = Infer<typeof OkResponseStruct>;
92
+ export declare type SnapRpcResponse = Infer<typeof SnapRpcResponse>;
93
+ export declare type Response = OkResponse | SnapRpcResponse;
94
+ declare type RequestParams<Params extends unknown[] | undefined> = Params extends undefined ? [] : Params;
95
+ declare type RequestFunction<Args extends RequestArguments, ResponseType extends JsonRpcSuccess<Json>> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;
96
+ export declare type Ping = RequestFunction<PingRequestArguments, OkResponse>;
97
+ export declare type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;
98
+ export declare type ExecuteSnap = RequestFunction<ExecuteSnapRequestArguments, OkResponse>;
99
+ export declare type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;
100
+ export {};
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertIsOnTransactionRequestArguments = exports.OnTransactionRequestArgumentsStruct = exports.SnapRpcRequestArgumentsStruct = exports.ExecuteSnapRequestArgumentsStruct = exports.TerminateRequestArgumentsStruct = exports.PingRequestArgumentsStruct = exports.isEndowmentsArray = exports.isEndowment = exports.EndowmentStruct = exports.JsonRpcRequestWithoutIdStruct = exports.validateExport = void 0;
4
+ const snaps_utils_1 = require("@metamask/snaps-utils");
5
+ const utils_1 = require("@metamask/utils");
6
+ const superstruct_1 = require("superstruct");
7
+ const VALIDATION_FUNCTIONS = {
8
+ [snaps_utils_1.HandlerType.OnRpcRequest]: validateFunctionExport,
9
+ [snaps_utils_1.HandlerType.OnTransaction]: validateFunctionExport,
10
+ [snaps_utils_1.HandlerType.SnapKeyring]: validateKeyringExport,
11
+ [snaps_utils_1.HandlerType.OnCronjob]: validateFunctionExport,
12
+ };
13
+ /**
14
+ * Validates a function export.
15
+ *
16
+ * @param snapExport - The export itself.
17
+ * @returns True if the export matches the expected shape, false otherwise.
18
+ */
19
+ function validateFunctionExport(snapExport) {
20
+ return typeof snapExport === 'function';
21
+ }
22
+ /**
23
+ * Validates a keyring export.
24
+ *
25
+ * @param snapExport - The export itself.
26
+ * @returns True if the export matches the expected shape, false otherwise.
27
+ */
28
+ function validateKeyringExport(snapExport) {
29
+ // TODO Decide whether we want more validation
30
+ return typeof snapExport === 'object';
31
+ }
32
+ /**
33
+ * Validates a given snap export.
34
+ *
35
+ * @param type - The type of export expected.
36
+ * @param snapExport - The export itself.
37
+ * @returns True if the export matches the expected shape, false otherwise.
38
+ */
39
+ function validateExport(type, snapExport) {
40
+ var _a;
41
+ const validationFunction = VALIDATION_FUNCTIONS[type];
42
+ return (_a = validationFunction === null || validationFunction === void 0 ? void 0 : validationFunction(snapExport)) !== null && _a !== void 0 ? _a : false;
43
+ }
44
+ exports.validateExport = validateExport;
45
+ exports.JsonRpcRequestWithoutIdStruct = (0, superstruct_1.assign)((0, superstruct_1.omit)(utils_1.JsonRpcRequestStruct, ['id']), (0, superstruct_1.object)({
46
+ id: (0, superstruct_1.optional)(utils_1.JsonRpcIdStruct),
47
+ }));
48
+ exports.EndowmentStruct = (0, superstruct_1.string)();
49
+ /**
50
+ * Check if the given value is an endowment.
51
+ *
52
+ * @param value - The value to check.
53
+ * @returns Whether the value is an endowment.
54
+ */
55
+ function isEndowment(value) {
56
+ return (0, superstruct_1.is)(value, exports.EndowmentStruct);
57
+ }
58
+ exports.isEndowment = isEndowment;
59
+ /**
60
+ * Check if the given value is an array of endowments.
61
+ *
62
+ * @param value - The value to check.
63
+ * @returns Whether the value is an array of endowments.
64
+ */
65
+ function isEndowmentsArray(value) {
66
+ return Array.isArray(value) && value.every(isEndowment);
67
+ }
68
+ exports.isEndowmentsArray = isEndowmentsArray;
69
+ const OkStruct = (0, superstruct_1.literal)('OK');
70
+ exports.PingRequestArgumentsStruct = (0, superstruct_1.optional)((0, superstruct_1.union)([(0, superstruct_1.literal)(undefined), (0, superstruct_1.array)()]));
71
+ exports.TerminateRequestArgumentsStruct = (0, superstruct_1.union)([
72
+ (0, superstruct_1.literal)(undefined),
73
+ (0, superstruct_1.array)(),
74
+ ]);
75
+ exports.ExecuteSnapRequestArgumentsStruct = (0, superstruct_1.tuple)([
76
+ (0, superstruct_1.string)(),
77
+ (0, superstruct_1.string)(),
78
+ (0, superstruct_1.optional)((0, superstruct_1.array)(exports.EndowmentStruct)),
79
+ ]);
80
+ exports.SnapRpcRequestArgumentsStruct = (0, superstruct_1.tuple)([
81
+ (0, superstruct_1.string)(),
82
+ (0, superstruct_1.enums)(Object.values(snaps_utils_1.HandlerType)),
83
+ (0, superstruct_1.string)(),
84
+ (0, superstruct_1.assign)(exports.JsonRpcRequestWithoutIdStruct, (0, superstruct_1.object)({
85
+ params: (0, superstruct_1.optional)((0, superstruct_1.record)((0, superstruct_1.string)(), utils_1.JsonStruct)),
86
+ })),
87
+ ]);
88
+ exports.OnTransactionRequestArgumentsStruct = (0, superstruct_1.object)({
89
+ // TODO: Improve `transaction` type.
90
+ transaction: (0, superstruct_1.record)((0, superstruct_1.string)(), utils_1.JsonStruct),
91
+ chainId: snaps_utils_1.ChainIdStruct,
92
+ transactionOrigin: (0, superstruct_1.nullable)((0, superstruct_1.string)()),
93
+ });
94
+ /**
95
+ * Asserts that the given value is a valid {@link OnTransactionRequestArguments}
96
+ * object.
97
+ *
98
+ * @param value - The value to validate.
99
+ * @throws If the value is not a valid {@link OnTransactionRequestArguments}
100
+ * object.
101
+ */
102
+ function assertIsOnTransactionRequestArguments(value) {
103
+ (0, utils_1.assertStruct)(value, exports.OnTransactionRequestArgumentsStruct, 'Invalid request params');
104
+ }
105
+ exports.assertIsOnTransactionRequestArguments = assertIsOnTransactionRequestArguments;
106
+ const OkResponseStruct = (0, superstruct_1.assign)(utils_1.JsonRpcSuccessStruct, (0, superstruct_1.object)({
107
+ result: OkStruct,
108
+ }));
109
+ const SnapRpcResponse = utils_1.JsonRpcSuccessStruct;
110
+ //# sourceMappingURL=validation.js.map