diff --git a/app/scripts/lib/personal-message-manager.js b/app/scripts/lib/personal-message-manager.js deleted file mode 100644 index bb0a2b0c1..000000000 --- a/app/scripts/lib/personal-message-manager.js +++ /dev/null @@ -1,370 +0,0 @@ -import EventEmitter from 'events'; -import { ObservableStore } from '@metamask/obs-store'; -import { bufferToHex } from 'ethereumjs-util'; -import { ethErrors } from 'eth-rpc-errors'; -import log from 'loglevel'; -import { MESSAGE_TYPE } from '../../../shared/constants/app'; -import { METAMASK_CONTROLLER_EVENTS } from '../metamask-controller'; -import createId from '../../../shared/modules/random-id'; -import { EVENT } from '../../../shared/constants/metametrics'; -import { detectSIWE } from '../../../shared/modules/siwe'; -import { stripHexPrefix } from '../../../shared/modules/hexstring-utils'; -import { addHexPrefix } from './util'; - -const hexRe = /^[0-9A-Fa-f]+$/gu; - -/** - * Represents, and contains data about, an 'personal_sign' type signature request. These are created when a - * signature for an personal_sign call is requested. - * - * @see {@link https://web3js.readthedocs.io/en/1.0/web3-eth-personal.html#sign} - * @typedef {object} PersonalMessage - * @property {number} id An id to track and identify the message object - * @property {object} msgParams The parameters to pass to the personal_sign method once the signature request is - * approved. - * @property {object} msgParams.metamaskId Added to msgParams for tracking and identification within MetaMask. - * @property {string} msgParams.data A hex string conversion of the raw buffer data of the signature request - * @property {number} time The epoch time at which the this message was created - * @property {string} status Indicates whether the signature request is 'unapproved', 'approved', 'signed' or 'rejected' - * @property {string} type The json-prc signing method for which a signature request has been made. A 'Message' will - * always have a 'personal_sign' type. - */ - -export default class PersonalMessageManager extends EventEmitter { - /** - * Controller in charge of managing - storing, adding, removing, updating - PersonalMessage. - * - * @param options - * @param options.metricsEvent - * @param options.securityProviderRequest - */ - constructor({ metricsEvent, securityProviderRequest }) { - super(); - this.memStore = new ObservableStore({ - unapprovedPersonalMsgs: {}, - unapprovedPersonalMsgCount: 0, - }); - - this.resetState = () => { - this.memStore.updateState({ - unapprovedPersonalMsgs: {}, - unapprovedPersonalMsgCount: 0, - }); - }; - - this.messages = []; - this.metricsEvent = metricsEvent; - this.securityProviderRequest = securityProviderRequest; - } - - /** - * A getter for the number of 'unapproved' PersonalMessages in this.messages - * - * @returns {number} The number of 'unapproved' PersonalMessages in this.messages - */ - get unapprovedPersonalMsgCount() { - return Object.keys(this.getUnapprovedMsgs()).length; - } - - /** - * A getter for the 'unapproved' PersonalMessages in this.messages - * - * @returns {object} An index of PersonalMessage ids to PersonalMessages, for all 'unapproved' PersonalMessages in - * this.messages - */ - getUnapprovedMsgs() { - return this.messages - .filter((msg) => msg.status === 'unapproved') - .reduce((result, msg) => { - result[msg.id] = msg; - return result; - }, {}); - } - - /** - * Creates a new PersonalMessage with an 'unapproved' status using the passed msgParams. this.addMsg is called to add - * the new PersonalMessage to this.messages, and to save the unapproved PersonalMessages from that list to - * this.memStore. - * - * @param {object} msgParams - The params for the eth_sign call to be made after the message is approved. - * @param {object} [req] - The original request object possibly containing the origin - * @returns {promise} When the message has been signed or rejected - */ - addUnapprovedMessageAsync(msgParams, req) { - return new Promise((resolve, reject) => { - if (!msgParams.from) { - reject( - new Error('MetaMask Message Signature: from field is required.'), - ); - return; - } - this.addUnapprovedMessage(msgParams, req).then((msgId) => { - this.once(`${msgId}:finished`, (data) => { - switch (data.status) { - case 'signed': - resolve(data.rawSig); - return; - case 'rejected': - reject( - ethErrors.provider.userRejectedRequest( - 'MetaMask Message Signature: User denied message signature.', - ), - ); - return; - case 'errored': - reject(new Error(`MetaMask Message Signature: ${data.error}`)); - return; - default: - reject( - new Error( - `MetaMask Message Signature: Unknown problem: ${JSON.stringify( - msgParams, - )}`, - ), - ); - } - }); - }); - }); - } - - /** - * Creates a new PersonalMessage with an 'unapproved' status using the passed msgParams. this.addMsg is called to add - * the new PersonalMessage to this.messages, and to save the unapproved PersonalMessages from that list to - * this.memStore. - * - * @param {object} msgParams - The params for the eth_sign call to be made after the message is approved. - * @param {object} [req] - The original request object possibly containing the origin - * @returns {number} The id of the newly created PersonalMessage. - */ - async addUnapprovedMessage(msgParams, req) { - log.debug( - `PersonalMessageManager addUnapprovedMessage: ${JSON.stringify( - msgParams, - )}`, - ); - // add origin from request - if (req) { - msgParams.origin = req.origin; - } - msgParams.data = this.normalizeMsgData(msgParams.data); - - // check for SIWE message - const siwe = detectSIWE(msgParams); - msgParams.siwe = siwe; - - // create txData obj with parameters and meta data - const time = new Date().getTime(); - const msgId = createId(); - const msgData = { - id: msgId, - msgParams, - time, - status: 'unapproved', - type: MESSAGE_TYPE.PERSONAL_SIGN, - }; - this.addMsg(msgData); - - const securityProviderResponse = await this.securityProviderRequest( - msgData, - msgData.type, - ); - - msgData.securityProviderResponse = securityProviderResponse; - - // signal update - this.emit('update'); - return msgId; - } - - /** - * Adds a passed PersonalMessage to this.messages, and calls this._saveMsgList() to save the unapproved PersonalMessages from that - * list to this.memStore. - * - * @param {Message} msg - The PersonalMessage to add to this.messages - */ - addMsg(msg) { - this.messages.push(msg); - this._saveMsgList(); - } - - /** - * Returns a specified PersonalMessage. - * - * @param {number} msgId - The id of the PersonalMessage to get - * @returns {PersonalMessage|undefined} The PersonalMessage with the id that matches the passed msgId, or undefined - * if no PersonalMessage has that id. - */ - getMsg(msgId) { - return this.messages.find((msg) => msg.id === msgId); - } - - /** - * Approves a PersonalMessage. Sets the message status via a call to this.setMsgStatusApproved, and returns a promise - * with any the message params modified for proper signing. - * - * @param {object} msgParams - The msgParams to be used when eth_sign is called, plus data added by MetaMask. - * @param {object} msgParams.metamaskId - Added to msgParams for tracking and identification within MetaMask. - * @returns {Promise} Promises the msgParams object with metamaskId removed. - */ - approveMessage(msgParams) { - this.setMsgStatusApproved(msgParams.metamaskId); - return this.prepMsgForSigning(msgParams); - } - - /** - * Sets a PersonalMessage status to 'approved' via a call to this._setMsgStatus. - * - * @param {number} msgId - The id of the PersonalMessage to approve. - */ - setMsgStatusApproved(msgId) { - this._setMsgStatus(msgId, 'approved'); - } - - /** - * Sets a PersonalMessage status to 'signed' via a call to this._setMsgStatus and updates that PersonalMessage in - * this.messages by adding the raw signature data of the signature request to the PersonalMessage - * - * @param {number} msgId - The id of the PersonalMessage to sign. - * @param {buffer} rawSig - The raw data of the signature request - */ - setMsgStatusSigned(msgId, rawSig) { - const msg = this.getMsg(msgId); - msg.rawSig = rawSig; - this._updateMsg(msg); - this._setMsgStatus(msgId, 'signed'); - } - - /** - * Removes the metamaskId property from passed msgParams and returns a promise which resolves the updated msgParams - * - * @param {object} msgParams - The msgParams to modify - * @returns {Promise} Promises the msgParams with the metamaskId property removed - */ - async prepMsgForSigning(msgParams) { - delete msgParams.metamaskId; - return msgParams; - } - - /** - * Sets a PersonalMessage status to 'rejected' via a call to this._setMsgStatus. - * - * @param {number} msgId - The id of the PersonalMessage to reject. - * @param reason - */ - rejectMsg(msgId, reason = undefined) { - if (reason) { - const msg = this.getMsg(msgId); - this.metricsEvent({ - event: reason, - category: EVENT.CATEGORIES.TRANSACTIONS, - properties: { - action: 'Sign Request', - type: msg.type, - }, - }); - } - this._setMsgStatus(msgId, 'rejected'); - } - - /** - * Sets a Message status to 'errored' via a call to this._setMsgStatus. - * - * @param {number} msgId - The id of the Message to error - * @param error - */ - errorMessage(msgId, error) { - const msg = this.getMsg(msgId); - msg.error = error; - this._updateMsg(msg); - this._setMsgStatus(msgId, 'errored'); - } - - /** - * Clears all unapproved messages from memory. - */ - clearUnapproved() { - this.messages = this.messages.filter((msg) => msg.status !== 'unapproved'); - this._saveMsgList(); - } - - /** - * Updates the status of a PersonalMessage in this.messages via a call to this._updateMsg - * - * @private - * @param {number} msgId - The id of the PersonalMessage to update. - * @param {string} status - The new status of the PersonalMessage. - * @throws A 'PersonalMessageManager - PersonalMessage not found for id: "${msgId}".' if there is no PersonalMessage - * in this.messages with an id equal to the passed msgId - * @fires An event with a name equal to `${msgId}:${status}`. The PersonalMessage is also fired. - * @fires If status is 'rejected' or 'signed', an event with a name equal to `${msgId}:finished` is fired along - * with the PersonalMessage - */ - _setMsgStatus(msgId, status) { - const msg = this.getMsg(msgId); - if (!msg) { - throw new Error( - `PersonalMessageManager - Message not found for id: "${msgId}".`, - ); - } - msg.status = status; - this._updateMsg(msg); - this.emit(`${msgId}:${status}`, msg); - if (status === 'rejected' || status === 'signed') { - this.emit(`${msgId}:finished`, msg); - } - } - - /** - * Sets a PersonalMessage in this.messages to the passed PersonalMessage if the ids are equal. Then saves the - * unapprovedPersonalMsgs index to storage via this._saveMsgList - * - * @private - * @param {PersonalMessage} msg - A PersonalMessage that will replace an existing PersonalMessage (with the same - * id) in this.messages - */ - _updateMsg(msg) { - const index = this.messages.findIndex((message) => message.id === msg.id); - if (index !== -1) { - this.messages[index] = msg; - } - this._saveMsgList(); - } - - /** - * Saves the unapproved PersonalMessages, and their count, to this.memStore - * - * @private - * @fires 'updateBadge' - */ - _saveMsgList() { - const unapprovedPersonalMsgs = this.getUnapprovedMsgs(); - const unapprovedPersonalMsgCount = Object.keys( - unapprovedPersonalMsgs, - ).length; - this.memStore.updateState({ - unapprovedPersonalMsgs, - unapprovedPersonalMsgCount, - }); - this.emit(METAMASK_CONTROLLER_EVENTS.UPDATE_BADGE); - } - - /** - * A helper function that converts raw buffer data to a hex, or just returns the data if it is already formatted as a hex. - * - * @param {any} data - The buffer data to convert to a hex - * @returns {string} A hex string conversion of the buffer data - */ - normalizeMsgData(data) { - try { - const stripped = stripHexPrefix(data); - if (stripped.match(hexRe)) { - return addHexPrefix(stripped); - } - } catch (e) { - log.debug(`Message was not hex encoded, interpreting as utf8.`); - } - - return bufferToHex(Buffer.from(data, 'utf8')); - } -} diff --git a/app/scripts/lib/personal-message-manager.test.js b/app/scripts/lib/personal-message-manager.test.js deleted file mode 100644 index e565c0229..000000000 --- a/app/scripts/lib/personal-message-manager.test.js +++ /dev/null @@ -1,182 +0,0 @@ -import { TransactionStatus } from '../../../shared/constants/transaction'; -import PersonalMessageManager from './personal-message-manager'; - -describe('Personal Message Manager', () => { - let messageManager; - - beforeEach(() => { - messageManager = new PersonalMessageManager({ - metricsEvent: jest.fn(), - securityProviderRequest: jest.fn(), - }); - }); - - describe('#getMsgList', () => { - it('when new should return empty array', () => { - const result = messageManager.messages; - expect(Array.isArray(result)).toStrictEqual(true); - expect(result).toHaveLength(0); - }); - }); - - describe('#addMsg', () => { - it('adds a Msg returned in getMsgList', () => { - const Msg = { - id: 1, - status: TransactionStatus.approved, - metamaskNetworkId: 'unit test', - }; - messageManager.addMsg(Msg); - const result = messageManager.messages; - expect(Array.isArray(result)).toStrictEqual(true); - expect(result).toHaveLength(1); - expect(result[0].id).toStrictEqual(1); - }); - }); - - describe('#setMsgStatusApproved', () => { - it('sets the Msg status to approved', () => { - const Msg = { - id: 1, - status: TransactionStatus.unapproved, - metamaskNetworkId: 'unit test', - }; - messageManager.addMsg(Msg); - messageManager.setMsgStatusApproved(1); - const result = messageManager.messages; - expect(Array.isArray(result)).toStrictEqual(true); - expect(result).toHaveLength(1); - expect(result[0].status).toStrictEqual(TransactionStatus.approved); - }); - }); - - describe('#rejectMsg', () => { - it('sets the Msg status to rejected', () => { - const Msg = { - id: 1, - status: TransactionStatus.unapproved, - metamaskNetworkId: 'unit test', - }; - messageManager.addMsg(Msg); - messageManager.rejectMsg(1); - const result = messageManager.messages; - expect(Array.isArray(result)).toStrictEqual(true); - expect(result).toHaveLength(1); - expect(result[0].status).toStrictEqual(TransactionStatus.rejected); - }); - }); - - describe('#_updateMsg', () => { - it('replaces the Msg with the same id', () => { - messageManager.addMsg({ - id: '1', - status: TransactionStatus.unapproved, - metamaskNetworkId: 'unit test', - }); - messageManager.addMsg({ - id: '2', - status: TransactionStatus.approved, - metamaskNetworkId: 'unit test', - }); - messageManager._updateMsg({ - id: '1', - status: 'blah', - hash: 'foo', - metamaskNetworkId: 'unit test', - }); - const result = messageManager.getMsg('1'); - expect(result.hash).toStrictEqual('foo'); - }); - }); - - describe('#getUnapprovedMsgs', () => { - it('returns unapproved Msgs in a hash', () => { - messageManager.addMsg({ - id: '1', - status: TransactionStatus.unapproved, - metamaskNetworkId: 'unit test', - }); - messageManager.addMsg({ - id: '2', - status: TransactionStatus.approved, - metamaskNetworkId: 'unit test', - }); - const result = messageManager.getUnapprovedMsgs(); - expect(typeof result).toStrictEqual('object'); - expect(result['1'].status).toStrictEqual(TransactionStatus.unapproved); - expect(result['2']).toBeUndefined(); - }); - }); - - describe('#getMsg', () => { - it('returns a Msg with the requested id', () => { - messageManager.addMsg({ - id: '1', - status: TransactionStatus.unapproved, - metamaskNetworkId: 'unit test', - }); - messageManager.addMsg({ - id: '2', - status: TransactionStatus.approved, - metamaskNetworkId: 'unit test', - }); - expect(messageManager.getMsg('1').status).toStrictEqual( - TransactionStatus.unapproved, - ); - expect(messageManager.getMsg('2').status).toStrictEqual( - TransactionStatus.approved, - ); - }); - }); - - describe('#normalizeMsgData', () => { - it('converts text to a utf8 hex string', () => { - const input = 'hello'; - const output = messageManager.normalizeMsgData(input); - expect(output).toStrictEqual('0x68656c6c6f'); - }); - - it('tolerates a hex prefix', () => { - const input = '0x12'; - const output = messageManager.normalizeMsgData(input); - expect(output).toStrictEqual('0x12'); - }); - - it('tolerates normal hex', () => { - const input = '12'; - const output = messageManager.normalizeMsgData(input); - expect(output).toStrictEqual('0x12'); - }); - }); - - describe('#addUnapprovedMessage', () => { - const origin = 'http://localhost:8080'; - const from = '0xFb2C15004343904e5f4082578c4e8e11105cF7e3'; - const msgParams = { - from, - data: '0x6c6f63616c686f73743a383038302077616e747320796f7520746f207369676e20696e207769746820796f757220457468657265756d206163636f756e743a0a3078466232433135303034333433393034653566343038323537386334653865313131303563463765330a0a436c69636b20746f207369676e20696e20616e642061636365707420746865205465726d73206f6620536572766963653a2068747470733a2f2f636f6d6d756e6974792e6d6574616d61736b2e696f2f746f730a0a5552493a20687474703a2f2f6c6f63616c686f73743a383038300a56657273696f6e3a20310a436861696e2049443a20310a4e6f6e63653a2053544d74364b514d7777644f58453330360a4973737565642041743a20323032322d30332d31385432313a34303a34302e3832335a0a5265736f75726365733a0a2d20697066733a2f2f516d653773733341525667787636725871565069696b4d4a3875324e4c676d67737a673133705972444b456f69750a2d2068747470733a2f2f6578616d706c652e636f6d2f6d792d776562322d636c61696d2e6a736f6e', - }; - - it('should detect SIWE messages', async () => { - const request = { origin }; - const nonSiweMsgParams = { - from, - data: '0x879a053d4800c6354e76c7985a865d2922c82fb5b3f4577b2fe08b998954f2e0', - }; - // siwe message - const msgId = await messageManager.addUnapprovedMessage( - msgParams, - request, - ); - const result = messageManager.getMsg(msgId); - expect(result.msgParams.siwe.isSIWEMessage).toStrictEqual(true); - // non-siwe message - const msgId2 = await messageManager.addUnapprovedMessage( - nonSiweMsgParams, - request, - ); - const result2 = messageManager.getMsg(msgId2); - expect(result2.msgParams.siwe.isSIWEMessage).toStrictEqual(false); - }); - }); -});