@metamask-previews/message-manager 7.3.0-preview.d32a7cc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/LICENSE +20 -0
  3. package/README.md +15 -0
  4. package/dist/AbstractMessageManager.d.ts +258 -0
  5. package/dist/AbstractMessageManager.d.ts.map +1 -0
  6. package/dist/AbstractMessageManager.js +294 -0
  7. package/dist/AbstractMessageManager.js.map +1 -0
  8. package/dist/DecryptMessageManager.d.ts +75 -0
  9. package/dist/DecryptMessageManager.d.ts.map +1 -0
  10. package/dist/DecryptMessageManager.js +97 -0
  11. package/dist/DecryptMessageManager.js.map +1 -0
  12. package/dist/EncryptionPublicKeyManager.d.ts +76 -0
  13. package/dist/EncryptionPublicKeyManager.d.ts.map +1 -0
  14. package/dist/EncryptionPublicKeyManager.js +95 -0
  15. package/dist/EncryptionPublicKeyManager.js.map +1 -0
  16. package/dist/MessageManager.d.ts +70 -0
  17. package/dist/MessageManager.d.ts.map +1 -0
  18. package/dist/MessageManager.js +72 -0
  19. package/dist/MessageManager.js.map +1 -0
  20. package/dist/PersonalMessageManager.d.ts +72 -0
  21. package/dist/PersonalMessageManager.d.ts.map +1 -0
  22. package/dist/PersonalMessageManager.js +75 -0
  23. package/dist/PersonalMessageManager.js.map +1 -0
  24. package/dist/TypedMessageManager.d.ts +98 -0
  25. package/dist/TypedMessageManager.d.ts.map +1 -0
  26. package/dist/TypedMessageManager.js +101 -0
  27. package/dist/TypedMessageManager.js.map +1 -0
  28. package/dist/index.d.ts +7 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +23 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/utils.d.ts +51 -0
  33. package/dist/utils.d.ts.map +1 -0
  34. package/dist/utils.js +145 -0
  35. package/dist/utils.js.map +1 -0
  36. package/package.json +57 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TypedMessageMan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AAC;YACF,MAAM,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;YACnC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,qBAAqB,CAAC,CAAC;YAC1D,OAAO,SAAS,CAAC;;KAClB;IAED;;;;;OAKG;IACH,uBAAuB,CAAC,SAAiB,EAAE,KAAa;QACtD,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;QAC3C,wBAAwB;QACxB,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO;SACR;QACD,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC;QACtB,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QAC5B,IAAI,CAAC,gBAAgB,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IAC9C,CAAC;IAED;;;;;;OAMG;IACH,qBAAqB,CACnB,aAAyC;QAEzC,OAAO,aAAa,CAAC,UAAU,CAAC;QAChC,OAAO,aAAa,CAAC,OAAO,CAAC;QAC7B,OAAO,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;IACxC,CAAC;CACF;AA/FD,kDA+FC;AAED,kBAAe,mBAAmB,CAAC","sourcesContent":["import { v1 as random } from 'uuid';\n\nimport type {\n AbstractMessage,\n AbstractMessageParams,\n AbstractMessageParamsMetamask,\n OriginalRequest,\n} from './AbstractMessageManager';\nimport { AbstractMessageManager } from './AbstractMessageManager';\nimport {\n validateTypedSignMessageDataV1,\n validateTypedSignMessageDataV3V4,\n} from './utils';\n\n/**\n * @type TypedMessage\n *\n * Represents and contains data about an 'eth_signTypedData' type signature request.\n * These are created when a signature for an eth_signTypedData call is requested.\n * @property id - An id to track and identify the message object\n * @property error - Error corresponding to eth_signTypedData error in failure case\n * @property messageParams - The parameters to pass to the eth_signTypedData method once\n * the signature request is approved\n * @property type - The json-prc signing method for which a signature request has been made.\n * A 'TypedMessage' which always has a 'eth_signTypedData' type\n * @property rawSig - Raw data of the signature request\n */\nexport interface TypedMessage extends AbstractMessage {\n error?: string;\n messageParams: TypedMessageParams;\n time: number;\n status: string;\n type: string;\n rawSig?: string;\n}\n\nexport type SignTypedDataMessageV3V4 = {\n types: Record<string, unknown>;\n domain: Record<string, unknown>;\n primaryType: string;\n message: unknown;\n};\n\n/**\n * @type TypedMessageParams\n *\n * Represents the parameters to pass to the eth_signTypedData method once the signature request is approved.\n * @property data - A hex string conversion of the raw buffer or an object containing data of the signature\n * request depending on version\n * @property from - Address to sign this message from\n * @property origin? - Added for request origin identification\n */\nexport interface TypedMessageParams extends AbstractMessageParams {\n data: Record<string, unknown>[] | string | SignTypedDataMessageV3V4;\n}\n\n/**\n * @type TypedMessageParamsMetamask\n *\n * Represents the parameters to pass to the eth_signTypedData method once the signature request is approved\n * plus data added by MetaMask.\n * @property metamaskId - Added for tracking and identification within MetaMask\n * @property data - A hex string conversion of the raw buffer or an object containing data of the signature\n * request depending on version\n * @property error? - Added for message errored\n * @property from - Address to sign this message from\n * @property origin? - Added for request origin identification\n * @property version - Compatibility version EIP712\n */\nexport interface TypedMessageParamsMetamask\n extends AbstractMessageParamsMetamask {\n data: TypedMessageParams['data'];\n metamaskId?: string;\n error?: string;\n version?: string;\n}\n\n/**\n * Controller in charge of managing - storing, adding, removing, updating - TypedMessages.\n */\nexport class TypedMessageManager extends AbstractMessageManager<\n TypedMessage,\n TypedMessageParams,\n TypedMessageParamsMetamask\n> {\n /**\n * Name of this controller used during composition\n */\n override name = 'TypedMessageManager';\n\n /**\n * Creates a new TypedMessage with an 'unapproved' status using the passed messageParams.\n * this.addMessage is called to add the new TypedMessage to this.messages, and to save the\n * unapproved TypedMessages.\n *\n * @param messageParams - The params for the 'eth_signTypedData' call to be made after the message\n * is approved.\n * @param req - The original request object possibly containing the origin.\n * @param version - Compatibility version EIP712.\n * @returns The id of the newly created TypedMessage.\n */\n async addUnapprovedMessage(\n messageParams: TypedMessageParams,\n req?: OriginalRequest,\n version?: string,\n ): Promise<string> {\n if (version === 'V1') {\n validateTypedSignMessageDataV1(messageParams);\n }\n\n if (version === 'V3' || version === 'V4') {\n const currentChainId = this.getCurrentChainId?.();\n validateTypedSignMessageDataV3V4(messageParams, currentChainId);\n }\n\n if (\n typeof messageParams.data !== 'string' &&\n (version === 'V3' || version === 'V4')\n ) {\n messageParams.data = JSON.stringify(messageParams.data);\n }\n\n const messageId = random();\n const messageParamsMetamask = {\n ...messageParams,\n metamaskId: messageId,\n version,\n };\n if (req) {\n messageParams.origin = req.origin;\n }\n const messageData: TypedMessage = {\n id: messageId,\n messageParams,\n securityAlertResponse: req?.securityAlertResponse,\n status: 'unapproved',\n time: Date.now(),\n type: 'eth_signTypedData',\n };\n await this.addMessage(messageData);\n this.hub.emit(`unapprovedMessage`, messageParamsMetamask);\n return messageId;\n }\n\n /**\n * Sets a TypedMessage status to 'errored' via a call to this.setMessageStatus.\n *\n * @param messageId - The id of the TypedMessage to error.\n * @param error - The error to be included in TypedMessage.\n */\n setMessageStatusErrored(messageId: string, error: string) {\n const message = this.getMessage(messageId);\n /* istanbul ignore if */\n if (!message) {\n return;\n }\n message.error = error;\n this.updateMessage(message);\n this.setMessageStatus(messageId, 'errored');\n }\n\n /**\n * Removes the metamaskId and version properties from passed messageParams and returns a promise which\n * resolves the updated messageParams.\n *\n * @param messageParams - The messageParams to modify.\n * @returns Promise resolving to the messageParams with the metamaskId and version properties removed.\n */\n prepMessageForSigning(\n messageParams: TypedMessageParamsMetamask,\n ): Promise<TypedMessageParams> {\n delete messageParams.metamaskId;\n delete messageParams.version;\n return Promise.resolve(messageParams);\n }\n}\n\nexport default TypedMessageManager;\n"]}
