@metamask-previews/eth-json-rpc-middleware 25.0.0-preview-ed70ef231 → 25.0.0-preview-ff2ab0583
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalize.js","sourceRoot":"","sources":["../../src/utils/normalize.ts"],"names":[],"mappings":"AAaA;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CAAC,WAAmB;IACvD,IAAI,IAAI,CAAC;IACT,IAAI,CAAC;QACH,IAAI,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;IACxC,CAAC;IAAC,MAAM,CAAC;QACP,yDAAyD;QACzD,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,MAAM,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC;IAEhD,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACvB,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,GAAG,IAAI;QACP,MAAM,EAAE;YACN,GAAG,IAAI,CAAC,MAAM;YACd,iBAAiB,EAAE,wBAAwB,CAAC,iBAAiB,CAAC;SAC/D;KACF,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAY;IAC5C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,
|
|
1
|
+
{"version":3,"file":"normalize.js","sourceRoot":"","sources":["../../src/utils/normalize.ts"],"names":[],"mappings":"AAaA;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CAAC,WAAmB;IACvD,IAAI,IAAI,CAAC;IACT,IAAI,CAAC;QACH,IAAI,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;IACxC,CAAC;IAAC,MAAM,CAAC;QACP,yDAAyD;QACzD,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,MAAM,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC;IAEhD,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACvB,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,GAAG,IAAI;QACP,MAAM,EAAE;YACN,GAAG,IAAI,CAAC,MAAM;YACd,iBAAiB,EAAE,wBAAwB,CAAC,iBAAiB,CAAC;SAC/D;KACF,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAY;IAC5C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC;AAED;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,OAAY;IAC5C,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7B,OAAO,KAAK,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;IACjC,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\ntype EIP712Domain = {\n verifyingContract: Hex;\n};\n\ntype SignTypedMessageDataV3V4 = {\n types: Record<string, unknown>;\n domain: EIP712Domain;\n primaryType: string;\n message: unknown;\n};\n\n/**\n * Normalizes the messageData for the eth_signTypedData\n *\n * @param messageData - The messageData to normalize.\n * @returns The normalized messageData.\n */\nexport function normalizeTypedMessage(messageData: string): string {\n let data;\n try {\n data = parseTypedMessage(messageData);\n } catch {\n // Ignore normalization errors and pass the message as is\n return messageData;\n }\n\n const { verifyingContract } = data.domain ?? {};\n\n if (!verifyingContract) {\n return messageData;\n }\n\n return JSON.stringify({\n ...data,\n domain: {\n ...data.domain,\n verifyingContract: normalizeContractAddress(verifyingContract),\n },\n });\n}\n\n/**\n * Parses the messageData to obtain the data object for EIP712 normalization\n *\n * @param data - The messageData to parse.\n * @returns The data object for EIP712 normalization.\n */\nexport function parseTypedMessage(data: string): SignTypedMessageDataV3V4 {\n if (typeof data !== 'string') {\n return data;\n }\n\n return JSON.parse(data);\n}\n\n/**\n * Normalizes the address to standard hexadecimal format\n *\n * @param address - The address to normalize.\n * @returns The normalized address.\n */\nfunction normalizeContractAddress(address: Hex): Hex {\n if (address.startsWith('0X')) {\n return `0x${address.slice(2)}`;\n }\n return address;\n}\n"]}
|
|
@@ -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;AAE3C,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAG5D;;;;;;;;;;GAUG;AACH,wBAAsB,6BAA6B,CACjD,OAAO,EAAE,GAAG,EACZ,OAAO,EAAE,uBAAuB,EAChC,EAAE,WAAW,EAAE,EAAE;IAAE,WAAW,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAAA;CAAE,GACtE,OAAO,CAAC,GAAG,CAAC,CA0Bd;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,UAAU,EACvC,KAAK,EAAE,OAAO,GAAG,UAAU,EAC3B,MAAM,EAAE,MAAM,CAAC,UAAU,CAAC,GACzB,OAAO,CAAC,KAAK,IAAI,UAAU,CAQ7B;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAGrD;AAmBD,eAAO,MAAM,8BAA8B,YACzC,WAAW,EACX,aAAa,EACb,W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,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(\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 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,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,CAAC;QAC5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D,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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/eth-json-rpc-middleware",
|
|
3
|
-
"version": "25.0.0-preview-
|
|
3
|
+
"version": "25.0.0-preview-ff2ab0583",
|
|
4
4
|
"description": "Ethereum-related json-rpc-engine middleware",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
"@types/jest": "^30.0.0",
|
|
66
66
|
"@typescript/native": "npm:typescript@^7.0.2",
|
|
67
67
|
"deep-freeze-strict": "^1.1.1",
|
|
68
|
-
"deepmerge": "^4.
|
|
68
|
+
"deepmerge": "^4.3.1",
|
|
69
69
|
"jest": "^30.4.2",
|
|
70
70
|
"rimraf": "^6.1.3",
|
|
71
71
|
"ts-jest": "^29.4.12",
|