@metamask-previews/eth-json-rpc-middleware 25.0.0-preview-3680ba557 → 25.0.0-preview-e4c191e3a

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.
package/CHANGELOG.md CHANGED
@@ -9,8 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Changed
11
11
 
12
- - **BREAKING:** `createWalletMiddleware` now requires a `getNetworkClientById` hook ([#10912](https://github.com/MetaMask/core/pull/10912))
13
- - **BREAKING:** The `getAccounts` hook of `createWalletMiddleware` now receives the CAIP-2 scope of the request as an optional second argument ([#10912](https://github.com/MetaMask/core/pull/10912))
14
12
  - Bump `@metamask/utils` from `^11.12.0` to `^12.0.0` ([#10192](https://github.com/MetaMask/core/pull/10192))
15
13
  - Bump `safe-stable-stringify` from `^2.4.3` to `^2.5.0` ([#10442](https://github.com/MetaMask/core/pull/10442))
16
14
  - Bump `@metamask/rpc-errors` from `^7.0.2` to `^7.0.3` ([#10718](https://github.com/MetaMask/core/pull/10718))
@@ -1,27 +1,19 @@
1
1
  import type { Struct } from '@metamask/superstruct';
2
2
  import type { Hex } from '@metamask/utils';
3
3
  import type { WalletMiddlewareContext } from '../wallet.js';
4
- type GetNetworkClientById = (id: string) => {
5
- configuration: {
6
- chainId: Hex;
7
- };
8
- };
9
4
  /**
10
5
  * Validates and normalizes a keyholder address for transaction- and
11
6
  * signature-related operations.
12
7
  *
13
8
  * @param address - The Ethereum address to validate and normalize.
14
- * @param chainId - An explicit chain ID for the request, if any.
15
9
  * @param context - The context of the request.
16
10
  * @param options - The options for the validation.
17
- * @param options.getAccounts - The function to get the accounts for the origin and scope.
18
- * @param options.getNetworkClientById - The function to get a network client by ID.
11
+ * @param options.getAccounts - The function to get the accounts for the origin.
19
12
  * @returns The normalized address, if valid. Otherwise, throws
20
13
  * an error
21
14
  */
22
- export declare function validateAndNormalizeKeyholder(address: Hex, chainId: string | number | undefined, context: WalletMiddlewareContext, { getAccounts, getNetworkClientById, }: {
23
- getAccounts: (origin: string, scope: string) => Promise<string[]>;
24
- getNetworkClientById: GetNetworkClientById;
15
+ export declare function validateAndNormalizeKeyholder(address: Hex, context: WalletMiddlewareContext, { getAccounts }: {
16
+ getAccounts: (origin: string) => Promise<string[]>;
25
17
  }): Promise<Hex>;
26
18
  /**
27
19
  * Validates the parameters of a request against a Superstruct schema.
@@ -161,5 +153,4 @@ export declare const MAX_TRANSACTION_PARAMS_SIZE_BYTES: number;
161
153
  * (wrong type, extraneous top-level key, or malformed nested field).
162
154
  */
163
155
  export declare function validateTransactionParams(params: unknown): void;
164
- export {};
165
156
  //# sourceMappingURL=validation.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAe,MAAM,uBAAuB,CAAC;AAWjE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAG3C,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAG5D,KAAK,oBAAoB,GAAG,CAAC,EAAE,EAAE,MAAM,KAAK;IAC1C,aAAa,EAAE;QAAE,OAAO,EAAE,GAAG,CAAA;KAAE,CAAC;CACjC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAsB,6BAA6B,CACjD,OAAO,EAAE,GAAG,EACZ,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,EACpC,OAAO,EAAE,uBAAuB,EAChC,EACE,WAAW,EACX,oBAAoB,GACrB,EAAE;IACD,WAAW,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAClE,oBAAoB,EAAE,oBAAoB,CAAC;CAC5C,GACA,OAAO,CAAC,GAAG,CAAC,CA2Bd;AAiCD;;;;;;;GAOG;AACH,wBA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  import { array, nullable, number, object, optional, string, union, validate, } from '@metamask/superstruct';
4
- import { hexToBigInt } from '@metamask/utils';
5
4
  import { parseTypedMessage } from './normalize.js';
6
5
  /**
7
6
  * Validates and normalizes a keyholder address for transaction- and
8
7
  * signature-related operations.
9
8
  *
10
9
  * @param address - The Ethereum address to validate and normalize.
11
- * @param chainId - An explicit chain ID for the request, if any.
12
10
  * @param context - The context of the request.
13
11
  * @param options - The options for the validation.
14
- * @param options.getAccounts - The function to get the accounts for the origin and scope.
15
- * @param options.getNetworkClientById - The function to get a network client by ID.
12
+ * @param options.getAccounts - The function to get the accounts for the origin.
16
13
  * @returns The normalized address, if valid. Otherwise, throws
17
14
  * an error
18
15
  */
19
- export async function validateAndNormalizeKeyholder(address, chainId, context, { getAccounts, getNetworkClientById, }) {
16
+ export async function validateAndNormalizeKeyholder(address, context, { getAccounts }) {
20
17
  if (typeof address === 'string' &&
21
18
  address.length > 0 &&
22
19
  resemblesAddress(address)) {
23
- const scope = getRequestScope(chainId, context, getNetworkClientById);
24
20
  // Ensure that an "unauthorized" error is thrown if the requester
25
21
  // does not have the `eth_accounts` permission.
26
- const accounts = await getAccounts(context.assertGet('origin'), scope);
22
+ const accounts = await getAccounts(context.assertGet('origin'));
27
23
  const normalizedAccounts = accounts.map((_address) => _address.toLowerCase());
28
24
  const normalizedAddress = address.toLowerCase();
29
25
  if (normalizedAccounts.includes(normalizedAddress)) {
@@ -35,28 +31,6 @@ export async function validateAndNormalizeKeyholder(address, chainId, context, {
35
31
  message: `Invalid parameters: must provide an Ethereum address.`,
36
32
  });
37
33
  }
38
- /**
39
- * Determines the CAIP-2 scope for a JSON-RPC request. Uses, in order
40
- * of precedence: the given chain ID, the `scope` in the request context, and
41
- * the chain ID of the request's network client.
42
- *
43
- * @param chainId - An explicit chain ID, if the request specifies one.
44
- * @param context - The context of the request.
45
- * @param getNetworkClientById - Hook to look up a network client by ID.
46
- * @returns The CAIP-2 scope of the request.
47
- */
48
- function getRequestScope(chainId, context, getNetworkClientById) {
49
- // This assumes all variants of chain ID can be parsed by the BigInt constructor
50
- if (chainId) {
51
- return `eip155:${BigInt(chainId).toString(10)}`;
52
- }
53
- const contextScope = context.get('scope');
54
- if (contextScope) {
55
- return contextScope;
56
- }
57
- const networkClient = getNetworkClientById(context.assertGet('networkClientId'));
58
- return `eip155:${hexToBigInt(networkClient.configuration.chainId).toString(10)}`;
59
- }
60
34
  /**
61
35
  * Validates the parameters of a request against a Superstruct schema.
62
36
  * Throws a JSON-RPC error if the parameters are invalid.
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjE,OAAO,EACL,KAAK,EACL,QAAQ,EACR,MAAM,EACN,MAAM,EACN,QAAQ,EACR,MAAM,EACN,KAAK,EACL,QAAQ,GACT,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAMnD;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAY,EACZ,OAAoC,EACpC,OAAgC,EAChC,EACE,WAAW,EACX,oBAAoB,GAIrB;IAED,IACE,OAAO,OAAO,KAAK,QAAQ;QAC3B,OAAO,CAAC,MAAM,GAAG,CAAC;QAClB,gBAAgB,CAAC,OAAO,CAAC,EACzB,CAAC;QACD,MAAM,KAAK,GAAG,eAAe,CAAC,OAAO,EAAE,OAAO,EAAE,oBAAoB,CAAC,CAAC;QACtE,iEAAiE;QACjE,+CAA+C;QAC/C,MAAM,QAAQ,GAAG,MAAM,WAAW,CAAC,OAAO,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,KAAK,CAAC,CAAC;QA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C1E,wFAAwF;AACxF,6EAA6E;AAC7E,2EAA2E;AAC3E,kEAAkE;AAClE,MAAM,CAAC,MAAM,iCAAiC,GAAG,GAAG,GAAG,IAAI,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,yBAAyB,CAAC,MAAe;IACvD,IACE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,UAAU;QAC3D,iCAAiC,EACjC,CAAC;QACD,MAAM,SAAS,CAAC,aAAa,CAAC,mBAAmB,CAAC,CAAC;IACrD,CAAC;IAED,cAAc,CAAC,MAAM,EAAE,uBAAuB,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { TYPED_MESSAGE_SCHEMA } from '@metamask/eth-sig-util';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { Struct, StructError } from '@metamask/superstruct';\nimport {\n array,\n nullable,\n number,\n object,\n optional,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\nimport type { Hex } from '@metamask/utils';\nimport { hexToBigInt } from '@metamask/utils';\n\nimport type { WalletMiddlewareContext } from '../wallet.js';\nimport { parseTypedMessage } from './normalize.js';\n\ntype GetNetworkClientById = (id: string) => {\n configuration: { chainId: Hex };\n};\n\n/**\n * Validates and normalizes a keyholder address for transaction- and\n * signature-related operations.\n *\n * @param address - The Ethereum address to validate and normalize.\n * @param chainId - An explicit chain ID for the request, if any.\n * @param context - The context of the request.\n * @param options - The options for the validation.\n * @param options.getAccounts - The function to get the accounts for the origin and scope.\n * @param options.getNetworkClientById - The function to get a network client by ID.\n * @returns The normalized address, if valid. Otherwise, throws\n * an error\n */\nexport async function validateAndNormalizeKeyholder(\n address: Hex,\n chainId: string | number | undefined,\n context: WalletMiddlewareContext,\n {\n getAccounts,\n getNetworkClientById,\n }: {\n getAccounts: (origin: string, scope: string) => Promise<string[]>;\n getNetworkClientById: GetNetworkClientById;\n },\n): Promise<Hex> {\n if (\n typeof address === 'string' &&\n address.length > 0 &&\n resemblesAddress(address)\n ) {\n const scope = getRequestScope(chainId, context, getNetworkClientById);\n // Ensure that an \"unauthorized\" error is thrown if the requester\n // does not have the `eth_accounts` permission.\n const accounts = await getAccounts(context.assertGet('origin'), scope);\n\n const normalizedAccounts: string[] = accounts.map((_address) =>\n _address.toLowerCase(),\n );\n\n const normalizedAddress = address.toLowerCase() as Hex;\n\n if (normalizedAccounts.includes(normalizedAddress)) {\n return normalizedAddress;\n }\n\n throw providerErrors.unauthorized();\n }\n\n throw rpcErrors.invalidParams({\n message: `Invalid parameters: must provide an Ethereum address.`,\n });\n}\n\n/**\n * Determines the CAIP-2 scope for a JSON-RPC request. Uses, in order\n * of precedence: the given chain ID, the `scope` in the request context, and\n * the chain ID of the request's network client.\n *\n * @param chainId - An explicit chain ID, if the request specifies one.\n * @param context - The context of the request.\n * @param getNetworkClientById - Hook to look up a network client by ID.\n * @returns The CAIP-2 scope of the request.\n */\nfunction getRequestScope(\n chainId: string | number | undefined,\n context: WalletMiddlewareContext,\n getNetworkClientById: GetNetworkClientById,\n): string {\n // This assumes all variants of chain ID can be parsed by the BigInt constructor\n if (chainId) {\n return `eip155:${BigInt(chainId).toString(10)}`;\n }\n\n const contextScope = context.get('scope');\n if (contextScope) {\n return contextScope;\n }\n\n const networkClient = getNetworkClientById(\n context.assertGet('networkClientId'),\n );\n return `eip155:${hexToBigInt(networkClient.configuration.chainId).toString(10)}`;\n}\n\n/**\n * Validates the parameters of a request against a Superstruct schema.\n * Throws a JSON-RPC error if the parameters are invalid.\n *\n * @param value - The value to validate.\n * @param struct - The Superstruct schema to validate against.\n * @throws An error if the parameters are invalid.\n */\nexport function validateParams<ParamsType>(\n value: unknown | ParamsType,\n struct: Struct<ParamsType>,\n): asserts value is ParamsType {\n const [error] = validate(value, struct);\n\n if (error) {\n throw rpcErrors.invalidParams(\n formatValidationError(error, `Invalid params`),\n );\n }\n}\n\n/**\n * Checks if a string resembles an Ethereum address.\n *\n * @param str - The string to check.\n * @returns True if the string resembles an Ethereum address, false otherwise.\n */\nexport function resemblesAddress(str: string): boolean {\n // hex prefix 2 + 20 bytes\n return str.length === 2 + 20 * 2;\n}\n\n/**\n * Formats a Superstruct validation error into a human-readable string.\n *\n * @param error - The Superstruct validation error.\n * @param message - The base error message to prepend to the formatted details.\n * @returns The formatted error.\n */\nfunction formatValidationError(error: StructError, message: string): string {\n return `${message}\\n\\n${error\n .failures()\n .map(\n (failure) =>\n `${failure.path.join(' > ')}${failure.path.length ? ' - ' : ''}${failure.message}`,\n )\n .join('\\n')}`;\n}\n\nexport const DANGEROUS_PROTOTYPE_PROPERTIES = [\n '__proto__',\n 'constructor',\n 'prototype',\n '__defineGetter__',\n '__defineSetter__',\n '__lookupGetter__',\n '__lookupSetter__',\n] as const;\n\n/**\n * Checks if a property name is dangerous for prototype pollution.\n *\n * @param key - The property name to check\n * @returns True if the property name is dangerous\n */\nfunction isDangerousProperty(key: string): boolean {\n return (DANGEROUS_PROTOTYPE_PROPERTIES as readonly string[]).includes(key);\n}\n\n/**\n * Recursively checks an object for dangerous prototype pollution properties.\n *\n * @param obj - The object to check\n * @throws rpcErrors.invalidInput() if a dangerous property is found\n */\nfunction checkObjectForPrototypePollution(obj: unknown): void {\n if (obj === null || obj === undefined) {\n return;\n }\n\n if (Array.isArray(obj)) {\n for (const item of obj) {\n checkObjectForPrototypePollution(item);\n }\n return;\n }\n\n if (typeof obj === 'object') {\n for (const key of Object.getOwnPropertyNames(obj)) {\n if (isDangerousProperty(key)) {\n throw rpcErrors.invalidInput();\n }\n checkObjectForPrototypePollution((obj as Record<string, unknown>)[key]);\n }\n }\n}\n\n/**\n * Validates V1 typed data (array format) for prototype pollution attacks.\n * V1 format: [{ type: 'string', name: 'fieldName', value: 'data' }, ...]\n *\n * @param data - The V1 typed data array to validate\n * @throws rpcErrors.invalidInput() if prototype pollution is detected\n */\nexport function validateTypedDataV1ForPrototypePollution(\n data: Record<string, unknown>[],\n): void {\n if (!data || !Array.isArray(data)) {\n return;\n }\n\n for (const item of data) {\n if (item && typeof item === 'object') {\n // Only check the 'value' field (the message data) for dangerous properties\n if (item.value !== null && typeof item.value === 'object') {\n checkObjectForPrototypePollution(item.value);\n }\n }\n }\n}\n\n/**\n * Validates V3/V4 typed data (EIP-712 format) for prototype pollution attacks.\n * Only checks the message field for dangerous properties.\n *\n * @param data - The stringified typed data to validate\n * @throws rpcErrors.invalidInput() if prototype pollution is detected\n */\nexport function validateTypedDataForPrototypePollution(data: string): void {\n const { message } = parseTypedMessage(data);\n\n // Check message recursively for dangerous properties\n if (message !== undefined) {\n checkObjectForPrototypePollution(message);\n }\n}\n\n/**\n * Validates that EIP-712 typed message data contains only keys defined in\n * the TYPED_MESSAGE_SCHEMA from `@metamask/eth-sig-util`. Rejects messages\n * with extraneous top-level keys.\n *\n * @param data - The stringified typed data to validate.\n * @throws rpcErrors.invalidInput() if extraneous keys are detected.\n */\nexport function validateTypedMessageKeys(data: string): void {\n const parsedData = parseTypedMessage(data);\n const allowedKeys = new Set([\n ...Object.keys(TYPED_MESSAGE_SCHEMA.properties),\n 'metadata',\n ]);\n const hasExtraneousKey = Object.keys(parsedData).some(\n (key) => !allowedKeys.has(key),\n );\n\n if (hasExtraneousKey) {\n throw rpcErrors.invalidInput();\n }\n\n // Advanced Permissions adds `metadata: { justification: string, origin: string }` to eth_signTypedData requests.\n // see GatorPermissionsController.decodePermissionFromPermissionContextForOrigin for more details.\n const { metadata } = parsedData as { metadata?: unknown };\n if (metadata !== undefined) {\n if (typeof metadata !== 'object' || metadata === null) {\n throw rpcErrors.invalidInput();\n }\n\n const { justification, origin } = metadata as {\n justification?: unknown;\n origin?: unknown;\n };\n\n if (typeof justification !== 'string' || typeof origin !== 'string') {\n throw rpcErrors.invalidInput();\n }\n\n // we only need to check the keys length, because we already checked the known keys (justification and origin).\n if (Object.keys(metadata).length !== 2) {\n throw rpcErrors.invalidInput();\n }\n }\n}\n\n// Numerical fields accept both hex strings and numbers, as some dapps send\n// numbers and `TransactionController` normalizes them downstream.\nconst QuantityStruct = union([string(), number()]);\n\nexport const TransactionParamsStruct = object({\n accessList: optional(\n nullable(\n array(object({ address: string(), storageKeys: array(string()) })),\n ),\n ),\n authorizationList: optional(\n nullable(\n array(\n object({\n address: string(),\n chainId: optional(nullable(QuantityStruct)),\n nonce: optional(nullable(QuantityStruct)),\n r: optional(nullable(string())),\n s: optional(nullable(string())),\n yParity: optional(nullable(QuantityStruct)),\n }),\n ),\n ),\n ),\n chainId: optional(nullable(QuantityStruct)),\n data: optional(nullable(string())),\n from: string(),\n gas: optional(nullable(QuantityStruct)),\n gasLimit: optional(nullable(QuantityStruct)),\n gasPrice: optional(nullable(QuantityStruct)),\n maxFeePerGas: optional(nullable(QuantityStruct)),\n maxPriorityFeePerGas: optional(nullable(QuantityStruct)),\n nonce: optional(nullable(QuantityStruct)),\n to: optional(nullable(string())),\n type: optional(nullable(string())),\n value: optional(nullable(QuantityStruct)),\n});\n\n// Upper bound derived from the largest valid eth_sendTransaction payload:\n// EIP-3860 caps initcode at 49,152 bytes → hex-encoded in 'data' field ≈ 98 KB of JSON.\n// 200 KB is ~2× that ceiling, giving clear headroom above any protocol-legal\n// transaction while blocking the padding attacks this cap defends against.\n// TODO(CONF-1662): tighten once P99 production data is available.\nexport const MAX_TRANSACTION_PARAMS_SIZE_BYTES = 200 * 1024;\n\n/**\n * Validates `eth_sendTransaction` / `eth_signTransaction` params against the\n * standard transaction schema and rejects payloads whose serialized size\n * exceeds `MAX_TRANSACTION_PARAMS_SIZE_BYTES`.\n *\n * Guards against two attack shapes:\n * - Size: valid-shaped but oversized payloads (e.g. `data` padded with\n * millions of hex zeros) that exhaust memory in downstream code. Checked\n * first via `JSON.stringify` so oversized input is rejected before schema\n * work.\n * - Structural: extraneous top-level keys or ill-typed fields (e.g.\n * `{ from, to, test: { b: { b: ... × 1200 } } }`) that would crash\n * downstream normalization / PPOM WASM with `RangeError: Maximum call\n * stack size exceeded`, silently bypassing security checks. Superstruct's\n * `object()` rejects unknown keys by name without accessing their values,\n * so hostile nested subtrees are never traversed by schema validation.\n *\n * @param params - The transaction params object supplied by the dapp.\n * @throws rpcErrors.invalidParams() if params is an array or exceeds the\n * serialized size limit.\n * @throws rpcErrors.invalidInput() if params fails schema validation\n * (wrong type, extraneous top-level key, or malformed nested field).\n */\nexport function validateTransactionParams(params: unknown): void {\n if (\n new TextEncoder().encode(JSON.stringify(params)).byteLength >\n MAX_TRANSACTION_PARAMS_SIZE_BYTES\n ) {\n throw rpcErrors.invalidParams('Request too large');\n }\n\n validateParams(params, TransactionParamsStruct);\n}\n"]}
1
+ {"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjE,OAAO,EACL,KAAK,EACL,QAAQ,EACR,MAAM,EACN,MAAM,EACN,QAAQ,EACR,MAAM,EACN,KAAK,EACL,QAAQ,GACT,MAAM,uBAAuB,CAAC;AAI/B,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAEnD;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAY,EACZ,OAAgC,EAChC,EAAE,WAAW,EAA0D;IAEvE,IACE,OAAO,OAAO,KAAK,QAAQ;QAC3B,OAAO,CAAC,MAAM,GAAG,CAAC;QAClB,gBAAgB,CAAC,OAAO,CAAC,EACzB,CAAC;QACD,iEAAiE;QACjE,+CAA+C;QAC/C,MAAM,QAAQ,GAAG,MAAM,WAAW,CAAC,OAAO,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC;QAEhE,MAAM,kBAAkB,GAAa,QAAQ,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAC7D,QAAQ,CAAC,WAAW,EAAE,CACvB,CAA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vC,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;IAC5C,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;IAC5C,YAAY,EAAE,QAAQ,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;IAChD,oBAAoB,EAAE,QAAQ,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;IACxD,KAAK,EAAE,QAAQ,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;IACzC,EAAE,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IAChC,IAAI,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IAClC,KAAK,EAAE,QAAQ,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;CAC1C,CAAC,CAAC;AAEH,0EAA0E;AAC1E,wFAAwF;AACxF,6EAA6E;AAC7E,2EAA2E;AAC3E,kEAAkE;AAClE,MAAM,CAAC,MAAM,iCAAiC,GAAG,GAAG,GAAG,IAAI,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,yBAAyB,CAAC,MAAe;IACvD,IACE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,UAAU;QAC3D,iCAAiC,EACjC,CAAC;QACD,MAAM,SAAS,CAAC,aAAa,CAAC,mBAAmB,CAAC,CAAC;IACrD,CAAC;IAED,cAAc,CAAC,MAAM,EAAE,uBAAuB,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { TYPED_MESSAGE_SCHEMA } from '@metamask/eth-sig-util';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { Struct, StructError } from '@metamask/superstruct';\nimport {\n array,\n nullable,\n number,\n object,\n optional,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\nimport type { Hex } from '@metamask/utils';\n\nimport type { WalletMiddlewareContext } from '../wallet.js';\nimport { parseTypedMessage } from './normalize.js';\n\n/**\n * Validates and normalizes a keyholder address for transaction- and\n * signature-related operations.\n *\n * @param address - The Ethereum address to validate and normalize.\n * @param context - The context of the request.\n * @param options - The options for the validation.\n * @param options.getAccounts - The function to get the accounts for the origin.\n * @returns The normalized address, if valid. Otherwise, throws\n * an error\n */\nexport async function validateAndNormalizeKeyholder(\n address: Hex,\n context: WalletMiddlewareContext,\n { getAccounts }: { getAccounts: (origin: string) => Promise<string[]> },\n): Promise<Hex> {\n if (\n typeof address === 'string' &&\n address.length > 0 &&\n resemblesAddress(address)\n ) {\n // Ensure that an \"unauthorized\" error is thrown if the requester\n // does not have the `eth_accounts` permission.\n const accounts = await getAccounts(context.assertGet('origin'));\n\n const normalizedAccounts: string[] = accounts.map((_address) =>\n _address.toLowerCase(),\n );\n\n const normalizedAddress = address.toLowerCase() as Hex;\n\n if (normalizedAccounts.includes(normalizedAddress)) {\n return normalizedAddress;\n }\n\n throw providerErrors.unauthorized();\n }\n\n throw rpcErrors.invalidParams({\n message: `Invalid parameters: must provide an Ethereum address.`,\n });\n}\n\n/**\n * Validates the parameters of a request against a Superstruct schema.\n * Throws a JSON-RPC error if the parameters are invalid.\n *\n * @param value - The value to validate.\n * @param struct - The Superstruct schema to validate against.\n * @throws An error if the parameters are invalid.\n */\nexport function validateParams<ParamsType>(\n value: unknown | ParamsType,\n struct: Struct<ParamsType>,\n): asserts value is ParamsType {\n const [error] = validate(value, struct);\n\n if (error) {\n throw rpcErrors.invalidParams(\n formatValidationError(error, `Invalid params`),\n );\n }\n}\n\n/**\n * Checks if a string resembles an Ethereum address.\n *\n * @param str - The string to check.\n * @returns True if the string resembles an Ethereum address, false otherwise.\n */\nexport function resemblesAddress(str: string): boolean {\n // hex prefix 2 + 20 bytes\n return str.length === 2 + 20 * 2;\n}\n\n/**\n * Formats a Superstruct validation error into a human-readable string.\n *\n * @param error - The Superstruct validation error.\n * @param message - The base error message to prepend to the formatted details.\n * @returns The formatted error.\n */\nfunction formatValidationError(error: StructError, message: string): string {\n return `${message}\\n\\n${error\n .failures()\n .map(\n (failure) =>\n `${failure.path.join(' > ')}${failure.path.length ? ' - ' : ''}${failure.message}`,\n )\n .join('\\n')}`;\n}\n\nexport const DANGEROUS_PROTOTYPE_PROPERTIES = [\n '__proto__',\n 'constructor',\n 'prototype',\n '__defineGetter__',\n '__defineSetter__',\n '__lookupGetter__',\n '__lookupSetter__',\n] as const;\n\n/**\n * Checks if a property name is dangerous for prototype pollution.\n *\n * @param key - The property name to check\n * @returns True if the property name is dangerous\n */\nfunction isDangerousProperty(key: string): boolean {\n return (DANGEROUS_PROTOTYPE_PROPERTIES as readonly string[]).includes(key);\n}\n\n/**\n * Recursively checks an object for dangerous prototype pollution properties.\n *\n * @param obj - The object to check\n * @throws rpcErrors.invalidInput() if a dangerous property is found\n */\nfunction checkObjectForPrototypePollution(obj: unknown): void {\n if (obj === null || obj === undefined) {\n return;\n }\n\n if (Array.isArray(obj)) {\n for (const item of obj) {\n checkObjectForPrototypePollution(item);\n }\n return;\n }\n\n if (typeof obj === 'object') {\n for (const key of Object.getOwnPropertyNames(obj)) {\n if (isDangerousProperty(key)) {\n throw rpcErrors.invalidInput();\n }\n checkObjectForPrototypePollution((obj as Record<string, unknown>)[key]);\n }\n }\n}\n\n/**\n * Validates V1 typed data (array format) for prototype pollution attacks.\n * V1 format: [{ type: 'string', name: 'fieldName', value: 'data' }, ...]\n *\n * @param data - The V1 typed data array to validate\n * @throws rpcErrors.invalidInput() if prototype pollution is detected\n */\nexport function validateTypedDataV1ForPrototypePollution(\n data: Record<string, unknown>[],\n): void {\n if (!data || !Array.isArray(data)) {\n return;\n }\n\n for (const item of data) {\n if (item && typeof item === 'object') {\n // Only check the 'value' field (the message data) for dangerous properties\n if (item.value !== null && typeof item.value === 'object') {\n checkObjectForPrototypePollution(item.value);\n }\n }\n }\n}\n\n/**\n * Validates V3/V4 typed data (EIP-712 format) for prototype pollution attacks.\n * Only checks the message field for dangerous properties.\n *\n * @param data - The stringified typed data to validate\n * @throws rpcErrors.invalidInput() if prototype pollution is detected\n */\nexport function validateTypedDataForPrototypePollution(data: string): void {\n const { message } = parseTypedMessage(data);\n\n // Check message recursively for dangerous properties\n if (message !== undefined) {\n checkObjectForPrototypePollution(message);\n }\n}\n\n/**\n * Validates that EIP-712 typed message data contains only keys defined in\n * the TYPED_MESSAGE_SCHEMA from `@metamask/eth-sig-util`. Rejects messages\n * with extraneous top-level keys.\n *\n * @param data - The stringified typed data to validate.\n * @throws rpcErrors.invalidInput() if extraneous keys are detected.\n */\nexport function validateTypedMessageKeys(data: string): void {\n const parsedData = parseTypedMessage(data);\n const allowedKeys = new Set([\n ...Object.keys(TYPED_MESSAGE_SCHEMA.properties),\n 'metadata',\n ]);\n const hasExtraneousKey = Object.keys(parsedData).some(\n (key) => !allowedKeys.has(key),\n );\n\n if (hasExtraneousKey) {\n throw rpcErrors.invalidInput();\n }\n\n // Advanced Permissions adds `metadata: { justification: string, origin: string }` to eth_signTypedData requests.\n // see GatorPermissionsController.decodePermissionFromPermissionContextForOrigin for more details.\n const { metadata } = parsedData as { metadata?: unknown };\n if (metadata !== undefined) {\n if (typeof metadata !== 'object' || metadata === null) {\n throw rpcErrors.invalidInput();\n }\n\n const { justification, origin } = metadata as {\n justification?: unknown;\n origin?: unknown;\n };\n\n if (typeof justification !== 'string' || typeof origin !== 'string') {\n throw rpcErrors.invalidInput();\n }\n\n // we only need to check the keys length, because we already checked the known keys (justification and origin).\n if (Object.keys(metadata).length !== 2) {\n throw rpcErrors.invalidInput();\n }\n }\n}\n\n// Numerical fields accept both hex strings and numbers, as some dapps send\n// numbers and `TransactionController` normalizes them downstream.\nconst QuantityStruct = union([string(), number()]);\n\nexport const TransactionParamsStruct = object({\n accessList: optional(\n nullable(\n array(object({ address: string(), storageKeys: array(string()) })),\n ),\n ),\n authorizationList: optional(\n nullable(\n array(\n object({\n address: string(),\n chainId: optional(nullable(QuantityStruct)),\n nonce: optional(nullable(QuantityStruct)),\n r: optional(nullable(string())),\n s: optional(nullable(string())),\n yParity: optional(nullable(QuantityStruct)),\n }),\n ),\n ),\n ),\n chainId: optional(nullable(QuantityStruct)),\n data: optional(nullable(string())),\n from: string(),\n gas: optional(nullable(QuantityStruct)),\n gasLimit: optional(nullable(QuantityStruct)),\n gasPrice: optional(nullable(QuantityStruct)),\n maxFeePerGas: optional(nullable(QuantityStruct)),\n maxPriorityFeePerGas: optional(nullable(QuantityStruct)),\n nonce: optional(nullable(QuantityStruct)),\n to: optional(nullable(string())),\n type: optional(nullable(string())),\n value: optional(nullable(QuantityStruct)),\n});\n\n// Upper bound derived from the largest valid eth_sendTransaction payload:\n// EIP-3860 caps initcode at 49,152 bytes → hex-encoded in 'data' field ≈ 98 KB of JSON.\n// 200 KB is ~2× that ceiling, giving clear headroom above any protocol-legal\n// transaction while blocking the padding attacks this cap defends against.\n// TODO(CONF-1662): tighten once P99 production data is available.\nexport const MAX_TRANSACTION_PARAMS_SIZE_BYTES = 200 * 1024;\n\n/**\n * Validates `eth_sendTransaction` / `eth_signTransaction` params against the\n * standard transaction schema and rejects payloads whose serialized size\n * exceeds `MAX_TRANSACTION_PARAMS_SIZE_BYTES`.\n *\n * Guards against two attack shapes:\n * - Size: valid-shaped but oversized payloads (e.g. `data` padded with\n * millions of hex zeros) that exhaust memory in downstream code. Checked\n * first via `JSON.stringify` so oversized input is rejected before schema\n * work.\n * - Structural: extraneous top-level keys or ill-typed fields (e.g.\n * `{ from, to, test: { b: { b: ... × 1200 } } }`) that would crash\n * downstream normalization / PPOM WASM with `RangeError: Maximum call\n * stack size exceeded`, silently bypassing security checks. Superstruct's\n * `object()` rejects unknown keys by name without accessing their values,\n * so hostile nested subtrees are never traversed by schema validation.\n *\n * @param params - The transaction params object supplied by the dapp.\n * @throws rpcErrors.invalidParams() if params is an array or exceeds the\n * serialized size limit.\n * @throws rpcErrors.invalidInput() if params fails schema validation\n * (wrong type, extraneous top-level key, or malformed nested field).\n */\nexport function validateTransactionParams(params: unknown): void {\n if (\n new TextEncoder().encode(JSON.stringify(params)).byteLength >\n MAX_TRANSACTION_PARAMS_SIZE_BYTES\n ) {\n throw rpcErrors.invalidParams('Request too large');\n }\n\n validateParams(params, TransactionParamsStruct);\n}\n"]}
package/dist/wallet.d.ts CHANGED
@@ -1,13 +1,12 @@
1
1
  import type { JsonRpcMiddleware, MiddlewareContext, MiddlewareParams } from '@metamask/json-rpc-engine/v2';
2
2
  import type { MessageRequest } from '@metamask/message-manager';
3
- import type { JsonRpcRequest, Json, Hex } from '@metamask/utils';
3
+ import type { JsonRpcRequest, Json } from '@metamask/utils';
4
4
  import type { ProcessGetGrantedExecutionPermissionsHook } from './methods/wallet-get-granted-execution-permissions.js';
5
5
  import type { ProcessGetSupportedExecutionPermissionsHook } from './methods/wallet-get-supported-execution-permissions.js';
6
6
  import type { ProcessRequestExecutionPermissionsHook } from './methods/wallet-request-execution-permissions.js';
7
7
  import type { ProcessRevokeExecutionPermissionHook } from './methods/wallet-revoke-execution-permission.js';
8
8
  export type TransactionParams = {
9
9
  from: string;
10
- chainId?: string | number;
11
10
  };
12
11
  export type MessageParams = TransactionParams & {
13
12
  data: string;
@@ -20,12 +19,7 @@ export type TypedMessageV1Params = Omit<TypedMessageParams, 'data'> & {
20
19
  data: Record<string, unknown>[];
21
20
  };
22
21
  export type WalletMiddlewareOptions = {
23
- getAccounts: (origin: string, scope?: string) => Promise<string[]>;
24
- getNetworkClientById: (id: string) => {
25
- configuration: {
26
- chainId: Hex;
27
- };
28
- };
22
+ getAccounts: (origin: string) => Promise<string[]>;
29
23
  processDecryptMessage?: (msgParams: MessageParams, req: MessageRequest) => Promise<string>;
30
24
  processEncryptionPublicKey?: (address: string, req: MessageRequest) => Promise<string>;
31
25
  processPersonalMessage?: (msgParams: MessageParams, req: JsonRpcRequest, context: WalletMiddlewareContext) => Promise<string>;
@@ -42,7 +36,6 @@ export type WalletMiddlewareOptions = {
42
36
  export type WalletMiddlewareKeyValues = {
43
37
  networkClientId: string;
44
38
  origin: string;
45
- scope?: string;
46
39
  securityAlertResponse?: Record<string, Json>;
47
40
  traceContext?: unknown;
48
41
  };
@@ -54,8 +47,7 @@ export type WalletMiddlewareParams = MiddlewareParams<JsonRpcRequest, WalletMidd
54
47
  * but at this point it's just an arbitrary label.
55
48
  *
56
49
  * @param options - The options for the middleware.
57
- * @param options.getAccounts - The function to get the accounts for the origin and scope.
58
- * @param options.getNetworkClientById - The function to get a network client by ID, used to determine the scope of a request.
50
+ * @param options.getAccounts - The function to get the accounts for the origin.
59
51
  * @param options.processDecryptMessage - The function to process the decrypt message request.
60
52
  * @param options.processEncryptionPublicKey - The function to process the encryption public key request.
61
53
  * @param options.processPersonalMessage - The function to process the personal message request.
@@ -70,5 +62,5 @@ export type WalletMiddlewareParams = MiddlewareParams<JsonRpcRequest, WalletMidd
70
62
  * @param options.processGetSupportedExecutionPermissions - The function to process the get supported execution permissions request.
71
63
  * @returns A JSON-RPC middleware that handles wallet-related JSON-RPC methods.
72
64
  */
73
- export declare function createWalletMiddleware({ getAccounts, getNetworkClientById, processDecryptMessage, processEncryptionPublicKey, processPersonalMessage, processTransaction, processSignTransaction, processTypedMessage, processTypedMessageV3, processTypedMessageV4, processRequestExecutionPermissions, processRevokeExecutionPermission, processGetGrantedExecutionPermissions, processGetSupportedExecutionPermissions, }: WalletMiddlewareOptions): JsonRpcMiddleware<JsonRpcRequest, Json, WalletMiddlewareContext>;
65
+ export declare function createWalletMiddleware({ getAccounts, processDecryptMessage, processEncryptionPublicKey, processPersonalMessage, processTransaction, processSignTransaction, processTypedMessage, processTypedMessageV3, processTypedMessageV4, processRequestExecutionPermissions, processRevokeExecutionPermission, processGetGrantedExecutionPermissions, processGetSupportedExecutionPermissions, }: WalletMiddlewareOptions): JsonRpcMiddleware<JsonRpcRequest, Json, WalletMiddlewareContext>;
74
66
  //# sourceMappingURL=wallet.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"wallet.d.ts","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AAW,EACX,qBAAqB,EACrB,0BAA0B,EAC1B,sBAAsB,EACtB,kBAAkB,EAClB,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,kCAAkC,EAClC,gCAAgC,EAChC,qCAAqC,EACrC,uCAAuC,GACxC,EAAE,uBAAuB,GAAG,iBAAiB,CAC5C,cAAc,EACd,IAAI,EACJ,uBAAuB,CACxB,CAidA"}
package/dist/wallet.js CHANGED
@@ -15,8 +15,7 @@ import { resemblesAddress, validateAndNormalizeKeyholder as validateKeyholder, v
15
15
  * but at this point it's just an arbitrary label.
16
16
  *
17
17
  * @param options - The options for the middleware.
18
- * @param options.getAccounts - The function to get the accounts for the origin and scope.
19
- * @param options.getNetworkClientById - The function to get a network client by ID, used to determine the scope of a request.
18
+ * @param options.getAccounts - The function to get the accounts for the origin.
20
19
  * @param options.processDecryptMessage - The function to process the decrypt message request.
21
20
  * @param options.processEncryptionPublicKey - The function to process the encryption public key request.
22
21
  * @param options.processPersonalMessage - The function to process the personal message request.
@@ -31,7 +30,7 @@ import { resemblesAddress, validateAndNormalizeKeyholder as validateKeyholder, v
31
30
  * @param options.processGetSupportedExecutionPermissions - The function to process the get supported execution permissions request.
32
31
  * @returns A JSON-RPC middleware that handles wallet-related JSON-RPC methods.
33
32
  */
34
- export function createWalletMiddleware({ getAccounts, getNetworkClientById, processDecryptMessage, processEncryptionPublicKey, processPersonalMessage, processTransaction, processSignTransaction, processTypedMessage, processTypedMessageV3, processTypedMessageV4, processRequestExecutionPermissions, processRevokeExecutionPermission, processGetGrantedExecutionPermissions, processGetSupportedExecutionPermissions, }) {
33
+ export function createWalletMiddleware({ getAccounts, processDecryptMessage, processEncryptionPublicKey, processPersonalMessage, processTransaction, processSignTransaction, processTypedMessage, processTypedMessageV3, processTypedMessageV4, processRequestExecutionPermissions, processRevokeExecutionPermission, processGetGrantedExecutionPermissions, processGetSupportedExecutionPermissions, }) {
35
34
  if (!getAccounts) {
36
35
  throw new Error('opts.getAccounts is required');
37
36
  }
@@ -75,7 +74,7 @@ export function createWalletMiddleware({ getAccounts, getNetworkClientById, proc
75
74
  * @returns The accounts for the origin.
76
75
  */
77
76
  async function lookupAccounts({ context, }) {
78
- return await getAccounts(context.assertGet('origin'), context.get('scope'));
77
+ return await getAccounts(context.assertGet('origin'));
79
78
  }
80
79
  /**
81
80
  * Gets the default account (i.e. first in the list) for the origin.
@@ -85,7 +84,7 @@ export function createWalletMiddleware({ getAccounts, getNetworkClientById, proc
85
84
  * @returns The default account for the origin.
86
85
  */
87
86
  async function lookupDefaultAccount({ context, }) {
88
- const accounts = await getAccounts(context.assertGet('origin'), context.get('scope'));
87
+ const accounts = await getAccounts(context.assertGet('origin'));
89
88
  return accounts[0] || null;
90
89
  }
91
90
  //
@@ -112,10 +111,9 @@ export function createWalletMiddleware({ getAccounts, getNetworkClientById, proc
112
111
  validateTransactionParams(params);
113
112
  const txParams = {
114
113
  ...params,
115
- from: await validateAndNormalizeKeyholder(
116
114
  // Not using nullish coalescing, since `params` may be `null`.
117
115
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
118
- params?.from || '', params?.chainId, context),
116
+ from: await validateAndNormalizeKeyholder(params?.from || '', context),
119
117
  };
120
118
  return await processTransaction(txParams, request, context);
121
119
  }
@@ -140,10 +138,9 @@ export function createWalletMiddleware({ getAccounts, getNetworkClientById, proc
140
138
  validateTransactionParams(params);
141
139
  const txParams = {
142
140
  ...params,
143
- from: await validateAndNormalizeKeyholder(
144
141
  // Not using nullish coalescing, since `params` may be `null`.
145
142
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
146
- params?.from || '', params?.chainId, context),
143
+ from: await validateAndNormalizeKeyholder(params?.from || '', context),
147
144
  };
148
145
  return await processSignTransaction(txParams, request, context);
149
146
  }
@@ -169,7 +166,7 @@ export function createWalletMiddleware({ getAccounts, getNetworkClientById, proc
169
166
  }
170
167
  const params = request.params;
171
168
  const message = params[0];
172
- const address = await validateAndNormalizeKeyholder(params[1], undefined, context);
169
+ const address = await validateAndNormalizeKeyholder(params[1], context);
173
170
  const version = 'V1';
174
171
  validateTypedDataV1ForPrototypePollution(message);
175
172
  // Not using nullish coalescing, since `params` may be `null`.
@@ -202,7 +199,7 @@ export function createWalletMiddleware({ getAccounts, getNetworkClientById, proc
202
199
  throw rpcErrors.invalidInput();
203
200
  }
204
201
  const params = request.params;
205
- const address = await validateAndNormalizeKeyholder(params[0], undefined, context);
202
+ const address = await validateAndNormalizeKeyholder(params[0], context);
206
203
  const message = normalizeTypedMessage(params[1]);
207
204
  validatePrimaryType(message);
208
205
  validateVerifyingContract(message);
@@ -234,7 +231,7 @@ export function createWalletMiddleware({ getAccounts, getNetworkClientById, proc
234
231
  throw rpcErrors.invalidInput();
235
232
  }
236
233
  const params = request.params;
237
- const address = await validateAndNormalizeKeyholder(params[0], undefined, context);
234
+ const address = await validateAndNormalizeKeyholder(params[0], context);
238
235
  const message = normalizeTypedMessage(params[1]);
239
236
  validateTypedMessageKeys(message);
240
237
  validatePrimaryType(message);
@@ -290,7 +287,7 @@ export function createWalletMiddleware({ getAccounts, getNetworkClientById, proc
290
287
  message = firstParam;
291
288
  address = secondParam;
292
289
  }
293
- address = await validateAndNormalizeKeyholder(address, undefined, context);
290
+ address = await validateAndNormalizeKeyholder(address, context);
294
291
  const msgParams = {
295
292
  ...extraParams,
296
293
  from: address,
@@ -339,7 +336,7 @@ export function createWalletMiddleware({ getAccounts, getNetworkClientById, proc
339
336
  throw rpcErrors.invalidInput();
340
337
  }
341
338
  const params = request.params;
342
- const address = await validateAndNormalizeKeyholder(params[0], undefined, context);
339
+ const address = await validateAndNormalizeKeyholder(params[0], context);
343
340
  return await processEncryptionPublicKey(address, {
344
341
  id: request.id,
345
342
  origin: context.assertGet('origin'),
@@ -365,7 +362,7 @@ export function createWalletMiddleware({ getAccounts, getNetworkClientById, proc
365
362
  }
366
363
  const params = request.params;
367
364
  const ciphertext = params[0];
368
- const address = await validateAndNormalizeKeyholder(params[1], undefined, context);
365
+ const address = await validateAndNormalizeKeyholder(params[1], context);
369
366
  // Not using nullish coalescing, since `params` may be `null`.
370
367
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
371
368
  const extraParams = params[2] || {};
@@ -388,16 +385,12 @@ export function createWalletMiddleware({ getAccounts, getNetworkClientById, proc
388
385
  * copy of it.
389
386
  *
390
387
  * @param address - The address to validate and normalize.
391
- * @param chainId - An explicit chain ID for the request, if any.
392
388
  * @param context - The context of the request.
393
389
  * @returns The normalized address, if valid. Otherwise, throws
394
390
  * an error
395
391
  */
396
- async function validateAndNormalizeKeyholder(address, chainId, context) {
397
- return validateKeyholder(address, chainId, context, {
398
- getAccounts,
399
- getNetworkClientById,
400
- });
392
+ async function validateAndNormalizeKeyholder(address, context) {
393
+ return validateKeyholder(address, context, { getAccounts });
401
394
  }
402
395
  }
403
396
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"wallet.js","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,wBAAwB,CAAC;AAMlD,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAExE,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAGpD,OAAO,EAAE,iDAAiD,EAAE,MAAM,uDAAuD,CAAC;AAE1H,OAAO,EAAE,mDAAmD,EAAE,MAAM,yDAAyD,CAAC;AAE9H,OAAO,EAAE,8CAA8C,EAAE,MAAM,mDAAmD,CAAC;AAEnH,OAAO,EAAE,4CAA4C,EAAE,MAAM,iDAAiD,CAAC;AAE/G,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAChF,OAAO,EACL,gBAAgB,EAChB,6BAA6B,IAAI,iBAAiB,EAClD,yBAAyB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cesContent":["import * as sigUtil from '@metamask/eth-sig-util';\nimport type {\n JsonRpcMiddleware,\n MiddlewareContext,\n MiddlewareParams,\n} from '@metamask/json-rpc-engine/v2';\nimport { createScaffoldMiddleware } from '@metamask/json-rpc-engine/v2';\nimport type { MessageRequest } from '@metamask/message-manager';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { isValidHexAddress } from '@metamask/utils';\nimport type { JsonRpcRequest, Json, Hex } from '@metamask/utils';\n\nimport { createWalletGetGrantedExecutionPermissionsHandler } from './methods/wallet-get-granted-execution-permissions.js';\nimport type { ProcessGetGrantedExecutionPermissionsHook } from './methods/wallet-get-granted-execution-permissions.js';\nimport { createWalletGetSupportedExecutionPermissionsHandler } from './methods/wallet-get-supported-execution-permissions.js';\nimport type { ProcessGetSupportedExecutionPermissionsHook } from './methods/wallet-get-supported-execution-permissions.js';\nimport { createWalletRequestExecutionPermissionsHandler } from './methods/wallet-request-execution-permissions.js';\nimport type { ProcessRequestExecutionPermissionsHook } from './methods/wallet-request-execution-permissions.js';\nimport { createWalletRevokeExecutionPermissionHandler } from './methods/wallet-revoke-execution-permission.js';\nimport type { ProcessRevokeExecutionPermissionHook } from './methods/wallet-revoke-execution-permission.js';\nimport { stripArrayTypeIfPresent } from './utils/common.js';\nimport { normalizeTypedMessage, parseTypedMessage } from './utils/normalize.js';\nimport {\n resemblesAddress,\n validateAndNormalizeKeyholder as validateKeyholder,\n validateTransactionParams,\n validateTypedDataForPrototypePollution,\n validateTypedDataV1ForPrototypePollution,\n validateTypedMessageKeys,\n} from './utils/validation.js';\n\nexport type TransactionParams = {\n from: string;\n chainId?: string | number;\n};\n\nexport type MessageParams = TransactionParams & {\n data: string;\n signatureMethod?: string;\n};\n\nexport type TypedMessageParams = MessageParams & {\n version: string;\n};\n\nexport type TypedMessageV1Params = Omit<TypedMessageParams, 'data'> & {\n data: Record<string, unknown>[];\n};\n\nexport type WalletMiddlewareOptions = {\n getAccounts: (origin: string, scope?: string) => Promise<string[]>;\n getNetworkClientById: (id: string) => { configuration: { chainId: Hex } };\n processDecryptMessage?: (\n msgParams: MessageParams,\n req: MessageRequest,\n ) => Promise<string>;\n processEncryptionPublicKey?: (\n address: string,\n req: MessageRequest,\n ) => Promise<string>;\n processPersonalMessage?: (\n msgParams: MessageParams,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n ) => Promise<string>;\n processTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n ) => Promise<string>;\n processSignTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n ) => Promise<string>;\n processTypedMessage?: (\n msgParams: TypedMessageV1Params,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n version: string,\n ) => Promise<string>;\n processTypedMessageV3?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n version: string,\n ) => Promise<string>;\n processTypedMessageV4?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n version: string,\n ) => Promise<string>;\n processRequestExecutionPermissions?: ProcessRequestExecutionPermissionsHook;\n processRevokeExecutionPermission?: ProcessRevokeExecutionPermissionHook;\n processGetGrantedExecutionPermissions?: ProcessGetGrantedExecutionPermissionsHook;\n processGetSupportedExecutionPermissions?: ProcessGetSupportedExecutionPermissionsHook;\n};\n\nexport type WalletMiddlewareKeyValues = {\n networkClientId: string;\n origin: string;\n scope?: string;\n securityAlertResponse?: Record<string, Json>;\n traceContext?: unknown;\n};\n\nexport type WalletMiddlewareContext =\n MiddlewareContext<WalletMiddlewareKeyValues>;\n\nexport type WalletMiddlewareParams = MiddlewareParams<\n JsonRpcRequest,\n WalletMiddlewareContext\n>;\n\n/**\n * Creates a JSON-RPC middleware that handles \"wallet\"-related JSON-RPC methods.\n * \"Wallet\" may have had a specific meaning at some point in the distant past,\n * but at this point it's just an arbitrary label.\n *\n * @param options - The options for the middleware.\n * @param options.getAccounts - The function to get the accounts for the origin and scope.\n * @param options.getNetworkClientById - The function to get a network client by ID, used to determine the scope of a request.\n * @param options.processDecryptMessage - The function to process the decrypt message request.\n * @param options.processEncryptionPublicKey - The function to process the encryption public key request.\n * @param options.processPersonalMessage - The function to process the personal message request.\n * @param options.processTransaction - The function to process the transaction request.\n * @param options.processSignTransaction - The function to process the sign transaction request.\n * @param options.processTypedMessage - The function to process the typed message request.\n * @param options.processTypedMessageV3 - The function to process the typed message v3 request.\n * @param options.processTypedMessageV4 - The function to process the typed message v4 request.\n * @param options.processRequestExecutionPermissions - The function to process the request execution permissions request.\n * @param options.processRevokeExecutionPermission - The function to process the revoke execution permission request.\n * @param options.processGetGrantedExecutionPermissions - The function to process the get granted execution permissions request.\n * @param options.processGetSupportedExecutionPermissions - The function to process the get supported execution permissions request.\n * @returns A JSON-RPC middleware that handles wallet-related JSON-RPC methods.\n */\nexport function createWalletMiddleware({\n getAccounts,\n getNetworkClientById,\n processDecryptMessage,\n processEncryptionPublicKey,\n processPersonalMessage,\n processTransaction,\n processSignTransaction,\n processTypedMessage,\n processTypedMessageV3,\n processTypedMessageV4,\n processRequestExecutionPermissions,\n processRevokeExecutionPermission,\n processGetGrantedExecutionPermissions,\n processGetSupportedExecutionPermissions,\n}: WalletMiddlewareOptions): JsonRpcMiddleware<\n JsonRpcRequest,\n Json,\n WalletMiddlewareContext\n> {\n if (!getAccounts) {\n throw new Error('opts.getAccounts is required');\n }\n\n return createScaffoldMiddleware<WalletMiddlewareContext>({\n // account lookups\n eth_accounts: lookupAccounts,\n eth_coinbase: lookupDefaultAccount,\n\n // tx signatures\n eth_sendTransaction: sendTransaction,\n eth_signTransaction: signTransaction,\n\n // message signatures\n eth_signTypedData: signTypedData,\n eth_signTypedData_v3: signTypedDataV3,\n eth_signTypedData_v4: signTypedDataV4,\n personal_sign: personalSign,\n eth_getEncryptionPublicKey: encryptionPublicKey,\n eth_decrypt: decryptMessage,\n personal_ecRecover: personalRecover,\n\n // EIP-7715\n wallet_requestExecutionPermissions:\n createWalletRequestExecutionPermissionsHandler({\n processRequestExecutionPermissions,\n }),\n wallet_revokeExecutionPermission:\n createWalletRevokeExecutionPermissionHandler({\n processRevokeExecutionPermission,\n }),\n wallet_getGrantedExecutionPermissions:\n createWalletGetGrantedExecutionPermissionsHandler({\n processGetGrantedExecutionPermissions,\n }),\n wallet_getSupportedExecutionPermissions:\n createWalletGetSupportedExecutionPermissionsHandler({\n processGetSupportedExecutionPermissions,\n }),\n });\n\n //\n // account lookups\n //\n\n /**\n * Gets the accounts for the origin.\n *\n * @param options - Options bag.\n * @param options.context - The context of the request.\n * @returns The accounts for the origin.\n */\n async function lookupAccounts({\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n return await getAccounts(context.assertGet('origin'), context.get('scope'));\n }\n\n /**\n * Gets the default account (i.e. first in the list) for the origin.\n *\n * @param options - Options bag.\n * @param options.context - The context of the request.\n * @returns The default account for the origin.\n */\n async function lookupDefaultAccount({\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n const accounts = await getAccounts(\n context.assertGet('origin'),\n context.get('scope'),\n );\n return accounts[0] || null;\n }\n\n //\n // transaction signatures\n //\n\n /**\n * Sends a transaction.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The transaction hash.\n */\n async function sendTransaction({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params[0] as TransactionParams | undefined;\n validateTransactionParams(params);\n const txParams: TransactionParams = {\n ...params,\n from: await validateAndNormalizeKeyholder(\n // Not using nullish coalescing, since `params` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n params?.from || '',\n params?.chainId,\n context,\n ),\n };\n return await processTransaction(txParams, request, context);\n }\n\n /**\n * Signs a transaction.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The signed transaction.\n */\n async function signTransaction({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processSignTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params[0] as TransactionParams | undefined;\n validateTransactionParams(params);\n const txParams: TransactionParams = {\n ...params,\n from: await validateAndNormalizeKeyholder(\n // Not using nullish coalescing, since `params` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n params?.from || '',\n params?.chainId,\n context,\n ),\n };\n return await processSignTransaction(txParams, request, context);\n }\n\n //\n // message signatures\n //\n\n /**\n * Signs a `eth_signTypedData` message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The signed message.\n */\n async function signTypedData({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processTypedMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [\n Record<string, unknown>[],\n string,\n Record<string, string>?,\n ];\n const message = params[0];\n const address = await validateAndNormalizeKeyholder(\n params[1],\n undefined,\n context,\n );\n const version = 'V1';\n validateTypedDataV1ForPrototypePollution(message);\n // Not using nullish coalescing, since `params` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n const extraParams = params[2] || {};\n const msgParams: TypedMessageV1Params = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'eth_signTypedData',\n version,\n };\n\n return await processTypedMessage(msgParams, request, context, version);\n }\n\n /**\n * Signs a `eth_signTypedData_v3` message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The signed message.\n */\n async function signTypedDataV3({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processTypedMessageV3) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(\n params[0],\n undefined,\n context,\n );\n const message = normalizeTypedMessage(params[1]);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n validateTypedDataForPrototypePollution(message);\n const version = 'V3';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v3',\n };\n\n return await processTypedMessageV3(msgParams, request, context, version);\n }\n\n /**\n * Signs a `eth_signTypedData_v4` message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The signed message.\n */\n async function signTypedDataV4({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processTypedMessageV4) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(\n params[0],\n undefined,\n context,\n );\n const message = normalizeTypedMessage(params[1]);\n validateTypedMessageKeys(message);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n validateTypedDataForPrototypePollution(message);\n const version = 'V4';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v4',\n };\n\n return await processTypedMessageV4(msgParams, request, context, version);\n }\n\n /**\n * Signs a `personal_sign` message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The signed message.\n */\n async function personalSign({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processPersonalMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [string, string, TransactionParams?];\n\n // process normally\n const firstParam = params[0];\n const secondParam = params[1];\n // non-standard \"extraParams\" to be appended to our \"msgParams\" obj\n // Not using nullish coalescing, since `params` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n const extraParams = params[2] || {};\n\n // We initially incorrectly ordered these parameters.\n // To gracefully respect users who adopted this API early,\n // we are currently gracefully recovering from the wrong param order\n // when it is clearly identifiable.\n //\n // That means when the first param is definitely an address,\n // and the second param is definitely not, but is hex.\n let address: string, message: string;\n if (resemblesAddress(firstParam) && !resemblesAddress(secondParam)) {\n address = firstParam;\n message = secondParam;\n } else {\n message = firstParam;\n address = secondParam;\n }\n address = await validateAndNormalizeKeyholder(address, undefined, context);\n\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'personal_sign',\n };\n\n return await processPersonalMessage(msgParams, request, context);\n }\n\n /**\n * Recovers the signer address from a `personal_sign` message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @returns The recovered signer address.\n */\n async function personalRecover({\n request,\n }: WalletMiddlewareParams): Promise<Json> {\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [string, string];\n const message = params[0];\n const signature = params[1];\n const signerAddress = sigUtil.recoverPersonalSignature({\n data: message,\n signature,\n });\n\n return signerAddress;\n }\n\n /**\n * Gets the encryption public key for an address.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The encryption public key.\n */\n async function encryptionPublicKey({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processEncryptionPublicKey) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [string];\n\n const address = await validateAndNormalizeKeyholder(\n params[0],\n undefined,\n context,\n );\n\n return await processEncryptionPublicKey(address, {\n id: request.id as string | number,\n origin: context.assertGet('origin'),\n securityAlertResponse: context.get('securityAlertResponse'),\n });\n }\n\n /**\n * Decrypts a message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The decrypted message.\n */\n async function decryptMessage({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processDecryptMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n const params = request.params as [string, string, Record<string, Json>?];\n\n const ciphertext: string = params[0];\n const address: string = await validateAndNormalizeKeyholder(\n params[1],\n undefined,\n context,\n );\n // Not using nullish coalescing, since `params` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n const extraParams = params[2] || {};\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: ciphertext,\n };\n\n return await processDecryptMessage(msgParams, {\n id: request.id as string | number,\n origin: context.assertGet('origin'),\n securityAlertResponse: context.get('securityAlertResponse'),\n });\n }\n\n //\n // utility\n //\n\n /**\n * Validates the keyholder address, and returns a normalized (i.e. lowercase)\n * copy of it.\n *\n * @param address - The address to validate and normalize.\n * @param chainId - An explicit chain ID for the request, if any.\n * @param context - The context of the request.\n * @returns The normalized address, if valid. Otherwise, throws\n * an error\n */\n async function validateAndNormalizeKeyholder(\n address: string,\n chainId: string | number | undefined,\n context: WalletMiddlewareContext,\n ): Promise<string> {\n return validateKeyholder(address as Hex, chainId, context, {\n getAccounts,\n getNetworkClientById,\n });\n }\n}\n\n/**\n * Validates primary of typedSignMessage, to ensure that it's type definition is present in message.\n *\n * @param data - The data passed in typedSign request.\n */\nfunction validatePrimaryType(data: string): void {\n const { primaryType, types } = parseTypedMessage(data);\n if (!types) {\n throw rpcErrors.invalidInput();\n }\n\n // Primary type can be an array.\n const baseType = stripArrayTypeIfPresent(primaryType);\n\n // Return if the base type is not defined in the types\n const baseTypeDefinitions = types[baseType];\n if (!baseTypeDefinitions) {\n throw rpcErrors.invalidInput();\n }\n}\n\n/**\n * Validates verifyingContract of typedSignMessage.\n *\n * @param data - The data passed in typedSign request.\n * This function allows the verifyingContract to be either:\n * - A valid hex address\n * - The string \"cosmos\" (as it is hard-coded in some Cosmos ecosystem's EVM adapters)\n * - An empty string\n */\nfunction validateVerifyingContract(data: string): void {\n const { domain: { verifyingContract } = {} } = parseTypedMessage(data);\n // Explicit check for cosmos here has been added to address this issue\n // https://github.com/MetaMask/eth-json-rpc-middleware/issues/337\n if (\n verifyingContract &&\n (verifyingContract as string) !== 'cosmos' &&\n !isValidHexAddress(verifyingContract)\n ) {\n throw rpcErrors.invalidInput();\n }\n}\n"]}
1
+ {"version":3,"file":"wallet.js","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,wBAAwB,CAAC;AAMlD,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAExE,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAGpD,OAAO,EAAE,iDAAiD,EAAE,MAAM,uDAAuD,CAAC;AAE1H,OAAO,EAAE,mDAAmD,EAAE,MAAM,yDAAyD,CAAC;AAE9H,OAAO,EAAE,8CAA8C,EAAE,MAAM,mDAAmD,CAAC;AAEnH,OAAO,EAAE,4CAA4C,EAAE,MAAM,iDAAiD,CAAC;AAE/G,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAChF,OAAO,EACL,gBAAgB,EAChB,6BAA6B,IAAI,iBAAiB,EAClD,yBAAyB,EACzB,sCAAsC,EACtC,wCAAwC,E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AAK,UAAU,6BAA6B,CAC1C,OAAe,EACf,OAAgC;QAEhC,OAAO,iBAAiB,CAAC,OAAc,EAAE,OAAO,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC;IACrE,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAAC,IAAY;IACvC,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC;IACjC,CAAC;IAED,gCAAgC;IAChC,MAAM,QAAQ,GAAG,uBAAuB,CAAC,WAAW,CAAC,CAAC;IAEtD,sDAAsD;IACtD,MAAM,mBAAmB,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC5C,IAAI,CAAC,mBAAmB,EAAE,CAAC;QACzB,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC;IACjC,CAAC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,yBAAyB,CAAC,IAAY;IAC7C,MAAM,EAAE,MAAM,EAAE,EAAE,iBAAiB,EAAE,GAAG,EAAE,EAAE,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvE,sEAAsE;IACtE,iEAAiE;IACjE,IACE,iBAAiB;QAChB,iBAA4B,KAAK,QAAQ;QAC1C,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,EACrC,CAAC;QACD,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC;IACjC,CAAC;AACH,CAAC","sourcesContent":["import * as sigUtil from '@metamask/eth-sig-util';\nimport type {\n JsonRpcMiddleware,\n MiddlewareContext,\n MiddlewareParams,\n} from '@metamask/json-rpc-engine/v2';\nimport { createScaffoldMiddleware } from '@metamask/json-rpc-engine/v2';\nimport type { MessageRequest } from '@metamask/message-manager';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { isValidHexAddress } from '@metamask/utils';\nimport type { JsonRpcRequest, Json, Hex } from '@metamask/utils';\n\nimport { createWalletGetGrantedExecutionPermissionsHandler } from './methods/wallet-get-granted-execution-permissions.js';\nimport type { ProcessGetGrantedExecutionPermissionsHook } from './methods/wallet-get-granted-execution-permissions.js';\nimport { createWalletGetSupportedExecutionPermissionsHandler } from './methods/wallet-get-supported-execution-permissions.js';\nimport type { ProcessGetSupportedExecutionPermissionsHook } from './methods/wallet-get-supported-execution-permissions.js';\nimport { createWalletRequestExecutionPermissionsHandler } from './methods/wallet-request-execution-permissions.js';\nimport type { ProcessRequestExecutionPermissionsHook } from './methods/wallet-request-execution-permissions.js';\nimport { createWalletRevokeExecutionPermissionHandler } from './methods/wallet-revoke-execution-permission.js';\nimport type { ProcessRevokeExecutionPermissionHook } from './methods/wallet-revoke-execution-permission.js';\nimport { stripArrayTypeIfPresent } from './utils/common.js';\nimport { normalizeTypedMessage, parseTypedMessage } from './utils/normalize.js';\nimport {\n resemblesAddress,\n validateAndNormalizeKeyholder as validateKeyholder,\n validateTransactionParams,\n validateTypedDataForPrototypePollution,\n validateTypedDataV1ForPrototypePollution,\n validateTypedMessageKeys,\n} from './utils/validation.js';\n\nexport type TransactionParams = {\n from: string;\n};\n\nexport type MessageParams = TransactionParams & {\n data: string;\n signatureMethod?: string;\n};\n\nexport type TypedMessageParams = MessageParams & {\n version: string;\n};\n\nexport type TypedMessageV1Params = Omit<TypedMessageParams, 'data'> & {\n data: Record<string, unknown>[];\n};\n\nexport type WalletMiddlewareOptions = {\n getAccounts: (origin: string) => Promise<string[]>;\n processDecryptMessage?: (\n msgParams: MessageParams,\n req: MessageRequest,\n ) => Promise<string>;\n processEncryptionPublicKey?: (\n address: string,\n req: MessageRequest,\n ) => Promise<string>;\n processPersonalMessage?: (\n msgParams: MessageParams,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n ) => Promise<string>;\n processTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n ) => Promise<string>;\n processSignTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n ) => Promise<string>;\n processTypedMessage?: (\n msgParams: TypedMessageV1Params,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n version: string,\n ) => Promise<string>;\n processTypedMessageV3?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n version: string,\n ) => Promise<string>;\n processTypedMessageV4?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n context: WalletMiddlewareContext,\n version: string,\n ) => Promise<string>;\n processRequestExecutionPermissions?: ProcessRequestExecutionPermissionsHook;\n processRevokeExecutionPermission?: ProcessRevokeExecutionPermissionHook;\n processGetGrantedExecutionPermissions?: ProcessGetGrantedExecutionPermissionsHook;\n processGetSupportedExecutionPermissions?: ProcessGetSupportedExecutionPermissionsHook;\n};\n\nexport type WalletMiddlewareKeyValues = {\n networkClientId: string;\n origin: string;\n securityAlertResponse?: Record<string, Json>;\n traceContext?: unknown;\n};\n\nexport type WalletMiddlewareContext =\n MiddlewareContext<WalletMiddlewareKeyValues>;\n\nexport type WalletMiddlewareParams = MiddlewareParams<\n JsonRpcRequest,\n WalletMiddlewareContext\n>;\n\n/**\n * Creates a JSON-RPC middleware that handles \"wallet\"-related JSON-RPC methods.\n * \"Wallet\" may have had a specific meaning at some point in the distant past,\n * but at this point it's just an arbitrary label.\n *\n * @param options - The options for the middleware.\n * @param options.getAccounts - The function to get the accounts for the origin.\n * @param options.processDecryptMessage - The function to process the decrypt message request.\n * @param options.processEncryptionPublicKey - The function to process the encryption public key request.\n * @param options.processPersonalMessage - The function to process the personal message request.\n * @param options.processTransaction - The function to process the transaction request.\n * @param options.processSignTransaction - The function to process the sign transaction request.\n * @param options.processTypedMessage - The function to process the typed message request.\n * @param options.processTypedMessageV3 - The function to process the typed message v3 request.\n * @param options.processTypedMessageV4 - The function to process the typed message v4 request.\n * @param options.processRequestExecutionPermissions - The function to process the request execution permissions request.\n * @param options.processRevokeExecutionPermission - The function to process the revoke execution permission request.\n * @param options.processGetGrantedExecutionPermissions - The function to process the get granted execution permissions request.\n * @param options.processGetSupportedExecutionPermissions - The function to process the get supported execution permissions request.\n * @returns A JSON-RPC middleware that handles wallet-related JSON-RPC methods.\n */\nexport function createWalletMiddleware({\n getAccounts,\n processDecryptMessage,\n processEncryptionPublicKey,\n processPersonalMessage,\n processTransaction,\n processSignTransaction,\n processTypedMessage,\n processTypedMessageV3,\n processTypedMessageV4,\n processRequestExecutionPermissions,\n processRevokeExecutionPermission,\n processGetGrantedExecutionPermissions,\n processGetSupportedExecutionPermissions,\n}: WalletMiddlewareOptions): JsonRpcMiddleware<\n JsonRpcRequest,\n Json,\n WalletMiddlewareContext\n> {\n if (!getAccounts) {\n throw new Error('opts.getAccounts is required');\n }\n\n return createScaffoldMiddleware<WalletMiddlewareContext>({\n // account lookups\n eth_accounts: lookupAccounts,\n eth_coinbase: lookupDefaultAccount,\n\n // tx signatures\n eth_sendTransaction: sendTransaction,\n eth_signTransaction: signTransaction,\n\n // message signatures\n eth_signTypedData: signTypedData,\n eth_signTypedData_v3: signTypedDataV3,\n eth_signTypedData_v4: signTypedDataV4,\n personal_sign: personalSign,\n eth_getEncryptionPublicKey: encryptionPublicKey,\n eth_decrypt: decryptMessage,\n personal_ecRecover: personalRecover,\n\n // EIP-7715\n wallet_requestExecutionPermissions:\n createWalletRequestExecutionPermissionsHandler({\n processRequestExecutionPermissions,\n }),\n wallet_revokeExecutionPermission:\n createWalletRevokeExecutionPermissionHandler({\n processRevokeExecutionPermission,\n }),\n wallet_getGrantedExecutionPermissions:\n createWalletGetGrantedExecutionPermissionsHandler({\n processGetGrantedExecutionPermissions,\n }),\n wallet_getSupportedExecutionPermissions:\n createWalletGetSupportedExecutionPermissionsHandler({\n processGetSupportedExecutionPermissions,\n }),\n });\n\n //\n // account lookups\n //\n\n /**\n * Gets the accounts for the origin.\n *\n * @param options - Options bag.\n * @param options.context - The context of the request.\n * @returns The accounts for the origin.\n */\n async function lookupAccounts({\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n return await getAccounts(context.assertGet('origin'));\n }\n\n /**\n * Gets the default account (i.e. first in the list) for the origin.\n *\n * @param options - Options bag.\n * @param options.context - The context of the request.\n * @returns The default account for the origin.\n */\n async function lookupDefaultAccount({\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n const accounts = await getAccounts(context.assertGet('origin'));\n return accounts[0] || null;\n }\n\n //\n // transaction signatures\n //\n\n /**\n * Sends a transaction.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The transaction hash.\n */\n async function sendTransaction({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params[0] as TransactionParams | undefined;\n validateTransactionParams(params);\n const txParams: TransactionParams = {\n ...params,\n // Not using nullish coalescing, since `params` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n from: await validateAndNormalizeKeyholder(params?.from || '', context),\n };\n return await processTransaction(txParams, request, context);\n }\n\n /**\n * Signs a transaction.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The signed transaction.\n */\n async function signTransaction({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processSignTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params[0] as TransactionParams | undefined;\n validateTransactionParams(params);\n const txParams: TransactionParams = {\n ...params,\n // Not using nullish coalescing, since `params` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n from: await validateAndNormalizeKeyholder(params?.from || '', context),\n };\n return await processSignTransaction(txParams, request, context);\n }\n\n //\n // message signatures\n //\n\n /**\n * Signs a `eth_signTypedData` message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The signed message.\n */\n async function signTypedData({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processTypedMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [\n Record<string, unknown>[],\n string,\n Record<string, string>?,\n ];\n const message = params[0];\n const address = await validateAndNormalizeKeyholder(params[1], context);\n const version = 'V1';\n validateTypedDataV1ForPrototypePollution(message);\n // Not using nullish coalescing, since `params` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n const extraParams = params[2] || {};\n const msgParams: TypedMessageV1Params = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'eth_signTypedData',\n version,\n };\n\n return await processTypedMessage(msgParams, request, context, version);\n }\n\n /**\n * Signs a `eth_signTypedData_v3` message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The signed message.\n */\n async function signTypedDataV3({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processTypedMessageV3) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(params[0], context);\n const message = normalizeTypedMessage(params[1]);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n validateTypedDataForPrototypePollution(message);\n const version = 'V3';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v3',\n };\n\n return await processTypedMessageV3(msgParams, request, context, version);\n }\n\n /**\n * Signs a `eth_signTypedData_v4` message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The signed message.\n */\n async function signTypedDataV4({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processTypedMessageV4) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(params[0], context);\n const message = normalizeTypedMessage(params[1]);\n validateTypedMessageKeys(message);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n validateTypedDataForPrototypePollution(message);\n const version = 'V4';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v4',\n };\n\n return await processTypedMessageV4(msgParams, request, context, version);\n }\n\n /**\n * Signs a `personal_sign` message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The signed message.\n */\n async function personalSign({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processPersonalMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [string, string, TransactionParams?];\n\n // process normally\n const firstParam = params[0];\n const secondParam = params[1];\n // non-standard \"extraParams\" to be appended to our \"msgParams\" obj\n // Not using nullish coalescing, since `params` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n const extraParams = params[2] || {};\n\n // We initially incorrectly ordered these parameters.\n // To gracefully respect users who adopted this API early,\n // we are currently gracefully recovering from the wrong param order\n // when it is clearly identifiable.\n //\n // That means when the first param is definitely an address,\n // and the second param is definitely not, but is hex.\n let address: string, message: string;\n if (resemblesAddress(firstParam) && !resemblesAddress(secondParam)) {\n address = firstParam;\n message = secondParam;\n } else {\n message = firstParam;\n address = secondParam;\n }\n address = await validateAndNormalizeKeyholder(address, context);\n\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'personal_sign',\n };\n\n return await processPersonalMessage(msgParams, request, context);\n }\n\n /**\n * Recovers the signer address from a `personal_sign` message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @returns The recovered signer address.\n */\n async function personalRecover({\n request,\n }: WalletMiddlewareParams): Promise<Json> {\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [string, string];\n const message = params[0];\n const signature = params[1];\n const signerAddress = sigUtil.recoverPersonalSignature({\n data: message,\n signature,\n });\n\n return signerAddress;\n }\n\n /**\n * Gets the encryption public key for an address.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The encryption public key.\n */\n async function encryptionPublicKey({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processEncryptionPublicKey) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = request.params as [string];\n\n const address = await validateAndNormalizeKeyholder(params[0], context);\n\n return await processEncryptionPublicKey(address, {\n id: request.id as string | number,\n origin: context.assertGet('origin'),\n securityAlertResponse: context.get('securityAlertResponse'),\n });\n }\n\n /**\n * Decrypts a message.\n *\n * @param options - Options bag.\n * @param options.request - The request.\n * @param options.context - The context of the request.\n * @returns The decrypted message.\n */\n async function decryptMessage({\n request,\n context,\n }: WalletMiddlewareParams): Promise<Json> {\n if (!processDecryptMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !request.params ||\n !Array.isArray(request.params) ||\n !(request.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n const params = request.params as [string, string, Record<string, Json>?];\n\n const ciphertext: string = params[0];\n const address: string = await validateAndNormalizeKeyholder(\n params[1],\n context,\n );\n // Not using nullish coalescing, since `params` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n const extraParams = params[2] || {};\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: ciphertext,\n };\n\n return await processDecryptMessage(msgParams, {\n id: request.id as string | number,\n origin: context.assertGet('origin'),\n securityAlertResponse: context.get('securityAlertResponse'),\n });\n }\n\n //\n // utility\n //\n\n /**\n * Validates the keyholder address, and returns a normalized (i.e. lowercase)\n * copy of it.\n *\n * @param address - The address to validate and normalize.\n * @param context - The context of the request.\n * @returns The normalized address, if valid. Otherwise, throws\n * an error\n */\n async function validateAndNormalizeKeyholder(\n address: string,\n context: WalletMiddlewareContext,\n ): Promise<string> {\n return validateKeyholder(address as Hex, context, { getAccounts });\n }\n}\n\n/**\n * Validates primary of typedSignMessage, to ensure that it's type definition is present in message.\n *\n * @param data - The data passed in typedSign request.\n */\nfunction validatePrimaryType(data: string): void {\n const { primaryType, types } = parseTypedMessage(data);\n if (!types) {\n throw rpcErrors.invalidInput();\n }\n\n // Primary type can be an array.\n const baseType = stripArrayTypeIfPresent(primaryType);\n\n // Return if the base type is not defined in the types\n const baseTypeDefinitions = types[baseType];\n if (!baseTypeDefinitions) {\n throw rpcErrors.invalidInput();\n }\n}\n\n/**\n * Validates verifyingContract of typedSignMessage.\n *\n * @param data - The data passed in typedSign request.\n * This function allows the verifyingContract to be either:\n * - A valid hex address\n * - The string \"cosmos\" (as it is hard-coded in some Cosmos ecosystem's EVM adapters)\n * - An empty string\n */\nfunction validateVerifyingContract(data: string): void {\n const { domain: { verifyingContract } = {} } = parseTypedMessage(data);\n // Explicit check for cosmos here has been added to address this issue\n // https://github.com/MetaMask/eth-json-rpc-middleware/issues/337\n if (\n verifyingContract &&\n (verifyingContract as string) !== 'cosmos' &&\n !isValidHexAddress(verifyingContract)\n ) {\n throw rpcErrors.invalidInput();\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/eth-json-rpc-middleware",
3
- "version": "25.0.0-preview-3680ba557",
3
+ "version": "25.0.0-preview-e4c191e3a",
4
4
  "description": "Ethereum-related json-rpc-engine middleware",
5
5
  "keywords": [
6
6
  "Ethereum",