@@ -0,0 +1,7 @@
1
+ export * from './AbstractMessageManager';
2
+ export * from './MessageManager';
3
+ export * from './PersonalMessageManager';
4
+ export * from './TypedMessageManager';
5
+ export * from './EncryptionPublicKeyManager';
6
+ export * from './DecryptMessageManager';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,0BAA0B,CAAC;AACzC,cAAc,kBAAkB,CAAC;AACjC,cAAc,0BAA0B,CAAC;AACzC,cAAc,uBAAuB,CAAC;AACtC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,yBAAyB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./AbstractMessageManager"), exports);
18
+ __exportStar(require("./MessageManager"), exports);
19
+ __exportStar(require("./PersonalMessageManager"), exports);
20
+ __exportStar(require("./TypedMessageManager"), exports);
21
+ __exportStar(require("./EncryptionPublicKeyManager"), exports);
22
+ __exportStar(require("./DecryptMessageManager"), exports);
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2DAAyC;AACzC,mDAAiC;AACjC,2DAAyC;AACzC,wDAAsC;AACtC,+DAA6C;AAC7C,0DAAwC","sourcesContent":["export * from './AbstractMessageManager';\nexport * from './MessageManager';\nexport * from './PersonalMessageManager';\nexport * from './TypedMessageManager';\nexport * from './EncryptionPublicKeyManager';\nexport * from './DecryptMessageManager';\n"]}
@@ -0,0 +1,51 @@
1
+ import type { Hex } from '@metamask/utils';
2
+ import type { DecryptMessageParams } from './DecryptMessageManager';
3
+ import type { EncryptionPublicKeyParams } from './EncryptionPublicKeyManager';
4
+ import type { MessageParams } from './MessageManager';
5
+ import type { PersonalMessageParams } from './PersonalMessageManager';
6
+ import type { TypedMessageParams } from './TypedMessageManager';
7
+ /**
8
+ * A helper function that converts rawmessageData buffer data to a hex, or just returns the data if
9
+ * it is already formatted as a hex.
10
+ *
11
+ * @param data - The buffer data to convert to a hex.
12
+ * @returns A hex string conversion of the buffer data.
13
+ */
14
+ export declare function normalizeMessageData(data: string): string;
15
+ /**
16
+ * Validates a PersonalMessageParams and MessageParams objects for required properties and throws in
17
+ * the event of any validation error.
18
+ *
19
+ * @param messageData - PersonalMessageParams object to validate.
20
+ */
21
+ export declare function validateSignMessageData(messageData: PersonalMessageParams | MessageParams): void;
22
+ /**
23
+ * Validates a TypedMessageParams object for required properties and throws in
24
+ * the event of any validation error for eth_signTypedMessage_V1.
25
+ *
26
+ * @param messageData - TypedMessageParams object to validate.
27
+ */
28
+ export declare function validateTypedSignMessageDataV1(messageData: TypedMessageParams): void;
29
+ /**
30
+ * Validates a TypedMessageParams object for required properties and throws in
31
+ * the event of any validation error for eth_signTypedMessage_V3.
32
+ *
33
+ * @param messageData - TypedMessageParams object to validate.
34
+ * @param currentChainId - The current chainId.
35
+ */
36
+ export declare function validateTypedSignMessageDataV3V4(messageData: TypedMessageParams, currentChainId: Hex | undefined): void;
37
+ /**
38
+ * Validates messageData for the eth_getEncryptionPublicKey message and throws in
39
+ * the event of any validation error.
40
+ *
41
+ * @param messageData - address string to validate.
42
+ */
43
+ export declare function validateEncryptionPublicKeyMessageData(messageData: EncryptionPublicKeyParams): void;
44
+ /**
45
+ * Validates messageData for the eth_decrypt message and throws in
46
+ * the event of any validation error.
47
+ *
48
+ * @param messageData - address string to validate.
49
+ */
50
+ export declare function validateDecryptedMessageData(messageData: DecryptMessageParams): void;
51
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAI3C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AAC9E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACtE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAiBhE;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,UAUhD;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,WAAW,EAAE,qBAAqB,GAAG,aAAa,QAQnD;AAED;;;;;GAKG;AACH,wBAAgB,8BAA8B,CAC5C,WAAW,EAAE,kBAAkB,QAgBhC;AAED;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAC9C,WAAW,EAAE,kBAAkB,EAC/B,cAAc,EAAE,GAAG,GAAG,SAAS,QAwDhC;AAED;;;;;GAKG;AACH,wBAAgB,sCAAsC,CACpD,WAAW,EAAE,yBAAyB,QAIvC;AAED;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,oBAAoB,QAIlC"}
package/dist/utils.js ADDED
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateDecryptedMessageData = exports.validateEncryptionPublicKeyMessageData = exports.validateTypedSignMessageDataV3V4 = exports.validateTypedSignMessageDataV1 = exports.validateSignMessageData = exports.normalizeMessageData = void 0;
4
+ const controller_utils_1 = require("@metamask/controller-utils");
5
+ const eth_sig_util_1 = require("@metamask/eth-sig-util");
6
+ const ethereumjs_util_1 = require("ethereumjs-util");
7
+ const jsonschema_1 = require("jsonschema");
8
+ const hexRe = /^[0-9A-Fa-f]+$/gu;
9
+ /**
10
+ * Validates an address string and throws in the event of any validation error.
11
+ *
12
+ * @param address - The address to validate.
13
+ * @param propertyName - The name of the property source to use in the error message.
14
+ */
15
+ function validateAddress(address, propertyName) {
16
+ if (!address || typeof address !== 'string' || !(0, controller_utils_1.isValidHexAddress)(address)) {
17
+ throw new Error(`Invalid "${propertyName}" address: ${address} must be a valid string.`);
18
+ }
19
+ }
20
+ /**
21
+ * A helper function that converts rawmessageData buffer data to a hex, or just returns the data if
22
+ * it is already formatted as a hex.
23
+ *
24
+ * @param data - The buffer data to convert to a hex.
25
+ * @returns A hex string conversion of the buffer data.
26
+ */
27
+ function normalizeMessageData(data) {
28
+ try {
29
+ const stripped = (0, ethereumjs_util_1.stripHexPrefix)(data);
30
+ if (stripped.match(hexRe)) {
31
+ return (0, ethereumjs_util_1.addHexPrefix)(stripped);
32
+ }
33
+ }
34
+ catch (e) {
35
+ /* istanbul ignore next */
36
+ }
37
+ return (0, ethereumjs_util_1.bufferToHex)(Buffer.from(data, 'utf8'));
38
+ }
39
+ exports.normalizeMessageData = normalizeMessageData;
40
+ /**
41
+ * Validates a PersonalMessageParams and MessageParams objects for required properties and throws in
42
+ * the event of any validation error.
43
+ *
44
+ * @param messageData - PersonalMessageParams object to validate.
45
+ */
46
+ function validateSignMessageData(messageData) {
47
+ const { from, data } = messageData;
48
+ validateAddress(from, 'from');
49
+ if (!data || typeof data !== 'string') {
50
+ throw new Error(`Invalid message "data": ${data} must be a valid string.`);
51
+ }
52
+ }
53
+ exports.validateSignMessageData = validateSignMessageData;
54
+ /**
55
+ * Validates a TypedMessageParams object for required properties and throws in
56
+ * the event of any validation error for eth_signTypedMessage_V1.
57
+ *
58
+ * @param messageData - TypedMessageParams object to validate.
59
+ */
60
+ function validateTypedSignMessageDataV1(messageData) {
61
+ validateAddress(messageData.from, 'from');
62
+ if (!messageData.data || !Array.isArray(messageData.data)) {
63
+ throw new Error(`Invalid message "data": ${messageData.data} must be a valid array.`);
64
+ }
65
+ try {
66
+ // typedSignatureHash will throw if the data is invalid.
67
+ (0, eth_sig_util_1.typedSignatureHash)(messageData.data);
68
+ }
69
+ catch (e) {
70
+ throw new Error(`Expected EIP712 typed data.`);
71
+ }
72
+ }
73
+ exports.validateTypedSignMessageDataV1 = validateTypedSignMessageDataV1;
74
+ /**
75
+ * Validates a TypedMessageParams object for required properties and throws in
76
+ * the event of any validation error for eth_signTypedMessage_V3.
77
+ *
78
+ * @param messageData - TypedMessageParams object to validate.
79
+ * @param currentChainId - The current chainId.
80
+ */
81
+ function validateTypedSignMessageDataV3V4(messageData, currentChainId) {
82
+ validateAddress(messageData.from, 'from');
83
+ if (!messageData.data ||
84
+ Array.isArray(messageData.data) ||
85
+ (typeof messageData.data !== 'object' &&
86
+ typeof messageData.data !== 'string')) {
87
+ throw new Error(`Invalid message "data": Must be a valid string or object.`);
88
+ }
89
+ let data;
90
+ if (typeof messageData.data === 'object') {
91
+ data = messageData.data;
92
+ }
93
+ else {
94
+ try {
95
+ data = JSON.parse(messageData.data);
96
+ }
97
+ catch (e) {
98
+ throw new Error('Data must be passed as a valid JSON string.');
99
+ }
100
+ }
101
+ const validation = (0, jsonschema_1.validate)(data, eth_sig_util_1.TYPED_MESSAGE_SCHEMA);
102
+ if (validation.errors.length > 0) {
103
+ throw new Error('Data must conform to EIP-712 schema. See https://git.io/fNtcx.');
104
+ }
105
+ if (!currentChainId) {
106
+ throw new Error('Current chainId cannot be null or undefined.');
107
+ }
108
+ let { chainId } = data.domain;
109
+ if (chainId) {
110
+ if (typeof chainId === 'string') {
111
+ chainId = parseInt(chainId, chainId.startsWith('0x') ? 16 : 10);
112
+ }
113
+ const activeChainId = parseInt(currentChainId, 16);
114
+ if (Number.isNaN(activeChainId)) {
115
+ throw new Error(`Cannot sign messages for chainId "${chainId}", because MetaMask is switching networks.`);
116
+ }
117
+ if (chainId !== activeChainId) {
118
+ throw new Error(`Provided chainId "${chainId}" must match the active chainId "${activeChainId}"`);
119
+ }
120
+ }
121
+ }
122
+ exports.validateTypedSignMessageDataV3V4 = validateTypedSignMessageDataV3V4;
123
+ /**
124
+ * Validates messageData for the eth_getEncryptionPublicKey message and throws in
125
+ * the event of any validation error.
126
+ *
127
+ * @param messageData - address string to validate.
128
+ */
129
+ function validateEncryptionPublicKeyMessageData(messageData) {
130
+ const { from } = messageData;
131
+ validateAddress(from, 'from');
132
+ }
133
+ exports.validateEncryptionPublicKeyMessageData = validateEncryptionPublicKeyMessageData;
134
+ /**
135
+ * Validates messageData for the eth_decrypt message and throws in
136
+ * the event of any validation error.
137
+ *
138
+ * @param messageData - address string to validate.
139
+ */
140
+ function validateDecryptedMessageData(messageData) {
141
+ const { from } = messageData;
142
+ validateAddress(from, 'from');
143
+ }
144
+ exports.validateDecryptedMessageData = validateDecryptedMessageData;
145
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,iEAA+D;AAC/D,yDAGgC;AAEhC,qDAA4E;AAC5E,2CAAsC;AAQtC,MAAM,KAAK,GAAG,kBAAkB,CAAC;AACjC;;;;;GAKG;AACH,SAAS,eAAe,CAAC,OAAe,EAAE,YAAoB;IAC5D,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,IAAA,oCAAiB,EAAC,OAAO,CAAC,EAAE;QAC1E,MAAM,IAAI,KAAK,CACb,YAAY,YAAY,cAAc,OAAO,0BAA0B,CACxE,CAAC;KACH;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,oBAAoB,CAAC,IAAY;IAC/C,IAAI;QACF,MAAM,QAAQ,GAAG,IAAA,gCAAc,EAAC,IAAI,CAAC,CAAC;QACtC,IAAI,QAAQ,CAAC,KAAK,CAAC,KAA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,IAAI,OAAO,KAAK,aAAa,EAAE;YAC7B,MAAM,IAAI,KAAK,CACb,qBAAqB,OAAO,oCAAoC,aAAa,GAAG,CACjF,CAAC;SACH;KACF;AACH,CAAC;AA1DD,4EA0DC;AAED;;;;;GAKG;AACH,SAAgB,sCAAsC,CACpD,WAAsC;IAEtC,MAAM,EAAE,IAAI,EAAE,GAAG,WAAW,CAAC;IAC7B,eAAe,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAChC,CAAC;AALD,wFAKC;AAED;;;;;GAKG;AACH,SAAgB,4BAA4B,CAC1C,WAAiC;IAEjC,MAAM,EAAE,IAAI,EAAE,GAAG,WAAW,CAAC;IAC7B,eAAe,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAChC,CAAC;AALD,oEAKC","sourcesContent":["import { isValidHexAddress } from '@metamask/controller-utils';\nimport {\n TYPED_MESSAGE_SCHEMA,\n typedSignatureHash,\n} from '@metamask/eth-sig-util';\nimport type { Hex } from '@metamask/utils';\nimport { addHexPrefix, bufferToHex, stripHexPrefix } from 'ethereumjs-util';\nimport { validate } from 'jsonschema';\n\nimport type { DecryptMessageParams } from './DecryptMessageManager';\nimport type { EncryptionPublicKeyParams } from './EncryptionPublicKeyManager';\nimport type { MessageParams } from './MessageManager';\nimport type { PersonalMessageParams } from './PersonalMessageManager';\nimport type { TypedMessageParams } from './TypedMessageManager';\n\nconst hexRe = /^[0-9A-Fa-f]+$/gu;\n/**\n * Validates an address string and throws in the event of any validation error.\n *\n * @param address - The address to validate.\n * @param propertyName - The name of the property source to use in the error message.\n */\nfunction validateAddress(address: string, propertyName: string) {\n if (!address || typeof address !== 'string' || !isValidHexAddress(address)) {\n throw new Error(\n `Invalid \"${propertyName}\" address: ${address} must be a valid string.`,\n );\n }\n}\n\n/**\n * A helper function that converts rawmessageData buffer data to a hex, or just returns the data if\n * it is already formatted as a hex.\n *\n * @param data - The buffer data to convert to a hex.\n * @returns A hex string conversion of the buffer data.\n */\nexport function normalizeMessageData(data: string) {\n try {\n const stripped = stripHexPrefix(data);\n if (stripped.match(hexRe)) {\n return addHexPrefix(stripped);\n }\n } catch (e) {\n /* istanbul ignore next */\n }\n return bufferToHex(Buffer.from(data, 'utf8'));\n}\n\n/**\n * Validates a PersonalMessageParams and MessageParams objects for required properties and throws in\n * the event of any validation error.\n *\n * @param messageData - PersonalMessageParams object to validate.\n */\nexport function validateSignMessageData(\n messageData: PersonalMessageParams | MessageParams,\n) {\n const { from, data } = messageData;\n validateAddress(from, 'from');\n\n if (!data || typeof data !== 'string') {\n throw new Error(`Invalid message \"data\": ${data} must be a valid string.`);\n }\n}\n\n/**\n * Validates a TypedMessageParams object for required properties and throws in\n * the event of any validation error for eth_signTypedMessage_V1.\n *\n * @param messageData - TypedMessageParams object to validate.\n */\nexport function validateTypedSignMessageDataV1(\n messageData: TypedMessageParams,\n) {\n validateAddress(messageData.from, 'from');\n\n if (!messageData.data || !Array.isArray(messageData.data)) {\n throw new Error(\n `Invalid message \"data\": ${messageData.data} must be a valid array.`,\n );\n }\n\n try {\n // typedSignatureHash will throw if the data is invalid.\n typedSignatureHash(messageData.data as any);\n } catch (e) {\n throw new Error(`Expected EIP712 typed data.`);\n }\n}\n\n/**\n * Validates a TypedMessageParams object for required properties and throws in\n * the event of any validation error for eth_signTypedMessage_V3.\n *\n * @param messageData - TypedMessageParams object to validate.\n * @param currentChainId - The current chainId.\n */\nexport function validateTypedSignMessageDataV3V4(\n messageData: TypedMessageParams,\n currentChainId: Hex | undefined,\n) {\n validateAddress(messageData.from, 'from');\n\n if (\n !messageData.data ||\n Array.isArray(messageData.data) ||\n (typeof messageData.data !== 'object' &&\n typeof messageData.data !== 'string')\n ) {\n throw new Error(\n `Invalid message \"data\": Must be a valid string or object.`,\n );\n }\n\n let data;\n if (typeof messageData.data === 'object') {\n data = messageData.data;\n } else {\n try {\n data = JSON.parse(messageData.data);\n } catch (e) {\n throw new Error('Data must be passed as a valid JSON string.');\n }\n }\n\n const validation = validate(data, TYPED_MESSAGE_SCHEMA);\n if (validation.errors.length > 0) {\n throw new Error(\n 'Data must conform to EIP-712 schema. See https://git.io/fNtcx.',\n );\n }\n\n if (!currentChainId) {\n throw new Error('Current chainId cannot be null or undefined.');\n }\n\n let { chainId } = data.domain;\n if (chainId) {\n if (typeof chainId === 'string') {\n chainId = parseInt(chainId, chainId.startsWith('0x') ? 16 : 10);\n }\n\n const activeChainId = parseInt(currentChainId, 16);\n if (Number.isNaN(activeChainId)) {\n throw new Error(\n `Cannot sign messages for chainId \"${chainId}\", because MetaMask is switching networks.`,\n );\n }\n\n if (chainId !== activeChainId) {\n throw new Error(\n `Provided chainId \"${chainId}\" must match the active chainId \"${activeChainId}\"`,\n );\n }\n }\n}\n\n/**\n * Validates messageData for the eth_getEncryptionPublicKey message and throws in\n * the event of any validation error.\n *\n * @param messageData - address string to validate.\n */\nexport function validateEncryptionPublicKeyMessageData(\n messageData: EncryptionPublicKeyParams,\n) {\n const { from } = messageData;\n validateAddress(from, 'from');\n}\n\n/**\n * Validates messageData for the eth_decrypt message and throws in\n * the event of any validation error.\n *\n * @param messageData - address string to validate.\n */\nexport function validateDecryptedMessageData(\n messageData: DecryptMessageParams,\n) {\n const { from } = messageData;\n validateAddress(from, 'from');\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@metamask-previews/message-manager",
3
+ "version": "7.3.0-preview.d32a7cc",
4
+ "description": "Stores and manages interactions with signing requests",
5
+ "keywords": [
6
+ "MetaMask",
7
+ "Ethereum"
8
+ ],
9
+ "homepage": "https://github.com/MetaMask/core/tree/main/packages/message-manager#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/MetaMask/core/issues"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/MetaMask/core.git"
16
+ },
17
+ "license": "MIT",
18
+ "main": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "files": [
21
+ "dist/"
22
+ ],
23
+ "scripts": {
24
+ "build:docs": "typedoc",
25
+ "changelog:validate": "../../scripts/validate-changelog.sh @metamask/message-manager",
26
+ "publish:preview": "yarn npm publish --tag preview",
27
+ "test": "jest",
28
+ "test:watch": "jest --watch"
29
+ },
30
+ "dependencies": {
31
+ "@metamask-previews/base-controller": "3.2.0-preview.d32a7cc",
32
+ "@metamask-previews/controller-utils": "4.3.1-preview.d32a7cc",
33
+ "@metamask/eth-sig-util": "^6.0.0",
34
+ "@metamask/utils": "^6.2.0",
35
+ "@types/uuid": "^8.3.0",
36
+ "ethereumjs-util": "^7.0.10",
37
+ "jsonschema": "^1.2.4",
38
+ "uuid": "^8.3.2"
39
+ },
40
+ "devDependencies": {
41
+ "@metamask/auto-changelog": "^3.1.0",
42
+ "@types/jest": "^27.4.1",
43
+ "deepmerge": "^4.2.2",
44
+ "jest": "^27.5.1",
45
+ "ts-jest": "^27.1.4",
46
+ "typedoc": "^0.22.15",
47
+ "typedoc-plugin-missing-exports": "^0.22.6",
48
+ "typescript": "~4.6.3"
49
+ },
50
+ "engines": {
51
+ "node": ">=16.0.0"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public",
55
+ "registry": "https://registry.npmjs.org/"
56
+ }
57
+ }