@metamask-previews/eth-json-rpc-middleware 23.1.3-preview-a511f243f → 23.1.3-preview-56569acf0
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 +1 -0
- package/dist/index.cjs +3 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -0
- package/dist/index.mjs.map +1 -1
- package/dist/utils/validation.cjs +86 -1
- package/dist/utils/validation.cjs.map +1 -1
- package/dist/utils/validation.d.cts +35 -0
- package/dist/utils/validation.d.cts.map +1 -1
- package/dist/utils/validation.d.mts +35 -0
- package/dist/utils/validation.d.mts.map +1 -1
- package/dist/utils/validation.mjs +84 -0
- package/dist/utils/validation.mjs.map +1 -1
- package/dist/wallet.cjs +2 -0
- package/dist/wallet.cjs.map +1 -1
- package/dist/wallet.d.cts.map +1 -1
- package/dist/wallet.d.mts.map +1 -1
- package/dist/wallet.mjs +3 -1
- package/dist/wallet.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
### Changed
|
|
11
11
|
|
|
12
|
+
- Add strict validation for `eth_sendTransaction` and `eth_signTransaction` params — reject requests whose params contain extraneous top-level keys or nest beyond `MAX_TRANSACTION_PARAM_DEPTH` (10). Prevents downstream normalization / PPOM WASM from crashing on deeply-nested junk fields and silently bypassing security scans. ([#9482](https://github.com/MetaMask/core/pull/9482))
|
|
12
13
|
- Bump `@metamask/utils` from `^11.9.0` to `^11.11.0` ([#9074](https://github.com/MetaMask/core/pull/9074))
|
|
13
14
|
- Bump `@metamask/json-rpc-engine` from `^10.2.4` to `^10.5.0` ([#8661](https://github.com/MetaMask/core/pull/8661), [#8746](https://github.com/MetaMask/core/pull/8746), [#8753](https://github.com/MetaMask/core/pull/8753))
|
|
14
15
|
- Bump `@metamask/message-manager` from `^14.1.1` to `^14.1.2` ([#8755](https://github.com/MetaMask/core/pull/8755))
|
package/dist/index.cjs
CHANGED
|
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.GetSupportedExecutionPermissionsResultStruct = exports.SupportedExecutionPermissionConfigStruct = exports.GetGrantedExecutionPermissionsResultStruct = exports.GrantedExecutionPermissionStruct = exports.createFetchMiddleware = void 0;
|
|
17
|
+
exports.validateTransactionParams = exports.GetSupportedExecutionPermissionsResultStruct = exports.SupportedExecutionPermissionConfigStruct = exports.GetGrantedExecutionPermissionsResultStruct = exports.GrantedExecutionPermissionStruct = exports.createFetchMiddleware = void 0;
|
|
18
18
|
__exportStar(require("./block-cache.cjs"), exports);
|
|
19
19
|
__exportStar(require("./block-ref-rewrite.cjs"), exports);
|
|
20
20
|
__exportStar(require("./block-ref.cjs"), exports);
|
|
@@ -30,5 +30,7 @@ Object.defineProperty(exports, "SupportedExecutionPermissionConfigStruct", { enu
|
|
|
30
30
|
Object.defineProperty(exports, "GetSupportedExecutionPermissionsResultStruct", { enumerable: true, get: function () { return wallet_get_supported_execution_permissions_1.GetSupportedExecutionPermissionsResultStruct; } });
|
|
31
31
|
__exportStar(require("./providerAsMiddleware.cjs"), exports);
|
|
32
32
|
__exportStar(require("./retryOnEmpty.cjs"), exports);
|
|
33
|
+
var validation_1 = require("./utils/validation.cjs");
|
|
34
|
+
Object.defineProperty(exports, "validateTransactionParams", { enumerable: true, get: function () { return validation_1.validateTransactionParams; } });
|
|
33
35
|
__exportStar(require("./wallet.cjs"), exports);
|
|
34
36
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,oDAA8B;AAC9B,0DAAoC;AACpC,kDAA4B;AAC5B,gEAA0C;AAC1C,qCAAgD;AAAvC,8GAAA,qBAAqB,OAAA;AAC9B,uDAAiC;AAiBjC,mHAG4D;AAF1D,4JAAA,gCAAgC,OAAA;AAChC,sKAAA,0CAA0C,OAAA;AAO5C,uHAG8D;AAF5D,sKAAA,wCAAwC,OAAA;AACxC,0KAAA,4CAA4C,OAAA;AAE9C,6DAAuC;AACvC,qDAA+B;AAC/B,+CAAyB","sourcesContent":["export * from './block-cache';\nexport * from './block-ref-rewrite';\nexport * from './block-ref';\nexport * from './block-tracker-inspector';\nexport { createFetchMiddleware } from './fetch';\nexport * from './inflight-cache';\nexport type {\n PermissionDependency,\n RequestExecutionPermissionsRequestParams,\n RequestExecutionPermissionsResult,\n ProcessRequestExecutionPermissionsHook,\n} from './methods/wallet-request-execution-permissions';\nexport type {\n ProcessRevokeExecutionPermissionHook,\n RevokeExecutionPermissionRequestParams,\n RevokeExecutionPermissionResult,\n} from './methods/wallet-revoke-execution-permission';\nexport type {\n GrantedExecutionPermission,\n GetGrantedExecutionPermissionsResult,\n ProcessGetGrantedExecutionPermissionsHook,\n} from './methods/wallet-get-granted-execution-permissions';\nexport {\n GrantedExecutionPermissionStruct,\n GetGrantedExecutionPermissionsResultStruct,\n} from './methods/wallet-get-granted-execution-permissions';\nexport type {\n SupportedExecutionPermissionConfig,\n GetSupportedExecutionPermissionsResult,\n ProcessGetSupportedExecutionPermissionsHook,\n} from './methods/wallet-get-supported-execution-permissions';\nexport {\n SupportedExecutionPermissionConfigStruct,\n GetSupportedExecutionPermissionsResultStruct,\n} from './methods/wallet-get-supported-execution-permissions';\nexport * from './providerAsMiddleware';\nexport * from './retryOnEmpty';\nexport * from './wallet';\n"]}
|
|
1
|
+
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,oDAA8B;AAC9B,0DAAoC;AACpC,kDAA4B;AAC5B,gEAA0C;AAC1C,qCAAgD;AAAvC,8GAAA,qBAAqB,OAAA;AAC9B,uDAAiC;AAiBjC,mHAG4D;AAF1D,4JAAA,gCAAgC,OAAA;AAChC,sKAAA,0CAA0C,OAAA;AAO5C,uHAG8D;AAF5D,sKAAA,wCAAwC,OAAA;AACxC,0KAAA,4CAA4C,OAAA;AAE9C,6DAAuC;AACvC,qDAA+B;AAC/B,qDAA+D;AAAtD,uHAAA,yBAAyB,OAAA;AAClC,+CAAyB","sourcesContent":["export * from './block-cache';\nexport * from './block-ref-rewrite';\nexport * from './block-ref';\nexport * from './block-tracker-inspector';\nexport { createFetchMiddleware } from './fetch';\nexport * from './inflight-cache';\nexport type {\n PermissionDependency,\n RequestExecutionPermissionsRequestParams,\n RequestExecutionPermissionsResult,\n ProcessRequestExecutionPermissionsHook,\n} from './methods/wallet-request-execution-permissions';\nexport type {\n ProcessRevokeExecutionPermissionHook,\n RevokeExecutionPermissionRequestParams,\n RevokeExecutionPermissionResult,\n} from './methods/wallet-revoke-execution-permission';\nexport type {\n GrantedExecutionPermission,\n GetGrantedExecutionPermissionsResult,\n ProcessGetGrantedExecutionPermissionsHook,\n} from './methods/wallet-get-granted-execution-permissions';\nexport {\n GrantedExecutionPermissionStruct,\n GetGrantedExecutionPermissionsResultStruct,\n} from './methods/wallet-get-granted-execution-permissions';\nexport type {\n SupportedExecutionPermissionConfig,\n GetSupportedExecutionPermissionsResult,\n ProcessGetSupportedExecutionPermissionsHook,\n} from './methods/wallet-get-supported-execution-permissions';\nexport {\n SupportedExecutionPermissionConfigStruct,\n GetSupportedExecutionPermissionsResultStruct,\n} from './methods/wallet-get-supported-execution-permissions';\nexport * from './providerAsMiddleware';\nexport * from './retryOnEmpty';\nexport { validateTransactionParams } from './utils/validation';\nexport * from './wallet';\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -12,5 +12,6 @@ export type { SupportedExecutionPermissionConfig, GetSupportedExecutionPermissio
|
|
|
12
12
|
export { SupportedExecutionPermissionConfigStruct, GetSupportedExecutionPermissionsResultStruct, } from "./methods/wallet-get-supported-execution-permissions.cjs";
|
|
13
13
|
export * from "./providerAsMiddleware.cjs";
|
|
14
14
|
export * from "./retryOnEmpty.cjs";
|
|
15
|
+
export { validateTransactionParams } from "./utils/validation.cjs";
|
|
15
16
|
export * from "./wallet.cjs";
|
|
16
17
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kCAA8B;AAC9B,wCAAoC;AACpC,gCAA4B;AAC5B,8CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAChD,qCAAiC;AACjC,YAAY,EACV,oBAAoB,EACpB,wCAAwC,EACxC,iCAAiC,EACjC,sCAAsC,GACvC,2DAAuD;AACxD,YAAY,EACV,oCAAoC,EACpC,sCAAsC,EACtC,+BAA+B,GAChC,yDAAqD;AACtD,YAAY,EACV,0BAA0B,EAC1B,oCAAoC,EACpC,yCAAyC,GAC1C,+DAA2D;AAC5D,OAAO,EACL,gCAAgC,EAChC,0CAA0C,GAC3C,+DAA2D;AAC5D,YAAY,EACV,kCAAkC,EAClC,sCAAsC,EACtC,2CAA2C,GAC5C,iEAA6D;AAC9D,OAAO,EACL,wCAAwC,EACxC,4CAA4C,GAC7C,iEAA6D;AAC9D,2CAAuC;AACvC,mCAA+B;AAC/B,6BAAyB"}
|
|
1
|
+
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kCAA8B;AAC9B,wCAAoC;AACpC,gCAA4B;AAC5B,8CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAChD,qCAAiC;AACjC,YAAY,EACV,oBAAoB,EACpB,wCAAwC,EACxC,iCAAiC,EACjC,sCAAsC,GACvC,2DAAuD;AACxD,YAAY,EACV,oCAAoC,EACpC,sCAAsC,EACtC,+BAA+B,GAChC,yDAAqD;AACtD,YAAY,EACV,0BAA0B,EAC1B,oCAAoC,EACpC,yCAAyC,GAC1C,+DAA2D;AAC5D,OAAO,EACL,gCAAgC,EAChC,0CAA0C,GAC3C,+DAA2D;AAC5D,YAAY,EACV,kCAAkC,EAClC,sCAAsC,EACtC,2CAA2C,GAC5C,iEAA6D;AAC9D,OAAO,EACL,wCAAwC,EACxC,4CAA4C,GAC7C,iEAA6D;AAC9D,2CAAuC;AACvC,mCAA+B;AAC/B,OAAO,EAAE,yBAAyB,EAAE,+BAA2B;AAC/D,6BAAyB"}
|
package/dist/index.d.mts
CHANGED
|
@@ -12,5 +12,6 @@ export type { SupportedExecutionPermissionConfig, GetSupportedExecutionPermissio
|
|
|
12
12
|
export { SupportedExecutionPermissionConfigStruct, GetSupportedExecutionPermissionsResultStruct, } from "./methods/wallet-get-supported-execution-permissions.mjs";
|
|
13
13
|
export * from "./providerAsMiddleware.mjs";
|
|
14
14
|
export * from "./retryOnEmpty.mjs";
|
|
15
|
+
export { validateTransactionParams } from "./utils/validation.mjs";
|
|
15
16
|
export * from "./wallet.mjs";
|
|
16
17
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kCAA8B;AAC9B,wCAAoC;AACpC,gCAA4B;AAC5B,8CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAChD,qCAAiC;AACjC,YAAY,EACV,oBAAoB,EACpB,wCAAwC,EACxC,iCAAiC,EACjC,sCAAsC,GACvC,2DAAuD;AACxD,YAAY,EACV,oCAAoC,EACpC,sCAAsC,EACtC,+BAA+B,GAChC,yDAAqD;AACtD,YAAY,EACV,0BAA0B,EAC1B,oCAAoC,EACpC,yCAAyC,GAC1C,+DAA2D;AAC5D,OAAO,EACL,gCAAgC,EAChC,0CAA0C,GAC3C,+DAA2D;AAC5D,YAAY,EACV,kCAAkC,EAClC,sCAAsC,EACtC,2CAA2C,GAC5C,iEAA6D;AAC9D,OAAO,EACL,wCAAwC,EACxC,4CAA4C,GAC7C,iEAA6D;AAC9D,2CAAuC;AACvC,mCAA+B;AAC/B,6BAAyB"}
|
|
1
|
+
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kCAA8B;AAC9B,wCAAoC;AACpC,gCAA4B;AAC5B,8CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAChD,qCAAiC;AACjC,YAAY,EACV,oBAAoB,EACpB,wCAAwC,EACxC,iCAAiC,EACjC,sCAAsC,GACvC,2DAAuD;AACxD,YAAY,EACV,oCAAoC,EACpC,sCAAsC,EACtC,+BAA+B,GAChC,yDAAqD;AACtD,YAAY,EACV,0BAA0B,EAC1B,oCAAoC,EACpC,yCAAyC,GAC1C,+DAA2D;AAC5D,OAAO,EACL,gCAAgC,EAChC,0CAA0C,GAC3C,+DAA2D;AAC5D,YAAY,EACV,kCAAkC,EAClC,sCAAsC,EACtC,2CAA2C,GAC5C,iEAA6D;AAC9D,OAAO,EACL,wCAAwC,EACxC,4CAA4C,GAC7C,iEAA6D;AAC9D,2CAAuC;AACvC,mCAA+B;AAC/B,OAAO,EAAE,yBAAyB,EAAE,+BAA2B;AAC/D,6BAAyB"}
|
package/dist/index.mjs
CHANGED
|
@@ -8,5 +8,6 @@ export { GrantedExecutionPermissionStruct, GetGrantedExecutionPermissionsResultS
|
|
|
8
8
|
export { SupportedExecutionPermissionConfigStruct, GetSupportedExecutionPermissionsResultStruct } from "./methods/wallet-get-supported-execution-permissions.mjs";
|
|
9
9
|
export * from "./providerAsMiddleware.mjs";
|
|
10
10
|
export * from "./retryOnEmpty.mjs";
|
|
11
|
+
export { validateTransactionParams } from "./utils/validation.mjs";
|
|
11
12
|
export * from "./wallet.mjs";
|
|
12
13
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kCAA8B;AAC9B,wCAAoC;AACpC,gCAA4B;AAC5B,8CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAChD,qCAAiC;AAiBjC,OAAO,EACL,gCAAgC,EAChC,0CAA0C,EAC3C,+DAA2D;AAM5D,OAAO,EACL,wCAAwC,EACxC,4CAA4C,EAC7C,iEAA6D;AAC9D,2CAAuC;AACvC,mCAA+B;AAC/B,6BAAyB","sourcesContent":["export * from './block-cache';\nexport * from './block-ref-rewrite';\nexport * from './block-ref';\nexport * from './block-tracker-inspector';\nexport { createFetchMiddleware } from './fetch';\nexport * from './inflight-cache';\nexport type {\n PermissionDependency,\n RequestExecutionPermissionsRequestParams,\n RequestExecutionPermissionsResult,\n ProcessRequestExecutionPermissionsHook,\n} from './methods/wallet-request-execution-permissions';\nexport type {\n ProcessRevokeExecutionPermissionHook,\n RevokeExecutionPermissionRequestParams,\n RevokeExecutionPermissionResult,\n} from './methods/wallet-revoke-execution-permission';\nexport type {\n GrantedExecutionPermission,\n GetGrantedExecutionPermissionsResult,\n ProcessGetGrantedExecutionPermissionsHook,\n} from './methods/wallet-get-granted-execution-permissions';\nexport {\n GrantedExecutionPermissionStruct,\n GetGrantedExecutionPermissionsResultStruct,\n} from './methods/wallet-get-granted-execution-permissions';\nexport type {\n SupportedExecutionPermissionConfig,\n GetSupportedExecutionPermissionsResult,\n ProcessGetSupportedExecutionPermissionsHook,\n} from './methods/wallet-get-supported-execution-permissions';\nexport {\n SupportedExecutionPermissionConfigStruct,\n GetSupportedExecutionPermissionsResultStruct,\n} from './methods/wallet-get-supported-execution-permissions';\nexport * from './providerAsMiddleware';\nexport * from './retryOnEmpty';\nexport * from './wallet';\n"]}
|
|
1
|
+
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kCAA8B;AAC9B,wCAAoC;AACpC,gCAA4B;AAC5B,8CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAChD,qCAAiC;AAiBjC,OAAO,EACL,gCAAgC,EAChC,0CAA0C,EAC3C,+DAA2D;AAM5D,OAAO,EACL,wCAAwC,EACxC,4CAA4C,EAC7C,iEAA6D;AAC9D,2CAAuC;AACvC,mCAA+B;AAC/B,OAAO,EAAE,yBAAyB,EAAE,+BAA2B;AAC/D,6BAAyB","sourcesContent":["export * from './block-cache';\nexport * from './block-ref-rewrite';\nexport * from './block-ref';\nexport * from './block-tracker-inspector';\nexport { createFetchMiddleware } from './fetch';\nexport * from './inflight-cache';\nexport type {\n PermissionDependency,\n RequestExecutionPermissionsRequestParams,\n RequestExecutionPermissionsResult,\n ProcessRequestExecutionPermissionsHook,\n} from './methods/wallet-request-execution-permissions';\nexport type {\n ProcessRevokeExecutionPermissionHook,\n RevokeExecutionPermissionRequestParams,\n RevokeExecutionPermissionResult,\n} from './methods/wallet-revoke-execution-permission';\nexport type {\n GrantedExecutionPermission,\n GetGrantedExecutionPermissionsResult,\n ProcessGetGrantedExecutionPermissionsHook,\n} from './methods/wallet-get-granted-execution-permissions';\nexport {\n GrantedExecutionPermissionStruct,\n GetGrantedExecutionPermissionsResultStruct,\n} from './methods/wallet-get-granted-execution-permissions';\nexport type {\n SupportedExecutionPermissionConfig,\n GetSupportedExecutionPermissionsResult,\n ProcessGetSupportedExecutionPermissionsHook,\n} from './methods/wallet-get-supported-execution-permissions';\nexport {\n SupportedExecutionPermissionConfigStruct,\n GetSupportedExecutionPermissionsResultStruct,\n} from './methods/wallet-get-supported-execution-permissions';\nexport * from './providerAsMiddleware';\nexport * from './retryOnEmpty';\nexport { validateTransactionParams } from './utils/validation';\nexport * from './wallet';\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.validateTypedMessageKeys = exports.validateTypedDataForPrototypePollution = exports.validateTypedDataV1ForPrototypePollution = exports.DANGEROUS_PROTOTYPE_PROPERTIES = exports.resemblesAddress = exports.validateParams = exports.validateAndNormalizeKeyholder = void 0;
|
|
3
|
+
exports.validateTransactionParams = exports.MAX_TRANSACTION_PARAM_DEPTH = exports.ALLOWED_TRANSACTION_PARAM_KEYS = exports.validateTypedMessageKeys = exports.validateTypedDataForPrototypePollution = exports.validateTypedDataV1ForPrototypePollution = exports.DANGEROUS_PROTOTYPE_PROPERTIES = exports.resemblesAddress = exports.validateParams = exports.validateAndNormalizeKeyholder = void 0;
|
|
4
4
|
const eth_sig_util_1 = require("@metamask/eth-sig-util");
|
|
5
5
|
const rpc_errors_1 = require("@metamask/rpc-errors");
|
|
6
6
|
const superstruct_1 = require("@metamask/superstruct");
|
|
@@ -189,4 +189,89 @@ function validateTypedMessageKeys(data) {
|
|
|
189
189
|
}
|
|
190
190
|
}
|
|
191
191
|
exports.validateTypedMessageKeys = validateTypedMessageKeys;
|
|
192
|
+
/**
|
|
193
|
+
* Top-level keys explicitly permitted on `eth_sendTransaction` and
|
|
194
|
+
* `eth_signTransaction` params. Any additional top-level key causes the
|
|
195
|
+
* request to be rejected before it reaches downstream consumers such as PPOM
|
|
196
|
+
* or the Security Alerts API.
|
|
197
|
+
*
|
|
198
|
+
* Derived from the dapp-facing subset of `TransactionParams` in
|
|
199
|
+
* `@metamask/transaction-controller`. Internal-only fields
|
|
200
|
+
* (`estimateGasError`, `estimatedBaseFee`, `estimateSuggested`,
|
|
201
|
+
* `estimateUsed`, `gasUsed`) are intentionally omitted — dapps should not be
|
|
202
|
+
* able to inject them.
|
|
203
|
+
*/
|
|
204
|
+
exports.ALLOWED_TRANSACTION_PARAM_KEYS = new Set([
|
|
205
|
+
'accessList',
|
|
206
|
+
'authorizationList',
|
|
207
|
+
'chainId',
|
|
208
|
+
'data',
|
|
209
|
+
'from',
|
|
210
|
+
'gas',
|
|
211
|
+
'gasLimit',
|
|
212
|
+
'gasPrice',
|
|
213
|
+
'maxFeePerGas',
|
|
214
|
+
'maxPriorityFeePerGas',
|
|
215
|
+
'nonce',
|
|
216
|
+
'to',
|
|
217
|
+
'type',
|
|
218
|
+
'value',
|
|
219
|
+
]);
|
|
220
|
+
/**
|
|
221
|
+
* Maximum nesting depth permitted anywhere inside a transaction params
|
|
222
|
+
* object. Legitimate params (including `accessList` and
|
|
223
|
+
* `authorizationList`) are at most ~4 levels deep. Anything beyond this is
|
|
224
|
+
* treated as a denial-of-service attempt against downstream normalization
|
|
225
|
+
* (which recurses and can overflow the call stack in native/WASM code).
|
|
226
|
+
*/
|
|
227
|
+
exports.MAX_TRANSACTION_PARAM_DEPTH = 10;
|
|
228
|
+
/**
|
|
229
|
+
* Recursively checks that a value does not nest beyond
|
|
230
|
+
* `MAX_TRANSACTION_PARAM_DEPTH`.
|
|
231
|
+
*
|
|
232
|
+
* @param value - The value to check.
|
|
233
|
+
* @param depth - The current depth. Callers should pass `0`.
|
|
234
|
+
* @throws rpcErrors.invalidInput() if the value nests too deeply.
|
|
235
|
+
*/
|
|
236
|
+
function assertMaxDepth(value, depth) {
|
|
237
|
+
if (depth > exports.MAX_TRANSACTION_PARAM_DEPTH) {
|
|
238
|
+
throw rpc_errors_1.rpcErrors.invalidInput();
|
|
239
|
+
}
|
|
240
|
+
if (value === null || typeof value !== 'object') {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (Array.isArray(value)) {
|
|
244
|
+
for (const item of value) {
|
|
245
|
+
assertMaxDepth(item, depth + 1);
|
|
246
|
+
}
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
for (const key of Object.getOwnPropertyNames(value)) {
|
|
250
|
+
assertMaxDepth(value[key], depth + 1);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Validates that `eth_sendTransaction` / `eth_signTransaction` params contain
|
|
255
|
+
* only spec-defined top-level keys and no excessively-nested structures.
|
|
256
|
+
*
|
|
257
|
+
* This guards against malicious dapps attaching deeply-nested junk fields
|
|
258
|
+
* (e.g. `{ from, to, data, test: { b: { b: { b: /* ~1200 levels *\/ } } } }`)
|
|
259
|
+
* that would otherwise crash downstream normalization or PPOM WASM with a
|
|
260
|
+
* `RangeError: Maximum call stack size exceeded`, bypassing security checks.
|
|
261
|
+
*
|
|
262
|
+
* @param params - The transaction params object supplied by the dapp.
|
|
263
|
+
* @throws rpcErrors.invalidInput() if params is not a plain object, contains
|
|
264
|
+
* an extraneous top-level key, or nests beyond `MAX_TRANSACTION_PARAM_DEPTH`.
|
|
265
|
+
*/
|
|
266
|
+
function validateTransactionParams(params) {
|
|
267
|
+
if (params === null || typeof params !== 'object' || Array.isArray(params)) {
|
|
268
|
+
throw rpc_errors_1.rpcErrors.invalidInput();
|
|
269
|
+
}
|
|
270
|
+
const hasExtraneousKey = Object.keys(params).some((key) => !exports.ALLOWED_TRANSACTION_PARAM_KEYS.has(key));
|
|
271
|
+
if (hasExtraneousKey) {
|
|
272
|
+
throw rpc_errors_1.rpcErrors.invalidInput();
|
|
273
|
+
}
|
|
274
|
+
assertMaxDepth(params, 0);
|
|
275
|
+
}
|
|
276
|
+
exports.validateTransactionParams = validateTransactionParams;
|
|
192
277
|
//# sourceMappingURL=validation.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.cjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":";;;AAAA,yDAA8D;AAC9D,qDAAiE;AAEjE,uDAAiD;AAIjD,+CAAgD;AAEhD;;;;;;;;;;GAUG;AACI,KAAK,UAAU,6BAA6B,CACjD,OAAY,EACZ,OAA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AAC,YAAY,EAAE,CAAC;IACjC,CAAC;IAED,iHAAiH;IACjH,kGAAkG;IAClG,MAAM,EAAE,QAAQ,EAAE,GAAG,UAAoC,CAAC;IAC1D,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;YACtD,MAAM,sBAAS,CAAC,YAAY,EAAE,CAAC;QACjC,CAAC;QAED,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,QAGjC,CAAC;QAEF,IAAI,OAAO,aAAa,KAAK,QAAQ,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;YACpE,MAAM,sBAAS,CAAC,YAAY,EAAE,CAAC;QACjC,CAAC;QAED,+GAA+G;QAC/G,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACvC,MAAM,sBAAS,CAAC,YAAY,EAAE,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC;AApCD,4DAoCC","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 { validate } from '@metamask/superstruct';\nimport type { Hex } from '@metamask/utils';\n\nimport type { WalletMiddlewareContext } from '../wallet';\nimport { parseTypedMessage } from './normalize';\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"]}
|
|
1
|
+
{"version":3,"file":"validation.cjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":";;;AAAA,yDAA8D;AAC9D,qDAAiE;AAEjE,uDAAiD;AAIjD,+CAAgD;AAEhD;;;;;;;;;;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,EA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AACH,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,yBAAyB,CAAC,MAAe;IACvD,IAAI,MAAM,KAAK,IAAI,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC3E,MAAM,sBAAS,CAAC,YAAY,EAAE,CAAC;IACjC,CAAC;IAED,MAAM,gBAAgB,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,CAC/C,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,sCAA8B,CAAC,GAAG,CAAC,GAAG,CAAC,CAClD,CAAC;IAEF,IAAI,gBAAgB,EAAE,CAAC;QACrB,MAAM,sBAAS,CAAC,YAAY,EAAE,CAAC;IACjC,CAAC;IAED,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AAC5B,CAAC;AAdD,8DAcC","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 { validate } from '@metamask/superstruct';\nimport type { Hex } from '@metamask/utils';\n\nimport type { WalletMiddlewareContext } from '../wallet';\nimport { parseTypedMessage } from './normalize';\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/**\n * Top-level keys explicitly permitted on `eth_sendTransaction` and\n * `eth_signTransaction` params. Any additional top-level key causes the\n * request to be rejected before it reaches downstream consumers such as PPOM\n * or the Security Alerts API.\n *\n * Derived from the dapp-facing subset of `TransactionParams` in\n * `@metamask/transaction-controller`. Internal-only fields\n * (`estimateGasError`, `estimatedBaseFee`, `estimateSuggested`,\n * `estimateUsed`, `gasUsed`) are intentionally omitted — dapps should not be\n * able to inject them.\n */\nexport const ALLOWED_TRANSACTION_PARAM_KEYS = new Set<string>([\n 'accessList',\n 'authorizationList',\n 'chainId',\n 'data',\n 'from',\n 'gas',\n 'gasLimit',\n 'gasPrice',\n 'maxFeePerGas',\n 'maxPriorityFeePerGas',\n 'nonce',\n 'to',\n 'type',\n 'value',\n]);\n\n/**\n * Maximum nesting depth permitted anywhere inside a transaction params\n * object. Legitimate params (including `accessList` and\n * `authorizationList`) are at most ~4 levels deep. Anything beyond this is\n * treated as a denial-of-service attempt against downstream normalization\n * (which recurses and can overflow the call stack in native/WASM code).\n */\nexport const MAX_TRANSACTION_PARAM_DEPTH = 10;\n\n/**\n * Recursively checks that a value does not nest beyond\n * `MAX_TRANSACTION_PARAM_DEPTH`.\n *\n * @param value - The value to check.\n * @param depth - The current depth. Callers should pass `0`.\n * @throws rpcErrors.invalidInput() if the value nests too deeply.\n */\nfunction assertMaxDepth(value: unknown, depth: number): void {\n if (depth > MAX_TRANSACTION_PARAM_DEPTH) {\n throw rpcErrors.invalidInput();\n }\n\n if (value === null || typeof value !== 'object') {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n assertMaxDepth(item, depth + 1);\n }\n return;\n }\n\n for (const key of Object.getOwnPropertyNames(\n value as Record<string, unknown>,\n )) {\n assertMaxDepth((value as Record<string, unknown>)[key], depth + 1);\n }\n}\n\n/**\n * Validates that `eth_sendTransaction` / `eth_signTransaction` params contain\n * only spec-defined top-level keys and no excessively-nested structures.\n *\n * This guards against malicious dapps attaching deeply-nested junk fields\n * (e.g. `{ from, to, data, test: { b: { b: { b: /* ~1200 levels *\\/ } } } }`)\n * that would otherwise crash downstream normalization or PPOM WASM with a\n * `RangeError: Maximum call stack size exceeded`, bypassing security checks.\n *\n * @param params - The transaction params object supplied by the dapp.\n * @throws rpcErrors.invalidInput() if params is not a plain object, contains\n * an extraneous top-level key, or nests beyond `MAX_TRANSACTION_PARAM_DEPTH`.\n */\nexport function validateTransactionParams(params: unknown): void {\n if (params === null || typeof params !== 'object' || Array.isArray(params)) {\n throw rpcErrors.invalidInput();\n }\n\n const hasExtraneousKey = Object.keys(params).some(\n (key) => !ALLOWED_TRANSACTION_PARAM_KEYS.has(key),\n );\n\n if (hasExtraneousKey) {\n throw rpcErrors.invalidInput();\n }\n\n assertMaxDepth(params, 0);\n}\n"]}
|
|
@@ -57,4 +57,39 @@ export declare function validateTypedDataForPrototypePollution(data: string): vo
|
|
|
57
57
|
* @throws rpcErrors.invalidInput() if extraneous keys are detected.
|
|
58
58
|
*/
|
|
59
59
|
export declare function validateTypedMessageKeys(data: string): void;
|
|
60
|
+
/**
|
|
61
|
+
* Top-level keys explicitly permitted on `eth_sendTransaction` and
|
|
62
|
+
* `eth_signTransaction` params. Any additional top-level key causes the
|
|
63
|
+
* request to be rejected before it reaches downstream consumers such as PPOM
|
|
64
|
+
* or the Security Alerts API.
|
|
65
|
+
*
|
|
66
|
+
* Derived from the dapp-facing subset of `TransactionParams` in
|
|
67
|
+
* `@metamask/transaction-controller`. Internal-only fields
|
|
68
|
+
* (`estimateGasError`, `estimatedBaseFee`, `estimateSuggested`,
|
|
69
|
+
* `estimateUsed`, `gasUsed`) are intentionally omitted — dapps should not be
|
|
70
|
+
* able to inject them.
|
|
71
|
+
*/
|
|
72
|
+
export declare const ALLOWED_TRANSACTION_PARAM_KEYS: Set<string>;
|
|
73
|
+
/**
|
|
74
|
+
* Maximum nesting depth permitted anywhere inside a transaction params
|
|
75
|
+
* object. Legitimate params (including `accessList` and
|
|
76
|
+
* `authorizationList`) are at most ~4 levels deep. Anything beyond this is
|
|
77
|
+
* treated as a denial-of-service attempt against downstream normalization
|
|
78
|
+
* (which recurses and can overflow the call stack in native/WASM code).
|
|
79
|
+
*/
|
|
80
|
+
export declare const MAX_TRANSACTION_PARAM_DEPTH = 10;
|
|
81
|
+
/**
|
|
82
|
+
* Validates that `eth_sendTransaction` / `eth_signTransaction` params contain
|
|
83
|
+
* only spec-defined top-level keys and no excessively-nested structures.
|
|
84
|
+
*
|
|
85
|
+
* This guards against malicious dapps attaching deeply-nested junk fields
|
|
86
|
+
* (e.g. `{ from, to, data, test: { b: { b: { b: /* ~1200 levels *\/ } } } }`)
|
|
87
|
+
* that would otherwise crash downstream normalization or PPOM WASM with a
|
|
88
|
+
* `RangeError: Maximum call stack size exceeded`, bypassing security checks.
|
|
89
|
+
*
|
|
90
|
+
* @param params - The transaction params object supplied by the dapp.
|
|
91
|
+
* @throws rpcErrors.invalidInput() if params is not a plain object, contains
|
|
92
|
+
* an extraneous top-level key, or nests beyond `MAX_TRANSACTION_PARAM_DEPTH`.
|
|
93
|
+
*/
|
|
94
|
+
export declare function validateTransactionParams(params: unknown): void;
|
|
60
95
|
//# sourceMappingURL=validation.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.d.cts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAe,8BAA8B;AAEjE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAE3C,OAAO,KAAK,EAAE,uBAAuB,EAAE,sBAAkB;AAGzD;;;;;;;;;;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,oIAQjC,CAAC;AA0CX;;;;;;GAMG;AACH,wBAAgB,wCAAwC,CACtD,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAC9B,IAAI,CAaN;AAED;;;;;;GAMG;AACH,wBAAgB,sCAAsC,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAOzE;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAoC3D"}
|
|
1
|
+
{"version":3,"file":"validation.d.cts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAe,8BAA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idInput() if extraneous keys are detected.
|
|
58
58
|
*/
|
|
59
59
|
export declare function validateTypedMessageKeys(data: string): void;
|
|
60
|
+
/**
|
|
61
|
+
* Top-level keys explicitly permitted on `eth_sendTransaction` and
|
|
62
|
+
* `eth_signTransaction` params. Any additional top-level key causes the
|
|
63
|
+
* request to be rejected before it reaches downstream consumers such as PPOM
|
|
64
|
+
* or the Security Alerts API.
|
|
65
|
+
*
|
|
66
|
+
* Derived from the dapp-facing subset of `TransactionParams` in
|
|
67
|
+
* `@metamask/transaction-controller`. Internal-only fields
|
|
68
|
+
* (`estimateGasError`, `estimatedBaseFee`, `estimateSuggested`,
|
|
69
|
+
* `estimateUsed`, `gasUsed`) are intentionally omitted — dapps should not be
|
|
70
|
+
* able to inject them.
|
|
71
|
+
*/
|
|
72
|
+
export declare const ALLOWED_TRANSACTION_PARAM_KEYS: Set<string>;
|
|
73
|
+
/**
|
|
74
|
+
* Maximum nesting depth permitted anywhere inside a transaction params
|
|
75
|
+
* object. Legitimate params (including `accessList` and
|
|
76
|
+
* `authorizationList`) are at most ~4 levels deep. Anything beyond this is
|
|
77
|
+
* treated as a denial-of-service attempt against downstream normalization
|
|
78
|
+
* (which recurses and can overflow the call stack in native/WASM code).
|
|
79
|
+
*/
|
|
80
|
+
export declare const MAX_TRANSACTION_PARAM_DEPTH = 10;
|
|
81
|
+
/**
|
|
82
|
+
* Validates that `eth_sendTransaction` / `eth_signTransaction` params contain
|
|
83
|
+
* only spec-defined top-level keys and no excessively-nested structures.
|
|
84
|
+
*
|
|
85
|
+
* This guards against malicious dapps attaching deeply-nested junk fields
|
|
86
|
+
* (e.g. `{ from, to, data, test: { b: { b: { b: /* ~1200 levels *\/ } } } }`)
|
|
87
|
+
* that would otherwise crash downstream normalization or PPOM WASM with a
|
|
88
|
+
* `RangeError: Maximum call stack size exceeded`, bypassing security checks.
|
|
89
|
+
*
|
|
90
|
+
* @param params - The transaction params object supplied by the dapp.
|
|
91
|
+
* @throws rpcErrors.invalidInput() if params is not a plain object, contains
|
|
92
|
+
* an extraneous top-level key, or nests beyond `MAX_TRANSACTION_PARAM_DEPTH`.
|
|
93
|
+
*/
|
|
94
|
+
export declare function validateTransactionParams(params: unknown): void;
|
|
60
95
|
//# sourceMappingURL=validation.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.d.mts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAe,8BAA8B;AAEjE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAE3C,OAAO,KAAK,EAAE,uBAAuB,EAAE,sBAAkB;AAGzD;;;;;;;;;;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,oIAQjC,CAAC;AA0CX;;;;;;GAMG;AACH,wBAAgB,wCAAwC,CACtD,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAC9B,IAAI,CAaN;AAED;;;;;;GAMG;AACH,wBAAgB,sCAAsC,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAOzE;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,I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yB,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI,CAc/D"}
|
|
@@ -180,4 +180,88 @@ export function validateTypedMessageKeys(data) {
|
|
|
180
180
|
}
|
|
181
181
|
}
|
|
182
182
|
}
|
|
183
|
+
/**
|
|
184
|
+
* Top-level keys explicitly permitted on `eth_sendTransaction` and
|
|
185
|
+
* `eth_signTransaction` params. Any additional top-level key causes the
|
|
186
|
+
* request to be rejected before it reaches downstream consumers such as PPOM
|
|
187
|
+
* or the Security Alerts API.
|
|
188
|
+
*
|
|
189
|
+
* Derived from the dapp-facing subset of `TransactionParams` in
|
|
190
|
+
* `@metamask/transaction-controller`. Internal-only fields
|
|
191
|
+
* (`estimateGasError`, `estimatedBaseFee`, `estimateSuggested`,
|
|
192
|
+
* `estimateUsed`, `gasUsed`) are intentionally omitted — dapps should not be
|
|
193
|
+
* able to inject them.
|
|
194
|
+
*/
|
|
195
|
+
export const ALLOWED_TRANSACTION_PARAM_KEYS = new Set([
|
|
196
|
+
'accessList',
|
|
197
|
+
'authorizationList',
|
|
198
|
+
'chainId',
|
|
199
|
+
'data',
|
|
200
|
+
'from',
|
|
201
|
+
'gas',
|
|
202
|
+
'gasLimit',
|
|
203
|
+
'gasPrice',
|
|
204
|
+
'maxFeePerGas',
|
|
205
|
+
'maxPriorityFeePerGas',
|
|
206
|
+
'nonce',
|
|
207
|
+
'to',
|
|
208
|
+
'type',
|
|
209
|
+
'value',
|
|
210
|
+
]);
|
|
211
|
+
/**
|
|
212
|
+
* Maximum nesting depth permitted anywhere inside a transaction params
|
|
213
|
+
* object. Legitimate params (including `accessList` and
|
|
214
|
+
* `authorizationList`) are at most ~4 levels deep. Anything beyond this is
|
|
215
|
+
* treated as a denial-of-service attempt against downstream normalization
|
|
216
|
+
* (which recurses and can overflow the call stack in native/WASM code).
|
|
217
|
+
*/
|
|
218
|
+
export const MAX_TRANSACTION_PARAM_DEPTH = 10;
|
|
219
|
+
/**
|
|
220
|
+
* Recursively checks that a value does not nest beyond
|
|
221
|
+
* `MAX_TRANSACTION_PARAM_DEPTH`.
|
|
222
|
+
*
|
|
223
|
+
* @param value - The value to check.
|
|
224
|
+
* @param depth - The current depth. Callers should pass `0`.
|
|
225
|
+
* @throws rpcErrors.invalidInput() if the value nests too deeply.
|
|
226
|
+
*/
|
|
227
|
+
function assertMaxDepth(value, depth) {
|
|
228
|
+
if (depth > MAX_TRANSACTION_PARAM_DEPTH) {
|
|
229
|
+
throw rpcErrors.invalidInput();
|
|
230
|
+
}
|
|
231
|
+
if (value === null || typeof value !== 'object') {
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (Array.isArray(value)) {
|
|
235
|
+
for (const item of value) {
|
|
236
|
+
assertMaxDepth(item, depth + 1);
|
|
237
|
+
}
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
for (const key of Object.getOwnPropertyNames(value)) {
|
|
241
|
+
assertMaxDepth(value[key], depth + 1);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Validates that `eth_sendTransaction` / `eth_signTransaction` params contain
|
|
246
|
+
* only spec-defined top-level keys and no excessively-nested structures.
|
|
247
|
+
*
|
|
248
|
+
* This guards against malicious dapps attaching deeply-nested junk fields
|
|
249
|
+
* (e.g. `{ from, to, data, test: { b: { b: { b: /* ~1200 levels *\/ } } } }`)
|
|
250
|
+
* that would otherwise crash downstream normalization or PPOM WASM with a
|
|
251
|
+
* `RangeError: Maximum call stack size exceeded`, bypassing security checks.
|
|
252
|
+
*
|
|
253
|
+
* @param params - The transaction params object supplied by the dapp.
|
|
254
|
+
* @throws rpcErrors.invalidInput() if params is not a plain object, contains
|
|
255
|
+
* an extraneous top-level key, or nests beyond `MAX_TRANSACTION_PARAM_DEPTH`.
|
|
256
|
+
*/
|
|
257
|
+
export function validateTransactionParams(params) {
|
|
258
|
+
if (params === null || typeof params !== 'object' || Array.isArray(params)) {
|
|
259
|
+
throw rpcErrors.invalidInput();
|
|
260
|
+
}
|
|
261
|
+
const hasExtraneousKey = Object.keys(params).some((key) => !ALLOWED_TRANSACTION_PARAM_KEYS.has(key));
|
|
262
|
+
if (hasExtraneousKey) {
|
|
263
|
+
throw rpcErrors.invalidInput();
|
|
264
|
+
}
|
|
265
|
+
assertMaxDepth(params, 0);
|
|
266
|
+
}
|
|
183
267
|
//# sourceMappingURL=validation.mjs.map
|
|
@@ -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,EAAE,QAAQ,EAAE,8BAA8B;AAIjD,OAAO,EAAE,iBAAiB,EAAE,wBAAoB;AAEhD;;;;;;;;;;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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/eth-sig-util';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { Struct, StructError } from '@metamask/superstruct';\nimport { validate } from '@metamask/superstruct';\nimport type { Hex } from '@metamask/utils';\n\nimport type { WalletMiddlewareContext } from '../wallet';\nimport { parseTypedMessage } from './normalize';\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"]}
|
|
1
|
+
{"version":3,"file":"validation.mjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":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nimport type { Struct, StructError } from '@metamask/superstruct';\nimport { validate } from '@metamask/superstruct';\nimport type { Hex } from '@metamask/utils';\n\nimport type { WalletMiddlewareContext } from '../wallet';\nimport { parseTypedMessage } from './normalize';\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/**\n * Top-level keys explicitly permitted on `eth_sendTransaction` and\n * `eth_signTransaction` params. Any additional top-level key causes the\n * request to be rejected before it reaches downstream consumers such as PPOM\n * or the Security Alerts API.\n *\n * Derived from the dapp-facing subset of `TransactionParams` in\n * `@metamask/transaction-controller`. Internal-only fields\n * (`estimateGasError`, `estimatedBaseFee`, `estimateSuggested`,\n * `estimateUsed`, `gasUsed`) are intentionally omitted — dapps should not be\n * able to inject them.\n */\nexport const ALLOWED_TRANSACTION_PARAM_KEYS = new Set<string>([\n 'accessList',\n 'authorizationList',\n 'chainId',\n 'data',\n 'from',\n 'gas',\n 'gasLimit',\n 'gasPrice',\n 'maxFeePerGas',\n 'maxPriorityFeePerGas',\n 'nonce',\n 'to',\n 'type',\n 'value',\n]);\n\n/**\n * Maximum nesting depth permitted anywhere inside a transaction params\n * object. Legitimate params (including `accessList` and\n * `authorizationList`) are at most ~4 levels deep. Anything beyond this is\n * treated as a denial-of-service attempt against downstream normalization\n * (which recurses and can overflow the call stack in native/WASM code).\n */\nexport const MAX_TRANSACTION_PARAM_DEPTH = 10;\n\n/**\n * Recursively checks that a value does not nest beyond\n * `MAX_TRANSACTION_PARAM_DEPTH`.\n *\n * @param value - The value to check.\n * @param depth - The current depth. Callers should pass `0`.\n * @throws rpcErrors.invalidInput() if the value nests too deeply.\n */\nfunction assertMaxDepth(value: unknown, depth: number): void {\n if (depth > MAX_TRANSACTION_PARAM_DEPTH) {\n throw rpcErrors.invalidInput();\n }\n\n if (value === null || typeof value !== 'object') {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n assertMaxDepth(item, depth + 1);\n }\n return;\n }\n\n for (const key of Object.getOwnPropertyNames(\n value as Record<string, unknown>,\n )) {\n assertMaxDepth((value as Record<string, unknown>)[key], depth + 1);\n }\n}\n\n/**\n * Validates that `eth_sendTransaction` / `eth_signTransaction` params contain\n * only spec-defined top-level keys and no excessively-nested structures.\n *\n * This guards against malicious dapps attaching deeply-nested junk fields\n * (e.g. `{ from, to, data, test: { b: { b: { b: /* ~1200 levels *\\/ } } } }`)\n * that would otherwise crash downstream normalization or PPOM WASM with a\n * `RangeError: Maximum call stack size exceeded`, bypassing security checks.\n *\n * @param params - The transaction params object supplied by the dapp.\n * @throws rpcErrors.invalidInput() if params is not a plain object, contains\n * an extraneous top-level key, or nests beyond `MAX_TRANSACTION_PARAM_DEPTH`.\n */\nexport function validateTransactionParams(params: unknown): void {\n if (params === null || typeof params !== 'object' || Array.isArray(params)) {\n throw rpcErrors.invalidInput();\n }\n\n const hasExtraneousKey = Object.keys(params).some(\n (key) => !ALLOWED_TRANSACTION_PARAM_KEYS.has(key),\n );\n\n if (hasExtraneousKey) {\n throw rpcErrors.invalidInput();\n }\n\n assertMaxDepth(params, 0);\n}\n"]}
|
package/dist/wallet.cjs
CHANGED
|
@@ -134,6 +134,7 @@ function createWalletMiddleware({ getAccounts, processDecryptMessage, processEnc
|
|
|
134
134
|
throw rpc_errors_1.rpcErrors.invalidInput();
|
|
135
135
|
}
|
|
136
136
|
const params = request.params[0];
|
|
137
|
+
(0, validation_1.validateTransactionParams)(params);
|
|
137
138
|
const txParams = {
|
|
138
139
|
...params,
|
|
139
140
|
// Not using nullish coalescing, since `params` may be `null`.
|
|
@@ -160,6 +161,7 @@ function createWalletMiddleware({ getAccounts, processDecryptMessage, processEnc
|
|
|
160
161
|
throw rpc_errors_1.rpcErrors.invalidInput();
|
|
161
162
|
}
|
|
162
163
|
const params = request.params[0];
|
|
164
|
+
(0, validation_1.validateTransactionParams)(params);
|
|
163
165
|
const txParams = {
|
|
164
166
|
...params,
|
|
165
167
|
// Not using nullish coalescing, since `params` may be `null`.
|
package/dist/wallet.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wallet.cjs","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gEAAkD;AAMlD,qDAAwE;AAExE,qDAAiD;AACjD,2CAAoD;AAGpD,qHAAuH;AAEvH,yHAA2H;AAE3H,6GAAgH;AAEhH,yGAA4G;AAE5G,+CAAyD;AACzD,qDAA6E;AAC7E,uDAM4B;AAmF5B;;;;;;;;;;;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;QAEhC,OAAO,IAAA,0CAAiB,EAAC,OAAc,EAAE,OAAO,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC;IACrE,CAAC;AACH,CAAC;AAjeD,wDAieC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAAC,IAAY;IACvC,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,GAAG,IAAA,6BAAiB,EAAC,IAAI,CAAC,CAAC;IACvD,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,sBAAS,CAAC,YAAY,EAAE,CAAC;IACjC,CAAC;IAED,gCAAgC;IAChC,MAAM,QAAQ,GAAG,IAAA,gCAAuB,EAAC,WAAW,CAAC,CAAC;IAEtD,sDAAsD;IACtD,MAAM,mBAAmB,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC5C,IAAI,CAAC,mBAAmB,EAAE,CAAC;QACzB,MAAM,sBAAS,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,IAAA,6BAAiB,EAAC,IAAI,CAAC,CAAC;IACvE,sEAAsE;IACtE,iEAAiE;IACjE,IACE,iBAAiB;QAChB,iBAA4B,KAAK,QAAQ;QAC1C,CAAC,IAAA,yBAAiB,EAAC,iBAAiB,CAAC,EACrC,CAAC;QACD,MAAM,sBAAS,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';\nimport type { ProcessGetGrantedExecutionPermissionsHook } from './methods/wallet-get-granted-execution-permissions';\nimport { createWalletGetSupportedExecutionPermissionsHandler } from './methods/wallet-get-supported-execution-permissions';\nimport type { ProcessGetSupportedExecutionPermissionsHook } from './methods/wallet-get-supported-execution-permissions';\nimport { createWalletRequestExecutionPermissionsHandler } from './methods/wallet-request-execution-permissions';\nimport type { ProcessRequestExecutionPermissionsHook } from './methods/wallet-request-execution-permissions';\nimport { createWalletRevokeExecutionPermissionHandler } from './methods/wallet-revoke-execution-permission';\nimport type { ProcessRevokeExecutionPermissionHook } from './methods/wallet-revoke-execution-permission';\nimport { stripArrayTypeIfPresent } from './utils/common';\nimport { normalizeTypedMessage, parseTypedMessage } from './utils/normalize';\nimport {\n resemblesAddress,\n validateAndNormalizeKeyholder as validateKeyholder,\n validateTypedDataForPrototypePollution,\n validateTypedDataV1ForPrototypePollution,\n validateTypedMessageKeys,\n} from './utils/validation';\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 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 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"]}
|
|
1
|
+
{"version":3,"file":"wallet.cjs","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gEAAkD;AAMlD,qDAAwE;AAExE,qDAAi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/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';\nimport type { ProcessGetGrantedExecutionPermissionsHook } from './methods/wallet-get-granted-execution-permissions';\nimport { createWalletGetSupportedExecutionPermissionsHandler } from './methods/wallet-get-supported-execution-permissions';\nimport type { ProcessGetSupportedExecutionPermissionsHook } from './methods/wallet-get-supported-execution-permissions';\nimport { createWalletRequestExecutionPermissionsHandler } from './methods/wallet-request-execution-permissions';\nimport type { ProcessRequestExecutionPermissionsHook } from './methods/wallet-request-execution-permissions';\nimport { createWalletRevokeExecutionPermissionHandler } from './methods/wallet-revoke-execution-permission';\nimport type { ProcessRevokeExecutionPermissionHook } from './methods/wallet-revoke-execution-permission';\nimport { stripArrayTypeIfPresent } from './utils/common';\nimport { normalizeTypedMessage, parseTypedMessage } from './utils/normalize';\nimport {\n resemblesAddress,\n validateAndNormalizeKeyholder as validateKeyholder,\n validateTransactionParams,\n validateTypedDataForPrototypePollution,\n validateTypedDataV1ForPrototypePollution,\n validateTypedMessageKeys,\n} from './utils/validation';\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/dist/wallet.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wallet.d.cts","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EACjB,qCAAqC;AAEtC,OAAO,KAAK,EAAE,cAAc,EAAE,kCAAkC;AAGhE,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAO,wBAAwB;AAGjE,OAAO,KAAK,EAAE,yCAAyC,EAAE,+DAA2D;AAEpH,OAAO,KAAK,EAAE,2CAA2C,EAAE,iEAA6D;AAExH,OAAO,KAAK,EAAE,sCAAsC,EAAE,2DAAuD;AAE7G,OAAO,KAAK,EAAE,oCAAoC,EAAE,yDAAqD;
|
|
1
|
+
{"version":3,"file":"wallet.d.cts","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EACjB,qCAAqC;AAEtC,OAAO,KAAK,EAAE,cAAc,EAAE,kCAAkC;AAGhE,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAO,wBAAwB;AAGjE,OAAO,KAAK,EAAE,yCAAyC,EAAE,+DAA2D;AAEpH,OAAO,KAAK,EAAE,2CAA2C,EAAE,iEAA6D;AAExH,OAAO,KAAK,EAAE,sCAAsC,EAAE,2DAAuD;AAE7G,OAAO,KAAK,EAAE,oCAAoC,EAAE,yDAAqD;AAYzG,MAAM,MAAM,iBAAiB,GAAG;IAC9B,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,iBAAiB,GAAG;IAC9C,IAAI,EAAE,MAAM,CAAC;IACb,eAAe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|
-
{"version":3,"file":"wallet.d.mts","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EACjB,qCAAqC;AAEtC,OAAO,KAAK,EAAE,cAAc,EAAE,kCAAkC;AAGhE,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAO,wBAAwB;AAGjE,OAAO,KAAK,EAAE,yCAAyC,EAAE,+DAA2D;AAEpH,OAAO,KAAK,EAAE,2CAA2C,EAAE,iEAA6D;AAExH,OAAO,KAAK,EAAE,sCAAsC,EAAE,2DAAuD;AAE7G,OAAO,KAAK,EAAE,oCAAoC,EAAE,yDAAqD;
|
|
1
|
+
{"version":3,"file":"wallet.d.mts","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EACjB,qCAAqC;AAEtC,OAAO,KAAK,EAAE,cAAc,EAAE,kCAAkC;AAGhE,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAO,wBAAwB;AAGjE,OAAO,KAAK,EAAE,yCAAyC,EAAE,+DAA2D;AAEpH,OAAO,KAAK,EAAE,2CAA2C,EAAE,iEAA6D;AAExH,OAAO,KAAK,EAAE,sCAAsC,EAAE,2DAAuD;AAE7G,OAAO,KAAK,EAAE,oCAAoC,EAAE,yDAAqD;AAYzG,MAAM,MAAM,iBAAiB,GAAG;IAC9B,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,iBAAiB,GAAG;IAC9C,IAAI,EAAE,MAAM,CAAC;IACb,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG,aAAa,GAAG;IAC/C,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG,IAAI,CAAC,kBAAkB,EAAE,M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kBAAkB,EAC7B,GAAG,EAAE,cAAc,EACnB,OAAO,EAAE,uBAAuB,EAChC,OAAO,EAAE,MAAM,KACZ,OAAO,CAAC,MAAM,CAAC,CAAC;IACrB,kCAAkC,CAAC,EAAE,sCAAsC,CAAC;IAC5E,gCAAgC,CAAC,EAAE,oCAAoC,CAAC;IACxE,qCAAqC,CAAC,EAAE,yCAAyC,CAAC;IAClF,uCAAuC,CAAC,EAAE,2CAA2C,CAAC;CACvF,CAAC;AAEF,MAAM,MAAM,yBAAyB,GAAG;IACtC,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,qBAAqB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAC7C,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,uBAAuB,GACjC,iBAAiB,CAAC,yBAAyB,CAAC,CAAC;AAE/C,MAAM,MAAM,sBAAsB,GAAG,gBAAgB,CACnD,cAAc,EACd,uBAAuB,CACxB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,sBAAsB,CAAC,EACrC,WAAW,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.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { createWalletRequestExecutionPermissionsHandler } from "./methods/wallet
|
|
|
8
8
|
import { createWalletRevokeExecutionPermissionHandler } from "./methods/wallet-revoke-execution-permission.mjs";
|
|
9
9
|
import { stripArrayTypeIfPresent } from "./utils/common.mjs";
|
|
10
10
|
import { normalizeTypedMessage, parseTypedMessage } from "./utils/normalize.mjs";
|
|
11
|
-
import { resemblesAddress, validateAndNormalizeKeyholder as validateKeyholder, validateTypedDataForPrototypePollution, validateTypedDataV1ForPrototypePollution, validateTypedMessageKeys } from "./utils/validation.mjs";
|
|
11
|
+
import { resemblesAddress, validateAndNormalizeKeyholder as validateKeyholder, validateTransactionParams, validateTypedDataForPrototypePollution, validateTypedDataV1ForPrototypePollution, validateTypedMessageKeys } from "./utils/validation.mjs";
|
|
12
12
|
/**
|
|
13
13
|
* Creates a JSON-RPC middleware that handles "wallet"-related JSON-RPC methods.
|
|
14
14
|
* "Wallet" may have had a specific meaning at some point in the distant past,
|
|
@@ -108,6 +108,7 @@ export function createWalletMiddleware({ getAccounts, processDecryptMessage, pro
|
|
|
108
108
|
throw rpcErrors.invalidInput();
|
|
109
109
|
}
|
|
110
110
|
const params = request.params[0];
|
|
111
|
+
validateTransactionParams(params);
|
|
111
112
|
const txParams = {
|
|
112
113
|
...params,
|
|
113
114
|
// Not using nullish coalescing, since `params` may be `null`.
|
|
@@ -134,6 +135,7 @@ export function createWalletMiddleware({ getAccounts, processDecryptMessage, pro
|
|
|
134
135
|
throw rpcErrors.invalidInput();
|
|
135
136
|
}
|
|
136
137
|
const params = request.params[0];
|
|
138
|
+
validateTransactionParams(params);
|
|
137
139
|
const txParams = {
|
|
138
140
|
...params,
|
|
139
141
|
// Not using nullish coalescing, since `params` may be `null`.
|
package/dist/wallet.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wallet.mjs","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,+BAA+B;AAMlD,OAAO,EAAE,wBAAwB,EAAE,qCAAqC;AAExE,OAAO,EAAE,SAAS,EAAE,6BAA6B;AACjD,OAAO,EAAE,iBAAiB,EAAE,wBAAwB;AAGpD,OAAO,EAAE,iDAAiD,EAAE,+DAA2D;AAEvH,OAAO,EAAE,mDAAmD,EAAE,iEAA6D;AAE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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';\nimport type { ProcessGetGrantedExecutionPermissionsHook } from './methods/wallet-get-granted-execution-permissions';\nimport { createWalletGetSupportedExecutionPermissionsHandler } from './methods/wallet-get-supported-execution-permissions';\nimport type { ProcessGetSupportedExecutionPermissionsHook } from './methods/wallet-get-supported-execution-permissions';\nimport { createWalletRequestExecutionPermissionsHandler } from './methods/wallet-request-execution-permissions';\nimport type { ProcessRequestExecutionPermissionsHook } from './methods/wallet-request-execution-permissions';\nimport { createWalletRevokeExecutionPermissionHandler } from './methods/wallet-revoke-execution-permission';\nimport type { ProcessRevokeExecutionPermissionHook } from './methods/wallet-revoke-execution-permission';\nimport { stripArrayTypeIfPresent } from './utils/common';\nimport { normalizeTypedMessage, parseTypedMessage } from './utils/normalize';\nimport {\n resemblesAddress,\n validateAndNormalizeKeyholder as validateKeyholder,\n validateTypedDataForPrototypePollution,\n validateTypedDataV1ForPrototypePollution,\n validateTypedMessageKeys,\n} from './utils/validation';\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 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 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.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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';\nimport type { ProcessGetGrantedExecutionPermissionsHook } from './methods/wallet-get-granted-execution-permissions';\nimport { createWalletGetSupportedExecutionPermissionsHandler } from './methods/wallet-get-supported-execution-permissions';\nimport type { ProcessGetSupportedExecutionPermissionsHook } from './methods/wallet-get-supported-execution-permissions';\nimport { createWalletRequestExecutionPermissionsHandler } from './methods/wallet-request-execution-permissions';\nimport type { ProcessRequestExecutionPermissionsHook } from './methods/wallet-request-execution-permissions';\nimport { createWalletRevokeExecutionPermissionHandler } from './methods/wallet-revoke-execution-permission';\nimport type { ProcessRevokeExecutionPermissionHook } from './methods/wallet-revoke-execution-permission';\nimport { stripArrayTypeIfPresent } from './utils/common';\nimport { normalizeTypedMessage, parseTypedMessage } from './utils/normalize';\nimport {\n resemblesAddress,\n validateAndNormalizeKeyholder as validateKeyholder,\n validateTransactionParams,\n validateTypedDataForPrototypePollution,\n validateTypedDataV1ForPrototypePollution,\n validateTypedMessageKeys,\n} from './utils/validation';\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"]}
|