diff --git a/packages/keyring-eth-money-mpc/CHANGELOG.md b/packages/keyring-eth-money-mpc/CHANGELOG.md index e75195d57..6fbd25054 100644 --- a/packages/keyring-eth-money-mpc/CHANGELOG.md +++ b/packages/keyring-eth-money-mpc/CHANGELOG.md @@ -7,10 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Add a read-only mode for clients without MFA ([#722](https://github.com/MetaMask/accounts/pull/722)) + - With `isMfaAvailable: false`, `setup` reads the address of the active key from `check-key-share` with a profile token without 2FA, and stores only the address. + - Signing, `rotateKeyShares`, `checkKeyShare` and `syncKeyShare` throw before any network call. + - A read-only keyring keeps a full persisted state, but does not sign with it. + - A read/write keyring that loads an address-only state imports the key share on `setup`, and throws if the imported address differs. + - The V2 `MpcMoneyKeyring` returns read-only accounts without methods. + - Add `isReadOnly` to the `MpcMoneyKeyring` contract. + - `CheckKeyShareResult` includes the optional `publicKey` of the latest share. + ### Changed +- **BREAKING:** Require the `isMfaAvailable` constructor option ([#722](https://github.com/MetaMask/accounts/pull/722)) + - Pass `true` to keep the current behavior. - Call `check-key-share` with `GET` instead of `POST` ([#717](https://github.com/MetaMask/accounts/pull/717)) - Requires an MPC backend that serves `GET /v1/check-key-share`. +- The V2 `createAccounts` always runs the inner `setup`, which is a no-op once the keyring is set up ([#722](https://github.com/MetaMask/accounts/pull/722)) ## [0.4.0] diff --git a/packages/keyring-eth-money-mpc/README.md b/packages/keyring-eth-money-mpc/README.md index 9a9c532c5..f1cf1e0fa 100644 --- a/packages/keyring-eth-money-mpc/README.md +++ b/packages/keyring-eth-money-mpc/README.md @@ -12,6 +12,21 @@ The keyring first calls `/sign` with a profile token without 2FA, and sends the Key generation, import, share rotation, share sync, and transaction signing always use a 2FA token. +## Read-only mode + +Pass `isMfaAvailable` when constructing the keyring. Derive it from the client's MFA feature flag. + +With `isMfaAvailable: false`, the keyring never requests a 2FA token: + +- `setup` calls `check-key-share` with a profile token without 2FA. It stores only the address derived from the returned `publicKey`. +- `setup` throws when the profile has no active key. +- Signing, `rotateKeyShares`, `checkKeyShare`, and `syncKeyShare` throw. +- The V2 adapter returns the account without methods. + +A read-only keyring that loads a full persisted state keeps it, but doesn't sign with it. + +When MFA becomes available, construct the keyring with `isMfaAvailable: true` and call `setup` (or the V2 `createAccounts`). The keyring imports the key share with a 2FA token. It throws if the imported address differs from the stored one. + ## Device-share backups Provide `getPrimaryMnemonic: () => Promise` when constructing the keyring. diff --git a/packages/keyring-eth-money-mpc/src/cloud.test.ts b/packages/keyring-eth-money-mpc/src/cloud.test.ts index f9b75abf8..49c665f46 100644 --- a/packages/keyring-eth-money-mpc/src/cloud.test.ts +++ b/packages/keyring-eth-money-mpc/src/cloud.test.ts @@ -462,6 +462,38 @@ describe('cloud helpers', () => { ); }); + it('returns the latest share public key with the epochs', async () => { + okJson({ + latestShareEpoch: 1, + latestBackupEpoch: 1, + activeEpoch: 1, + publicKey: '0x010203', + }); + + expect( + await checkKeyShare({ + baseURL: 'https://cloud.example', + token: 'token-1', + }), + ).toStrictEqual({ + latestShareEpoch: 1, + latestBackupEpoch: 1, + activeEpoch: 1, + publicKey: '0x010203', + }); + }); + + it('rejects a public key that is not 0x-prefixed hex', async () => { + okJson({ activeEpoch: 1, publicKey: '010203' }); + + await expect( + checkKeyShare({ + baseURL: 'https://cloud.example', + token: 'token-1', + }), + ).rejects.toThrow(/^Failed to check key share: bad response format$/u); + }); + it('rejects key share epoch metadata with the wrong shape', async () => { okJson({ activeEpoch: '1' }); diff --git a/packages/keyring-eth-money-mpc/src/cloud.ts b/packages/keyring-eth-money-mpc/src/cloud.ts index 3e7c1ae60..8675d3b58 100644 --- a/packages/keyring-eth-money-mpc/src/cloud.ts +++ b/packages/keyring-eth-money-mpc/src/cloud.ts @@ -11,7 +11,7 @@ import { string, type, } from '@metamask/superstruct'; -import { base64ToBytes, bytesToBase64 } from '@metamask/utils'; +import { base64ToBytes, bytesToBase64, StrictHexStruct } from '@metamask/utils'; import { MFA_REQUIRED_CODE } from './types.js'; import type { MoneyAccountSignatureRequest } from './types.js'; @@ -31,6 +31,11 @@ const CheckKeyShareResponseStruct = type({ latestShareEpoch: exactOptional(shareEpochStruct), latestBackupEpoch: exactOptional(shareEpochStruct), activeEpoch: exactOptional(shareEpochStruct), + /** + * Public key of the latest share: the pending share when one exists, + * otherwise the active share. + */ + publicKey: exactOptional(StrictHexStruct), }); export type CheckKeyShareResult = Infer; @@ -400,7 +405,8 @@ export async function storeKeyShareBackup(opts: { } /** - * Return the latest share/backup epochs and the active epoch from the backend. + * Return the latest share/backup epochs, the active epoch, and the latest + * share public key from the backend. * * @param opts - Request options. * @param opts.baseURL - MPC backend base URL. diff --git a/packages/keyring-eth-money-mpc/src/mpc-money-keyring.test.ts b/packages/keyring-eth-money-mpc/src/mpc-money-keyring.test.ts index 7ddd41dbb..0e2bd6999 100644 --- a/packages/keyring-eth-money-mpc/src/mpc-money-keyring.test.ts +++ b/packages/keyring-eth-money-mpc/src/mpc-money-keyring.test.ts @@ -194,8 +194,10 @@ const makeRootSession = (statusPayload = 'data persisted') => { const makeKeyring = ( getProfileToken = jest.fn().mockResolvedValue('token'), getPrimaryMnemonic = jest.fn().mockResolvedValue(mockMnemonicBytes), + isMfaAvailable = true, ) => new MpcMoneyKeyring({ + isMfaAvailable, cl24Lib: {} as never, dkls23Lib: {} as never, cloudURL: 'https://cloud.example', @@ -267,6 +269,7 @@ describe('MpcMoneyKeyring', () => { const webSocket = { send: jest.fn() }; const keyring = new MpcMoneyKeyring({ + isMfaAvailable: true, cl24Lib: {} as never, dkls23Lib: {} as never, cloudURL: 'https://cloud.example', @@ -1325,4 +1328,227 @@ describe('MpcMoneyKeyring', () => { `getAppKeyAddress(${mockDerivedAddress}, example.com): not implemented`, ); }); + + describe('address-only state', () => { + const otherAddress = '0x2222222222222222222222222222222222222222' as Hex; + + it('round-trips an address-only state', async () => { + const keyring = makeKeyring(); + + await keyring.deserialize({ address: mockDerivedAddress }); + + expect(await keyring.serialize()).toStrictEqual({ + address: mockDerivedAddress, + }); + expect(await keyring.getAccounts()).toStrictEqual([mockDerivedAddress]); + expect(await keyring.addAccounts()).toStrictEqual([mockDerivedAddress]); + }); + + it('rejects an address-only state with an invalid address', async () => { + const keyring = makeKeyring(); + + await expect(keyring.deserialize({ address: '0x1234' })).rejects.toThrow( + 'Invalid state', + ); + }); + + it('requires setup before signing', async () => { + const getProfileToken = jest.fn().mockResolvedValue('token'); + const keyring = makeKeyring(getProfileToken); + await keyring.deserialize({ address: mockDerivedAddress }); + + await expect( + keyring.signPersonalMessage(mockDerivedAddress, '0x68656c6c6f'), + ).rejects.toThrow('MpcMoneyKeyring: no key share, run setup first'); + expect(getProfileToken).not.toHaveBeenCalled(); + expect(mockStartSign).not.toHaveBeenCalled(); + }); + + it('imports the key share for the stored address on setup', async () => { + const getProfileToken = jest.fn().mockResolvedValue('token'); + const keyring = makeKeyring(getProfileToken); + await keyring.deserialize({ address: mockDerivedAddress }); + mockCreateIdentity.mockResolvedValueOnce({ partyId: 'imported-user' }); + mockThresholdKeyFromJson.mockReturnValueOnce(makeThresholdKey()); + + await keyring.setup(); + + expect(getProfileToken).toHaveBeenCalledWith({ twoFactor: true }); + expect(mockCheckKeyShare).not.toHaveBeenCalled(); + expect(mockStartCreateKey).not.toHaveBeenCalled(); + expect(mockRegisterClient).toHaveBeenCalledWith({ + baseURL: 'https://cloud.example', + token: 'token', + clientNetId: 'imported-user', + }); + expect(await keyring.getAccounts()).toStrictEqual([mockDerivedAddress]); + expect(await keyring.serialize()).toStrictEqual({ + netCreds: { partyId: 'imported-user' }, + keyShare: makeThresholdKey(), + serverNetId: 'cloud-user', + shareEpoch: mockShareEpoch, + tssSetup: null, + }); + }); + + it('rejects an imported key share for another address', async () => { + const keyring = makeKeyring(); + await keyring.deserialize({ address: otherAddress }); + mockCreateIdentity.mockResolvedValueOnce({ partyId: 'imported-user' }); + mockThresholdKeyFromJson.mockReturnValueOnce(makeThresholdKey()); + + await expect(keyring.setup()).rejects.toThrow( + 'MpcMoneyKeyring: imported key share address does not match expected account', + ); + expect(mockRegisterClient).not.toHaveBeenCalled(); + expect(await keyring.serialize()).toStrictEqual({ + address: otherAddress, + }); + }); + }); + + describe('read-only mode', () => { + const mockPublicKey = '0x04010203' as Hex; + + const makeReadOnlyKeyring = ( + getProfileToken = jest.fn().mockResolvedValue('token'), + getPrimaryMnemonic = jest.fn().mockResolvedValue(mockMnemonicBytes), + ) => makeKeyring(getProfileToken, getPrimaryMnemonic, false); + + it('reports whether the keyring is read-only', () => { + expect(makeReadOnlyKeyring().isReadOnly).toBe(true); + expect(makeKeyring().isReadOnly).toBe(false); + }); + + it('fetches only the address on setup', async () => { + const getProfileToken = jest.fn().mockResolvedValue('token'); + const getPrimaryMnemonic = jest.fn(); + const keyring = makeReadOnlyKeyring(getProfileToken, getPrimaryMnemonic); + mockCheckKeyShare.mockResolvedValueOnce({ + latestShareEpoch: mockShareEpoch, + latestBackupEpoch: mockShareEpoch, + activeEpoch: mockShareEpoch, + publicKey: mockPublicKey, + }); + + await keyring.setup(); + + expect(getProfileToken).toHaveBeenCalledTimes(1); + expect(getProfileToken).toHaveBeenCalledWith(); + expect(mockCheckKeyShare).toHaveBeenCalledWith({ + baseURL: 'https://cloud.example', + token: 'token', + }); + expect( + jest.requireMock('./util').publicKeyToAddressHex, + ).toHaveBeenCalledWith(new Uint8Array([4, 1, 2, 3])); + expect(getPrimaryMnemonic).not.toHaveBeenCalled(); + expect(mockCreateIdentity).not.toHaveBeenCalled(); + expect(mockGetNetId).not.toHaveBeenCalled(); + expect(mockStartCreateKey).not.toHaveBeenCalled(); + expect(mockLoadKeyShareBackup).not.toHaveBeenCalled(); + expect(await keyring.getAccounts()).toStrictEqual([mockDerivedAddress]); + expect(await keyring.serialize()).toStrictEqual({ + address: mockDerivedAddress, + }); + }); + + it.each([ + ['no key', {}], + [ + 'only a pending share', + { latestShareEpoch: 1, latestBackupEpoch: 1, publicKey: mockPublicKey }, + ], + [ + 'no public key', + { latestShareEpoch: 1, latestBackupEpoch: 1, activeEpoch: 1 }, + ], + ])('throws on setup when the backend has %s', async (_name, check) => { + const keyring = makeReadOnlyKeyring(); + mockCheckKeyShare.mockResolvedValueOnce(check); + + await expect(keyring.setup()).rejects.toThrow( + 'MpcMoneyKeyring: no MPC key for this profile', + ); + expect(await keyring.serialize()).toStrictEqual({}); + expect(await keyring.getAccounts()).toStrictEqual([]); + }); + + it.each([ + ['an address-only state', { address: mockDerivedAddress }], + ['a full state', makeSerializedState()], + ])('setup is a no-op with %s', async (_name, state) => { + const keyring = makeReadOnlyKeyring(); + await keyring.deserialize(state as unknown as Json); + + await keyring.setup(); + + expect(mockCheckKeyShare).not.toHaveBeenCalled(); + expect(mockLoadKeyShareBackup).not.toHaveBeenCalled(); + expect(await keyring.serialize()).toStrictEqual(state); + }); + + it('keeps a full state without signing with it', async () => { + const keyring = makeReadOnlyKeyring(); + const state = makeSerializedState(); + await deserializeState(keyring, state); + + expect(await keyring.getAccounts()).toStrictEqual([mockDerivedAddress]); + await expect( + keyring.signPersonalMessage(mockDerivedAddress, '0x68656c6c6f'), + ).rejects.toThrow('MpcMoneyKeyring: read-only, MFA is not available'); + expect(await keyring.serialize()).toStrictEqual(state); + }); + + it.each([ + [ + 'signPersonalMessage', + async (keyring: MpcMoneyKeyring) => + keyring.signPersonalMessage(mockDerivedAddress, '0x68656c6c6f'), + ], + [ + 'signTypedData', + async (keyring: MpcMoneyKeyring) => + keyring.signTypedData( + mockDerivedAddress, + [{ type: 'string', name: 'message', value: 'hello' }], + {}, + ), + ], + [ + 'signEip7702Authorization', + async (keyring: MpcMoneyKeyring) => + keyring.signEip7702Authorization(mockDerivedAddress, [ + 1, + '0x1234567890abcdef1234567890abcdef12345678', + 1, + ]), + ], + [ + 'rotateKeyShares', + async (keyring: MpcMoneyKeyring) => keyring.rotateKeyShares(), + ], + [ + 'checkKeyShare', + async (keyring: MpcMoneyKeyring) => keyring.checkKeyShare(), + ], + [ + 'syncKeyShare', + async (keyring: MpcMoneyKeyring) => keyring.syncKeyShare(), + ], + ])('blocks %s before any network call', async (_name, operation) => { + const getProfileToken = jest.fn().mockResolvedValue('token'); + const keyring = makeReadOnlyKeyring(getProfileToken); + await keyring.deserialize({ address: mockDerivedAddress }); + + await expect(operation(keyring)).rejects.toThrow( + 'MpcMoneyKeyring: read-only, MFA is not available', + ); + expect(getProfileToken).not.toHaveBeenCalled(); + expect(mockCheckKeyShare).not.toHaveBeenCalled(); + expect(mockStartSign).not.toHaveBeenCalled(); + expect(mockStartRotateKeyShares).not.toHaveBeenCalled(); + expect(mockLoadKeyShareBackup).not.toHaveBeenCalled(); + }); + }); }); diff --git a/packages/keyring-eth-money-mpc/src/mpc-money-keyring.ts b/packages/keyring-eth-money-mpc/src/mpc-money-keyring.ts index 53beb7956..fbf7b2059 100644 --- a/packages/keyring-eth-money-mpc/src/mpc-money-keyring.ts +++ b/packages/keyring-eth-money-mpc/src/mpc-money-keyring.ts @@ -34,6 +34,7 @@ import { } from '@metamask/superstruct'; import { bytesToHex, + HexAddressStruct, hexToBytes, JsonStruct, stringToBytes, @@ -56,7 +57,7 @@ import { MFA_REQUIRED_CODE } from './types.js'; import type { MoneyAccountSignatureRequest, MpcMoneyKeyring as MpcMoneyKeyringContract, - MpcMoneyKeyringInitializedState, + MpcMoneyKeyringAccountState, MpcMoneyKeyringOpts, MpcMoneyKeyringSerializer, MpcMoneyKeyringState, @@ -92,6 +93,10 @@ const InitializedStorageStruct = type({ tssSetup: nullable(string()), }); +const AddressOnlyStorageStruct = type({ + address: HexAddressStruct, +}); + /** * Whether `state` carries the initialized-keyring fields. * @@ -184,13 +189,15 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { readonly type: string = mpcMoneyKeyringType; + readonly isReadOnly: boolean; + readonly #networkManager: CentrifugeNetworkManager; readonly #tss: Dkls23TssLib; readonly #dkm: CL24DKM; - #state?: MpcMoneyKeyringInitializedState; + #state?: MpcMoneyKeyringAccountState; readonly #cloudURL: string; @@ -211,6 +218,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { * @param opts - TSS libraries, backend URLs, and token callbacks. */ constructor(opts: MpcMoneyKeyringOpts) { + this.isReadOnly = !opts.isMfaAvailable; this.#dkm = new CL24DKM(opts.cl24Lib); this.#tss = new Dkls23TssLib(opts.dkls23Lib); this.#cloudURL = opts.cloudURL; @@ -239,6 +247,10 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { return {}; } + if (this.#state.status === 'address-only') { + return { address: this.#state.address }; + } + const { netCreds, keyShare, serverNetId, shareEpoch, tssSetup } = this.#state; return { @@ -277,6 +289,16 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { if (hasInitializedFields(state)) { throw new Error('Invalid state'); } + + if (is(state, AddressOnlyStorageStruct)) { + this.#state = { status: 'address-only', address: state.address }; + return; + } + + // Reject malformed address-only state instead of treating it as fresh state. + if ('address' in state) { + throw new Error('Invalid state'); + } } /** @@ -284,6 +306,9 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { * import when an active epoch exists for the profile, create otherwise. * A pending share or backup is replaced by create. * + * A read-only keyring only fetches the account address. A read/write keyring + * that holds only an address imports the share for that address. + * * Serialized with sign, rotate and sync so overlapping `setup` calls run * setup once: the second call waits, sees the initialized state and returns. * @@ -296,11 +321,20 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { */ async setup(): Promise { return this.#serializeOp(async () => { + if (this.isReadOnly) { + if (!this.#state) { + await this.#setupAddressOnly(); + } + return; + } + if (this.#state?.status === 'initialized') { return; } - if (await this.#hasBackendKeyState()) { + if (this.#state?.status === 'address-only') { + await this.#setupImport(this.#state.address); + } else if (await this.#hasBackendKeyState()) { await this.#setupImport(); } else { await this.#setupCreate(); @@ -308,6 +342,30 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { }); } + /** + * Fetch the address of the active key without loading a key share. + * + * The backend reports the public key of the latest share, which may be + * pending. A pending share without an active epoch comes from an unfinished + * create that a later create replaces, so the address is only trusted when + * an active epoch exists. A pending rotation keeps the public key. + */ + async #setupAddressOnly(): Promise { + const token = await this.#getProfileToken(); + const { activeEpoch, publicKey } = await checkKeyShareRemote({ + baseURL: this.#cloudURL, + token, + }); + if (activeEpoch === undefined || publicKey === undefined) { + throw new Error('MpcMoneyKeyring: no MPC key for this profile'); + } + + this.#state = { + status: 'address-only', + address: publicKeyToAddressHex(hexToBytes(publicKey)), + }; + } + /** * Check whether the backend has an activated key for the profile. * @@ -476,11 +534,15 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { * @returns The addresses of all accounts in the keyring. */ async getAccounts(): Promise { - if (!this.#state || this.#state.status !== 'initialized') { + if (!this.#state) { return []; } - return [this.#address()]; + if (this.#state.status === 'address-only') { + return [this.#state.address]; + } + + return [publicKeyToAddressHex(this.#state.keyShare.publicKey)]; } /** @@ -655,7 +717,13 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { }); } - async #setupImport(): Promise { + /** + * Import the active share from the backend backup. + * + * @param expectedAddress - Address the imported share must match, when the + * keyring already exposes an account. + */ + async #setupImport(expectedAddress?: Hex): Promise { const token = await this.#getProfileToken({ twoFactor: true }); const netCreds = await this.#networkManager.createIdentity(); const serverNetId = await getNetId({ @@ -669,6 +737,15 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { }); const keyShare = await this.#decryptKeyShare(loaded.encryptedKeyShare); + if (expectedAddress !== undefined) { + const importedAddress = publicKeyToAddressHex(keyShare.publicKey); + if (!equalAddresses(importedAddress, expectedAddress)) { + throw new Error( + 'MpcMoneyKeyring: imported key share address does not match expected account', + ); + } + } + await registerClient({ baseURL: this.#cloudURL, token, @@ -694,7 +771,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { const { keyShare, netCreds, serverNetId, shareEpoch } = state; let { tssSetup } = state; - const addr = this.#address(); + const addr = publicKeyToAddressHex(keyShare.publicKey); if (!equalAddresses(address, addr)) { throw new Error(`account ${address} not found`); } @@ -893,13 +970,15 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { } #assertState(): MpcMoneyKeyringState { - if (!this.#state || this.#state.status !== 'initialized') { + if (this.isReadOnly) { + throw new Error('MpcMoneyKeyring: read-only, MFA is not available'); + } + if (!this.#state) { throw new Error('Keyring not initialized'); } + if (this.#state.status === 'address-only') { + throw new Error('MpcMoneyKeyring: no key share, run setup first'); + } return this.#state; } - - #address(): Hex { - return publicKeyToAddressHex(this.#assertState().keyShare.publicKey); - } } diff --git a/packages/keyring-eth-money-mpc/src/types.ts b/packages/keyring-eth-money-mpc/src/types.ts index 66ba79e66..10a44d335 100644 --- a/packages/keyring-eth-money-mpc/src/types.ts +++ b/packages/keyring-eth-money-mpc/src/types.ts @@ -59,6 +59,13 @@ export type Cl24Lib = ConstructorParameters[0]; export type Dkls23Lib = ConstructorParameters[0]; export type MpcMoneyKeyringOpts = { + /** + * Whether the client can provide a 2FA profile token. + * + * When `false`, the keyring is read-only: `setup` only fetches the account + * address from the backend, and signing and share maintenance throw. + */ + isMfaAvailable: boolean; cl24Lib: Cl24Lib; dkls23Lib: Dkls23Lib; cloudURL: string; @@ -90,6 +97,30 @@ export type MpcMoneyKeyringInitializedState = { status: 'initialized'; } & MpcMoneyKeyringState; +/** + * Keyring state that knows the account address but holds no key share. + */ +export type MpcMoneyKeyringAddressOnlyState = { + status: 'address-only'; + address: Hex; +}; + +/** + * Internal state of a keyring that holds an account. + * An absent state (`undefined`) means the keyring has not been set up. + * + * State transitions during setup: + * - absent -> initialized: create or import a key share when MFA is available. + * - absent -> address-only: fetch the account address when MFA is unavailable. + * - address-only -> initialized: import the matching key share when MFA is available. + * + * An address-only state can be restored into an MFA-capable instance. + * Import must preserve the account address that the keyring already exposes. + */ +export type MpcMoneyKeyringAccountState = + | MpcMoneyKeyringInitializedState + | MpcMoneyKeyringAddressOnlyState; + export type MpcMoneyKeyringSerializer = { thresholdKey: JsonSerializer; networkIdentity: JsonSerializer; @@ -101,10 +132,17 @@ export type MpcMoneyKeyringSerializer = { */ export type MpcMoneyKeyring = EthKeyring & { /** - * Run key generation or import. + * Whether the keyring was constructed without MFA. A read-only keyring + * exposes the account address but cannot sign. + */ + readonly isReadOnly: boolean; + + /** + * Run key generation or import, or only fetch the account address when the + * keyring is read-only. * - * The mode is inferred from the backend: import when a key share or - * backup exists for the profile, create otherwise. + * The mode is inferred from the backend: import when an active key exists + * for the profile, create otherwise. */ setup(): Promise; diff --git a/packages/keyring-eth-money-mpc/src/v2/mpc-money-keyring.test.ts b/packages/keyring-eth-money-mpc/src/v2/mpc-money-keyring.test.ts index 7b1f48fd6..69994666a 100644 --- a/packages/keyring-eth-money-mpc/src/v2/mpc-money-keyring.test.ts +++ b/packages/keyring-eth-money-mpc/src/v2/mpc-money-keyring.test.ts @@ -32,6 +32,7 @@ const EXPECTED_METHODS = MPC_MONEY_KEYRING_METHODS; */ type MockMpcMoneyKeyringV1 = { type: string; + isReadOnly: boolean; getAccounts: jest.Mock; setup: jest.Mock; serialize: jest.Mock; @@ -55,6 +56,7 @@ type MockMpcMoneyKeyringV1 = { function createInner(): MockMpcMoneyKeyringV1 { return { type: 'MPC Money Keyring', + isReadOnly: false, getAccounts: jest.fn().mockResolvedValue([] as Hex[]), setup: jest.fn().mockResolvedValue(undefined), serialize: jest.fn().mockResolvedValue({}), @@ -75,17 +77,21 @@ function createInner(): MockMpcMoneyKeyringV1 { * * @param args - Setup arguments. * @param args.accounts - The addresses reported by the inner keyring. + * @param args.isReadOnly - Whether the inner keyring is read-only. * @returns The wrapper and the mocked inner keyring. */ function setup({ accounts = [] as Hex[], + isReadOnly = false, }: { accounts?: Hex[]; + isReadOnly?: boolean; } = {}): { wrapper: MpcMoneyKeyring; inner: MockMpcMoneyKeyringV1; } { const inner = createInner(); + inner.isReadOnly = isReadOnly; inner.getAccounts.mockResolvedValue(accounts); const wrapper = new MpcMoneyKeyring({ @@ -180,6 +186,15 @@ describe('MpcMoneyKeyring (v2 wrapper)', () => { expect(account?.options.exportable).toBe(false); }); + it('returns the account without methods when the inner keyring is read-only', async () => { + const { wrapper } = setup({ accounts: [MOCK_ADDRESS], isReadOnly: true }); + + const [account] = await wrapper.getAccounts(); + + expect(account?.address).toBe(MOCK_ADDRESS); + expect(account?.methods).toStrictEqual([]); + }); + it('returns the same account on repeated calls', async () => { const { wrapper, inner } = setup({ accounts: [MOCK_ADDRESS] }); @@ -203,9 +218,9 @@ describe('MpcMoneyKeyring (v2 wrapper)', () => { describe('createAccounts', () => { it('runs setup via the inner keyring', async () => { const { wrapper, inner } = setup(); - inner.getAccounts - .mockResolvedValueOnce([]) - .mockResolvedValueOnce([MOCK_ADDRESS]); + inner.setup.mockImplementation(async () => { + inner.getAccounts.mockResolvedValue([MOCK_ADDRESS]); + }); const accounts = await wrapper.createAccounts({ type: 'custom' }); @@ -214,14 +229,34 @@ describe('MpcMoneyKeyring (v2 wrapper)', () => { expect(accounts[0]?.address).toBe(MOCK_ADDRESS); }); - it('is idempotent when the account already exists', async () => { + it('runs setup and returns the same account when it already exists', async () => { const { wrapper, inner } = setup({ accounts: [MOCK_ADDRESS] }); + const [existing] = await wrapper.getAccounts(); const accounts = await wrapper.createAccounts({ type: 'custom' }); - expect(inner.setup).not.toHaveBeenCalled(); - expect(accounts).toHaveLength(1); - expect(accounts[0]?.address).toBe(MOCK_ADDRESS); + expect(inner.setup).toHaveBeenCalledTimes(1); + expect(accounts).toStrictEqual([existing]); + }); + + it('rejects signing requests when the inner keyring is read-only', async () => { + const { wrapper, inner } = setup({ + accounts: [MOCK_ADDRESS], + isReadOnly: true, + }); + const [account] = await wrapper.getAccounts(); + const accountId = account?.id ?? ('' as AccountId); + + await expect( + wrapper.submitRequest( + createMockRequest(accountId, EthMethod.PersonalSign, [ + '0x68656c6c6f', + ]), + ), + ).rejects.toThrow( + `Account ${accountId} cannot handle method: ${EthMethod.PersonalSign}`, + ); + expect(inner.signPersonalMessage).not.toHaveBeenCalled(); }); it('throws when the inner keyring does not produce an account', async () => { diff --git a/packages/keyring-eth-money-mpc/src/v2/mpc-money-keyring.ts b/packages/keyring-eth-money-mpc/src/v2/mpc-money-keyring.ts index fdcae00dc..c66a33142 100644 --- a/packages/keyring-eth-money-mpc/src/v2/mpc-money-keyring.ts +++ b/packages/keyring-eth-money-mpc/src/v2/mpc-money-keyring.ts @@ -107,7 +107,7 @@ export class MpcMoneyKeyring type: EthAccountType.Eoa, address, scopes: [...this.capabilities.scopes], - methods: [...MPC_MONEY_KEYRING_METHODS], + methods: this.inner.isReadOnly ? [] : [...MPC_MONEY_KEYRING_METHODS], options: { entropy: { type: KeyringAccountEntropyTypeOption.Mpc, @@ -138,6 +138,9 @@ export class MpcMoneyKeyring /** * Create the account according to the provided options. * + * Always runs the inner `setup`, which is a no-op once the keyring is set + * up, so that a keyring holding only an address can load its key share. + * * @param options - Options describing how to create the account. * @returns A promise that resolves to a list containing the created * account. @@ -154,11 +157,6 @@ export class MpcMoneyKeyring ); } - const accounts = await this.getAccounts(); - if (accounts.length > 0) { - return accounts; - } - await this.inner.setup(); const [createdAccount] = await this.getAccounts();