@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,294 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.AbstractMessageManager = void 0;
24
+ const base_controller_1 = require("@metamask/base-controller");
25
+ const events_1 = require("events");
26
+ /**
27
+ * Controller in charge of managing - storing, adding, removing, updating - Messages.
28
+ */
29
+ class AbstractMessageManager extends base_controller_1.BaseController {
30
+ /**
31
+ * Creates an AbstractMessageManager instance.
32
+ *
33
+ * @param config - Initial options used to configure this controller.
34
+ * @param state - Initial state to set on this controller.
35
+ * @param securityProviderRequest - A function for verifying a message, whether it is malicious or not.
36
+ * @param additionalFinishStatuses - Optional list of statuses that are accepted to emit a finished event.
37
+ * @param getCurrentChainId - Optional function to get the current chainId.
38
+ */
39
+ constructor(config, state, securityProviderRequest, additionalFinishStatuses, getCurrentChainId) {
40
+ super(config, state);
41
+ /**
42
+ * EventEmitter instance used to listen to specific message events
43
+ */
44
+ this.hub = new events_1.EventEmitter();
45
+ /**
46
+ * Name of this controller used during composition
47
+ */
48
+ this.name = 'AbstractMessageManager';
49
+ this.defaultState = {
50
+ unapprovedMessages: {},
51
+ unapprovedMessagesCount: 0,
52
+ };
53
+ this.messages = [];
54
+ this.securityProviderRequest = securityProviderRequest;
55
+ this.additionalFinishStatuses = additionalFinishStatuses !== null && additionalFinishStatuses !== void 0 ? additionalFinishStatuses : [];
56
+ this.getCurrentChainId = getCurrentChainId;
57
+ this.initialize();
58
+ }
59
+ /**
60
+ * Saves the unapproved messages, and their count to state.
61
+ *
62
+ * @param emitUpdateBadge - Whether to emit the updateBadge event.
63
+ */
64
+ saveMessageList(emitUpdateBadge = true) {
65
+ const unapprovedMessages = this.getUnapprovedMessages();
66
+ const unapprovedMessagesCount = this.getUnapprovedMessagesCount();
67
+ this.update({ unapprovedMessages, unapprovedMessagesCount });
68
+ if (emitUpdateBadge) {
69
+ this.hub.emit('updateBadge');
70
+ }
71
+ }
72
+ /**
73
+ * Updates the status of a Message in this.messages.
74
+ *
75
+ * @param messageId - The id of the Message to update.
76
+ * @param status - The new status of the Message.
77
+ */
78
+ setMessageStatus(messageId, status) {
79
+ const message = this.getMessage(messageId);
80
+ if (!message) {
81
+ throw new Error(`${this.name}: Message not found for id: ${messageId}.`);
82
+ }
83
+ message.status = status;
84
+ this.updateMessage(message);
85
+ this.hub.emit(`${messageId}:${status}`, message);
86
+ if (status === 'rejected' ||
87
+ status === 'signed' ||
88
+ status === 'errored' ||
89
+ this.additionalFinishStatuses.includes(status)) {
90
+ this.hub.emit(`${messageId}:finished`, message);
91
+ }
92
+ }
93
+ /**
94
+ * Sets a Message in this.messages to the passed Message if the ids are equal.
95
+ * Then saves the unapprovedMessage list to storage.
96
+ *
97
+ * @param message - A Message that will replace an existing Message (with the id) in this.messages.
98
+ * @param emitUpdateBadge - Whether to emit the updateBadge event.
99
+ */
100
+ updateMessage(message, emitUpdateBadge = true) {
101
+ const index = this.messages.findIndex((msg) => message.id === msg.id);
102
+ /* istanbul ignore next */
103
+ if (index !== -1) {
104
+ this.messages[index] = message;
105
+ }
106
+ this.saveMessageList(emitUpdateBadge);
107
+ }
108
+ /**
109
+ * Verifies a message is malicious or not by checking it against a security provider.
110
+ *
111
+ * @param message - The message to verify.
112
+ * @returns A promise that resolves to a secured message with additional security provider response data.
113
+ */
114
+ securityCheck(message) {
115
+ return __awaiter(this, void 0, void 0, function* () {
116
+ if (this.securityProviderRequest) {
117
+ const securityProviderResponse = yield this.securityProviderRequest(message, message.type);
118
+ return Object.assign(Object.assign({}, message), { securityProviderResponse });
119
+ }
120
+ return message;
121
+ });
122
+ }
123
+ /**
124
+ * A getter for the number of 'unapproved' Messages in this.messages.
125
+ *
126
+ * @returns The number of 'unapproved' Messages in this.messages.
127
+ */
128
+ getUnapprovedMessagesCount() {
129
+ return Object.keys(this.getUnapprovedMessages()).length;
130
+ }
131
+ /**
132
+ * A getter for the 'unapproved' Messages in state messages.
133
+ *
134
+ * @returns An index of Message ids to Messages, for all 'unapproved' Messages in this.messages.
135
+ */
136
+ getUnapprovedMessages() {
137
+ return this.messages
138
+ .filter((message) => message.status === 'unapproved')
139
+ .reduce((result, message) => {
140
+ result[message.id] = message;
141
+ return result;
142
+ }, {});
143
+ }
144
+ /**
145
+ * Adds a passed Message to this.messages, and calls this.saveMessageList() to save
146
+ * the unapproved Messages from that list to this.messages.
147
+ *
148
+ * @param message - The Message to add to this.messages.
149
+ */
150
+ addMessage(message) {
151
+ return __awaiter(this, void 0, void 0, function* () {
152
+ const securedMessage = yield this.securityCheck(message);
153
+ this.messages.push(securedMessage);
154
+ this.saveMessageList();
155
+ });
156
+ }
157
+ /**
158
+ * Returns a specified Message.
159
+ *
160
+ * @param messageId - The id of the Message to get.
161
+ * @returns The Message with the id that matches the passed messageId, or undefined
162
+ * if no Message has that id.
163
+ */
164
+ getMessage(messageId) {
165
+ return this.messages.find((message) => message.id === messageId);
166
+ }
167
+ /**
168
+ * Returns all the messages.
169
+ *
170
+ * @returns An array of messages.
171
+ */
172
+ getAllMessages() {
173
+ return this.messages;
174
+ }
175
+ /**
176
+ * Approves a Message. Sets the message status via a call to this.setMessageStatusApproved,
177
+ * and returns a promise with any the message params modified for proper signing.
178
+ *
179
+ * @param messageParams - The messageParams to be used when signing method is called,
180
+ * plus data added by MetaMask.
181
+ * @returns Promise resolving to the messageParams with the metamaskId property removed.
182
+ */
183
+ approveMessage(messageParams) {
184
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
185
+ // @ts-ignore
186
+ this.setMessageStatusApproved(messageParams.metamaskId);
187
+ return this.prepMessageForSigning(messageParams);
188
+ }
189
+ /**
190
+ * Sets a Message status to 'approved' via a call to this.setMessageStatus.
191
+ *
192
+ * @param messageId - The id of the Message to approve.
193
+ */
194
+ setMessageStatusApproved(messageId) {
195
+ this.setMessageStatus(messageId, 'approved');
196
+ }
197
+ /**
198
+ * Sets message status to inProgress in order to allow users to use extension
199
+ * while waiting for a custodian signature.
200
+ *
201
+ * @param messageId - The id of the message to set to inProgress
202
+ */
203
+ setMessageStatusInProgress(messageId) {
204
+ this.setMessageStatus(messageId, 'inProgress');
205
+ }
206
+ /**
207
+ * Sets a Message status to 'signed' via a call to this.setMessageStatus and updates
208
+ * that Message in this.messages by adding the raw signature data of the signature
209
+ * request to the Message.
210
+ *
211
+ * @param messageId - The id of the Message to sign.
212
+ * @param rawSig - The raw data of the signature request.
213
+ */
214
+ setMessageStatusSigned(messageId, rawSig) {
215
+ this.setMessageStatusAndResult(messageId, rawSig, 'signed');
216
+ }
217
+ /**
218
+ * Sets the message via a call to this.setResult and updates status of the message.
219
+ *
220
+ * @param messageId - The id of the Message to sign.
221
+ * @param rawSig - The data to update rawSig in the message.
222
+ * @param status - The new message status.
223
+ */
224
+ setMessageStatusAndResult(messageId, rawSig, status) {
225
+ this.setResult(messageId, rawSig);
226
+ this.setMessageStatus(messageId, status);
227
+ }
228
+ /**
229
+ * Sets the message result.
230
+ *
231
+ * @param messageId - The id of the Message to sign.
232
+ * @param result - The data to update result in the message.
233
+ */
234
+ setResult(messageId, result) {
235
+ const message = this.getMessage(messageId);
236
+ /* istanbul ignore if */
237
+ if (!message) {
238
+ return;
239
+ }
240
+ message.rawSig = result;
241
+ this.updateMessage(message, false);
242
+ }
243
+ /**
244
+ * Sets the messsage metadata
245
+ *
246
+ * @param messageId - The id of the Message to update
247
+ * @param metadata - The data with which to replace the metadata property in the message
248
+ */
249
+ setMetadata(messageId, metadata) {
250
+ const message = this.getMessage(messageId);
251
+ if (!message) {
252
+ throw new Error(`${this.name}: Message not found for id: ${messageId}.`);
253
+ }
254
+ message.metadata = metadata;
255
+ this.updateMessage(message, false);
256
+ }
257
+ /**
258
+ * Sets a Message status to 'rejected' via a call to this.setMessageStatus.
259
+ *
260
+ * @param messageId - The id of the Message to reject.
261
+ */
262
+ rejectMessage(messageId) {
263
+ this.setMessageStatus(messageId, 'rejected');
264
+ }
265
+ /**
266
+ * Creates a promise which will resolve or reject when the message process is finished.
267
+ *
268
+ * @param messageParamsWithId - The params for the personal_sign call to be made after the message is approved.
269
+ * @param messageName - The name of the message
270
+ * @returns Promise resolving to the raw data of the signature request.
271
+ */
272
+ waitForFinishStatus(messageParamsWithId, messageName) {
273
+ return __awaiter(this, void 0, void 0, function* () {
274
+ const { metamaskId: messageId } = messageParamsWithId, messageParams = __rest(messageParamsWithId, ["metamaskId"]);
275
+ return new Promise((resolve, reject) => {
276
+ this.hub.once(`${messageId}:finished`, (data) => {
277
+ switch (data.status) {
278
+ case 'signed':
279
+ return resolve(data.rawSig);
280
+ case 'rejected':
281
+ return reject(new Error(`MetaMask ${messageName} Signature: User denied message signature.`));
282
+ case 'errored':
283
+ return reject(new Error(`MetaMask ${messageName} Signature: ${data.error}`));
284
+ default:
285
+ return reject(new Error(`MetaMask ${messageName} Signature: Unknown problem: ${JSON.stringify(messageParams)}`));
286
+ }
287
+ });
288
+ });
289
+ });
290
+ }
291
+ }
292
+ exports.AbstractMessageManager = AbstractMessageManager;
293
+ exports.default = AbstractMessageManager;
294
+ //# sourceMappingURL=AbstractMessageManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AbstractMessageManager.js","sourceRoot":"","sources":["../src/AbstractMessageManager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AACA,+DAA2D;AAE3D,mCAAsC;AAsFtC;;GAEG;AACH,MAAsB,sBAIpB,SAAQ,gCAAkD;IA6F1D;;;;;;;;OAQG;IACH,YACE,MAA4B,EAC5B,KAAuC,EACvC,uBAAiD,EACjD,wBAAmC,EACnC,iBAAqC;QAErC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QA1BvB;;WAEG;QACH,QAAG,GAAG,IAAI,qBAAY,EAAE,CAAC;QAEzB;;WAEG;QACM,SAAI,GAAG,wBAAwB,CAAC;QAmBvC,IAAI,CAAC,YAAY,GAAG;YAClB,kBAAkB,EAAE,EAAE;YACtB,uBAAuB,EAAE,CAAC;SAC3B,CAAC;QACF,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAC;QACvD,IAAI,CAAC,wBAAwB,GAAG,wBAAwB,aAAxB,wBAAwB,cAAxB,wBAAwB,GAAI,EAAE,CAAC;QAC/D,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,CAAC,UAAU,EAAE,CAAC;IACpB,CAAC;IA9GD;;;;OAIG;IACO,eAAe,CAAC,eAAe,GAAG,IAAI;QAC9C,MAAM,kBAAkB,GAAG,IAAI,CAAC,qBAAqB,EAAE,CAAC;QACxD,MAAM,uBAAuB,GAAG,IAAI,CAAC,0BAA0B,EAAE,CAAC;QAClE,IAAI,CAAC,MAAM,CAAC,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,CAAC,CAAC;QAC7D,IAAI,eAAe,EAAE;YACnB,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;SAC9B;IACH,CAAC;IAED;;;;;OAKG;IACO,gBAAgB,CAA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IACH,aAAa,CAAC,SAAiB;QAC7B,IAAI,CAAC,gBAAgB,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;IAC/C,CAAC;IAED;;;;;;OAMG;IACG,mBAAmB,CACvB,mBAAkD,EAClD,WAAmB;;YAEnB,MAAM,EAAE,UAAU,EAAE,SAAS,KAAuB,mBAAmB,EAArC,aAAa,UAAK,mBAAmB,EAAjE,cAA2C,CAAsB,CAAC;YACxE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBACrC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,SAAS,WAAW,EAAE,CAAC,IAAqB,EAAE,EAAE;oBAC/D,QAAQ,IAAI,CAAC,MAAM,EAAE;wBACnB,KAAK,QAAQ;4BACX,OAAO,OAAO,CAAC,IAAI,CAAC,MAAgB,CAAC,CAAC;wBACxC,KAAK,UAAU;4BACb,OAAO,MAAM,CACX,IAAI,KAAK,CACP,YAAY,WAAW,4CAA4C,CACpE,CACF,CAAC;wBACJ,KAAK,SAAS;4BACZ,OAAO,MAAM,CACX,IAAI,KAAK,CAAC,YAAY,WAAW,eAAe,IAAI,CAAC,KAAK,EAAE,CAAC,CAC9D,CAAC;wBACJ;4BACE,OAAO,MAAM,CACX,IAAI,KAAK,CACP,YAAY,WAAW,gCAAgC,IAAI,CAAC,SAAS,CACnE,aAAa,CACd,EAAE,CACJ,CACF,CAAC;qBACL;gBACH,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC;KAAA;CACF;AAvVD,wDAuVC;AAED,kBAAe,sBAAsB,CAAC","sourcesContent":["import type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport { EventEmitter } from 'events';\n\n/**\n * @type OriginalRequest\n *\n * Represents the original request object for adding a message.\n * @property origin? - Is it is specified, represents the origin\n */\nexport interface OriginalRequest {\n origin?: string;\n securityAlertResponse?: Record<string, Json>;\n}\n\n/**\n * @type Message\n *\n * Represents and contains data about a signing type signature request.\n * @property id - An id to track and identify the message object\n * @property type - The json-prc signing method for which a signature request has been made.\n * A 'Message' which always has a signing type\n * @property rawSig - Raw data of the signature request\n * @property securityProviderResponse - Response from a security provider, whether it is malicious or not\n * @property metadata - Additional data for the message, for example external identifiers\n */\nexport interface AbstractMessage {\n id: string;\n time: number;\n status: string;\n type: string;\n rawSig?: string;\n securityProviderResponse?: Record<string, Json>;\n securityAlertResponse?: Record<string, Json>;\n metadata?: Json;\n error?: string;\n}\n\n/**\n * @type MessageParams\n *\n * Represents the parameters to pass to the signing method once the signature request is approved.\n * @property from - Address from which the message is processed\n * @property origin? - Added for request origin identification\n * @property deferSetAsSigned? - Whether to defer setting the message as signed immediately after the keyring is told to sign it\n */\nexport interface AbstractMessageParams {\n from: string;\n origin?: string;\n deferSetAsSigned?: boolean;\n}\n\n/**\n * @type MessageParamsMetamask\n *\n * Represents the parameters to pass to the signing 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 from - Address from which the message is processed\n * @property origin? - Added for request origin identification\n */\nexport interface AbstractMessageParamsMetamask extends AbstractMessageParams {\n metamaskId?: string;\n}\n\n/**\n * @type MessageManagerState\n *\n * Message Manager state\n * @property unapprovedMessages - A collection of all Messages in the 'unapproved' state\n * @property unapprovedMessagesCount - The count of all Messages in this.unapprovedMessages\n */\nexport interface MessageManagerState<M extends AbstractMessage>\n extends BaseState {\n unapprovedMessages: { [key: string]: M };\n unapprovedMessagesCount: number;\n}\n\n/**\n * A function for verifying a message, whether it is malicious or not\n */\nexport type SecurityProviderRequest = (\n requestData: AbstractMessage,\n messageType: string,\n) => Promise<Json>;\n\ntype getCurrentChainId = () => Hex;\n\n/**\n * Controller in charge of managing - storing, adding, removing, updating - Messages.\n */\nexport abstract class AbstractMessageManager<\n M extends AbstractMessage,\n P extends AbstractMessageParams,\n PM extends AbstractMessageParamsMetamask,\n> extends BaseController<BaseConfig, MessageManagerState<M>> {\n protected messages: M[];\n\n protected getCurrentChainId: getCurrentChainId | undefined;\n\n private readonly securityProviderRequest: SecurityProviderRequest | undefined;\n\n private readonly additionalFinishStatuses: string[];\n\n /**\n * Saves the unapproved messages, and their count to state.\n *\n * @param emitUpdateBadge - Whether to emit the updateBadge event.\n */\n protected saveMessageList(emitUpdateBadge = true) {\n const unapprovedMessages = this.getUnapprovedMessages();\n const unapprovedMessagesCount = this.getUnapprovedMessagesCount();\n this.update({ unapprovedMessages, unapprovedMessagesCount });\n if (emitUpdateBadge) {\n this.hub.emit('updateBadge');\n }\n }\n\n /**\n * Updates the status of a Message in this.messages.\n *\n * @param messageId - The id of the Message to update.\n * @param status - The new status of the Message.\n */\n protected setMessageStatus(messageId: string, status: string) {\n const message = this.getMessage(messageId);\n if (!message) {\n throw new Error(`${this.name}: Message not found for id: ${messageId}.`);\n }\n message.status = status;\n this.updateMessage(message);\n this.hub.emit(`${messageId}:${status}`, message);\n if (\n status === 'rejected' ||\n status === 'signed' ||\n status === 'errored' ||\n this.additionalFinishStatuses.includes(status)\n ) {\n this.hub.emit(`${messageId}:finished`, message);\n }\n }\n\n /**\n * Sets a Message in this.messages to the passed Message if the ids are equal.\n * Then saves the unapprovedMessage list to storage.\n *\n * @param message - A Message that will replace an existing Message (with the id) in this.messages.\n * @param emitUpdateBadge - Whether to emit the updateBadge event.\n */\n protected updateMessage(message: M, emitUpdateBadge = true) {\n const index = this.messages.findIndex((msg) => message.id === msg.id);\n /* istanbul ignore next */\n if (index !== -1) {\n this.messages[index] = message;\n }\n this.saveMessageList(emitUpdateBadge);\n }\n\n /**\n * Verifies a message is malicious or not by checking it against a security provider.\n *\n * @param message - The message to verify.\n * @returns A promise that resolves to a secured message with additional security provider response data.\n */\n private async securityCheck(message: M): Promise<M> {\n if (this.securityProviderRequest) {\n const securityProviderResponse = await this.securityProviderRequest(\n message,\n message.type,\n );\n return {\n ...message,\n securityProviderResponse,\n };\n }\n return message;\n }\n\n /**\n * EventEmitter instance used to listen to specific message events\n */\n hub = new EventEmitter();\n\n /**\n * Name of this controller used during composition\n */\n override name = 'AbstractMessageManager';\n\n /**\n * Creates an AbstractMessageManager instance.\n *\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n * @param securityProviderRequest - A function for verifying a message, whether it is malicious or not.\n * @param additionalFinishStatuses - Optional list of statuses that are accepted to emit a finished event.\n * @param getCurrentChainId - Optional function to get the current chainId.\n */\n constructor(\n config?: Partial<BaseConfig>,\n state?: Partial<MessageManagerState<M>>,\n securityProviderRequest?: SecurityProviderRequest,\n additionalFinishStatuses?: string[],\n getCurrentChainId?: getCurrentChainId,\n ) {\n super(config, state);\n this.defaultState = {\n unapprovedMessages: {},\n unapprovedMessagesCount: 0,\n };\n this.messages = [];\n this.securityProviderRequest = securityProviderRequest;\n this.additionalFinishStatuses = additionalFinishStatuses ?? [];\n this.getCurrentChainId = getCurrentChainId;\n this.initialize();\n }\n\n /**\n * A getter for the number of 'unapproved' Messages in this.messages.\n *\n * @returns The number of 'unapproved' Messages in this.messages.\n */\n getUnapprovedMessagesCount() {\n return Object.keys(this.getUnapprovedMessages()).length;\n }\n\n /**\n * A getter for the 'unapproved' Messages in state messages.\n *\n * @returns An index of Message ids to Messages, for all 'unapproved' Messages in this.messages.\n */\n getUnapprovedMessages() {\n return this.messages\n .filter((message) => message.status === 'unapproved')\n .reduce((result: { [key: string]: M }, message: M) => {\n result[message.id] = message;\n return result;\n }, {}) as { [key: string]: M };\n }\n\n /**\n * Adds a passed Message to this.messages, and calls this.saveMessageList() to save\n * the unapproved Messages from that list to this.messages.\n *\n * @param message - The Message to add to this.messages.\n */\n async addMessage(message: M) {\n const securedMessage = await this.securityCheck(message);\n this.messages.push(securedMessage);\n this.saveMessageList();\n }\n\n /**\n * Returns a specified Message.\n *\n * @param messageId - The id of the Message to get.\n * @returns The Message with the id that matches the passed messageId, or undefined\n * if no Message has that id.\n */\n getMessage(messageId: string) {\n return this.messages.find((message) => message.id === messageId);\n }\n\n /**\n * Returns all the messages.\n *\n * @returns An array of messages.\n */\n getAllMessages() {\n return this.messages;\n }\n\n /**\n * Approves a Message. Sets the message status via a call to this.setMessageStatusApproved,\n * and returns a promise with any the message params modified for proper signing.\n *\n * @param messageParams - The messageParams to be used when signing method is called,\n * plus data added by MetaMask.\n * @returns Promise resolving to the messageParams with the metamaskId property removed.\n */\n approveMessage(messageParams: PM): Promise<P> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.setMessageStatusApproved(messageParams.metamaskId);\n return this.prepMessageForSigning(messageParams);\n }\n\n /**\n * Sets a Message status to 'approved' via a call to this.setMessageStatus.\n *\n * @param messageId - The id of the Message to approve.\n */\n setMessageStatusApproved(messageId: string) {\n this.setMessageStatus(messageId, 'approved');\n }\n\n /**\n * Sets message status to inProgress in order to allow users to use extension\n * while waiting for a custodian signature.\n *\n * @param messageId - The id of the message to set to inProgress\n */\n setMessageStatusInProgress(messageId: string) {\n this.setMessageStatus(messageId, 'inProgress');\n }\n\n /**\n * Sets a Message status to 'signed' via a call to this.setMessageStatus and updates\n * that Message in this.messages by adding the raw signature data of the signature\n * request to the Message.\n *\n * @param messageId - The id of the Message to sign.\n * @param rawSig - The raw data of the signature request.\n */\n setMessageStatusSigned(messageId: string, rawSig: string) {\n this.setMessageStatusAndResult(messageId, rawSig, 'signed');\n }\n\n /**\n * Sets the message via a call to this.setResult and updates status of the message.\n *\n * @param messageId - The id of the Message to sign.\n * @param rawSig - The data to update rawSig in the message.\n * @param status - The new message status.\n */\n setMessageStatusAndResult(messageId: string, rawSig: string, status: string) {\n this.setResult(messageId, rawSig);\n this.setMessageStatus(messageId, status);\n }\n\n /**\n * Sets the message result.\n *\n * @param messageId - The id of the Message to sign.\n * @param result - The data to update result in the message.\n */\n setResult(messageId: string, result: string) {\n const message = this.getMessage(messageId);\n /* istanbul ignore if */\n if (!message) {\n return;\n }\n message.rawSig = result;\n this.updateMessage(message, false);\n }\n\n /**\n * Sets the messsage metadata\n *\n * @param messageId - The id of the Message to update\n * @param metadata - The data with which to replace the metadata property in the message\n */\n\n setMetadata(messageId: string, metadata: Json) {\n const message = this.getMessage(messageId);\n if (!message) {\n throw new Error(`${this.name}: Message not found for id: ${messageId}.`);\n }\n message.metadata = metadata;\n this.updateMessage(message, false);\n }\n\n /**\n * Removes the metamaskId property 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 property removed\n */\n abstract prepMessageForSigning(messageParams: PM): Promise<P>;\n\n /**\n * Creates a new Message with an 'unapproved' status using the passed messageParams.\n * this.addMessage is called to add the new Message to this.messages, and to save the\n * unapproved Messages.\n *\n * @param messageParams - Message parameters for the message to add\n * @param req - The original request object possibly containing the origin.\n * @param version? - The version of the JSON RPC protocol the request is using.\n * @returns The id of the newly created message.\n */\n abstract addUnapprovedMessage(\n messageParams: PM,\n request: OriginalRequest,\n version?: string,\n ): Promise<string>;\n\n /**\n * Sets a Message status to 'rejected' via a call to this.setMessageStatus.\n *\n * @param messageId - The id of the Message to reject.\n */\n rejectMessage(messageId: string) {\n this.setMessageStatus(messageId, 'rejected');\n }\n\n /**\n * Creates a promise which will resolve or reject when the message process is finished.\n *\n * @param messageParamsWithId - The params for the personal_sign call to be made after the message is approved.\n * @param messageName - The name of the message\n * @returns Promise resolving to the raw data of the signature request.\n */\n async waitForFinishStatus(\n messageParamsWithId: AbstractMessageParamsMetamask,\n messageName: string,\n ): Promise<string> {\n const { metamaskId: messageId, ...messageParams } = messageParamsWithId;\n return new Promise((resolve, reject) => {\n this.hub.once(`${messageId}:finished`, (data: AbstractMessage) => {\n switch (data.status) {\n case 'signed':\n return resolve(data.rawSig as string);\n case 'rejected':\n return reject(\n new Error(\n `MetaMask ${messageName} Signature: User denied message signature.`,\n ),\n );\n case 'errored':\n return reject(\n new Error(`MetaMask ${messageName} Signature: ${data.error}`),\n );\n default:\n return reject(\n new Error(\n `MetaMask ${messageName} Signature: Unknown problem: ${JSON.stringify(\n messageParams,\n )}`,\n ),\n );\n }\n });\n });\n }\n}\n\nexport default AbstractMessageManager;\n"]}
@@ -0,0 +1,75 @@
1
+ import type { AbstractMessage, AbstractMessageParams, AbstractMessageParamsMetamask, OriginalRequest } from './AbstractMessageManager';
2
+ import { AbstractMessageManager } from './AbstractMessageManager';
3
+ /**
4
+ * @type DecryptMessage
5
+ *
6
+ * Represents and contains data about a 'eth_decrypt' type signature request.
7
+ * These are created when a signature for an eth_decrypt call is requested.
8
+ * @property id - An id to track and identify the message object
9
+ * @property messageParams - The parameters to pass to the eth_decrypt method once the request is approved
10
+ * @property type - The json-prc signing method for which a signature request has been made.
11
+ * A 'DecryptMessage' which always has a 'eth_decrypt' type
12
+ */
13
+ export interface DecryptMessage extends AbstractMessage {
14
+ messageParams: DecryptMessageParams;
15
+ }
16
+ /**
17
+ * @type DecryptMessageParams
18
+ *
19
+ * Represents the parameters to pass to the eth_decrypt method once the request is approved.
20
+ * @property data - A hex string conversion of the raw buffer data of the signature request
21
+ */
22
+ export interface DecryptMessageParams extends AbstractMessageParams {
23
+ data: string;
24
+ }
25
+ /**
26
+ * @type DecryptMessageParamsMetamask
27
+ *
28
+ * Represents the parameters to pass to the eth_decrypt method once the request is approved
29
+ * plus data added by MetaMask.
30
+ * @property metamaskId - Added for tracking and identification within MetaMask
31
+ * @property data - A hex string conversion of the raw buffer data of the signature request
32
+ * @property from - Address to sign this message from
33
+ * @property origin? - Added for request origin identification
34
+ */
35
+ export interface DecryptMessageParamsMetamask extends AbstractMessageParamsMetamask {
36
+ data: string;
37
+ }
38
+ /**
39
+ * Controller in charge of managing - storing, adding, removing, updating - DecryptMessages.
40
+ */
41
+ export declare class DecryptMessageManager extends AbstractMessageManager<DecryptMessage, DecryptMessageParams, DecryptMessageParamsMetamask> {
42
+ /**
43
+ * Name of this controller used during composition
44
+ */
45
+ name: string;
46
+ /**
47
+ * Creates a new Message with an 'unapproved' status using the passed messageParams.
48
+ * this.addMessage is called to add the new Message to this.messages, and to save the unapproved Messages.
49
+ *
50
+ * @param messageParams - The params for the personal_sign call to be made after the message is approved.
51
+ * @param req - The original request object possibly containing the origin.
52
+ * @returns Promise resolving to the raw data of the signature request.
53
+ */
54
+ addUnapprovedMessageAsync(messageParams: DecryptMessageParams, req?: OriginalRequest): Promise<string>;
55
+ /**
56
+ * Creates a new Message with an 'unapproved' status using the passed messageParams.
57
+ * this.addMessage is called to add the new Message to this.messages, and to save the
58
+ * unapproved Messages.
59
+ *
60
+ * @param messageParams - The params for the personal_sign call to be made after the message
61
+ * is approved.
62
+ * @param req - The original request object possibly containing the origin.
63
+ * @returns The id of the newly created message.
64
+ */
65
+ addUnapprovedMessage(messageParams: DecryptMessageParams, req?: OriginalRequest): Promise<string>;
66
+ /**
67
+ * Removes the metamaskId property from passed messageParams and returns a promise which
68
+ * resolves the updated messageParams.
69
+ *
70
+ * @param messageParams - The messageParams to modify.
71
+ * @returns Promise resolving to the messageParams with the metamaskId property removed.
72
+ */
73
+ prepMessageForSigning(messageParams: DecryptMessageParamsMetamask): Promise<DecryptMessageParams>;
74
+ }
75
+ //# sourceMappingURL=DecryptMessageManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DecryptMessageManager.d.ts","sourceRoot":"","sources":["../src/DecryptMessageManager.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,eAAe,EACf,qBAAqB,EACrB,6BAA6B,EAC7B,eAAe,EAChB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAGlE;;;;;;;;;GASG;AACH,MAAM,WAAW,cAAe,SAAQ,eAAe;IACrD,aAAa,EAAE,oBAAoB,CAAC;CACrC;AAED;;;;;GAKG;AACH,MAAM,WAAW,oBAAqB,SAAQ,qBAAqB;IACjE,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,4BACf,SAAQ,6BAA6B;IACrC,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;GAEG;AACH,qBAAa,qBAAsB,SAAQ,sBAAsB,CAC/D,cAAc,EACd,oBAAoB,EACpB,4BAA4B,CAC7B;IACC;;OAEG;IACM,IAAI,SAA2B;IAExC;;;;;;;OAOG;IACG,yBAAyB,CAC7B,aAAa,EAAE,oBAAoB,EACnC,GAAG,CAAC,EAAE,eAAe,GACpB,OAAO,CAAC,MAAM,CAAC;IAkClB;;;;;;;;;OASG;IACG,oBAAoB,CACxB,aAAa,EAAE,oBAAoB,EACnC,GAAG,CAAC,EAAE,eAAe;IAsBvB;;;;;;OAMG;IACH,qBAAqB,CACnB,aAAa,EAAE,4BAA4B,GAC1C,OAAO,CAAC,oBAAoB,CAAC;CAIjC"}
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.DecryptMessageManager = void 0;
13
+ const uuid_1 = require("uuid");
14
+ const AbstractMessageManager_1 = require("./AbstractMessageManager");
15
+ const utils_1 = require("./utils");
16
+ /**
17
+ * Controller in charge of managing - storing, adding, removing, updating - DecryptMessages.
18
+ */
19
+ class DecryptMessageManager extends AbstractMessageManager_1.AbstractMessageManager {
20
+ constructor() {
21
+ super(...arguments);
22
+ /**
23
+ * Name of this controller used during composition
24
+ */
25
+ this.name = 'DecryptMessageManager';
26
+ }
27
+ /**
28
+ * Creates a new Message with an 'unapproved' status using the passed messageParams.
29
+ * this.addMessage is called to add the new Message to this.messages, and to save the unapproved Messages.
30
+ *
31
+ * @param messageParams - The params for the personal_sign call to be made after the message is approved.
32
+ * @param req - The original request object possibly containing the origin.
33
+ * @returns Promise resolving to the raw data of the signature request.
34
+ */
35
+ addUnapprovedMessageAsync(messageParams, req) {
36
+ return __awaiter(this, void 0, void 0, function* () {
37
+ (0, utils_1.validateDecryptedMessageData)(messageParams);
38
+ const messageId = yield this.addUnapprovedMessage(messageParams, req);
39
+ return new Promise((resolve, reject) => {
40
+ this.hub.once(`${messageId}:finished`, (data) => {
41
+ switch (data.status) {
42
+ case 'decrypted':
43
+ return resolve(data.rawSig);
44
+ case 'rejected':
45
+ return reject(new Error('MetaMask DecryptMessage: User denied message decryption.'));
46
+ case 'errored':
47
+ return reject(new Error('MetaMask DecryptMessage: This message cannot be decrypted.'));
48
+ default:
49
+ return reject(new Error(`MetaMask DecryptMessage: Unknown problem: ${JSON.stringify(messageParams)}`));
50
+ }
51
+ });
52
+ });
53
+ });
54
+ }
55
+ /**
56
+ * Creates a new Message with an 'unapproved' status using the passed messageParams.
57
+ * this.addMessage is called to add the new Message to this.messages, and to save the
58
+ * unapproved Messages.
59
+ *
60
+ * @param messageParams - The params for the personal_sign call to be made after the message
61
+ * is approved.
62
+ * @param req - The original request object possibly containing the origin.
63
+ * @returns The id of the newly created message.
64
+ */
65
+ addUnapprovedMessage(messageParams, req) {
66
+ return __awaiter(this, void 0, void 0, function* () {
67
+ if (req) {
68
+ messageParams.origin = req.origin;
69
+ }
70
+ messageParams.data = (0, utils_1.normalizeMessageData)(messageParams.data);
71
+ const messageId = (0, uuid_1.v1)();
72
+ const messageData = {
73
+ id: messageId,
74
+ messageParams,
75
+ status: 'unapproved',
76
+ time: Date.now(),
77
+ type: 'eth_decrypt',
78
+ };
79
+ yield this.addMessage(messageData);
80
+ this.hub.emit(`unapprovedMessage`, Object.assign(Object.assign({}, messageParams), { metamaskId: messageId }));
81
+ return messageId;
82
+ });
83
+ }
84
+ /**
85
+ * Removes the metamaskId property from passed messageParams and returns a promise which
86
+ * resolves the updated messageParams.
87
+ *
88
+ * @param messageParams - The messageParams to modify.
89
+ * @returns Promise resolving to the messageParams with the metamaskId property removed.
90
+ */
91
+ prepMessageForSigning(messageParams) {
92
+ delete messageParams.metamaskId;
93
+ return Promise.resolve(messageParams);
94
+ }
95
+ }
96
+ exports.DecryptMessageManager = DecryptMessageManager;
97
+ //# sourceMappingURL=DecryptMessageManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DecryptMessageManager.js","sourceRoot":"","sources":["../src/DecryptMessageManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,+BAAoC;AAQpC,qEAAkE;AAClE,mCAA6E;AAyC7E;;GAEG;AACH,MAAa,qBAAsB,SAAQ,+CAI1C;IAJD;;QAKE;;WAEG;QACM,SAAI,GAAG,uBAAuB,CAAC;IA8F1C,CAAC;IA5FC;;;;;;;OAOG;IACG,yBAAyB,CAC7B,aAAmC,EACnC,GAAqB;;YAErB,IAAA,oCAA4B,EAAC,aAAa,CAAC,CAAC;YAC5C,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,oBAAoB,CAAC,aAAa,EAAE,GAAG,CAAC,CAAC;YAEtE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBACrC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,SAAS,WAAW,EAAE,CAAC,IAAoB,EAAE,EAAE;oBAC9D,QAAQ,IAAI,CAAC,MAAM,EAAE;wBACnB,KAAK,WAAW;4BACd,OAAO,OAAO,CAAC,IAAI,CAAC,MAAgB,CAAC,CAAC;wBACxC,KAAK,UAAU;4BACb,OAAO,MAAM,CACX,IAAI,KAAK,CACP,0DAA0D,CAC3D,CACF,CAAC;wBACJ,KAAK,SAAS;4BACZ,OAAO,MAAM,CACX,IAAI,KAAK,CACP,4DAA4D,CAC7D,CACF,CAAC;wBACJ;4BACE,OAAO,MAAM,CACX,IAAI,KAAK,CACP,6CAA6C,IAAI,CAAC,SAAS,CACzD,aAAa,CACd,EAAE,CACJ,CACF,CAAC;qBACL;gBACH,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC;KAAA;IAED;;;;;;;;;OASG;IACG,oBAAoB,CACxB,aAAmC,EACnC,GAAqB;;YAErB,IAAI,GAAG,EAAE;gBACP,aAAa,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;aACnC;YACD,aAAa,CAAC,IAAI,GAAG,IAAA,4BAAoB,EAAC,aAAa,CAAC,IAAI,CAAC,CAAC;YAC9D,MAAM,SAAS,GAAG,IAAA,SAAM,GAAE,CAAC;YAC3B,MAAM,WAAW,GAAmB;gBAClC,EAAE,EAAE,SAAS;gBACb,aAAa;gBACb,MAAM,EAAE,YAAY;gBACpB,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE;gBAChB,IAAI,EAAE,aAAa;aACpB,CAAC;YACF,MAAM,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;YACnC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,mBAAmB,kCAC5B,aAAa,GACb,EAAE,UAAU,EAAE,SAAS,EAAE,EAC5B,CAAC;YACH,OAAO,SAAS,CAAC;QACnB,CAAC;KAAA;IAED;;;;;;OAMG;IACH,qBAAqB,CACnB,aAA2C;QAE3C,OAAO,aAAa,CAAC,UAAU,CAAC;QAChC,OAAO,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;IACxC,CAAC;CACF;AAtGD,sDAsGC","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 { normalizeMessageData, validateDecryptedMessageData } from './utils';\n\n/**\n * @type DecryptMessage\n *\n * Represents and contains data about a 'eth_decrypt' type signature request.\n * These are created when a signature for an eth_decrypt call is requested.\n * @property id - An id to track and identify the message object\n * @property messageParams - The parameters to pass to the eth_decrypt method once the request is approved\n * @property type - The json-prc signing method for which a signature request has been made.\n * A 'DecryptMessage' which always has a 'eth_decrypt' type\n */\nexport interface DecryptMessage extends AbstractMessage {\n messageParams: DecryptMessageParams;\n}\n\n/**\n * @type DecryptMessageParams\n *\n * Represents the parameters to pass to the eth_decrypt method once the request is approved.\n * @property data - A hex string conversion of the raw buffer data of the signature request\n */\nexport interface DecryptMessageParams extends AbstractMessageParams {\n data: string;\n}\n\n/**\n * @type DecryptMessageParamsMetamask\n *\n * Represents the parameters to pass to the eth_decrypt method once the 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 data of the signature request\n * @property from - Address to sign this message from\n * @property origin? - Added for request origin identification\n */\nexport interface DecryptMessageParamsMetamask\n extends AbstractMessageParamsMetamask {\n data: string;\n}\n\n/**\n * Controller in charge of managing - storing, adding, removing, updating - DecryptMessages.\n */\nexport class DecryptMessageManager extends AbstractMessageManager<\n DecryptMessage,\n DecryptMessageParams,\n DecryptMessageParamsMetamask\n> {\n /**\n * Name of this controller used during composition\n */\n override name = 'DecryptMessageManager';\n\n /**\n * Creates a new Message with an 'unapproved' status using the passed messageParams.\n * this.addMessage is called to add the new Message to this.messages, and to save the unapproved Messages.\n *\n * @param messageParams - The params for the personal_sign call to be made after the message is approved.\n * @param req - The original request object possibly containing the origin.\n * @returns Promise resolving to the raw data of the signature request.\n */\n async addUnapprovedMessageAsync(\n messageParams: DecryptMessageParams,\n req?: OriginalRequest,\n ): Promise<string> {\n validateDecryptedMessageData(messageParams);\n const messageId = await this.addUnapprovedMessage(messageParams, req);\n\n return new Promise((resolve, reject) => {\n this.hub.once(`${messageId}:finished`, (data: DecryptMessage) => {\n switch (data.status) {\n case 'decrypted':\n return resolve(data.rawSig as string);\n case 'rejected':\n return reject(\n new Error(\n 'MetaMask DecryptMessage: User denied message decryption.',\n ),\n );\n case 'errored':\n return reject(\n new Error(\n 'MetaMask DecryptMessage: This message cannot be decrypted.',\n ),\n );\n default:\n return reject(\n new Error(\n `MetaMask DecryptMessage: Unknown problem: ${JSON.stringify(\n messageParams,\n )}`,\n ),\n );\n }\n });\n });\n }\n\n /**\n * Creates a new Message with an 'unapproved' status using the passed messageParams.\n * this.addMessage is called to add the new Message to this.messages, and to save the\n * unapproved Messages.\n *\n * @param messageParams - The params for the personal_sign call to be made after the message\n * is approved.\n * @param req - The original request object possibly containing the origin.\n * @returns The id of the newly created message.\n */\n async addUnapprovedMessage(\n messageParams: DecryptMessageParams,\n req?: OriginalRequest,\n ) {\n if (req) {\n messageParams.origin = req.origin;\n }\n messageParams.data = normalizeMessageData(messageParams.data);\n const messageId = random();\n const messageData: DecryptMessage = {\n id: messageId,\n messageParams,\n status: 'unapproved',\n time: Date.now(),\n type: 'eth_decrypt',\n };\n await this.addMessage(messageData);\n this.hub.emit(`unapprovedMessage`, {\n ...messageParams,\n ...{ metamaskId: messageId },\n });\n return messageId;\n }\n\n /**\n * Removes the metamaskId property 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 property removed.\n */\n prepMessageForSigning(\n messageParams: DecryptMessageParamsMetamask,\n ): Promise<DecryptMessageParams> {\n delete messageParams.metamaskId;\n return Promise.resolve(messageParams);\n }\n}\n"]}
@@ -0,0 +1,76 @@
1
+ import type { AbstractMessage, AbstractMessageParams, AbstractMessageParamsMetamask, OriginalRequest } from './AbstractMessageManager';
2
+ import { AbstractMessageManager } from './AbstractMessageManager';
3
+ /**
4
+ * @type EncryptionPublicKey
5
+ *
6
+ * Represents and contains data about a 'eth_getEncryptionPublicKey' type request.
7
+ * These are created when an encryption public key is requested.
8
+ * @property id - An id to track and identify the message object
9
+ * @property messageParams - The parameters to pass to the eth_getEncryptionPublicKey method once the request is approved
10
+ * @property type - The json-prc method for which an encryption public key request has been made.
11
+ * A 'Message' which always has a 'eth_getEncryptionPublicKey' type
12
+ * @property rawSig - Encryption public key
13
+ */
14
+ export interface EncryptionPublicKey extends AbstractMessage {
15
+ messageParams: EncryptionPublicKeyParams;
16
+ }
17
+ /**
18
+ * @type EncryptionPublicKeyParams
19
+ *
20
+ * Represents the parameters to pass to the method once the request is approved.
21
+ * @property from - Address from which to extract the encryption public key
22
+ * @property origin? - Added for request origin identification
23
+ */
24
+ export declare type EncryptionPublicKeyParams = AbstractMessageParams;
25
+ /**
26
+ * @type MessageParamsMetamask
27
+ *
28
+ * Represents the parameters to pass to the eth_getEncryptionPublicKey method once the request is approved
29
+ * plus data added by MetaMask.
30
+ * @property metamaskId - Added for tracking and identification within MetaMask
31
+ * @property data - Encryption public key
32
+ * @property from - Address from which to extract the encryption public key
33
+ * @property origin? - Added for request origin identification
34
+ */
35
+ export interface EncryptionPublicKeyParamsMetamask extends AbstractMessageParamsMetamask {
36
+ data: string;
37
+ }
38
+ /**
39
+ * Controller in charge of managing - storing, adding, removing, updating - Messages.
40
+ */
41
+ export declare class EncryptionPublicKeyManager extends AbstractMessageManager<EncryptionPublicKey, EncryptionPublicKeyParams, EncryptionPublicKeyParamsMetamask> {
42
+ /**
43
+ * Name of this controller used during composition
44
+ */
45
+ name: string;
46
+ /**
47
+ * Creates a new Message with an 'unapproved' status using the passed messageParams.
48
+ * this.addMessage is called to add the new Message to this.messages, and to save the unapproved Messages.
49
+ *
50
+ * @param messageParams - The params for the eth_getEncryptionPublicKey call to be made after the message is approved.
51
+ * @param req - The original request object possibly containing the origin.
52
+ * @returns Promise resolving to the raw data of the request.
53
+ */
54
+ addUnapprovedMessageAsync(messageParams: EncryptionPublicKeyParams, req?: OriginalRequest): Promise<string>;
55
+ /**
56
+ * Creates a new Message with an 'unapproved' status using the passed messageParams.
57
+ * this.addMessage is called to add the new Message to this.messages, and to save the
58
+ * unapproved Messages.
59
+ *
60
+ * @param messageParams - The params for the eth_getEncryptionPublicKey call to be made after the message
61
+ * is approved.
62
+ * @param req - The original request object possibly containing the origin.
63
+ * @returns The id of the newly created message.
64
+ */
65
+ addUnapprovedMessage(messageParams: EncryptionPublicKeyParams, req?: OriginalRequest): Promise<string>;
66
+ /**
67
+ * Removes the metamaskId property from passed messageParams and returns a promise which
68
+ * resolves the updated messageParams.
69
+ *
70
+ * @param messageParams - The messageParams to modify.
71
+ * @returns Promise resolving to the messageParams with the metamaskId property removed.
72
+ */
73
+ prepMessageForSigning(messageParams: EncryptionPublicKeyParamsMetamask): Promise<EncryptionPublicKeyParams>;
74
+ }
75
+ export default EncryptionPublicKeyManager;
76
+ //# sourceMappingURL=EncryptionPublicKeyManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EncryptionPublicKeyManager.d.ts","sourceRoot":"","sources":["../src/EncryptionPublicKeyManager.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,eAAe,EACf,qBAAqB,EACrB,6BAA6B,EAC7B,eAAe,EAChB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAGlE;;;;;;;;;;GAUG;AACH,MAAM,WAAW,mBAAoB,SAAQ,eAAe;IAC1D,aAAa,EAAE,yBAAyB,CAAC;CAC1C;AAED;;;;;;GAMG;AACH,oBAAY,yBAAyB,GAAG,qBAAqB,CAAC;AAE9D;;;;;;;;;GASG;AACH,MAAM,WAAW,iCACf,SAAQ,6BAA6B;IACrC,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;GAEG;AACH,qBAAa,0BAA2B,SAAQ,sBAAsB,CACpE,mBAAmB,EACnB,yBAAyB,EACzB,iCAAiC,CAClC;IACC;;OAEG;IACM,IAAI,SAAgC;IAE7C;;;;;;;OAOG;IACG,yBAAyB,CAC7B,aAAa,EAAE,yBAAyB,EACxC,GAAG,CAAC,EAAE,eAAe,GACpB,OAAO,CAAC,MAAM,CAAC;IA4BlB;;;;;;;;;OASG;IACG,oBAAoB,CACxB,aAAa,EAAE,yBAAyB,EACxC,GAAG,CAAC,EAAE,eAAe,GACpB,OAAO,CAAC,MAAM,CAAC;IAoBlB;;;;;;OAMG;IACH,qBAAqB,CACnB,aAAa,EAAE,iCAAiC,GAC/C,OAAO,CAAC,yBAAyB,CAAC;CAItC;AAED,eAAe,0BAA0B,CAAC"}