@metamask-previews/message-manager 11.0.3-preview-e5e6db48 → 11.0.3-preview-e96ca40c
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 +0 -8
- package/dist/AbstractMessageManager.cjs +48 -53
- package/dist/AbstractMessageManager.cjs.map +1 -1
- package/dist/AbstractMessageManager.d.cts +49 -48
- package/dist/AbstractMessageManager.d.cts.map +1 -1
- package/dist/AbstractMessageManager.d.mts +49 -48
- package/dist/AbstractMessageManager.d.mts.map +1 -1
- package/dist/AbstractMessageManager.mjs +49 -54
- package/dist/AbstractMessageManager.mjs.map +1 -1
- package/dist/DecryptMessageManager.cjs +8 -11
- package/dist/DecryptMessageManager.cjs.map +1 -1
- package/dist/DecryptMessageManager.d.cts +10 -22
- package/dist/DecryptMessageManager.d.cts.map +1 -1
- package/dist/DecryptMessageManager.d.mts +10 -22
- package/dist/DecryptMessageManager.d.mts.map +1 -1
- package/dist/DecryptMessageManager.mjs +8 -11
- package/dist/DecryptMessageManager.mjs.map +1 -1
- package/dist/EncryptionPublicKeyManager.cjs +8 -11
- package/dist/EncryptionPublicKeyManager.cjs.map +1 -1
- package/dist/EncryptionPublicKeyManager.d.cts +10 -21
- package/dist/EncryptionPublicKeyManager.d.cts.map +1 -1
- package/dist/EncryptionPublicKeyManager.d.mts +10 -21
- package/dist/EncryptionPublicKeyManager.d.mts.map +1 -1
- package/dist/EncryptionPublicKeyManager.mjs +8 -11
- package/dist/EncryptionPublicKeyManager.mjs.map +1 -1
- package/package.json +3 -3
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
2
|
+
import type { BaseConfig, BaseState } from "@metamask/base-controller";
|
|
3
|
+
import { BaseControllerV1 } from "@metamask/base-controller";
|
|
4
4
|
import type { ApprovalType } from "@metamask/controller-utils";
|
|
5
|
-
import type { Json } from "@metamask/utils";
|
|
5
|
+
import type { Hex, Json } from "@metamask/utils";
|
|
6
6
|
import { EventEmitter } from "events";
|
|
7
7
|
/**
|
|
8
8
|
* @type OriginalRequest
|
|
@@ -10,13 +10,13 @@ import { EventEmitter } from "events";
|
|
|
10
10
|
* Represents the original request object for adding a message.
|
|
11
11
|
* @property origin? - Is it is specified, represents the origin
|
|
12
12
|
*/
|
|
13
|
-
export
|
|
13
|
+
export interface OriginalRequest {
|
|
14
14
|
id?: number;
|
|
15
15
|
origin?: string;
|
|
16
16
|
securityAlertResponse?: Record<string, Json>;
|
|
17
|
-
}
|
|
17
|
+
}
|
|
18
18
|
/**
|
|
19
|
-
* @type
|
|
19
|
+
* @type Message
|
|
20
20
|
*
|
|
21
21
|
* Represents and contains data about a signing type signature request.
|
|
22
22
|
* @property id - An id to track and identify the message object
|
|
@@ -26,7 +26,7 @@ export type OriginalRequest = {
|
|
|
26
26
|
* @property securityProviderResponse - Response from a security provider, whether it is malicious or not
|
|
27
27
|
* @property metadata - Additional data for the message, for example external identifiers
|
|
28
28
|
*/
|
|
29
|
-
export
|
|
29
|
+
export interface AbstractMessage {
|
|
30
30
|
id: string;
|
|
31
31
|
time: number;
|
|
32
32
|
status: string;
|
|
@@ -36,7 +36,7 @@ export type AbstractMessage = {
|
|
|
36
36
|
securityAlertResponse?: Record<string, Json>;
|
|
37
37
|
metadata?: Json;
|
|
38
38
|
error?: string;
|
|
39
|
-
}
|
|
39
|
+
}
|
|
40
40
|
/**
|
|
41
41
|
* @type AbstractMessageParams
|
|
42
42
|
*
|
|
@@ -46,12 +46,12 @@ export type AbstractMessage = {
|
|
|
46
46
|
* @property requestId? - Original request id
|
|
47
47
|
* @property deferSetAsSigned? - Whether to defer setting the message as signed immediately after the keyring is told to sign it
|
|
48
48
|
*/
|
|
49
|
-
export
|
|
49
|
+
export interface AbstractMessageParams {
|
|
50
50
|
from: string;
|
|
51
51
|
origin?: string;
|
|
52
52
|
requestId?: number;
|
|
53
53
|
deferSetAsSigned?: boolean;
|
|
54
|
-
}
|
|
54
|
+
}
|
|
55
55
|
/**
|
|
56
56
|
* @type MessageParamsMetamask
|
|
57
57
|
*
|
|
@@ -61,9 +61,9 @@ export type AbstractMessageParams = {
|
|
|
61
61
|
* @property from - Address from which the message is processed
|
|
62
62
|
* @property origin? - Added for request origin identification
|
|
63
63
|
*/
|
|
64
|
-
export
|
|
64
|
+
export interface AbstractMessageParamsMetamask extends AbstractMessageParams {
|
|
65
65
|
metamaskId?: string;
|
|
66
|
-
}
|
|
66
|
+
}
|
|
67
67
|
/**
|
|
68
68
|
* @type MessageManagerState
|
|
69
69
|
*
|
|
@@ -71,43 +71,25 @@ export type AbstractMessageParamsMetamask = AbstractMessageParams & {
|
|
|
71
71
|
* @property unapprovedMessages - A collection of all Messages in the 'unapproved' state
|
|
72
72
|
* @property unapprovedMessagesCount - The count of all Messages in this.unapprovedMessages
|
|
73
73
|
*/
|
|
74
|
-
export
|
|
75
|
-
unapprovedMessages:
|
|
74
|
+
export interface MessageManagerState<M extends AbstractMessage> extends BaseState {
|
|
75
|
+
unapprovedMessages: {
|
|
76
|
+
[key: string]: M;
|
|
77
|
+
};
|
|
76
78
|
unapprovedMessagesCount: number;
|
|
77
|
-
}
|
|
78
|
-
export type UpdateBadgeEvent = {
|
|
79
|
-
type: `${string}:updateBadge`;
|
|
80
|
-
payload: [unusedPayload: string];
|
|
81
|
-
};
|
|
79
|
+
}
|
|
82
80
|
/**
|
|
83
81
|
* A function for verifying a message, whether it is malicious or not
|
|
84
82
|
*/
|
|
85
83
|
export type SecurityProviderRequest = (requestData: AbstractMessage, messageType: string) => Promise<Json>;
|
|
86
|
-
|
|
87
|
-
* AbstractMessageManager constructor options.
|
|
88
|
-
*
|
|
89
|
-
* @property additionalFinishStatuses - Optional list of statuses that are accepted to emit a finished event.
|
|
90
|
-
* @property messenger - Controller messaging system.
|
|
91
|
-
* @property name - The name of the manager.
|
|
92
|
-
* @property securityProviderRequest - A function for verifying a message, whether it is malicious or not.
|
|
93
|
-
* @property state - Initial state to set on this controller.
|
|
94
|
-
*/
|
|
95
|
-
export type AbstractMessageManagerOptions<Message extends AbstractMessage, Action extends ActionConstraint, Event extends EventConstraint> = {
|
|
96
|
-
additionalFinishStatuses?: string[];
|
|
97
|
-
messenger: RestrictedControllerMessenger<string, Action, Event | UpdateBadgeEvent, string, string>;
|
|
98
|
-
name: string;
|
|
99
|
-
securityProviderRequest?: SecurityProviderRequest;
|
|
100
|
-
state?: MessageManagerState<Message>;
|
|
101
|
-
};
|
|
84
|
+
type getCurrentChainId = () => Hex;
|
|
102
85
|
/**
|
|
103
86
|
* Controller in charge of managing - storing, adding, removing, updating - Messages.
|
|
104
87
|
*/
|
|
105
|
-
export declare abstract class AbstractMessageManager<
|
|
106
|
-
protected messages:
|
|
88
|
+
export declare abstract class AbstractMessageManager<M extends AbstractMessage, P extends AbstractMessageParams, PM extends AbstractMessageParamsMetamask> extends BaseControllerV1<BaseConfig, MessageManagerState<M>> {
|
|
89
|
+
protected messages: M[];
|
|
90
|
+
protected getCurrentChainId: getCurrentChainId | undefined;
|
|
107
91
|
private readonly securityProviderRequest;
|
|
108
92
|
private readonly additionalFinishStatuses;
|
|
109
|
-
internalEvents: EventEmitter<[never]>;
|
|
110
|
-
constructor({ additionalFinishStatuses, messenger, name, securityProviderRequest, state, }: AbstractMessageManagerOptions<Message, Action, Event>);
|
|
111
93
|
/**
|
|
112
94
|
* Adds request props to the messsage params and returns a new messageParams object.
|
|
113
95
|
* @param messageParams - The messageParams to add the request props to.
|
|
@@ -150,7 +132,7 @@ export declare abstract class AbstractMessageManager<Message extends AbstractMes
|
|
|
150
132
|
* @param message - A Message that will replace an existing Message (with the id) in this.messages.
|
|
151
133
|
* @param emitUpdateBadge - Whether to emit the updateBadge event.
|
|
152
134
|
*/
|
|
153
|
-
protected updateMessage(message:
|
|
135
|
+
protected updateMessage(message: M, emitUpdateBadge?: boolean): void;
|
|
154
136
|
/**
|
|
155
137
|
* Verifies a message is malicious or not by checking it against a security provider.
|
|
156
138
|
*
|
|
@@ -158,7 +140,24 @@ export declare abstract class AbstractMessageManager<Message extends AbstractMes
|
|
|
158
140
|
* @returns A promise that resolves to a secured message with additional security provider response data.
|
|
159
141
|
*/
|
|
160
142
|
private securityCheck;
|
|
161
|
-
|
|
143
|
+
/**
|
|
144
|
+
* EventEmitter instance used to listen to specific message events
|
|
145
|
+
*/
|
|
146
|
+
hub: EventEmitter;
|
|
147
|
+
/**
|
|
148
|
+
* Name of this controller used during composition
|
|
149
|
+
*/
|
|
150
|
+
name: string;
|
|
151
|
+
/**
|
|
152
|
+
* Creates an AbstractMessageManager instance.
|
|
153
|
+
*
|
|
154
|
+
* @param config - Initial options used to configure this controller.
|
|
155
|
+
* @param state - Initial state to set on this controller.
|
|
156
|
+
* @param securityProviderRequest - A function for verifying a message, whether it is malicious or not.
|
|
157
|
+
* @param additionalFinishStatuses - Optional list of statuses that are accepted to emit a finished event.
|
|
158
|
+
* @param getCurrentChainId - Optional function to get the current chainId.
|
|
159
|
+
*/
|
|
160
|
+
constructor(config?: Partial<BaseConfig>, state?: Partial<MessageManagerState<M>>, securityProviderRequest?: SecurityProviderRequest, additionalFinishStatuses?: string[], getCurrentChainId?: getCurrentChainId);
|
|
162
161
|
/**
|
|
163
162
|
* A getter for the number of 'unapproved' Messages in this.messages.
|
|
164
163
|
*
|
|
@@ -170,14 +169,16 @@ export declare abstract class AbstractMessageManager<Message extends AbstractMes
|
|
|
170
169
|
*
|
|
171
170
|
* @returns An index of Message ids to Messages, for all 'unapproved' Messages in this.messages.
|
|
172
171
|
*/
|
|
173
|
-
getUnapprovedMessages():
|
|
172
|
+
getUnapprovedMessages(): {
|
|
173
|
+
[key: string]: M;
|
|
174
|
+
};
|
|
174
175
|
/**
|
|
175
176
|
* Adds a passed Message to this.messages, and calls this.saveMessageList() to save
|
|
176
177
|
* the unapproved Messages from that list to this.messages.
|
|
177
178
|
*
|
|
178
179
|
* @param message - The Message to add to this.messages.
|
|
179
180
|
*/
|
|
180
|
-
addMessage(message:
|
|
181
|
+
addMessage(message: M): Promise<void>;
|
|
181
182
|
/**
|
|
182
183
|
* Returns a specified Message.
|
|
183
184
|
*
|
|
@@ -185,13 +186,13 @@ export declare abstract class AbstractMessageManager<Message extends AbstractMes
|
|
|
185
186
|
* @returns The Message with the id that matches the passed messageId, or undefined
|
|
186
187
|
* if no Message has that id.
|
|
187
188
|
*/
|
|
188
|
-
getMessage(messageId: string):
|
|
189
|
+
getMessage(messageId: string): M | undefined;
|
|
189
190
|
/**
|
|
190
191
|
* Returns all the messages.
|
|
191
192
|
*
|
|
192
193
|
* @returns An array of messages.
|
|
193
194
|
*/
|
|
194
|
-
getAllMessages():
|
|
195
|
+
getAllMessages(): M[];
|
|
195
196
|
/**
|
|
196
197
|
* Approves a Message. Sets the message status via a call to this.setMessageStatusApproved,
|
|
197
198
|
* and returns a promise with any the message params modified for proper signing.
|
|
@@ -200,7 +201,7 @@ export declare abstract class AbstractMessageManager<Message extends AbstractMes
|
|
|
200
201
|
* plus data added by MetaMask.
|
|
201
202
|
* @returns Promise resolving to the messageParams with the metamaskId property removed.
|
|
202
203
|
*/
|
|
203
|
-
approveMessage(messageParams:
|
|
204
|
+
approveMessage(messageParams: PM): Promise<P>;
|
|
204
205
|
/**
|
|
205
206
|
* Sets a Message status to 'approved' via a call to this.setMessageStatus.
|
|
206
207
|
*
|
|
@@ -252,7 +253,7 @@ export declare abstract class AbstractMessageManager<Message extends AbstractMes
|
|
|
252
253
|
* @param messageParams - The messageParams to modify
|
|
253
254
|
* @returns Promise resolving to the messageParams with the metamaskId property removed
|
|
254
255
|
*/
|
|
255
|
-
abstract prepMessageForSigning(messageParams:
|
|
256
|
+
abstract prepMessageForSigning(messageParams: PM): Promise<P>;
|
|
256
257
|
/**
|
|
257
258
|
* Creates a new Message with an 'unapproved' status using the passed messageParams.
|
|
258
259
|
* this.addMessage is called to add the new Message to this.messages, and to save the
|
|
@@ -263,7 +264,7 @@ export declare abstract class AbstractMessageManager<Message extends AbstractMes
|
|
|
263
264
|
* @param version? - The version of the JSON RPC protocol the request is using.
|
|
264
265
|
* @returns The id of the newly created message.
|
|
265
266
|
*/
|
|
266
|
-
abstract addUnapprovedMessage(messageParams:
|
|
267
|
+
abstract addUnapprovedMessage(messageParams: PM, request: OriginalRequest, version?: string): Promise<string>;
|
|
267
268
|
/**
|
|
268
269
|
* Sets a Message status to 'rejected' via a call to this.setMessageStatus.
|
|
269
270
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractMessageManager.d.mts","sourceRoot":"","sources":["../src/AbstractMessageManager.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"AbstractMessageManager.d.mts","sourceRoot":"","sources":["../src/AbstractMessageManager.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,kCAAkC;AACvE,OAAO,EAAE,gBAAgB,EAAE,kCAAkC;AAC7D,OAAO,KAAK,EAAE,YAAY,EAAE,mCAAmC;AAC/D,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,wBAAwB;AAGjD,OAAO,EAAE,YAAY,EAAE,eAAe;AAGtC;;;;;GAKG;AAIH,MAAM,WAAW,eAAe;IAC9B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,qBAAqB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;CAC9C;AAED;;;;;;;;;;GAUG;AAIH,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wBAAwB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAChD,qBAAqB,CAAC,EAAE,MAAM,CAAC,MAA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AAsB,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAIxD;;;;;;OAMG;IACH,yBAAyB,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAK3E;;;;;OAKG;IACH,SAAS,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAU3C;;;;;OAKG;IAEH,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI;IAS7C;;;;;;OAMG;IACH,QAAQ,CAAC,qBAAqB,CAAC,aAAa,EAAE,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC;IAE7D;;;;;;;;;OASG;IACH,QAAQ,CAAC,oBAAoB,CAC3B,aAAa,EAAE,EAAE,EACjB,OAAO,EAAE,eAAe,EACxB,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,CAAC;IAElB;;;;OAIG;IACH,aAAa,CAAC,SAAS,EAAE,MAAM;IAI/B;;;;;;OAMG;IACG,mBAAmB,CACvB,mBAAmB,EAAE,6BAA6B,EAClD,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,CAAC;CAiCnB;AAED,eAAe,sBAAsB,CAAC"}
|
|
@@ -1,35 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { BaseControllerV1 } from "@metamask/base-controller";
|
|
2
2
|
// This package purposefully relies on Node's EventEmitter module.
|
|
3
3
|
// eslint-disable-next-line import/no-nodejs-modules
|
|
4
4
|
import { EventEmitter } from "events";
|
|
5
5
|
import { v1 as random } from "uuid";
|
|
6
|
-
const stateMetadata = {
|
|
7
|
-
unapprovedMessages: { persist: false, anonymous: false },
|
|
8
|
-
unapprovedMessagesCount: { persist: false, anonymous: false },
|
|
9
|
-
};
|
|
10
|
-
const getDefaultState = () => ({
|
|
11
|
-
unapprovedMessages: {},
|
|
12
|
-
unapprovedMessagesCount: 0,
|
|
13
|
-
});
|
|
14
6
|
/**
|
|
15
7
|
* Controller in charge of managing - storing, adding, removing, updating - Messages.
|
|
16
8
|
*/
|
|
17
|
-
export class AbstractMessageManager extends
|
|
18
|
-
constructor({ additionalFinishStatuses, messenger, name, securityProviderRequest, state = {}, }) {
|
|
19
|
-
super({
|
|
20
|
-
messenger,
|
|
21
|
-
metadata: stateMetadata,
|
|
22
|
-
name,
|
|
23
|
-
state: {
|
|
24
|
-
...getDefaultState(),
|
|
25
|
-
...state,
|
|
26
|
-
},
|
|
27
|
-
});
|
|
28
|
-
this.internalEvents = new EventEmitter();
|
|
29
|
-
this.messages = [];
|
|
30
|
-
this.securityProviderRequest = securityProviderRequest;
|
|
31
|
-
this.additionalFinishStatuses = additionalFinishStatuses ?? [];
|
|
32
|
-
}
|
|
9
|
+
export class AbstractMessageManager extends BaseControllerV1 {
|
|
33
10
|
/**
|
|
34
11
|
* Adds request props to the messsage params and returns a new messageParams object.
|
|
35
12
|
* @param messageParams - The messageParams to add the request props to.
|
|
@@ -70,14 +47,11 @@ export class AbstractMessageManager extends BaseController {
|
|
|
70
47
|
* @param emitUpdateBadge - Whether to emit the updateBadge event.
|
|
71
48
|
*/
|
|
72
49
|
saveMessageList(emitUpdateBadge = true) {
|
|
73
|
-
this.
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
state.unapprovedMessagesCount = this.getUnapprovedMessagesCount();
|
|
77
|
-
});
|
|
50
|
+
const unapprovedMessages = this.getUnapprovedMessages();
|
|
51
|
+
const unapprovedMessagesCount = this.getUnapprovedMessagesCount();
|
|
52
|
+
this.update({ unapprovedMessages, unapprovedMessagesCount });
|
|
78
53
|
if (emitUpdateBadge) {
|
|
79
|
-
|
|
80
|
-
this.messagingSystem.publish(`${this.name}:updateBadge`, '');
|
|
54
|
+
this.hub.emit('updateBadge');
|
|
81
55
|
}
|
|
82
56
|
}
|
|
83
57
|
/**
|
|
@@ -91,17 +65,14 @@ export class AbstractMessageManager extends BaseController {
|
|
|
91
65
|
if (!message) {
|
|
92
66
|
throw new Error(`${this.name}: Message not found for id: ${messageId}.`);
|
|
93
67
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
};
|
|
98
|
-
this.updateMessage(updatedMessage);
|
|
99
|
-
this.internalEvents.emit(`${messageId}:${status}`, updatedMessage);
|
|
68
|
+
message.status = status;
|
|
69
|
+
this.updateMessage(message);
|
|
70
|
+
this.hub.emit(`${messageId}:${status}`, message);
|
|
100
71
|
if (status === 'rejected' ||
|
|
101
72
|
status === 'signed' ||
|
|
102
73
|
status === 'errored' ||
|
|
103
74
|
this.additionalFinishStatuses.includes(status)) {
|
|
104
|
-
this.
|
|
75
|
+
this.hub.emit(`${messageId}:finished`, message);
|
|
105
76
|
}
|
|
106
77
|
}
|
|
107
78
|
/**
|
|
@@ -135,11 +106,34 @@ export class AbstractMessageManager extends BaseController {
|
|
|
135
106
|
}
|
|
136
107
|
return message;
|
|
137
108
|
}
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
109
|
+
/**
|
|
110
|
+
* Creates an AbstractMessageManager instance.
|
|
111
|
+
*
|
|
112
|
+
* @param config - Initial options used to configure this controller.
|
|
113
|
+
* @param state - Initial state to set on this controller.
|
|
114
|
+
* @param securityProviderRequest - A function for verifying a message, whether it is malicious or not.
|
|
115
|
+
* @param additionalFinishStatuses - Optional list of statuses that are accepted to emit a finished event.
|
|
116
|
+
* @param getCurrentChainId - Optional function to get the current chainId.
|
|
117
|
+
*/
|
|
118
|
+
constructor(config, state, securityProviderRequest, additionalFinishStatuses, getCurrentChainId) {
|
|
119
|
+
super(config, state);
|
|
120
|
+
/**
|
|
121
|
+
* EventEmitter instance used to listen to specific message events
|
|
122
|
+
*/
|
|
123
|
+
this.hub = new EventEmitter();
|
|
124
|
+
/**
|
|
125
|
+
* Name of this controller used during composition
|
|
126
|
+
*/
|
|
127
|
+
this.name = 'AbstractMessageManager';
|
|
128
|
+
this.defaultState = {
|
|
129
|
+
unapprovedMessages: {},
|
|
130
|
+
unapprovedMessagesCount: 0,
|
|
131
|
+
};
|
|
132
|
+
this.messages = [];
|
|
133
|
+
this.securityProviderRequest = securityProviderRequest;
|
|
134
|
+
this.additionalFinishStatuses = additionalFinishStatuses ?? [];
|
|
135
|
+
this.getCurrentChainId = getCurrentChainId;
|
|
136
|
+
this.initialize();
|
|
143
137
|
}
|
|
144
138
|
/**
|
|
145
139
|
* A getter for the number of 'unapproved' Messages in this.messages.
|
|
@@ -256,10 +250,8 @@ export class AbstractMessageManager extends BaseController {
|
|
|
256
250
|
if (!message) {
|
|
257
251
|
return;
|
|
258
252
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
rawSig: result,
|
|
262
|
-
}, false);
|
|
253
|
+
message.rawSig = result;
|
|
254
|
+
this.updateMessage(message, false);
|
|
263
255
|
}
|
|
264
256
|
/**
|
|
265
257
|
* Sets the messsage metadata
|
|
@@ -272,10 +264,8 @@ export class AbstractMessageManager extends BaseController {
|
|
|
272
264
|
if (!message) {
|
|
273
265
|
throw new Error(`${this.name}: Message not found for id: ${messageId}.`);
|
|
274
266
|
}
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
metadata,
|
|
278
|
-
}, false);
|
|
267
|
+
message.metadata = metadata;
|
|
268
|
+
this.updateMessage(message, false);
|
|
279
269
|
}
|
|
280
270
|
/**
|
|
281
271
|
* Sets a Message status to 'rejected' via a call to this.setMessageStatus.
|
|
@@ -295,14 +285,19 @@ export class AbstractMessageManager extends BaseController {
|
|
|
295
285
|
async waitForFinishStatus(messageParamsWithId, messageName) {
|
|
296
286
|
const { metamaskId: messageId, ...messageParams } = messageParamsWithId;
|
|
297
287
|
return new Promise((resolve, reject) => {
|
|
298
|
-
|
|
288
|
+
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
289
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
290
|
+
this.hub.once(`${messageId}:finished`, (data) => {
|
|
299
291
|
switch (data.status) {
|
|
300
292
|
case 'signed':
|
|
301
293
|
return resolve(data.rawSig);
|
|
302
294
|
case 'rejected':
|
|
303
295
|
return reject(new Error(`MetaMask ${messageName} Signature: User denied message signature.`));
|
|
304
296
|
case 'errored':
|
|
305
|
-
return reject(
|
|
297
|
+
return reject(
|
|
298
|
+
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
299
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
300
|
+
new Error(`MetaMask ${messageName} Signature: ${data.error}`));
|
|
306
301
|
default:
|
|
307
302
|
return reject(new Error(`MetaMask ${messageName} Signature: Unknown problem: ${JSON.stringify(messageParams)}`));
|
|
308
303
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractMessageManager.mjs","sourceRoot":"","sources":["../src/AbstractMessageManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAQ3D,kEAAkE;AAClE,oDAAoD;AACpD,OAAO,EAAE,YAAY,EAAE,eAAe;AAEtC,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,aAAa;AAEpC,MAAM,aAAa,GAAG;IACpB,kBAAkB,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE;IACxD,uBAAuB,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE;CAC9D,CAAC;AAEF,MAAM,eAAe,GAAG,GAAG,EAAE,CAAC,CAAC;IAC7B,kBAAkB,EAAE,EAAE;IACtB,uBAAuB,EAAE,CAAC;CAC3B,CAAC,CAAC;AAsHH;;GAEG;AACH,MAAM,OAAgB,sBAMpB,SAAQ,cAUT;IASC,YAAY,EACV,wBAAwB,EACxB,SAAS,EACT,IAAI,EACJ,uBAAuB,EACvB,KAAK,GAAG,EAAkC,GACY;QACtD,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE,aAAa;YACvB,IAAI;YACJ,KAAK,EAAE;gBACL,G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,CAAC","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport type {\n ActionConstraint,\n EventConstraint,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport type { ApprovalType } from '@metamask/controller-utils';\nimport type { Json } from '@metamask/utils';\n// This package purposefully relies on Node's EventEmitter module.\n// eslint-disable-next-line import/no-nodejs-modules\nimport { EventEmitter } from 'events';\nimport type { Draft } from 'immer';\nimport { v1 as random } from 'uuid';\n\nconst stateMetadata = {\n unapprovedMessages: { persist: false, anonymous: false },\n unapprovedMessagesCount: { persist: false, anonymous: false },\n};\n\nconst getDefaultState = () => ({\n unapprovedMessages: {},\n unapprovedMessagesCount: 0,\n});\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 type OriginalRequest = {\n id?: number;\n origin?: string;\n securityAlertResponse?: Record<string, Json>;\n};\n\n/**\n * @type AbstractMessage\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 type 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 AbstractMessageParams\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 requestId? - Original request id\n * @property deferSetAsSigned? - Whether to defer setting the message as signed immediately after the keyring is told to sign it\n */\nexport type AbstractMessageParams = {\n from: string;\n origin?: string;\n requestId?: number;\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 type AbstractMessageParamsMetamask = 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 type MessageManagerState<Message extends AbstractMessage> = {\n unapprovedMessages: Record<string, Message>;\n unapprovedMessagesCount: number;\n};\n\nexport type UpdateBadgeEvent = {\n type: `${string}:updateBadge`;\n payload: [unusedPayload: string];\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\n/**\n * AbstractMessageManager constructor options.\n *\n * @property additionalFinishStatuses - Optional list of statuses that are accepted to emit a finished event.\n * @property messenger - Controller messaging system.\n * @property name - The name of the manager.\n * @property securityProviderRequest - A function for verifying a message, whether it is malicious or not.\n * @property state - Initial state to set on this controller.\n */\nexport type AbstractMessageManagerOptions<\n Message extends AbstractMessage,\n Action extends ActionConstraint,\n Event extends EventConstraint,\n> = {\n additionalFinishStatuses?: string[];\n messenger: RestrictedControllerMessenger<\n string,\n Action,\n Event | UpdateBadgeEvent,\n string,\n string\n >;\n name: string;\n securityProviderRequest?: SecurityProviderRequest;\n state?: MessageManagerState<Message>;\n};\n\n/**\n * Controller in charge of managing - storing, adding, removing, updating - Messages.\n */\nexport abstract class AbstractMessageManager<\n Message extends AbstractMessage,\n Params extends AbstractMessageParams,\n ParamsMetamask extends AbstractMessageParamsMetamask,\n Action extends ActionConstraint,\n Event extends EventConstraint,\n> extends BaseController<\n string,\n MessageManagerState<Message>,\n RestrictedControllerMessenger<\n string,\n Action,\n Event | UpdateBadgeEvent,\n string,\n string\n >\n> {\n protected messages: Message[];\n\n private readonly securityProviderRequest: SecurityProviderRequest | undefined;\n\n private readonly additionalFinishStatuses: string[];\n\n internalEvents = new EventEmitter();\n\n constructor({\n additionalFinishStatuses,\n messenger,\n name,\n securityProviderRequest,\n state = {} as MessageManagerState<Message>,\n }: AbstractMessageManagerOptions<Message, Action, Event>) {\n super({\n messenger,\n metadata: stateMetadata,\n name,\n state: {\n ...getDefaultState(),\n ...state,\n },\n });\n this.messages = [];\n this.securityProviderRequest = securityProviderRequest;\n this.additionalFinishStatuses = additionalFinishStatuses ?? [];\n }\n\n /**\n * Adds request props to the messsage params and returns a new messageParams object.\n * @param messageParams - The messageParams to add the request props to.\n * @param req - The original request object.\n * @returns The messageParams with the request props added.\n */\n protected addRequestToMessageParams<\n MessageParams extends AbstractMessageParams,\n >(messageParams: MessageParams, req?: OriginalRequest) {\n const updatedMessageParams = {\n ...messageParams,\n };\n\n if (req) {\n updatedMessageParams.requestId = req.id;\n updatedMessageParams.origin = req.origin;\n }\n\n return updatedMessageParams;\n }\n\n /**\n * Creates a new Message with a random id and an 'unapproved' status.\n * @param messageParams - The messageParams to add the request props to.\n * @param type - The approval type of the message.\n * @param req - The original request object.\n * @returns The new unapproved message for a specified type.\n */\n protected createUnapprovedMessage<\n MessageParams extends AbstractMessageParams,\n >(messageParams: MessageParams, type: ApprovalType, req?: OriginalRequest) {\n const messageId = random();\n\n return {\n id: messageId,\n messageParams,\n securityAlertResponse: req?.securityAlertResponse,\n status: 'unapproved',\n time: Date.now(),\n type,\n };\n }\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 this.update((state) => {\n state.unapprovedMessages =\n this.getUnapprovedMessages() as unknown as Record<\n string,\n Draft<Message>\n >;\n state.unapprovedMessagesCount = this.getUnapprovedMessagesCount();\n });\n if (emitUpdateBadge) {\n // Empty payload is used to satisfy event constraint for BaseControllerV2\n this.messagingSystem.publish(`${this.name as string}: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(\n `${this.name as string}: Message not found for id: ${messageId}.`,\n );\n }\n const updatedMessage = {\n ...message,\n status,\n };\n this.updateMessage(updatedMessage);\n this.internalEvents.emit(`${messageId}:${status}`, updatedMessage);\n if (\n status === 'rejected' ||\n status === 'signed' ||\n status === 'errored' ||\n this.additionalFinishStatuses.includes(status)\n ) {\n this.internalEvents.emit(\n `${messageId as string}:finished`,\n updatedMessage,\n );\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: Message, 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: Message): Promise<Message> {\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 clearUnapprovedMessages() {\n this.update((state) => {\n state.unapprovedMessages = {};\n state.unapprovedMessagesCount = 0;\n });\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: Record<string, Message>, message) => {\n result[message.id] = message;\n return result;\n }, {});\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: Message) {\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: ParamsMetamask): Promise<Params> {\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 this.updateMessage(\n {\n ...message,\n rawSig: result,\n },\n false,\n );\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 setMetadata(messageId: string, metadata: Json) {\n const message = this.getMessage(messageId);\n if (!message) {\n throw new Error(\n `${this.name as string}: Message not found for id: ${messageId}.`,\n );\n }\n this.updateMessage(\n {\n ...message,\n metadata,\n },\n false,\n );\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(\n messageParams: ParamsMetamask,\n ): Promise<Params>;\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: ParamsMetamask,\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.internalEvents.once(\n `${messageId as string}:finished`,\n (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(\n `MetaMask ${messageName} Signature: ${data.error as string}`,\n ),\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}\n\nexport default AbstractMessageManager;\n"]}
|
|
1
|
+
{"version":3,"file":"AbstractMessageManager.mjs","sourceRoot":"","sources":["../src/AbstractMessageManager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,kCAAkC;AAG7D,kEAAkE;AAClE,oDAAoD;AACpD,OAAO,EAAE,YAAY,EAAE,eAAe;AACtC,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,aAAa;AA2GpC;;GAEG;AACH,MAAM,OAAgB,sBAUpB,SAAQ,gBAAoD;IAS5D;;;;;OAKG;IACO,yBAAyB,CAEjC,aAA4B,EAAE,GAAqB;QACnD,MAAM,oBAAoB,GAAG;YAC3B,GAAG,aAAa;SACjB,CAAC;QAEF,IAAI,GAAG,EAAE;YACP,oBAAoB,CAAC,SAAS,GAAG,GAAG,CAAC,EAAE,CAAC;YACxC,oBAAoB,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;SAC1C;QAED,OAAO,oBAAoB,CAAC;IAC9B,CAAC;IAED;;;;;;OAMG;IACO,uBAAuB,CAE/B,aAA4B,EAAE,IAAkB,EAAE,GAAqB;QACvE,MAAM,SAAS,GAAG,MAAM,EA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AAC,gBAAgB,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;IAC/C,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,mBAAmB,CACvB,mBAAkD,EAClD,WAAmB;QAEnB,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,GAAG,aAAa,EAAE,GAAG,mBAAmB,CAAC;QACxE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,gFAAgF;YAChF,4EAA4E;YAC5E,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,SAAS,WAAW,EAAE,CAAC,IAAqB,EAAE,EAAE;gBAC/D,QAAQ,IAAI,CAAC,MAAM,EAAE;oBACnB,KAAK,QAAQ;wBACX,OAAO,OAAO,CAAC,IAAI,CAAC,MAAgB,CAAC,CAAC;oBACxC,KAAK,UAAU;wBACb,OAAO,MAAM,CACX,IAAI,KAAK,CACP,YAAY,WAAW,4CAA4C,CACpE,CACF,CAAC;oBACJ,KAAK,SAAS;wBACZ,OAAO,MAAM;wBACX,gFAAgF;wBAChF,4EAA4E;wBAC5E,IAAI,KAAK,CAAC,YAAY,WAAW,eAAe,IAAI,CAAC,KAAK,EAAE,CAAC,CAC9D,CAAC;oBACJ;wBACE,OAAO,MAAM,CACX,IAAI,KAAK,CACP,YAAY,WAAW,gCAAgC,IAAI,CAAC,SAAS,CACnE,aAAa,CACd,EAAE,CACJ,CACF,CAAC;iBACL;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAED,eAAe,sBAAsB,CAAC","sourcesContent":["import type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { BaseControllerV1 } from '@metamask/base-controller';\nimport type { ApprovalType } from '@metamask/controller-utils';\nimport type { Hex, Json } from '@metamask/utils';\n// This package purposefully relies on Node's EventEmitter module.\n// eslint-disable-next-line import/no-nodejs-modules\nimport { EventEmitter } from 'events';\nimport { v1 as random } from 'uuid';\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 */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface OriginalRequest {\n id?: number;\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 */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\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 AbstractMessageParams\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 requestId? - Original request id\n * @property deferSetAsSigned? - Whether to defer setting the message as signed immediately after the keyring is told to sign it\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AbstractMessageParams {\n from: string;\n origin?: string;\n requestId?: number;\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 */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\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 */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions, @typescript-eslint/naming-convention\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\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\ntype getCurrentChainId = () => Hex;\n\n/**\n * Controller in charge of managing - storing, adding, removing, updating - Messages.\n */\nexport abstract class AbstractMessageManager<\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n M extends AbstractMessage,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n P extends AbstractMessageParams,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n PM extends AbstractMessageParamsMetamask,\n> extends BaseControllerV1<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 * Adds request props to the messsage params and returns a new messageParams object.\n * @param messageParams - The messageParams to add the request props to.\n * @param req - The original request object.\n * @returns The messageParams with the request props added.\n */\n protected addRequestToMessageParams<\n MessageParams extends AbstractMessageParams,\n >(messageParams: MessageParams, req?: OriginalRequest) {\n const updatedMessageParams = {\n ...messageParams,\n };\n\n if (req) {\n updatedMessageParams.requestId = req.id;\n updatedMessageParams.origin = req.origin;\n }\n\n return updatedMessageParams;\n }\n\n /**\n * Creates a new Message with a random id and an 'unapproved' status.\n * @param messageParams - The messageParams to add the request props to.\n * @param type - The approval type of the message.\n * @param req - The original request object.\n * @returns The new unapproved message for a specified type.\n */\n protected createUnapprovedMessage<\n MessageParams extends AbstractMessageParams,\n >(messageParams: MessageParams, type: ApprovalType, req?: OriginalRequest) {\n const messageId = random();\n\n return {\n id: messageId,\n messageParams,\n securityAlertResponse: req?.securityAlertResponse,\n status: 'unapproved',\n time: Date.now(),\n type,\n };\n }\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: EventEmitter = 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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\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"]}
|
|
@@ -4,19 +4,16 @@ exports.DecryptMessageManager = void 0;
|
|
|
4
4
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
5
5
|
const AbstractMessageManager_1 = require("./AbstractMessageManager.cjs");
|
|
6
6
|
const utils_1 = require("./utils.cjs");
|
|
7
|
-
const managerName = 'DecryptMessageManager';
|
|
8
7
|
/**
|
|
9
8
|
* Controller in charge of managing - storing, adding, removing, updating - DecryptMessages.
|
|
10
9
|
*/
|
|
11
10
|
class DecryptMessageManager extends AbstractMessageManager_1.AbstractMessageManager {
|
|
12
|
-
constructor(
|
|
13
|
-
super(
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
state,
|
|
19
|
-
});
|
|
11
|
+
constructor() {
|
|
12
|
+
super(...arguments);
|
|
13
|
+
/**
|
|
14
|
+
* Name of this controller used during composition
|
|
15
|
+
*/
|
|
16
|
+
this.name = 'DecryptMessageManager';
|
|
20
17
|
}
|
|
21
18
|
/**
|
|
22
19
|
* Creates a new Message with an 'unapproved' status using the passed messageParams.
|
|
@@ -30,7 +27,7 @@ class DecryptMessageManager extends AbstractMessageManager_1.AbstractMessageMana
|
|
|
30
27
|
(0, utils_1.validateDecryptedMessageData)(messageParams);
|
|
31
28
|
const messageId = await this.addUnapprovedMessage(messageParams, req);
|
|
32
29
|
return new Promise((resolve, reject) => {
|
|
33
|
-
this.
|
|
30
|
+
this.hub.once(`${messageId}:finished`, (data) => {
|
|
34
31
|
switch (data.status) {
|
|
35
32
|
case 'decrypted':
|
|
36
33
|
return resolve(data.rawSig);
|
|
@@ -60,7 +57,7 @@ class DecryptMessageManager extends AbstractMessageManager_1.AbstractMessageMana
|
|
|
60
57
|
const messageData = this.createUnapprovedMessage(updatedMessageParams, controller_utils_1.ApprovalType.EthDecrypt, req);
|
|
61
58
|
const messageId = messageData.id;
|
|
62
59
|
await this.addMessage(messageData);
|
|
63
|
-
this.
|
|
60
|
+
this.hub.emit(`unapprovedMessage`, {
|
|
64
61
|
...updatedMessageParams,
|
|
65
62
|
metamaskId: messageId,
|
|
66
63
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DecryptMessageManager.cjs","sourceRoot":"","sources":["../src/DecryptMessageManager.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"DecryptMessageManager.cjs","sourceRoot":"","sources":["../src/DecryptMessageManager.ts"],"names":[],"mappings":";;;AAAA,iEAA0D;AAQ1D,yEAAkE;AAClE,uCAA6E;AAkD7E;;GAEG;AACH,MAAa,qBAAsB,SAAQ,+CAI1C;IAJD;;QAKE;;WAEG;QACM,SAAI,GAAG,uBAAgC,CAAC;IAgGnD,CAAC;IA9FC;;;;;;;OAOG;IACH,KAAK,CAAC,yBAAyB,CAC7B,aAAmC,EACnC,GAAqB;QAErB,IAAA,oCAA4B,EAAC,aAAa,CAAC,CAAC;QAC5C,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,oBAAoB,CAAC,aAAa,EAAE,GAAG,CAAC,CAAC;QAEtE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,IAAI,CA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AO,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;IACxC,CAAC;CACF;AAxGD,sDAwGC","sourcesContent":["import { ApprovalType } from '@metamask/controller-utils';\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 */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\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 */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\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 */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\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' as const;\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 const updatedMessageParams = this.addRequestToMessageParams(\n messageParams,\n req,\n ) satisfies DecryptMessageParams;\n messageParams.data = normalizeMessageData(messageParams.data);\n\n const messageData = this.createUnapprovedMessage(\n updatedMessageParams,\n ApprovalType.EthDecrypt,\n req,\n ) satisfies DecryptMessage;\n\n const messageId = messageData.id;\n\n await this.addMessage(messageData);\n this.hub.emit(`unapprovedMessage`, {\n ...updatedMessageParams,\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"]}
|