@metamask-previews/eth-json-rpc-middleware 24.0.0-preview-d23deb68f → 24.0.0-preview-4165cebcf
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 +5 -0
- package/dist/utils/validation.cjs +4 -4
- package/dist/utils/validation.cjs.map +1 -1
- package/dist/utils/validation.d.cts +14 -14
- package/dist/utils/validation.d.mts +14 -14
- package/dist/utils/validation.mjs +4 -4
- package/dist/utils/validation.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -11,6 +11,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
11
11
|
|
|
12
12
|
- Bump `@metamask/superstruct` from `^3.1.0` to `^3.4.1` ([#9754](https://github.com/MetaMask/core/pull/9754))
|
|
13
13
|
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- Accept numeric values for quantity fields in `eth_sendTransaction` / `eth_signTransaction` params ([#9967](https://github.com/MetaMask/core/pull/9967))
|
|
17
|
+
- `chainId` (top-level and in `authorizationList` entries) and `authorizationList` `nonce` / `yParity` now accept both hex strings and numbers, matching the other quantity fields (`gas`, `value`, `nonce`, etc.) and restoring pre-`24.0.0` behavior
|
|
18
|
+
|
|
14
19
|
## [24.0.0]
|
|
15
20
|
|
|
16
21
|
### Changed
|
|
@@ -196,13 +196,13 @@ exports.TransactionParamsStruct = (0, superstruct_1.object)({
|
|
|
196
196
|
accessList: (0, superstruct_1.optional)((0, superstruct_1.array)((0, superstruct_1.object)({ address: (0, superstruct_1.string)(), storageKeys: (0, superstruct_1.array)((0, superstruct_1.string)()) }))),
|
|
197
197
|
authorizationList: (0, superstruct_1.optional)((0, superstruct_1.array)((0, superstruct_1.object)({
|
|
198
198
|
address: (0, superstruct_1.string)(),
|
|
199
|
-
chainId: (0, superstruct_1.optional)(
|
|
200
|
-
nonce: (0, superstruct_1.optional)(
|
|
199
|
+
chainId: (0, superstruct_1.optional)(QuantityStruct),
|
|
200
|
+
nonce: (0, superstruct_1.optional)(QuantityStruct),
|
|
201
201
|
r: (0, superstruct_1.optional)((0, superstruct_1.string)()),
|
|
202
202
|
s: (0, superstruct_1.optional)((0, superstruct_1.string)()),
|
|
203
|
-
yParity: (0, superstruct_1.optional)(
|
|
203
|
+
yParity: (0, superstruct_1.optional)(QuantityStruct),
|
|
204
204
|
}))),
|
|
205
|
-
chainId: (0, superstruct_1.optional)(
|
|
205
|
+
chainId: (0, superstruct_1.optional)(QuantityStruct),
|
|
206
206
|
data: (0, superstruct_1.optional)((0, superstruct_1.string)()),
|
|
207
207
|
from: (0, superstruct_1.string)(),
|
|
208
208
|
gas: (0, superstruct_1.optional)(QuantityStruct),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.cjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":";;;AAAA,yDAA8D;AAC9D,qDAAiE;AAEjE,uDAQ+B;AAI/B,kDAAmD;AAEnD;;;;;;;;;;GAUG;AACI,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,CAAC;QAEF,MAAM,iBAAiB,GAAG,OAAO,CAAC,WAAW,EAAS,CAAC;QAEvD,IAAI,kBAAkB,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,CAAC;YACnD,OAAO,iB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,sBAAQ,EAAC,cAAc,CAAC;IAClC,QAAQ,EAAE,IAAA,sBAAQ,EAAC,cAAc,CAAC;IAClC,YAAY,EAAE,IAAA,sBAAQ,EAAC,cAAc,CAAC;IACtC,oBAAoB,EAAE,IAAA,sBAAQ,EAAC,cAAc,CAAC;IAC9C,KAAK,EAAE,IAAA,sBAAQ,EAAC,cAAc,CAAC;IAC/B,EAAE,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,GAAE,CAAC;IACtB,IAAI,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,GAAE,CAAC;IACxB,KAAK,EAAE,IAAA,sBAAQ,EAAC,cAAc,CAAC;CAChC,CAAC,CAAC;AAEH,0EAA0E;AAC1E,wFAAwF;AACxF,6EAA6E;AAC7E,2EAA2E;AAC3E,kEAAkE;AACrD,QAAA,iCAAiC,GAAG,GAAG,GAAG,IAAI,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,SAAgB,yBAAyB,CAAC,MAAe;IACvD,IACE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,UAAU;QAC3D,yCAAiC,EACjC,CAAC;QACD,MAAM,sBAAS,CAAC,aAAa,CAAC,mBAAmB,CAAC,CAAC;IACrD,CAAC;IAED,cAAc,CAAC,MAAM,EAAE,+BAAuB,CAAC,CAAC;AAClD,CAAC;AATD,8DASC","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 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(\n obj as Record<string, unknown>,\n )) {\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 array(object({ address: string(), storageKeys: array(string()) })),\n ),\n authorizationList: optional(\n array(\n object({\n address: string(),\n chainId: optional(string()),\n nonce: optional(string()),\n r: optional(string()),\n s: optional(string()),\n yParity: optional(string()),\n }),\n ),\n ),\n chainId: optional(string()),\n data: optional(string()),\n from: string(),\n gas: optional(QuantityStruct),\n gasLimit: optional(QuantityStruct),\n gasPrice: optional(QuantityStruct),\n maxFeePerGas: optional(QuantityStruct),\n maxPriorityFeePerGas: optional(QuantityStruct),\n nonce: optional(QuantityStruct),\n to: optional(string()),\n type: optional(string()),\n value: optional(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.cjs","sourceRoot":"","sources":["../../src/utils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AACH,SAAgB,yBAAyB,CAAC,MAAe;IACvD,IACE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,UAAU;QAC3D,yCAAiC,EACjC,CAAC;QACD,MAAM,sBAAS,CAAC,aAAa,CAAC,mBAAmB,CAAC,CAAC;IACrD,CAAC;IAED,cAAc,CAAC,MAAM,EAAE,+BAAuB,CAAC,CAAC;AAClD,CAAC;AATD,8DASC","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 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(\n obj as Record<string, unknown>,\n )) {\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 array(object({ address: string(), storageKeys: array(string()) })),\n ),\n authorizationList: optional(\n array(\n object({\n address: string(),\n chainId: optional(QuantityStruct),\n nonce: optional(QuantityStruct),\n r: optional(string()),\n s: optional(string()),\n yParity: optional(QuantityStruct),\n }),\n ),\n ),\n chainId: optional(QuantityStruct),\n data: optional(string()),\n from: string(),\n gas: optional(QuantityStruct),\n gasLimit: optional(QuantityStruct),\n gasPrice: optional(QuantityStruct),\n maxFeePerGas: optional(QuantityStruct),\n maxPriorityFeePerGas: optional(QuantityStruct),\n nonce: optional(QuantityStruct),\n to: optional(string()),\n type: optional(string()),\n value: optional(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"]}
|
|
@@ -61,7 +61,7 @@ export declare const TransactionParamsStruct: Struct<{
|
|
|
61
61
|
from: string;
|
|
62
62
|
data?: string | undefined;
|
|
63
63
|
type?: string | undefined;
|
|
64
|
-
chainId?: string | undefined;
|
|
64
|
+
chainId?: string | number | undefined;
|
|
65
65
|
to?: string | undefined;
|
|
66
66
|
value?: string | number | undefined;
|
|
67
67
|
accessList?: {
|
|
@@ -70,11 +70,11 @@ export declare const TransactionParamsStruct: Struct<{
|
|
|
70
70
|
}[] | undefined;
|
|
71
71
|
authorizationList?: {
|
|
72
72
|
address: string;
|
|
73
|
-
chainId?: string | undefined;
|
|
74
|
-
nonce?: string | undefined;
|
|
73
|
+
chainId?: string | number | undefined;
|
|
74
|
+
nonce?: string | number | undefined;
|
|
75
75
|
r?: string | undefined;
|
|
76
76
|
s?: string | undefined;
|
|
77
|
-
yParity?: string | undefined;
|
|
77
|
+
yParity?: string | number | undefined;
|
|
78
78
|
}[] | undefined;
|
|
79
79
|
nonce?: string | number | undefined;
|
|
80
80
|
gas?: string | number | undefined;
|
|
@@ -95,27 +95,27 @@ export declare const TransactionParamsStruct: Struct<{
|
|
|
95
95
|
}>>;
|
|
96
96
|
authorizationList: Struct<{
|
|
97
97
|
address: string;
|
|
98
|
-
chainId?: string | undefined;
|
|
99
|
-
nonce?: string | undefined;
|
|
98
|
+
chainId?: string | number | undefined;
|
|
99
|
+
nonce?: string | number | undefined;
|
|
100
100
|
r?: string | undefined;
|
|
101
101
|
s?: string | undefined;
|
|
102
|
-
yParity?: string | undefined;
|
|
102
|
+
yParity?: string | number | undefined;
|
|
103
103
|
}[] | undefined, Struct<{
|
|
104
104
|
address: string;
|
|
105
|
-
chainId?: string | undefined;
|
|
106
|
-
nonce?: string | undefined;
|
|
105
|
+
chainId?: string | number | undefined;
|
|
106
|
+
nonce?: string | number | undefined;
|
|
107
107
|
r?: string | undefined;
|
|
108
108
|
s?: string | undefined;
|
|
109
|
-
yParity?: string | undefined;
|
|
109
|
+
yParity?: string | number | undefined;
|
|
110
110
|
}, {
|
|
111
111
|
address: Struct<string, null>;
|
|
112
|
-
chainId: Struct<string | undefined, null>;
|
|
113
|
-
nonce: Struct<string | undefined, null>;
|
|
112
|
+
chainId: Struct<string | number | undefined, null>;
|
|
113
|
+
nonce: Struct<string | number | undefined, null>;
|
|
114
114
|
r: Struct<string | undefined, null>;
|
|
115
115
|
s: Struct<string | undefined, null>;
|
|
116
|
-
yParity: Struct<string | undefined, null>;
|
|
116
|
+
yParity: Struct<string | number | undefined, null>;
|
|
117
117
|
}>>;
|
|
118
|
-
chainId: Struct<string | undefined, null>;
|
|
118
|
+
chainId: Struct<string | number | undefined, null>;
|
|
119
119
|
data: Struct<string | undefined, null>;
|
|
120
120
|
from: Struct<string, null>;
|
|
121
121
|
gas: Struct<string | number | undefined, null>;
|
|
@@ -61,7 +61,7 @@ export declare const TransactionParamsStruct: Struct<{
|
|
|
61
61
|
from: string;
|
|
62
62
|
data?: string | undefined;
|
|
63
63
|
type?: string | undefined;
|
|
64
|
-
chainId?: string | undefined;
|
|
64
|
+
chainId?: string | number | undefined;
|
|
65
65
|
to?: string | undefined;
|
|
66
66
|
value?: string | number | undefined;
|
|
67
67
|
accessList?: {
|
|
@@ -70,11 +70,11 @@ export declare const TransactionParamsStruct: Struct<{
|
|
|
70
70
|
}[] | undefined;
|
|
71
71
|
authorizationList?: {
|
|
72
72
|
address: string;
|
|
73
|
-
chainId?: string | undefined;
|
|
74
|
-
nonce?: string | undefined;
|
|
73
|
+
chainId?: string | number | undefined;
|
|
74
|
+
nonce?: string | number | undefined;
|
|
75
75
|
r?: string | undefined;
|
|
76
76
|
s?: string | undefined;
|
|
77
|
-
yParity?: string | undefined;
|
|
77
|
+
yParity?: string | number | undefined;
|
|
78
78
|
}[] | undefined;
|
|
79
79
|
nonce?: string | number | undefined;
|
|
80
80
|
gas?: string | number | undefined;
|
|
@@ -95,27 +95,27 @@ export declare const TransactionParamsStruct: Struct<{
|
|
|
95
95
|
}>>;
|
|
96
96
|
authorizationList: Struct<{
|
|
97
97
|
address: string;
|
|
98
|
-
chainId?: string | undefined;
|
|
99
|
-
nonce?: string | undefined;
|
|
98
|
+
chainId?: string | number | undefined;
|
|
99
|
+
nonce?: string | number | undefined;
|
|
100
100
|
r?: string | undefined;
|
|
101
101
|
s?: string | undefined;
|
|
102
|
-
yParity?: string | undefined;
|
|
102
|
+
yParity?: string | number | undefined;
|
|
103
103
|
}[] | undefined, Struct<{
|
|
104
104
|
address: string;
|
|
105
|
-
chainId?: string | undefined;
|
|
106
|
-
nonce?: string | undefined;
|
|
105
|
+
chainId?: string | number | undefined;
|
|
106
|
+
nonce?: string | number | undefined;
|
|
107
107
|
r?: string | undefined;
|
|
108
108
|
s?: string | undefined;
|
|
109
|
-
yParity?: string | undefined;
|
|
109
|
+
yParity?: string | number | undefined;
|
|
110
110
|
}, {
|
|
111
111
|
address: Struct<string, null>;
|
|
112
|
-
chainId: Struct<string | undefined, null>;
|
|
113
|
-
nonce: Struct<string | undefined, null>;
|
|
112
|
+
chainId: Struct<string | number | undefined, null>;
|
|
113
|
+
nonce: Struct<string | number | undefined, null>;
|
|
114
114
|
r: Struct<string | undefined, null>;
|
|
115
115
|
s: Struct<string | undefined, null>;
|
|
116
|
-
yParity: Struct<string | undefined, null>;
|
|
116
|
+
yParity: Struct<string | number | undefined, null>;
|
|
117
117
|
}>>;
|
|
118
|
-
chainId: Struct<string | undefined, null>;
|
|
118
|
+
chainId: Struct<string | number | undefined, null>;
|
|
119
119
|
data: Struct<string | undefined, null>;
|
|
120
120
|
from: Struct<string, null>;
|
|
121
121
|
gas: Struct<string | number | undefined, null>;
|
|
@@ -187,13 +187,13 @@ export const TransactionParamsStruct = object({
|
|
|
187
187
|
accessList: optional(array(object({ address: string(), storageKeys: array(string()) }))),
|
|
188
188
|
authorizationList: optional(array(object({
|
|
189
189
|
address: string(),
|
|
190
|
-
chainId: optional(
|
|
191
|
-
nonce: optional(
|
|
190
|
+
chainId: optional(QuantityStruct),
|
|
191
|
+
nonce: optional(QuantityStruct),
|
|
192
192
|
r: optional(string()),
|
|
193
193
|
s: optional(string()),
|
|
194
|
-
yParity: optional(
|
|
194
|
+
yParity: optional(QuantityStruct),
|
|
195
195
|
}))),
|
|
196
|
-
chainId: optional(
|
|
196
|
+
chainId: optional(QuantityStruct),
|
|
197
197
|
data: optional(string()),
|
|
198
198
|
from: string(),
|
|
199
199
|
gas: optional(QuantityStruct),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.mjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,+BAA+B;AAC9D,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,6BAA6B;AAEjE,OAAO,EACL,KAAK,EACL,MAAM,EACN,MAAM,EACN,QAAQ,EACR,MAAM,EACN,KAAK,EACL,QAAQ,EACT,8BAA8B;AAI/B,OAAO,EAAE,iBAAiB,EAAE,wBAAuB;AAEnD;;;;;;;;;;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c-errors';\nimport type { Struct, StructError } from '@metamask/superstruct';\nimport {\n array,\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(\n obj as Record<string, unknown>,\n )) {\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 array(object({ address: string(), storageKeys: array(string()) })),\n ),\n authorizationList: optional(\n array(\n object({\n address: string(),\n chainId: optional(string()),\n nonce: optional(string()),\n r: optional(string()),\n s: optional(string()),\n yParity: optional(string()),\n }),\n ),\n ),\n chainId: optional(string()),\n data: optional(string()),\n from: string(),\n gas: optional(QuantityStruct),\n gasLimit: optional(QuantityStruct),\n gasPrice: optional(QuantityStruct),\n maxFeePerGas: optional(QuantityStruct),\n maxPriorityFeePerGas: optional(QuantityStruct),\n nonce: optional(QuantityStruct),\n to: optional(string()),\n type: optional(string()),\n value: optional(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.mjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,+BAA+B;AAC9D,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,6BAA6B;AAEjE,OAAO,EACL,KAAK,EACL,MAAM,EACN,MAAM,EACN,QAAQ,EACR,MAAM,EACN,KAAK,EACL,QAAQ,EACT,8BAA8B;AAI/B,OAAO,EAAE,iBAAiB,EAAE,wBAAuB;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,CAAC;QAEF,MAAM,iBAAiB,GAAG,OAAO,CAAC,WAAW,EAAS,CAAC;QAEvD,IAAI,kBAAkB,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,CAAC;YACnD,OAAO,iBAAiB,CAAC;QAC3B,CAAC;QAED,MAAM,cAAc,CAAC,YAAY,EAAE,CAAC;IACtC,CAAC;IAED,MAAM,SAAS,CAAC,aAAa,CA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E;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 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(\n obj as Record<string, unknown>,\n )) {\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 array(object({ address: string(), storageKeys: array(string()) })),\n ),\n authorizationList: optional(\n array(\n object({\n address: string(),\n chainId: optional(QuantityStruct),\n nonce: optional(QuantityStruct),\n r: optional(string()),\n s: optional(string()),\n yParity: optional(QuantityStruct),\n }),\n ),\n ),\n chainId: optional(QuantityStruct),\n data: optional(string()),\n from: string(),\n gas: optional(QuantityStruct),\n gasLimit: optional(QuantityStruct),\n gasPrice: optional(QuantityStruct),\n maxFeePerGas: optional(QuantityStruct),\n maxPriorityFeePerGas: optional(QuantityStruct),\n nonce: optional(QuantityStruct),\n to: optional(string()),\n type: optional(string()),\n value: optional(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"]}
|