@metamask-previews/mfa-recovery-controller 0.0.0-preview-701acab40 → 0.0.0-preview-d8f16be
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 +2 -0
- package/README.md +15 -0
- package/dist/MfaRecoveryController-method-action-types.d.ts +16 -1
- package/dist/MfaRecoveryController-method-action-types.d.ts.map +1 -1
- package/dist/MfaRecoveryController-method-action-types.js.map +1 -1
- package/dist/MfaRecoveryController.d.ts +19 -2
- package/dist/MfaRecoveryController.d.ts.map +1 -1
- package/dist/MfaRecoveryController.js +69 -2
- package/dist/MfaRecoveryController.js.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/recovery-registration-lock-provider.d.ts +30 -0
- package/dist/recovery-registration-lock-provider.d.ts.map +1 -0
- package/dist/recovery-registration-lock-provider.js +49 -0
- package/dist/recovery-registration-lock-provider.js.map +1 -0
- package/dist/types.d.ts +8 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -23,6 +23,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
23
23
|
- Rejects SIWE identifiers with malformed verifier fields, an invalid address or domain, or a `namespace` that is not their verifier's `domain:chainId` with `invalid_identifier` ([#11151](https://github.com/MetaMask/core/pull/11151))
|
|
24
24
|
- Rejects duplicate identifiers with `duplicate_identifier` and more than 16 identifiers with `too_many_identifiers` ([#11151](https://github.com/MetaMask/core/pull/11151))
|
|
25
25
|
- Clears a `writing` mutation in `abort()` and `resume()` once its approval has expired and no escrow applied it; `resume()` then throws `MutationRejectedError` ([#11151](https://github.com/MetaMask/core/pull/11151))
|
|
26
|
+
- Requires a `lockProvider` and adds `acquireLock` and `releaseLock`; the lease is acquired, or extended if already held, before every approval, and its ID is persisted in `lockId` ([#10910](https://github.com/MetaMask/core/pull/10910))
|
|
27
|
+
- Exports `RecoveryRegistrationLockProvider`, `RecoveryRegistrationLockProviderOptions`, `RecoveryRegistrationLockProviderMessenger` and `RecoveryLockProvider` for holding the lease in the recovery registration service ([#10910](https://github.com/MetaMask/core/pull/10910))
|
|
26
28
|
- Exports `MfaRecoveryController`, `getDefaultMfaRecoveryControllerState`, and the controller's action, event, messenger, state, and options types.
|
|
27
29
|
- Exports `AuthApiRecoveryAuthProvider`, `AuthApiRecoveryAuthProviderOptions` and `AuthApiRecoveryAuthProviderMessenger` for requesting approvals through `AuthenticationController:requestMfaApproval`, using the profile id from `AuthenticationController:refreshCanonicalProfileId` ([#10883](https://github.com/MetaMask/core/pull/10883))
|
|
28
30
|
- Exports `CubistEscrowProvider` and `CubistEscrowProviderOptions` for storing recovery secrets with CubeSigner. `CubistEscrowProviderOptions` takes a `getClient` callback instead of a CubeSigner client so callers can create and refresh the session lazily ([#11280](https://github.com/MetaMask/core/pull/11280))
|
package/README.md
CHANGED
|
@@ -6,6 +6,21 @@ Pending mutations are encrypted in controller state. `resume()` completes them;
|
|
|
6
6
|
`abort()` is allowed before writing, or once the write approval has expired and
|
|
7
7
|
no escrow applied the mutation. See [Architecture](ARCHITECTURE.md).
|
|
8
8
|
|
|
9
|
+
## Recovery Lock
|
|
10
|
+
|
|
11
|
+
Configure `RecoveryRegistrationLockProvider` with the registration service URL,
|
|
12
|
+
`fetch`, and a messenger that can call
|
|
13
|
+
`AuthenticationController:getBearerToken` and
|
|
14
|
+
`AuthenticationController:refreshCanonicalProfileId`.
|
|
15
|
+
|
|
16
|
+
Call `acquireLock()` before reading identifiers, hold it while changing Auth
|
|
17
|
+
identifiers and mutating, then call `releaseLock()`. Call `acquireLock()` again
|
|
18
|
+
after long user interaction to extend the lease.
|
|
19
|
+
|
|
20
|
+
The controller acquires the 6-minute lease before every 5-minute approval, and
|
|
21
|
+
escrows reject expired approvals. So once another operation can take the lease,
|
|
22
|
+
this operation's approvals are dead.
|
|
23
|
+
|
|
9
24
|
## Auth API Integration
|
|
10
25
|
|
|
11
26
|
Configure `AuthApiRecoveryAuthProvider` with a messenger that can call
|
|
@@ -3,6 +3,21 @@
|
|
|
3
3
|
* Do not edit manually.
|
|
4
4
|
*/
|
|
5
5
|
import type { MfaRecoveryController } from './MfaRecoveryController.js';
|
|
6
|
+
/**
|
|
7
|
+
* Acquires or extends the per-profile recovery lease. Hold it from the first
|
|
8
|
+
* read through any Auth identifier changes and mutations.
|
|
9
|
+
*/
|
|
10
|
+
export type MfaRecoveryControllerAcquireLockAction = {
|
|
11
|
+
type: `MfaRecoveryController:acquireLock`;
|
|
12
|
+
handler: MfaRecoveryController['acquireLock'];
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Releases the lease. A pending mutation must finish first.
|
|
16
|
+
*/
|
|
17
|
+
export type MfaRecoveryControllerReleaseLockAction = {
|
|
18
|
+
type: `MfaRecoveryController:releaseLock`;
|
|
19
|
+
handler: MfaRecoveryController['releaseLock'];
|
|
20
|
+
};
|
|
6
21
|
/**
|
|
7
22
|
* Creates version 1 of a recovery record.
|
|
8
23
|
*
|
|
@@ -105,5 +120,5 @@ export type MfaRecoveryControllerGetPhaseAction = {
|
|
|
105
120
|
/**
|
|
106
121
|
* Union of all MfaRecoveryController action types.
|
|
107
122
|
*/
|
|
108
|
-
export type MfaRecoveryControllerMethodActions = MfaRecoveryControllerRegisterAction | MfaRecoveryControllerUpdateRecoverySecretAction | MfaRecoveryControllerUpdateIdentifiersAction | MfaRecoveryControllerAuthenticateIdentifierAction | MfaRecoveryControllerGetRecoverySecretAction | MfaRecoveryControllerGetIdentifiersAction | MfaRecoveryControllerResumeAction | MfaRecoveryControllerAbortAction | MfaRecoveryControllerGetPhaseAction;
|
|
123
|
+
export type MfaRecoveryControllerMethodActions = MfaRecoveryControllerAcquireLockAction | MfaRecoveryControllerReleaseLockAction | MfaRecoveryControllerRegisterAction | MfaRecoveryControllerUpdateRecoverySecretAction | MfaRecoveryControllerUpdateIdentifiersAction | MfaRecoveryControllerAuthenticateIdentifierAction | MfaRecoveryControllerGetRecoverySecretAction | MfaRecoveryControllerGetIdentifiersAction | MfaRecoveryControllerResumeAction | MfaRecoveryControllerAbortAction | MfaRecoveryControllerGetPhaseAction;
|
|
109
124
|
//# sourceMappingURL=MfaRecoveryController-method-action-types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MfaRecoveryController-method-action-types.d.ts","sourceRoot":"","sources":["../src/MfaRecoveryController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAExE;;;;;;GAMG;AACH,MAAM,MAAM,mCAAmC,GAAG;IAChD,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,qBAAqB,CAAC,UAAU,CAAC,CAAC;CAC5C,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,+CAA+C,GAAG;IAC5D,IAAI,EAAE,4CAA4C,CAAC;IACnD,OAAO,EAAE,qBAAqB,CAAC,sBAAsB,CAAC,CAAC;CACxD,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,4CAA4C,GAAG;IACzD,IAAI,EAAE,yCAAyC,CAAC;IAChD,OAAO,EAAE,qBAAqB,CAAC,mBAAmB,CAAC,CAAC;CACrD,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,iDAAiD,GAAG;IAC9D,IAAI,EAAE,8CAA8C,CAAC;IACrD,OAAO,EAAE,qBAAqB,CAAC,wBAAwB,CAAC,CAAC;CAC1D,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,4CAA4C,GAAG;IACzD,IAAI,EAAE,yCAAyC,CAAC;IAChD,OAAO,EAAE,qBAAqB,CAAC,mBAAmB,CAAC,CAAC;CACrD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,yCAAyC,GAAG;IACtD,IAAI,EAAE,sCAAsC,CAAC;IAC7C,OAAO,EAAE,qBAAqB,CAAC,gBAAgB,CAAC,CAAC;CAClD,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,qBAAqB,CAAC,QAAQ,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C,IAAI,EAAE,6BAA6B,CAAC;IACpC,OAAO,EAAE,qBAAqB,CAAC,OAAO,CAAC,CAAC;CACzC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,mCAAmC,GAAG;IAChD,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,qBAAqB,CAAC,UAAU,CAAC,CAAC;CAC5C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kCAAkC,GAC1C,mCAAmC,GACnC,+CAA+C,GAC/C,4CAA4C,GAC5C,iDAAiD,GACjD,4CAA4C,GAC5C,yCAAyC,GACzC,iCAAiC,GACjC,gCAAgC,GAChC,mCAAmC,CAAC"}
|
|
1
|
+
{"version":3,"file":"MfaRecoveryController-method-action-types.d.ts","sourceRoot":"","sources":["../src/MfaRecoveryController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAExE;;;GAGG;AACH,MAAM,MAAM,sCAAsC,GAAG;IACnD,IAAI,EAAE,mCAAmC,CAAC;IAC1C,OAAO,EAAE,qBAAqB,CAAC,aAAa,CAAC,CAAC;CAC/C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sCAAsC,GAAG;IACnD,IAAI,EAAE,mCAAmC,CAAC;IAC1C,OAAO,EAAE,qBAAqB,CAAC,aAAa,CAAC,CAAC;CAC/C,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,mCAAmC,GAAG;IAChD,IA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C,UAAU,CAAC,CAAC;CAC5C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kCAAkC,GAC1C,sCAAsC,GACtC,sCAAsC,GACtC,mCAAmC,GACnC,+CAA+C,GAC/C,4CAA4C,GAC5C,iDAAiD,GACjD,4CAA4C,GAC5C,yCAAyC,GACzC,iCAAiC,GACjC,gCAAgC,GAChC,mCAAmC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MfaRecoveryController-method-action-types.js","sourceRoot":"","sources":["../src/MfaRecoveryController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { MfaRecoveryController } from './MfaRecoveryController.js';\n\n/**\n * Creates version 1 of a recovery record.\n *\n * @param recoverySecret - Secret replicated in full to every escrow.\n * @param identifiers - Ownership-approved identifier set. Must contain at\n * least two identifiers.\n */\nexport type MfaRecoveryControllerRegisterAction = {\n type: `MfaRecoveryController:register`;\n handler: MfaRecoveryController['register'];\n};\n\n/**\n * Replaces the recovery secret.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param recoverySecret - New secret.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\nexport type MfaRecoveryControllerUpdateRecoverySecretAction = {\n type: `MfaRecoveryController:updateRecoverySecret`;\n handler: MfaRecoveryController['updateRecoverySecret'];\n};\n\n/**\n * Replaces the complete identifier set.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param identifiers - New identifier set. Must contain at least two\n * identifiers.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\nexport type MfaRecoveryControllerUpdateIdentifiersAction = {\n type: `MfaRecoveryController:updateIdentifiers`;\n handler: MfaRecoveryController['updateIdentifiers'];\n};\n\n/**\n * Authenticates an identifier with a single login. Returns an ephemeral\n * {@link IdentifierSession} for {@link getRecoverySecret}. For seedless\n * social logins, the session also carries `seedlessAuthData` for\n * `SeedlessOnboardingController.authenticate`. Callers decide whether they\n * need `seedlessAuthData` (and its `revokeToken`), drop it after seedless\n * authenticate, and keep the key-bound session fields for recovery reads.\n *\n * @param identifier - Identifier to authenticate.\n * @returns Session for recovery reads, with seedless auth data when the\n * login returned it.\n */\nexport type MfaRecoveryControllerAuthenticateIdentifierAction = {\n type: `MfaRecoveryController:authenticateIdentifier`;\n handler: MfaRecoveryController['authenticateIdentifier'];\n};\n\n/**\n * Reads the recovery secret from available escrows and returns the highest\n * consistent version. `epoch` is the current recovery version and is required\n * by later mutations. Does not wait for a pending mutation to be repaired.\n *\n * @param session - Identifier authentication session used to authorize the\n * read.\n * @returns Recovered secret bytes and the selected epoch.\n */\nexport type MfaRecoveryControllerGetRecoverySecretAction = {\n type: `MfaRecoveryController:getRecoverySecret`;\n handler: MfaRecoveryController['getRecoverySecret'];\n};\n\n/**\n * Reads the enrolled identifiers from available escrows at the highest\n * consistent version, with Auth's current identifiers. Needs no recent MFA,\n * so a new device can build an {@link updateIdentifiers} call from it.\n *\n * @returns Enrolled identifiers, `epoch`, and Auth's identifiers.\n */\nexport type MfaRecoveryControllerGetIdentifiersAction = {\n type: `MfaRecoveryController:getIdentifiers`;\n handler: MfaRecoveryController['getIdentifiers'];\n};\n\n/**\n * Completes a persisted pending mutation, if any. Clears a `writing` one,\n * throwing `MutationRejectedError`, once its approval has expired and no\n * escrow applied it.\n */\nexport type MfaRecoveryControllerResumeAction = {\n type: `MfaRecoveryController:resume`;\n handler: MfaRecoveryController['resume'];\n};\n\n/**\n * Drops `authorizing` pending. Drops `writing` pending only once its approval\n * has expired and no escrow applied it; otherwise finish it with\n * {@link resume}.\n */\nexport type MfaRecoveryControllerAbortAction = {\n type: `MfaRecoveryController:abort`;\n handler: MfaRecoveryController['abort'];\n};\n\n/**\n * @returns Current recovery phase.\n */\nexport type MfaRecoveryControllerGetPhaseAction = {\n type: `MfaRecoveryController:getPhase`;\n handler: MfaRecoveryController['getPhase'];\n};\n\n/**\n * Union of all MfaRecoveryController action types.\n */\nexport type MfaRecoveryControllerMethodActions =\n | MfaRecoveryControllerRegisterAction\n | MfaRecoveryControllerUpdateRecoverySecretAction\n | MfaRecoveryControllerUpdateIdentifiersAction\n | MfaRecoveryControllerAuthenticateIdentifierAction\n | MfaRecoveryControllerGetRecoverySecretAction\n | MfaRecoveryControllerGetIdentifiersAction\n | MfaRecoveryControllerResumeAction\n | MfaRecoveryControllerAbortAction\n | MfaRecoveryControllerGetPhaseAction;\n"]}
|
|
1
|
+
{"version":3,"file":"MfaRecoveryController-method-action-types.js","sourceRoot":"","sources":["../src/MfaRecoveryController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { MfaRecoveryController } from './MfaRecoveryController.js';\n\n/**\n * Acquires or extends the per-profile recovery lease. Hold it from the first\n * read through any Auth identifier changes and mutations.\n */\nexport type MfaRecoveryControllerAcquireLockAction = {\n type: `MfaRecoveryController:acquireLock`;\n handler: MfaRecoveryController['acquireLock'];\n};\n\n/**\n * Releases the lease. A pending mutation must finish first.\n */\nexport type MfaRecoveryControllerReleaseLockAction = {\n type: `MfaRecoveryController:releaseLock`;\n handler: MfaRecoveryController['releaseLock'];\n};\n\n/**\n * Creates version 1 of a recovery record.\n *\n * @param recoverySecret - Secret replicated in full to every escrow.\n * @param identifiers - Ownership-approved identifier set. Must contain at\n * least two identifiers.\n */\nexport type MfaRecoveryControllerRegisterAction = {\n type: `MfaRecoveryController:register`;\n handler: MfaRecoveryController['register'];\n};\n\n/**\n * Replaces the recovery secret.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param recoverySecret - New secret.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\nexport type MfaRecoveryControllerUpdateRecoverySecretAction = {\n type: `MfaRecoveryController:updateRecoverySecret`;\n handler: MfaRecoveryController['updateRecoverySecret'];\n};\n\n/**\n * Replaces the complete identifier set.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param identifiers - New identifier set. Must contain at least two\n * identifiers.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\nexport type MfaRecoveryControllerUpdateIdentifiersAction = {\n type: `MfaRecoveryController:updateIdentifiers`;\n handler: MfaRecoveryController['updateIdentifiers'];\n};\n\n/**\n * Authenticates an identifier with a single login. Returns an ephemeral\n * {@link IdentifierSession} for {@link getRecoverySecret}. For seedless\n * social logins, the session also carries `seedlessAuthData` for\n * `SeedlessOnboardingController.authenticate`. Callers decide whether they\n * need `seedlessAuthData` (and its `revokeToken`), drop it after seedless\n * authenticate, and keep the key-bound session fields for recovery reads.\n *\n * @param identifier - Identifier to authenticate.\n * @returns Session for recovery reads, with seedless auth data when the\n * login returned it.\n */\nexport type MfaRecoveryControllerAuthenticateIdentifierAction = {\n type: `MfaRecoveryController:authenticateIdentifier`;\n handler: MfaRecoveryController['authenticateIdentifier'];\n};\n\n/**\n * Reads the recovery secret from available escrows and returns the highest\n * consistent version. `epoch` is the current recovery version and is required\n * by later mutations. Does not wait for a pending mutation to be repaired.\n *\n * @param session - Identifier authentication session used to authorize the\n * read.\n * @returns Recovered secret bytes and the selected epoch.\n */\nexport type MfaRecoveryControllerGetRecoverySecretAction = {\n type: `MfaRecoveryController:getRecoverySecret`;\n handler: MfaRecoveryController['getRecoverySecret'];\n};\n\n/**\n * Reads the enrolled identifiers from available escrows at the highest\n * consistent version, with Auth's current identifiers. Needs no recent MFA,\n * so a new device can build an {@link updateIdentifiers} call from it.\n *\n * @returns Enrolled identifiers, `epoch`, and Auth's identifiers.\n */\nexport type MfaRecoveryControllerGetIdentifiersAction = {\n type: `MfaRecoveryController:getIdentifiers`;\n handler: MfaRecoveryController['getIdentifiers'];\n};\n\n/**\n * Completes a persisted pending mutation, if any. Clears a `writing` one,\n * throwing `MutationRejectedError`, once its approval has expired and no\n * escrow applied it.\n */\nexport type MfaRecoveryControllerResumeAction = {\n type: `MfaRecoveryController:resume`;\n handler: MfaRecoveryController['resume'];\n};\n\n/**\n * Drops `authorizing` pending. Drops `writing` pending only once its approval\n * has expired and no escrow applied it; otherwise finish it with\n * {@link resume}.\n */\nexport type MfaRecoveryControllerAbortAction = {\n type: `MfaRecoveryController:abort`;\n handler: MfaRecoveryController['abort'];\n};\n\n/**\n * @returns Current recovery phase.\n */\nexport type MfaRecoveryControllerGetPhaseAction = {\n type: `MfaRecoveryController:getPhase`;\n handler: MfaRecoveryController['getPhase'];\n};\n\n/**\n * Union of all MfaRecoveryController action types.\n */\nexport type MfaRecoveryControllerMethodActions =\n | MfaRecoveryControllerAcquireLockAction\n | MfaRecoveryControllerReleaseLockAction\n | MfaRecoveryControllerRegisterAction\n | MfaRecoveryControllerUpdateRecoverySecretAction\n | MfaRecoveryControllerUpdateIdentifiersAction\n | MfaRecoveryControllerAuthenticateIdentifierAction\n | MfaRecoveryControllerGetRecoverySecretAction\n | MfaRecoveryControllerGetIdentifiersAction\n | MfaRecoveryControllerResumeAction\n | MfaRecoveryControllerAbortAction\n | MfaRecoveryControllerGetPhaseAction;\n"]}
|
|
@@ -2,9 +2,13 @@ import type { ControllerGetStateAction, ControllerStateChangedEvent } from '@met
|
|
|
2
2
|
import { BaseController } from '@metamask/base-controller';
|
|
3
3
|
import type { Messenger } from '@metamask/messenger';
|
|
4
4
|
import type { MfaRecoveryControllerMethodActions } from './MfaRecoveryController-method-action-types.js';
|
|
5
|
-
import type { Identifier, IdentifierSession, PendingOperationEncryptor, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryIdentifiers, RecoveryPhase, RecoveredSecret } from './types.js';
|
|
5
|
+
import type { Identifier, IdentifierSession, PendingOperationEncryptor, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryIdentifiers, RecoveryLockProvider, RecoveryPhase, RecoveredSecret } from './types.js';
|
|
6
6
|
declare const CONTROLLER_NAME = "MfaRecoveryController";
|
|
7
7
|
export type MfaRecoveryControllerState = {
|
|
8
|
+
/**
|
|
9
|
+
* Held recovery lease ID, reused when retrying, or `null`.
|
|
10
|
+
*/
|
|
11
|
+
lockId: string | null;
|
|
8
12
|
/**
|
|
9
13
|
* Encrypted pending mutation, or `null` when idle.
|
|
10
14
|
*/
|
|
@@ -35,6 +39,10 @@ export type MfaRecoveryControllerOptions = {
|
|
|
35
39
|
* Authenticates the MetaMask profile and issues request-bound attestations.
|
|
36
40
|
*/
|
|
37
41
|
authProvider: RecoveryAuthProvider;
|
|
42
|
+
/**
|
|
43
|
+
* Holds the per-profile recovery lease.
|
|
44
|
+
*/
|
|
45
|
+
lockProvider: RecoveryLockProvider;
|
|
38
46
|
/**
|
|
39
47
|
* Obtains key-bound identifier tokens from an IdP.
|
|
40
48
|
*/
|
|
@@ -59,7 +67,16 @@ export type MfaRecoveryControllerOptions = {
|
|
|
59
67
|
*/
|
|
60
68
|
export declare class MfaRecoveryController extends BaseController<typeof CONTROLLER_NAME, MfaRecoveryControllerState, MfaRecoveryControllerMessenger> {
|
|
61
69
|
#private;
|
|
62
|
-
constructor({ messenger, state, authProvider, identifierAuthProvider, escrows, pendingOperationEncryptor, now, }: MfaRecoveryControllerOptions);
|
|
70
|
+
constructor({ messenger, state, authProvider, lockProvider, identifierAuthProvider, escrows, pendingOperationEncryptor, now, }: MfaRecoveryControllerOptions);
|
|
71
|
+
/**
|
|
72
|
+
* Acquires or extends the per-profile recovery lease. Hold it from the first
|
|
73
|
+
* read through any Auth identifier changes and mutations.
|
|
74
|
+
*/
|
|
75
|
+
acquireLock(): Promise<void>;
|
|
76
|
+
/**
|
|
77
|
+
* Releases the lease. A pending mutation must finish first.
|
|
78
|
+
*/
|
|
79
|
+
releaseLock(): Promise<void>;
|
|
63
80
|
/**
|
|
64
81
|
* Creates version 1 of a recovery record.
|
|
65
82
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MfaRecoveryController.d.ts","sourceRoot":"","sources":["../src/MfaRecoveryController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,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CAAC,IAAI,CAAC,CA2BjC;IAED;;;;;;OAMG;IACG,QAAQ,CACZ,cAAc,EAAE,UAAU,EAC1B,WAAW,EAAE,UAAU,EAAE,GACxB,OAAO,CAAC,IAAI,CAAC,CAYf;IAED;;;;;;OAMG;IACG,oBAAoB,CACxB,UAAU,EAAE,UAAU,EACtB,cAAc,EAAE,UAAU,EAC1B,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAUf;IAED;;;;;;;OAOG;IACG,iBAAiB,CACrB,UAAU,EAAE,UAAU,EACtB,WAAW,EAAE,UAAU,EAAE,EACzB,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CASf;IAED;;;;;;;;;;;OAWG;IACG,sBAAsB,CAC1B,UAAU,EAAE,UAAU,GACrB,OAAO,CAAC,iBAAiB,CAAC,CA6B5B;IAED;;;;;;;;OAQG;IACG,iBAAiB,CACrB,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,eAAe,CAAC,CAsE1B;IAED;;;;;;OAMG;IACG,cAAc,IAAI,OAAO,CAAC,mBAAmB,CAAC,CA8BnD;IAED;;;;OAIG;IACG,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAI5B;IAED;;;;OAIG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAa3B;IAED;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,aAAa,CAAC,CAIvC;CAigBF"}
|
|
@@ -9,6 +9,8 @@ import { assertValidPendingOperation, pendingPayloadHasIdentifiers, pendingPaylo
|
|
|
9
9
|
import { getRecoveryPhase } from './state-machine.js';
|
|
10
10
|
const CONTROLLER_NAME = 'MfaRecoveryController';
|
|
11
11
|
const MESSENGER_EXPOSED_METHODS = [
|
|
12
|
+
'acquireLock',
|
|
13
|
+
'releaseLock',
|
|
12
14
|
'register',
|
|
13
15
|
'updateRecoverySecret',
|
|
14
16
|
'updateIdentifiers',
|
|
@@ -20,6 +22,12 @@ const MESSENGER_EXPOSED_METHODS = [
|
|
|
20
22
|
'getPhase',
|
|
21
23
|
];
|
|
22
24
|
const mfaRecoveryControllerMetadata = {
|
|
25
|
+
lockId: {
|
|
26
|
+
persist: true,
|
|
27
|
+
includeInDebugSnapshot: false,
|
|
28
|
+
includeInStateLogs: false,
|
|
29
|
+
usedInUi: false,
|
|
30
|
+
},
|
|
23
31
|
pendingOperation: {
|
|
24
32
|
persist: true,
|
|
25
33
|
includeInDebugSnapshot: false,
|
|
@@ -31,19 +39,20 @@ const mfaRecoveryControllerMetadata = {
|
|
|
31
39
|
* @returns The default {@link MfaRecoveryController} state.
|
|
32
40
|
*/
|
|
33
41
|
export function getDefaultMfaRecoveryControllerState() {
|
|
34
|
-
return { pendingOperation: null };
|
|
42
|
+
return { lockId: null, pendingOperation: null };
|
|
35
43
|
}
|
|
36
44
|
/**
|
|
37
45
|
* Coordinates MFA recovery secret replication across independent escrows.
|
|
38
46
|
*/
|
|
39
47
|
export class MfaRecoveryController extends BaseController {
|
|
40
48
|
#authProvider;
|
|
49
|
+
#lockProvider;
|
|
41
50
|
#identifierAuthProvider;
|
|
42
51
|
#escrows;
|
|
43
52
|
#encryptor;
|
|
44
53
|
#now;
|
|
45
54
|
#lock = Promise.resolve();
|
|
46
|
-
constructor({ messenger, state, authProvider, identifierAuthProvider, escrows, pendingOperationEncryptor, now = unixNow, }) {
|
|
55
|
+
constructor({ messenger, state, authProvider, lockProvider, identifierAuthProvider, escrows, pendingOperationEncryptor, now = unixNow, }) {
|
|
47
56
|
if (escrows.length === 0) {
|
|
48
57
|
throw new MfaRecoveryError('At least one escrow is required', 'empty_escrow_set');
|
|
49
58
|
}
|
|
@@ -61,12 +70,47 @@ export class MfaRecoveryController extends BaseController {
|
|
|
61
70
|
},
|
|
62
71
|
});
|
|
63
72
|
this.#authProvider = authProvider;
|
|
73
|
+
this.#lockProvider = lockProvider;
|
|
64
74
|
this.#identifierAuthProvider = identifierAuthProvider;
|
|
65
75
|
this.#escrows = [...escrows];
|
|
66
76
|
this.#encryptor = pendingOperationEncryptor;
|
|
67
77
|
this.#now = now;
|
|
68
78
|
this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
|
|
69
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* Acquires or extends the per-profile recovery lease. Hold it from the first
|
|
82
|
+
* read through any Auth identifier changes and mutations.
|
|
83
|
+
*/
|
|
84
|
+
async acquireLock() {
|
|
85
|
+
await this.#withLock(async () => this.#acquireLease());
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Releases the lease. A pending mutation must finish first.
|
|
89
|
+
*/
|
|
90
|
+
async releaseLock() {
|
|
91
|
+
await this.#withLock(async () => {
|
|
92
|
+
if (await this.#loadPending()) {
|
|
93
|
+
throw new MfaRecoveryError('A pending mutation must be resumed or aborted first', 'pending_mutation');
|
|
94
|
+
}
|
|
95
|
+
const { lockId } = this.state;
|
|
96
|
+
if (lockId === null) {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
await this.#lockProvider.release(lockId);
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
// A conflict means another ID holds the lease, so it is not ours.
|
|
104
|
+
if (!(error instanceof MfaRecoveryError) ||
|
|
105
|
+
error.code !== 'recovery_lock_conflict') {
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
this.update((state) => {
|
|
110
|
+
state.lockId = null;
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
}
|
|
70
114
|
/**
|
|
71
115
|
* Creates version 1 of a recovery record.
|
|
72
116
|
*
|
|
@@ -342,6 +386,9 @@ export class MfaRecoveryController extends BaseController {
|
|
|
342
386
|
});
|
|
343
387
|
}
|
|
344
388
|
async #authorizeMutation(mutation) {
|
|
389
|
+
// The lease outlives the approval, so no write lands after another
|
|
390
|
+
// operation can take the lease.
|
|
391
|
+
await this.#acquireLease();
|
|
345
392
|
const { approval, identifiers } = await this.#authProvider.authorizeRecoveryRequest({
|
|
346
393
|
requestHash: mutation.requestHash,
|
|
347
394
|
audiences: this.#escrows.map((escrow) => escrow.authAudience),
|
|
@@ -589,6 +636,26 @@ export class MfaRecoveryController extends BaseController {
|
|
|
589
636
|
state.pendingOperation = null;
|
|
590
637
|
});
|
|
591
638
|
}
|
|
639
|
+
async #acquireLease() {
|
|
640
|
+
const lockId = this.state.lockId ?? randomId();
|
|
641
|
+
this.update((state) => {
|
|
642
|
+
state.lockId = lockId;
|
|
643
|
+
});
|
|
644
|
+
try {
|
|
645
|
+
await this.#lockProvider.acquire(lockId);
|
|
646
|
+
}
|
|
647
|
+
catch (error) {
|
|
648
|
+
// A conflict means another ID holds the lease. Other failures may have
|
|
649
|
+
// acquired it, so keep the ID for a retry.
|
|
650
|
+
if (error instanceof MfaRecoveryError &&
|
|
651
|
+
error.code === 'recovery_lock_conflict') {
|
|
652
|
+
this.update((state) => {
|
|
653
|
+
state.lockId = null;
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
throw error;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
592
659
|
async #withLock(fn) {
|
|
593
660
|
const run = this.#lock.then(fn, fn);
|
|
594
661
|
this.#lock = run.then(() => undefined, () => undefined);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MfaRecoveryController.js","sourceRoot":"","sources":["../src/MfaRecoveryController.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEvE,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,eAAe,EACf,IAAI,EACJ,QAAQ,EACR,OAAO,EACP,SAAS,GACV,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,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CAAC,gBAAgB,GAAG,IAAI,CAAC;QAChC,CAAC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,SAAS,CACb,EAA8B;QAE9B,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QACpC,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CACnB,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;QACF,OAAO,MAAM,GAAG,CAAC;IACnB,CAAC;CACF;AAED;;;;;;GAMG;AACH,SAAS,0BAA0B,CACjC,OAAgD,EAChD,gBAAmC;IAEnC,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,SAAS,GAAiC,IAAI,CAAC;IACnD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IACE,MAAM,CAAC,MAAM,KAAK,UAAU;YAC5B,CAAC,CAAC,MAAM,CAAC,MAAM,YAAY,qBAAqB,CAAC,EACjD,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,SAAS,KAAK,MAAM,CAAC,MAAM,CAAC;IAC9B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport { bytesToHex, hexToBytes, isHexAddress } from '@metamask/utils';\n\nimport { decodeAuthControllerToken } from './auth-controller-token.js';\nimport {\n decryptFromPublic,\n encryptToPublic,\n generateWrapKey,\n hash,\n randomId,\n unixNow,\n wrapKeyId,\n} from './crypto.js';\nimport {\n IncompleteMutationError,\n MfaRecoveryError,\n MutationRejectedError,\n} from './errors.js';\nimport {\n isFulfilledResult,\n isMutationReceipt,\n selectHighestConsistentVersion,\n verifyMutationReceipt,\n} from './escrow-utils.js';\nimport {\n authorizeEscrowsWithToken,\n countDistinctIdentifiers,\n getIdentifierAuthMode,\n getSiweNamespace,\n MAX_IDENTIFIERS,\n MIN_IDENTIFIERS,\n requestIdentifierLogin,\n validateSeedlessAuthData,\n} from './identifier-auth.js';\nimport type { MfaRecoveryControllerMethodActions } from './MfaRecoveryController-method-action-types.js';\nimport {\n assertValidPendingOperation,\n pendingPayloadHasIdentifiers,\n pendingPayloadHasRecoverySecret,\n} from './pending-operation-validation.js';\nimport { getRecoveryPhase } from './state-machine.js';\nimport type {\n GetIdentifiersResponse,\n Identifier,\n IdentifierAuthorization,\n IdentifierSession,\n KeyBoundCredential,\n Mutation,\n MutationPayload,\n MutationReceipt,\n PendingOperation,\n PendingOperationEncryptor,\n PendingRegisterPayload,\n PendingUpdateIdentifiersPayload,\n PendingUpdateRecoverySecretPayload,\n RecoveryAuthProvider,\n RecoveryEscrowProvider,\n RecoveryIdentifierAuthProvider,\n RecoveryIdentifiers,\n RecoveryPhase,\n RecoveredSecret,\n WrappedSecret,\n WritingPendingOperation,\n} from './types.js';\n\nconst CONTROLLER_NAME = 'MfaRecoveryController';\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'register',\n 'updateRecoverySecret',\n 'updateIdentifiers',\n 'authenticateIdentifier',\n 'getRecoverySecret',\n 'getIdentifiers',\n 'resume',\n 'abort',\n 'getPhase',\n] as const;\n\nexport type MfaRecoveryControllerState = {\n /**\n * Encrypted pending mutation, or `null` when idle.\n */\n pendingOperation: string | null;\n};\n\nconst mfaRecoveryControllerMetadata = {\n pendingOperation: {\n persist: true,\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n usedInUi: true,\n },\n} satisfies StateMetadata<MfaRecoveryControllerState>;\n\n/**\n * @returns The default {@link MfaRecoveryController} state.\n */\nexport function getDefaultMfaRecoveryControllerState(): MfaRecoveryControllerState {\n return { pendingOperation: null };\n}\n\nexport type MfaRecoveryControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n MfaRecoveryControllerState\n>;\n\nexport type MfaRecoveryControllerActions =\n | MfaRecoveryControllerGetStateAction\n | MfaRecoveryControllerMethodActions;\n\ntype AllowedActions = never;\n\nexport type MfaRecoveryControllerStateChangedEvent =\n ControllerStateChangedEvent<\n typeof CONTROLLER_NAME,\n MfaRecoveryControllerState\n >;\n\nexport type MfaRecoveryControllerEvents =\n MfaRecoveryControllerStateChangedEvent;\n\ntype AllowedEvents = never;\n\nexport type MfaRecoveryControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n MfaRecoveryControllerActions | AllowedActions,\n MfaRecoveryControllerEvents | AllowedEvents\n>;\n\nexport type MfaRecoveryControllerOptions = {\n /**\n * The messenger suited for this controller.\n */\n messenger: MfaRecoveryControllerMessenger;\n\n /**\n * The desired state with which to initialize this controller. Missing\n * properties will be filled in with defaults.\n */\n state?: Partial<MfaRecoveryControllerState>;\n\n /**\n * Authenticates the MetaMask profile and issues request-bound attestations.\n */\n authProvider: RecoveryAuthProvider;\n\n /**\n * Obtains key-bound identifier tokens from an IdP.\n */\n identifierAuthProvider: RecoveryIdentifierAuthProvider;\n\n /**\n * Ordered, non-empty set of recovery escrow replicas. This is build-time\n * configuration; public methods cannot override it.\n */\n escrows: RecoveryEscrowProvider[];\n\n /**\n * Encrypts pending mutation state using wallet secure storage.\n */\n pendingOperationEncryptor: PendingOperationEncryptor;\n\n /**\n * Clock used for AuthController token expiry checks. Unix seconds.\n * Defaults to {@link unixNow}.\n */\n now?: () => number;\n};\n\ntype MutateParams = {\n epoch: number;\n} & (\n | {\n operation: 'register';\n payload: PendingRegisterPayload;\n identifier: null;\n }\n | {\n operation: 'updateRecoverySecret';\n payload: PendingUpdateRecoverySecretPayload;\n identifier: Identifier;\n }\n | {\n operation: 'updateIdentifiers';\n payload: PendingUpdateIdentifiersPayload;\n identifier: Identifier;\n }\n);\n\n/**\n * Coordinates MFA recovery secret replication across independent escrows.\n */\nexport class MfaRecoveryController extends BaseController<\n typeof CONTROLLER_NAME,\n MfaRecoveryControllerState,\n MfaRecoveryControllerMessenger\n> {\n readonly #authProvider: RecoveryAuthProvider;\n\n readonly #identifierAuthProvider: RecoveryIdentifierAuthProvider;\n\n readonly #escrows: RecoveryEscrowProvider[];\n\n readonly #encryptor: PendingOperationEncryptor;\n\n readonly #now: () => number;\n\n #lock: Promise<void> = Promise.resolve();\n\n constructor({\n messenger,\n state,\n authProvider,\n identifierAuthProvider,\n escrows,\n pendingOperationEncryptor,\n now = unixNow,\n }: MfaRecoveryControllerOptions) {\n if (escrows.length === 0) {\n throw new MfaRecoveryError(\n 'At least one escrow is required',\n 'empty_escrow_set',\n );\n }\n const escrowIds = escrows.map((escrow) => escrow.id);\n if (new Set(escrowIds).size !== escrowIds.length) {\n throw new MfaRecoveryError('Duplicate escrow id', 'duplicate_escrow_id');\n }\n\n super({\n messenger,\n metadata: mfaRecoveryControllerMetadata,\n name: CONTROLLER_NAME,\n state: {\n ...getDefaultMfaRecoveryControllerState(),\n ...state,\n },\n });\n\n this.#authProvider = authProvider;\n this.#identifierAuthProvider = identifierAuthProvider;\n this.#escrows = [...escrows];\n this.#encryptor = pendingOperationEncryptor;\n this.#now = now;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Creates version 1 of a recovery record.\n *\n * @param recoverySecret - Secret replicated in full to every escrow.\n * @param identifiers - Ownership-approved identifier set. Must contain at\n * least two identifiers.\n */\n async register(\n recoverySecret: Uint8Array,\n identifiers: Identifier[],\n ): Promise<void> {\n this.#assertValidIdentifiers(identifiers);\n this.#assertIdentifierSet(identifiers);\n await this.#mutate({\n operation: 'register',\n payload: {\n identifiers,\n recoverySecret: bytesToHex(recoverySecret),\n },\n identifier: null,\n epoch: 0,\n });\n }\n\n /**\n * Replaces the recovery secret.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param recoverySecret - New secret.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\n async updateRecoverySecret(\n identifier: Identifier,\n recoverySecret: Uint8Array,\n epoch: number,\n ): Promise<void> {\n this.#assertValidIdentifiers([identifier]);\n await this.#mutate({\n operation: 'updateRecoverySecret',\n payload: {\n recoverySecret: bytesToHex(recoverySecret),\n },\n identifier,\n epoch,\n });\n }\n\n /**\n * Replaces the complete identifier set.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param identifiers - New identifier set. Must contain at least two\n * identifiers.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\n async updateIdentifiers(\n identifier: Identifier,\n identifiers: Identifier[],\n epoch: number,\n ): Promise<void> {\n this.#assertValidIdentifiers([identifier, ...identifiers]);\n this.#assertIdentifierSet(identifiers);\n await this.#mutate({\n operation: 'updateIdentifiers',\n payload: { identifiers },\n identifier,\n epoch,\n });\n }\n\n /**\n * Authenticates an identifier with a single login. Returns an ephemeral\n * {@link IdentifierSession} for {@link getRecoverySecret}. For seedless\n * social logins, the session also carries `seedlessAuthData` for\n * `SeedlessOnboardingController.authenticate`. Callers decide whether they\n * need `seedlessAuthData` (and its `revokeToken`), drop it after seedless\n * authenticate, and keep the key-bound session fields for recovery reads.\n *\n * @param identifier - Identifier to authenticate.\n * @returns Session for recovery reads, with seedless auth data when the\n * login returned it.\n */\n async authenticateIdentifier(\n identifier: Identifier,\n ): Promise<IdentifierSession> {\n this.#assertValidIdentifiers([identifier]);\n const requestId = randomId();\n const ephemeral = await generateWrapKey();\n const pkE = ephemeral.publicKey;\n const requestHash = await hash({\n operation: 'getRecoverySecret',\n requestId,\n pkE,\n });\n const { seedlessAuthData, ...credential } = await requestIdentifierLogin({\n identifier,\n requestHash,\n identifierAuthProvider: this.#identifierAuthProvider,\n });\n return {\n ...credential,\n requestId,\n ephemeralPrivateKey: ephemeral.privateKey,\n pkE,\n ...(seedlessAuthData === undefined\n ? {}\n : {\n seedlessAuthData: validateSeedlessAuthData(\n seedlessAuthData,\n identifier,\n ),\n }),\n };\n }\n\n /**\n * Reads the recovery secret from available escrows and returns the highest\n * consistent version. `epoch` is the current recovery version and is required\n * by later mutations. Does not wait for a pending mutation to be repaired.\n *\n * @param session - Identifier authentication session used to authorize the\n * read.\n * @returns Recovered secret bytes and the selected epoch.\n */\n async getRecoverySecret(\n session: IdentifierSession,\n ): Promise<RecoveredSecret> {\n return await this.#withLock(async () => {\n const { token, requestId, pkE } = session;\n this.#assertValidIdentifiers([token.identifier]);\n const requestHash = await hash({\n operation: 'getRecoverySecret',\n requestId,\n pkE,\n });\n if (token.requestHash !== requestHash) {\n throw new MfaRecoveryError(\n 'Invalid identifier session',\n 'invalid_identifier_session',\n );\n }\n const available = await this.#getAvailableEscrows();\n if (available.length === 0) {\n throw new MfaRecoveryError(\n 'No escrow is available',\n 'no_available_escrow',\n );\n }\n const { approval } = await this.#authProvider.authorizeRecoveryRequest({\n requestHash,\n audiences: available.map((escrow) => escrow.authAudience),\n requireTwoFactor: true,\n });\n const authorizedEscrows = await authorizeEscrowsWithToken({\n escrows: available,\n credentials: [\n {\n token: session.token,\n proofPrivateKey: session.proofPrivateKey,\n },\n ],\n authControllerToken: approval,\n });\n const results = await Promise.allSettled(\n authorizedEscrows.map(async ({ escrow, authorizations }) => {\n const [authorization] = authorizations;\n const response = await escrow.getSecret(\n approval,\n authorization,\n requestId,\n pkE,\n );\n if (response.wrapKeyId !== (await wrapKeyId(escrow.wrapPublicKey))) {\n throw new MfaRecoveryError(\n 'Unexpected wrap key',\n 'wrap_key_mismatch',\n );\n }\n return {\n escrowId: escrow.id,\n recoverySecret: await decryptFromPublic(\n session.ephemeralPrivateKey,\n escrow.wrapPublicKey,\n response.recoverySecret.ciphertext,\n ),\n version: response.version,\n lastMutationId: response.lastMutationId,\n };\n }),\n );\n const selected = selectHighestConsistentVersion(results);\n return {\n recoverySecret: selected.recoverySecret,\n epoch: selected.version,\n };\n });\n }\n\n /**\n * Reads the enrolled identifiers from available escrows at the highest\n * consistent version, with Auth's current identifiers. Needs no recent MFA,\n * so a new device can build an {@link updateIdentifiers} call from it.\n *\n * @returns Enrolled identifiers, `epoch`, and Auth's identifiers.\n */\n async getIdentifiers(): Promise<RecoveryIdentifiers> {\n return await this.#withLock(async () => {\n const available = await this.#getAvailableEscrows();\n if (available.length === 0) {\n throw new MfaRecoveryError(\n 'No escrow is available',\n 'no_available_escrow',\n );\n }\n const { authIdentifiers, results } =\n await this.#authorizeAndReadIdentifiers(available);\n const responses = results\n .filter(isFulfilledResult)\n .map((result) => result.value);\n if (responses.length === 0) {\n throw new MfaRecoveryError(\n 'No escrow returned identifiers',\n 'read_failed',\n );\n }\n const epoch = Math.max(...responses.map(({ version }) => version));\n const highest = responses.filter(({ version }) => version === epoch);\n const hashes = await Promise.all(\n highest.map(async ({ identifiers }) => await hash(identifiers)),\n );\n if (new Set(hashes).size !== 1) {\n throw new MfaRecoveryError('Replica corruption', 'replica_corruption');\n }\n return { identifiers: highest[0].identifiers, epoch, authIdentifiers };\n });\n }\n\n /**\n * Completes a persisted pending mutation, if any. Clears a `writing` one,\n * throwing `MutationRejectedError`, once its approval has expired and no\n * escrow applied it.\n */\n async resume(): Promise<void> {\n await this.#withLock(async () => {\n await this.#repairPendingMutation();\n });\n }\n\n /**\n * Drops `authorizing` pending. Drops `writing` pending only once its approval\n * has expired and no escrow applied it; otherwise finish it with\n * {@link resume}.\n */\n async abort(): Promise<void> {\n await this.#withLock(async () => {\n const pending = await this.#loadPending();\n if (pending?.phase === 'writing' && !(await this.#isUnapplied(pending))) {\n throw new MfaRecoveryError(\n 'Cannot abort a mutation that may have been applied',\n 'abort_not_allowed',\n );\n }\n if (pending) {\n await this.#clearPending();\n }\n });\n }\n\n /**\n * @returns Current recovery phase.\n */\n async getPhase(): Promise<RecoveryPhase> {\n return await this.#withLock(async () =>\n getRecoveryPhase(await this.#loadPending()),\n );\n }\n\n // No write can land after its approval expires, and escrow versions only\n // grow, so every escrow below `newVersion` means none applied it.\n async #isUnapplied({\n mutation,\n authControllerToken,\n }: WritingPendingOperation): Promise<boolean> {\n const claims = decodeAuthControllerToken(authControllerToken);\n if (claims && claims.exp > this.#now()) {\n return false;\n }\n const { results } = await this.#authorizeAndReadIdentifiers(this.#escrows);\n return results.every(\n (result) =>\n isFulfilledResult(result) && result.value.version < mutation.newVersion,\n );\n }\n\n // Read approvals need no 2FA.\n async #authorizeAndReadIdentifiers(\n escrows: RecoveryEscrowProvider[],\n ): Promise<{\n authIdentifiers: Identifier[];\n results: PromiseSettledResult<GetIdentifiersResponse>[];\n }> {\n const { approval, identifiers } =\n await this.#authProvider.authorizeRecoveryRequest({\n requestHash: await hash({ operation: 'getIdentifiers' }),\n audiences: escrows.map((escrow) => escrow.authAudience),\n });\n const results = await Promise.allSettled(\n escrows.map(async (escrow) => await escrow.getIdentifiers(approval)),\n );\n return { authIdentifiers: identifiers, results };\n }\n\n async #mutate(params: MutateParams): Promise<void> {\n const { operation, payload, identifier, epoch } = params;\n await this.#withLock(async () => {\n if (await this.#loadPending()) {\n throw new MfaRecoveryError(\n 'A pending mutation must be resumed or aborted first',\n 'pending_mutation',\n );\n }\n\n await this.#assertEscrowsAvailable(this.#escrows);\n\n const profileId = await this.#authProvider.getAuthenticatedProfileId();\n const audiences = this.#escrows.map((escrow) => escrow.id);\n const currentVersion = this.#resolveCurrentRecoveryVersion(epoch);\n const payloadHash = await hash(payload);\n\n const mutationFields = {\n id: randomId(),\n profileId,\n operation,\n expectedVersion: currentVersion,\n newVersion: currentVersion + 1,\n payloadHash,\n audiences,\n };\n const mutation: Mutation = {\n ...mutationFields,\n requestHash: await hash(mutationFields),\n };\n\n const pending: PendingOperation = {\n phase: 'authorizing',\n mutation,\n payload,\n identifier,\n };\n await this.#persistPending(pending);\n\n await this.#replicateMutation({\n ...pending,\n phase: 'writing',\n ...(await this.#authorizeMutation(mutation)),\n receipts: [],\n });\n });\n }\n\n async #authorizeMutation(\n mutation: Mutation,\n ): Promise<\n Pick<WritingPendingOperation, 'authControllerToken' | 'approvedIdentifiers'>\n > {\n const { approval, identifiers } =\n await this.#authProvider.authorizeRecoveryRequest({\n requestHash: mutation.requestHash,\n audiences: this.#escrows.map((escrow) => escrow.authAudience),\n requireTwoFactor: true,\n });\n return { authControllerToken: approval, approvedIdentifiers: identifiers };\n }\n\n async #repairPendingMutation(): Promise<void> {\n const pending = await this.#loadPending();\n if (!pending) {\n return;\n }\n\n if (pending.phase === 'authorizing') {\n await this.#assertEscrowsAvailable(this.#escrows);\n await this.#replicateMutation({\n ...pending,\n phase: 'writing',\n ...(await this.#authorizeMutation(pending.mutation)),\n receipts: [],\n });\n return;\n }\n\n // writing phase. Renewing would only prompt for MFA again.\n if (await this.#isUnapplied(pending)) {\n await this.#clearPending();\n throw new MutationRejectedError(\n 'No escrow applied the mutation before its approval expired',\n );\n }\n await this.#replicateMutation(pending);\n }\n\n async #replicateMutation(pending: WritingPendingOperation): Promise<void> {\n const { mutation } = pending;\n const remainingEscrows = await this.#getRemainingEscrows(pending);\n if (remainingEscrows.length === 0) {\n await this.#clearPending();\n return;\n }\n\n await this.#assertEscrowsAvailable(remainingEscrows);\n\n const claims = decodeAuthControllerToken(pending.authControllerToken);\n const writing =\n claims && claims.exp > this.#now()\n ? pending\n : { ...pending, ...(await this.#authorizeMutation(mutation)) };\n await this.#assertPending(writing);\n const authorizations = await this.#authorizeEscrows(\n writing,\n remainingEscrows,\n );\n const payloads = await Promise.all(\n remainingEscrows.map(async (escrow) =>\n this.#payloadForEscrow(writing, escrow),\n ),\n );\n\n await this.#persistPending(writing);\n const results = await Promise.allSettled(\n remainingEscrows.map((escrow, index) =>\n escrow.applyMutation(\n mutation,\n writing.authControllerToken,\n authorizations[index],\n payloads[index],\n writing.approvedIdentifiers,\n ),\n ),\n );\n\n const { receipts, hasInvalidReceipt } = await this.#collectMutationReceipts(\n results,\n remainingEscrows,\n mutation,\n writing.receipts,\n );\n const rejection = unanimousMutationRejection(results, writing.receipts);\n if (rejection) {\n await this.#clearPending();\n throw rejection;\n }\n await this.#persistPending({ ...writing, receipts });\n\n if (hasInvalidReceipt) {\n throw new MfaRecoveryError('Invalid mutation receipt', 'invalid_receipt');\n }\n\n if (\n new Set(receipts.map((receipt) => receipt.escrowId)).size !==\n this.#escrows.length\n ) {\n throw new IncompleteMutationError(mutation.id);\n }\n await this.#clearPending();\n }\n\n async #assertEscrowsAvailable(\n escrows: RecoveryEscrowProvider[],\n ): Promise<void> {\n const availableEscrows = await this.#getAvailableEscrows(escrows);\n // Do we want to wait for all escrows to be available?\n if (availableEscrows.length !== escrows.length) {\n throw new MfaRecoveryError(\n 'All configured escrows are required for mutation',\n 'escrow_unavailable',\n );\n }\n }\n\n async #getRemainingEscrows(\n pending: WritingPendingOperation,\n ): Promise<RecoveryEscrowProvider[]> {\n const { mutation } = pending;\n const remainingEscrows: RecoveryEscrowProvider[] = [];\n for (const escrow of this.#escrows) {\n const receipt = pending.receipts.find(\n (item) => item.escrowId === escrow.id,\n );\n if (receipt === undefined) {\n remainingEscrows.push(escrow);\n continue;\n }\n if (!(await verifyMutationReceipt(receipt, mutation, escrow))) {\n throw new MfaRecoveryError(\n 'Invalid mutation receipt',\n 'invalid_receipt',\n );\n }\n }\n if (\n remainingEscrows.length + pending.receipts.length !==\n this.#escrows.length\n ) {\n throw new MfaRecoveryError(\n 'Receipt escrow is not configured',\n 'unknown_receipt_escrow',\n );\n }\n return remainingEscrows;\n }\n\n async #collectMutationReceipts(\n results: PromiseSettledResult<MutationReceipt>[],\n escrows: RecoveryEscrowProvider[],\n mutation: Mutation,\n existingReceipts: MutationReceipt[],\n ): Promise<{ receipts: MutationReceipt[]; hasInvalidReceipt: boolean }> {\n const receipts = [...existingReceipts];\n let hasInvalidReceipt = false;\n for (const [index, result] of results.entries()) {\n if (!isFulfilledResult(result)) {\n continue;\n }\n const escrow = escrows[index];\n if (\n !isMutationReceipt(result.value) ||\n !(await verifyMutationReceipt(result.value, mutation, escrow))\n ) {\n hasInvalidReceipt = true;\n continue;\n }\n receipts.push(result.value);\n }\n return { receipts, hasInvalidReceipt };\n }\n\n /**\n * Proves the update's enrolled identifier and each SIWE identifier the\n * escrows have not enrolled, all against one challenge per escrow.\n *\n * @param writing - Writing pending mutation.\n * @param escrows - Escrows to authorize.\n * @returns Each escrow's identifier authorizations, in `escrows` order.\n */\n async #authorizeEscrows(\n writing: WritingPendingOperation,\n escrows: RecoveryEscrowProvider[],\n ): Promise<IdentifierAuthorization[][]> {\n const identifiers = [\n ...(writing.identifier ? [writing.identifier] : []),\n ...(await this.#findNewSiweIdentifiers(writing, escrows)),\n ];\n if (identifiers.length === 0) {\n return escrows.map(() => []);\n }\n const credentials: KeyBoundCredential[] = [];\n for (const identifier of identifiers) {\n getIdentifierAuthMode(identifier.type);\n const { token, proofPrivateKey } = await requestIdentifierLogin({\n identifier,\n requestHash: writing.mutation.requestHash,\n identifierAuthProvider: this.#identifierAuthProvider,\n });\n // Writes authorize registered/enrolled identifiers, so the subject must\n // match exactly; only reads may discover it from an empty value.\n if (token.identifier.value !== identifier.value) {\n throw new MfaRecoveryError(\n 'Identifier token is not bound to this request',\n 'invalid_identifier_token',\n );\n }\n credentials.push({ token, proofPrivateKey });\n }\n const authorized = await authorizeEscrowsWithToken({\n escrows,\n credentials,\n authControllerToken: writing.authControllerToken,\n });\n if (authorized.length !== escrows.length) {\n throw new MfaRecoveryError(\n 'Unable to authorize every escrow',\n 'identifier_auth_failed',\n );\n }\n return authorized.map(({ authorizations }) => authorizations);\n }\n\n // SIWE identifiers some escrow has not enrolled. Escrows that already\n // applied the mutation replay their receipt and ignore the extra proofs.\n async #findNewSiweIdentifiers(\n { mutation, payload, authControllerToken }: WritingPendingOperation,\n escrows: RecoveryEscrowProvider[],\n ): Promise<Identifier[]> {\n const siweIdentifiers = pendingPayloadHasIdentifiers(payload)\n ? payload.identifiers.filter(({ type }) => type === 'siwe')\n : [];\n if (mutation.operation === 'register' || siweIdentifiers.length === 0) {\n return siweIdentifiers;\n }\n const responses = await Promise.all(\n escrows.map((escrow) => escrow.getIdentifiers(authControllerToken)),\n );\n const enrolledPerEscrow = responses.map(({ identifiers }) => identifiers);\n // Escrows compare SIWE addresses case-insensitively.\n const isEnrolledInEveryEscrow = ({\n namespace,\n value,\n }: Identifier): boolean =>\n enrolledPerEscrow.every((enrolled) =>\n enrolled.some(\n (other) =>\n other.type === 'siwe' &&\n other.namespace === namespace &&\n other.value.toLowerCase() === value.toLowerCase(),\n ),\n );\n return siweIdentifiers.filter(\n (identifier) => !isEnrolledInEveryEscrow(identifier),\n );\n }\n\n async #payloadForEscrow(\n pending: WritingPendingOperation,\n escrow: RecoveryEscrowProvider,\n ): Promise<MutationPayload> {\n const { payload } = pending;\n if (!pendingPayloadHasRecoverySecret(payload)) {\n return {\n identifiers: payload.identifiers,\n };\n }\n const recoverySecret = await this.#wrapRecoverySecret(\n hexToBytes(payload.recoverySecret),\n escrow.wrapPublicKey,\n );\n if (pendingPayloadHasIdentifiers(payload)) {\n return {\n identifiers: payload.identifiers,\n recoverySecret,\n };\n }\n return { recoverySecret };\n }\n\n #resolveCurrentRecoveryVersion(epoch: number): number {\n if (!Number.isInteger(epoch) || epoch < 0) {\n throw new MfaRecoveryError('Invalid epoch', 'invalid_epoch');\n }\n return epoch;\n }\n\n async #getAvailableEscrows(\n escrows: RecoveryEscrowProvider[] = this.#escrows,\n ): Promise<RecoveryEscrowProvider[]> {\n const flags = await Promise.allSettled(\n escrows.map(async (escrow) => ({\n escrow,\n available: await escrow.isAvailable(),\n })),\n );\n return flags.flatMap((result) =>\n isFulfilledResult(result) && result.value.available\n ? [result.value.escrow]\n : [],\n );\n }\n\n #assertValidIdentifiers(identifiers: Identifier[]): void {\n for (const identifier of identifiers) {\n getIdentifierAuthMode(identifier.type);\n if (\n identifier.type === 'siwe' &&\n (!isHexAddress(identifier.value.toLowerCase()) ||\n identifier.namespace !== getSiweNamespace(identifier))\n ) {\n throw new MfaRecoveryError(\n 'SIWE value must be an address and namespace the verifier domain:chainId',\n 'invalid_identifier',\n );\n }\n }\n }\n\n #assertIdentifierSet(identifiers: Identifier[]): void {\n const distinct = countDistinctIdentifiers(identifiers);\n if (distinct < MIN_IDENTIFIERS) {\n throw new MfaRecoveryError(\n `Requires at least ${MIN_IDENTIFIERS} identifiers`,\n 'too_few_identifiers',\n );\n }\n if (distinct !== identifiers.length) {\n throw new MfaRecoveryError(\n 'Duplicate identifier',\n 'duplicate_identifier',\n );\n }\n if (identifiers.length > MAX_IDENTIFIERS) {\n throw new MfaRecoveryError(\n `Supports at most ${MAX_IDENTIFIERS} identifiers`,\n 'too_many_identifiers',\n );\n }\n }\n\n async #wrapRecoverySecret(\n plaintext: Uint8Array,\n wrapPublicKey: Uint8Array,\n ): Promise<WrappedSecret> {\n const ephemeral = await generateWrapKey();\n return {\n pkE: ephemeral.publicKey,\n ciphertext: await encryptToPublic(\n ephemeral.privateKey,\n wrapPublicKey,\n plaintext,\n ),\n };\n }\n\n async #loadPending(): Promise<PendingOperation | null> {\n const { pendingOperation } = this.state;\n if (pendingOperation === null) {\n return null;\n }\n const pending = (await this.#encryptor.decrypt(\n pendingOperation,\n )) as unknown;\n await this.#assertPending(pending);\n return pending as PendingOperation;\n }\n\n async #persistPending(operation: PendingOperation): Promise<void> {\n await this.#assertPending(operation);\n const encrypted = await this.#encryptor.encrypt(operation);\n this.update((state) => {\n state.pendingOperation = encrypted;\n });\n }\n\n async #assertPending(pending: unknown): Promise<void> {\n await assertValidPendingOperation(\n pending,\n this.#escrows.map((escrow) => escrow.id),\n );\n }\n\n async #clearPending(): Promise<void> {\n this.update((state) => {\n state.pendingOperation = null;\n });\n }\n\n async #withLock<ReturnValue>(\n fn: () => Promise<ReturnValue>,\n ): Promise<ReturnValue> {\n const run = this.#lock.then(fn, fn);\n this.#lock = run.then(\n () => undefined,\n () => undefined,\n );\n return await run;\n }\n}\n\n/**\n * Every remaining escrow refused the mutation, and none has a receipt.\n *\n * @param results - Settled apply results for the remaining escrows.\n * @param existingReceipts - Receipts already stored for this mutation.\n * @returns The first refusal, or `null` when the write may have been applied.\n */\nfunction unanimousMutationRejection(\n results: PromiseSettledResult<MutationReceipt>[],\n existingReceipts: MutationReceipt[],\n): MutationRejectedError | null {\n if (existingReceipts.length > 0 || results.length === 0) {\n return null;\n }\n let rejection: MutationRejectedError | null = null;\n for (const result of results) {\n if (\n result.status !== 'rejected' ||\n !(result.reason instanceof MutationRejectedError)\n ) {\n return null;\n }\n rejection ??= result.reason;\n }\n return rejection;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"MfaRecoveryController.js","sourceRoot":"","sources":["../src/MfaRecoveryController.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEvE,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,eAAe,EACf,IAAI,EACJ,QAAQ,EACR,OAAO,EACP,SAAS,GACV,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,yBAAyB,EACzB,wBAAwB,EACxB,qBAAqB,EACrB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,EAC5B,+BAA+B,GAChC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AA0BtD,MAAM,eAAe,GAAG,uBAAuB,CAAC;AAEhD,MAAM,yBAAyB,GAAG;IAChC,aAAa;IACb,aA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BACjC,KAAK,CAAC,IAAI,KAAK,wBAAwB,EACvC,CAAC;gBACD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;oBACpB,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC;gBACtB,CAAC,CAAC,CAAC;YACL,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAED,KAAK,CAAC,SAAS,CACb,EAA8B;QAE9B,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QACpC,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CACnB,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;QACF,OAAO,MAAM,GAAG,CAAC;IACnB,CAAC;CACF;AAED;;;;;;GAMG;AACH,SAAS,0BAA0B,CACjC,OAAgD,EAChD,gBAAmC;IAEnC,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,SAAS,GAAiC,IAAI,CAAC;IACnD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IACE,MAAM,CAAC,MAAM,KAAK,UAAU;YAC5B,CAAC,CAAC,MAAM,CAAC,MAAM,YAAY,qBAAqB,CAAC,EACjD,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,SAAS,KAAK,MAAM,CAAC,MAAM,CAAC;IAC9B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport { bytesToHex, hexToBytes, isHexAddress } from '@metamask/utils';\n\nimport { decodeAuthControllerToken } from './auth-controller-token.js';\nimport {\n decryptFromPublic,\n encryptToPublic,\n generateWrapKey,\n hash,\n randomId,\n unixNow,\n wrapKeyId,\n} from './crypto.js';\nimport {\n IncompleteMutationError,\n MfaRecoveryError,\n MutationRejectedError,\n} from './errors.js';\nimport {\n isFulfilledResult,\n isMutationReceipt,\n selectHighestConsistentVersion,\n verifyMutationReceipt,\n} from './escrow-utils.js';\nimport {\n authorizeEscrowsWithToken,\n countDistinctIdentifiers,\n getIdentifierAuthMode,\n getSiweNamespace,\n MAX_IDENTIFIERS,\n MIN_IDENTIFIERS,\n requestIdentifierLogin,\n validateSeedlessAuthData,\n} from './identifier-auth.js';\nimport type { MfaRecoveryControllerMethodActions } from './MfaRecoveryController-method-action-types.js';\nimport {\n assertValidPendingOperation,\n pendingPayloadHasIdentifiers,\n pendingPayloadHasRecoverySecret,\n} from './pending-operation-validation.js';\nimport { getRecoveryPhase } from './state-machine.js';\nimport type {\n GetIdentifiersResponse,\n Identifier,\n IdentifierAuthorization,\n IdentifierSession,\n KeyBoundCredential,\n Mutation,\n MutationPayload,\n MutationReceipt,\n PendingOperation,\n PendingOperationEncryptor,\n PendingRegisterPayload,\n PendingUpdateIdentifiersPayload,\n PendingUpdateRecoverySecretPayload,\n RecoveryAuthProvider,\n RecoveryEscrowProvider,\n RecoveryIdentifierAuthProvider,\n RecoveryIdentifiers,\n RecoveryLockProvider,\n RecoveryPhase,\n RecoveredSecret,\n WrappedSecret,\n WritingPendingOperation,\n} from './types.js';\n\nconst CONTROLLER_NAME = 'MfaRecoveryController';\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'acquireLock',\n 'releaseLock',\n 'register',\n 'updateRecoverySecret',\n 'updateIdentifiers',\n 'authenticateIdentifier',\n 'getRecoverySecret',\n 'getIdentifiers',\n 'resume',\n 'abort',\n 'getPhase',\n] as const;\n\nexport type MfaRecoveryControllerState = {\n /**\n * Held recovery lease ID, reused when retrying, or `null`.\n */\n lockId: string | null;\n /**\n * Encrypted pending mutation, or `null` when idle.\n */\n pendingOperation: string | null;\n};\n\nconst mfaRecoveryControllerMetadata = {\n lockId: {\n persist: true,\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n usedInUi: false,\n },\n pendingOperation: {\n persist: true,\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n usedInUi: true,\n },\n} satisfies StateMetadata<MfaRecoveryControllerState>;\n\n/**\n * @returns The default {@link MfaRecoveryController} state.\n */\nexport function getDefaultMfaRecoveryControllerState(): MfaRecoveryControllerState {\n return { lockId: null, pendingOperation: null };\n}\n\nexport type MfaRecoveryControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n MfaRecoveryControllerState\n>;\n\nexport type MfaRecoveryControllerActions =\n | MfaRecoveryControllerGetStateAction\n | MfaRecoveryControllerMethodActions;\n\ntype AllowedActions = never;\n\nexport type MfaRecoveryControllerStateChangedEvent =\n ControllerStateChangedEvent<\n typeof CONTROLLER_NAME,\n MfaRecoveryControllerState\n >;\n\nexport type MfaRecoveryControllerEvents =\n MfaRecoveryControllerStateChangedEvent;\n\ntype AllowedEvents = never;\n\nexport type MfaRecoveryControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n MfaRecoveryControllerActions | AllowedActions,\n MfaRecoveryControllerEvents | AllowedEvents\n>;\n\nexport type MfaRecoveryControllerOptions = {\n /**\n * The messenger suited for this controller.\n */\n messenger: MfaRecoveryControllerMessenger;\n\n /**\n * The desired state with which to initialize this controller. Missing\n * properties will be filled in with defaults.\n */\n state?: Partial<MfaRecoveryControllerState>;\n\n /**\n * Authenticates the MetaMask profile and issues request-bound attestations.\n */\n authProvider: RecoveryAuthProvider;\n\n /**\n * Holds the per-profile recovery lease.\n */\n lockProvider: RecoveryLockProvider;\n\n /**\n * Obtains key-bound identifier tokens from an IdP.\n */\n identifierAuthProvider: RecoveryIdentifierAuthProvider;\n\n /**\n * Ordered, non-empty set of recovery escrow replicas. This is build-time\n * configuration; public methods cannot override it.\n */\n escrows: RecoveryEscrowProvider[];\n\n /**\n * Encrypts pending mutation state using wallet secure storage.\n */\n pendingOperationEncryptor: PendingOperationEncryptor;\n\n /**\n * Clock used for AuthController token expiry checks. Unix seconds.\n * Defaults to {@link unixNow}.\n */\n now?: () => number;\n};\n\ntype MutateParams = {\n epoch: number;\n} & (\n | {\n operation: 'register';\n payload: PendingRegisterPayload;\n identifier: null;\n }\n | {\n operation: 'updateRecoverySecret';\n payload: PendingUpdateRecoverySecretPayload;\n identifier: Identifier;\n }\n | {\n operation: 'updateIdentifiers';\n payload: PendingUpdateIdentifiersPayload;\n identifier: Identifier;\n }\n);\n\n/**\n * Coordinates MFA recovery secret replication across independent escrows.\n */\nexport class MfaRecoveryController extends BaseController<\n typeof CONTROLLER_NAME,\n MfaRecoveryControllerState,\n MfaRecoveryControllerMessenger\n> {\n readonly #authProvider: RecoveryAuthProvider;\n\n readonly #lockProvider: RecoveryLockProvider;\n\n readonly #identifierAuthProvider: RecoveryIdentifierAuthProvider;\n\n readonly #escrows: RecoveryEscrowProvider[];\n\n readonly #encryptor: PendingOperationEncryptor;\n\n readonly #now: () => number;\n\n #lock: Promise<void> = Promise.resolve();\n\n constructor({\n messenger,\n state,\n authProvider,\n lockProvider,\n identifierAuthProvider,\n escrows,\n pendingOperationEncryptor,\n now = unixNow,\n }: MfaRecoveryControllerOptions) {\n if (escrows.length === 0) {\n throw new MfaRecoveryError(\n 'At least one escrow is required',\n 'empty_escrow_set',\n );\n }\n const escrowIds = escrows.map((escrow) => escrow.id);\n if (new Set(escrowIds).size !== escrowIds.length) {\n throw new MfaRecoveryError('Duplicate escrow id', 'duplicate_escrow_id');\n }\n\n super({\n messenger,\n metadata: mfaRecoveryControllerMetadata,\n name: CONTROLLER_NAME,\n state: {\n ...getDefaultMfaRecoveryControllerState(),\n ...state,\n },\n });\n\n this.#authProvider = authProvider;\n this.#lockProvider = lockProvider;\n this.#identifierAuthProvider = identifierAuthProvider;\n this.#escrows = [...escrows];\n this.#encryptor = pendingOperationEncryptor;\n this.#now = now;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Acquires or extends the per-profile recovery lease. Hold it from the first\n * read through any Auth identifier changes and mutations.\n */\n async acquireLock(): Promise<void> {\n await this.#withLock(async () => this.#acquireLease());\n }\n\n /**\n * Releases the lease. A pending mutation must finish first.\n */\n async releaseLock(): Promise<void> {\n await this.#withLock(async () => {\n if (await this.#loadPending()) {\n throw new MfaRecoveryError(\n 'A pending mutation must be resumed or aborted first',\n 'pending_mutation',\n );\n }\n const { lockId } = this.state;\n if (lockId === null) {\n return;\n }\n try {\n await this.#lockProvider.release(lockId);\n } catch (error) {\n // A conflict means another ID holds the lease, so it is not ours.\n if (\n !(error instanceof MfaRecoveryError) ||\n error.code !== 'recovery_lock_conflict'\n ) {\n throw error;\n }\n }\n this.update((state) => {\n state.lockId = null;\n });\n });\n }\n\n /**\n * Creates version 1 of a recovery record.\n *\n * @param recoverySecret - Secret replicated in full to every escrow.\n * @param identifiers - Ownership-approved identifier set. Must contain at\n * least two identifiers.\n */\n async register(\n recoverySecret: Uint8Array,\n identifiers: Identifier[],\n ): Promise<void> {\n this.#assertValidIdentifiers(identifiers);\n this.#assertIdentifierSet(identifiers);\n await this.#mutate({\n operation: 'register',\n payload: {\n identifiers,\n recoverySecret: bytesToHex(recoverySecret),\n },\n identifier: null,\n epoch: 0,\n });\n }\n\n /**\n * Replaces the recovery secret.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param recoverySecret - New secret.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\n async updateRecoverySecret(\n identifier: Identifier,\n recoverySecret: Uint8Array,\n epoch: number,\n ): Promise<void> {\n this.#assertValidIdentifiers([identifier]);\n await this.#mutate({\n operation: 'updateRecoverySecret',\n payload: {\n recoverySecret: bytesToHex(recoverySecret),\n },\n identifier,\n epoch,\n });\n }\n\n /**\n * Replaces the complete identifier set.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param identifiers - New identifier set. Must contain at least two\n * identifiers.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\n async updateIdentifiers(\n identifier: Identifier,\n identifiers: Identifier[],\n epoch: number,\n ): Promise<void> {\n this.#assertValidIdentifiers([identifier, ...identifiers]);\n this.#assertIdentifierSet(identifiers);\n await this.#mutate({\n operation: 'updateIdentifiers',\n payload: { identifiers },\n identifier,\n epoch,\n });\n }\n\n /**\n * Authenticates an identifier with a single login. Returns an ephemeral\n * {@link IdentifierSession} for {@link getRecoverySecret}. For seedless\n * social logins, the session also carries `seedlessAuthData` for\n * `SeedlessOnboardingController.authenticate`. Callers decide whether they\n * need `seedlessAuthData` (and its `revokeToken`), drop it after seedless\n * authenticate, and keep the key-bound session fields for recovery reads.\n *\n * @param identifier - Identifier to authenticate.\n * @returns Session for recovery reads, with seedless auth data when the\n * login returned it.\n */\n async authenticateIdentifier(\n identifier: Identifier,\n ): Promise<IdentifierSession> {\n this.#assertValidIdentifiers([identifier]);\n const requestId = randomId();\n const ephemeral = await generateWrapKey();\n const pkE = ephemeral.publicKey;\n const requestHash = await hash({\n operation: 'getRecoverySecret',\n requestId,\n pkE,\n });\n const { seedlessAuthData, ...credential } = await requestIdentifierLogin({\n identifier,\n requestHash,\n identifierAuthProvider: this.#identifierAuthProvider,\n });\n return {\n ...credential,\n requestId,\n ephemeralPrivateKey: ephemeral.privateKey,\n pkE,\n ...(seedlessAuthData === undefined\n ? {}\n : {\n seedlessAuthData: validateSeedlessAuthData(\n seedlessAuthData,\n identifier,\n ),\n }),\n };\n }\n\n /**\n * Reads the recovery secret from available escrows and returns the highest\n * consistent version. `epoch` is the current recovery version and is required\n * by later mutations. Does not wait for a pending mutation to be repaired.\n *\n * @param session - Identifier authentication session used to authorize the\n * read.\n * @returns Recovered secret bytes and the selected epoch.\n */\n async getRecoverySecret(\n session: IdentifierSession,\n ): Promise<RecoveredSecret> {\n return await this.#withLock(async () => {\n const { token, requestId, pkE } = session;\n this.#assertValidIdentifiers([token.identifier]);\n const requestHash = await hash({\n operation: 'getRecoverySecret',\n requestId,\n pkE,\n });\n if (token.requestHash !== requestHash) {\n throw new MfaRecoveryError(\n 'Invalid identifier session',\n 'invalid_identifier_session',\n );\n }\n const available = await this.#getAvailableEscrows();\n if (available.length === 0) {\n throw new MfaRecoveryError(\n 'No escrow is available',\n 'no_available_escrow',\n );\n }\n const { approval } = await this.#authProvider.authorizeRecoveryRequest({\n requestHash,\n audiences: available.map((escrow) => escrow.authAudience),\n requireTwoFactor: true,\n });\n const authorizedEscrows = await authorizeEscrowsWithToken({\n escrows: available,\n credentials: [\n {\n token: session.token,\n proofPrivateKey: session.proofPrivateKey,\n },\n ],\n authControllerToken: approval,\n });\n const results = await Promise.allSettled(\n authorizedEscrows.map(async ({ escrow, authorizations }) => {\n const [authorization] = authorizations;\n const response = await escrow.getSecret(\n approval,\n authorization,\n requestId,\n pkE,\n );\n if (response.wrapKeyId !== (await wrapKeyId(escrow.wrapPublicKey))) {\n throw new MfaRecoveryError(\n 'Unexpected wrap key',\n 'wrap_key_mismatch',\n );\n }\n return {\n escrowId: escrow.id,\n recoverySecret: await decryptFromPublic(\n session.ephemeralPrivateKey,\n escrow.wrapPublicKey,\n response.recoverySecret.ciphertext,\n ),\n version: response.version,\n lastMutationId: response.lastMutationId,\n };\n }),\n );\n const selected = selectHighestConsistentVersion(results);\n return {\n recoverySecret: selected.recoverySecret,\n epoch: selected.version,\n };\n });\n }\n\n /**\n * Reads the enrolled identifiers from available escrows at the highest\n * consistent version, with Auth's current identifiers. Needs no recent MFA,\n * so a new device can build an {@link updateIdentifiers} call from it.\n *\n * @returns Enrolled identifiers, `epoch`, and Auth's identifiers.\n */\n async getIdentifiers(): Promise<RecoveryIdentifiers> {\n return await this.#withLock(async () => {\n const available = await this.#getAvailableEscrows();\n if (available.length === 0) {\n throw new MfaRecoveryError(\n 'No escrow is available',\n 'no_available_escrow',\n );\n }\n const { authIdentifiers, results } =\n await this.#authorizeAndReadIdentifiers(available);\n const responses = results\n .filter(isFulfilledResult)\n .map((result) => result.value);\n if (responses.length === 0) {\n throw new MfaRecoveryError(\n 'No escrow returned identifiers',\n 'read_failed',\n );\n }\n const epoch = Math.max(...responses.map(({ version }) => version));\n const highest = responses.filter(({ version }) => version === epoch);\n const hashes = await Promise.all(\n highest.map(async ({ identifiers }) => await hash(identifiers)),\n );\n if (new Set(hashes).size !== 1) {\n throw new MfaRecoveryError('Replica corruption', 'replica_corruption');\n }\n return { identifiers: highest[0].identifiers, epoch, authIdentifiers };\n });\n }\n\n /**\n * Completes a persisted pending mutation, if any. Clears a `writing` one,\n * throwing `MutationRejectedError`, once its approval has expired and no\n * escrow applied it.\n */\n async resume(): Promise<void> {\n await this.#withLock(async () => {\n await this.#repairPendingMutation();\n });\n }\n\n /**\n * Drops `authorizing` pending. Drops `writing` pending only once its approval\n * has expired and no escrow applied it; otherwise finish it with\n * {@link resume}.\n */\n async abort(): Promise<void> {\n await this.#withLock(async () => {\n const pending = await this.#loadPending();\n if (pending?.phase === 'writing' && !(await this.#isUnapplied(pending))) {\n throw new MfaRecoveryError(\n 'Cannot abort a mutation that may have been applied',\n 'abort_not_allowed',\n );\n }\n if (pending) {\n await this.#clearPending();\n }\n });\n }\n\n /**\n * @returns Current recovery phase.\n */\n async getPhase(): Promise<RecoveryPhase> {\n return await this.#withLock(async () =>\n getRecoveryPhase(await this.#loadPending()),\n );\n }\n\n // No write can land after its approval expires, and escrow versions only\n // grow, so every escrow below `newVersion` means none applied it.\n async #isUnapplied({\n mutation,\n authControllerToken,\n }: WritingPendingOperation): Promise<boolean> {\n const claims = decodeAuthControllerToken(authControllerToken);\n if (claims && claims.exp > this.#now()) {\n return false;\n }\n const { results } = await this.#authorizeAndReadIdentifiers(this.#escrows);\n return results.every(\n (result) =>\n isFulfilledResult(result) && result.value.version < mutation.newVersion,\n );\n }\n\n // Read approvals need no 2FA.\n async #authorizeAndReadIdentifiers(\n escrows: RecoveryEscrowProvider[],\n ): Promise<{\n authIdentifiers: Identifier[];\n results: PromiseSettledResult<GetIdentifiersResponse>[];\n }> {\n const { approval, identifiers } =\n await this.#authProvider.authorizeRecoveryRequest({\n requestHash: await hash({ operation: 'getIdentifiers' }),\n audiences: escrows.map((escrow) => escrow.authAudience),\n });\n const results = await Promise.allSettled(\n escrows.map(async (escrow) => await escrow.getIdentifiers(approval)),\n );\n return { authIdentifiers: identifiers, results };\n }\n\n async #mutate(params: MutateParams): Promise<void> {\n const { operation, payload, identifier, epoch } = params;\n await this.#withLock(async () => {\n if (await this.#loadPending()) {\n throw new MfaRecoveryError(\n 'A pending mutation must be resumed or aborted first',\n 'pending_mutation',\n );\n }\n\n await this.#assertEscrowsAvailable(this.#escrows);\n\n const profileId = await this.#authProvider.getAuthenticatedProfileId();\n const audiences = this.#escrows.map((escrow) => escrow.id);\n const currentVersion = this.#resolveCurrentRecoveryVersion(epoch);\n const payloadHash = await hash(payload);\n\n const mutationFields = {\n id: randomId(),\n profileId,\n operation,\n expectedVersion: currentVersion,\n newVersion: currentVersion + 1,\n payloadHash,\n audiences,\n };\n const mutation: Mutation = {\n ...mutationFields,\n requestHash: await hash(mutationFields),\n };\n\n const pending: PendingOperation = {\n phase: 'authorizing',\n mutation,\n payload,\n identifier,\n };\n await this.#persistPending(pending);\n\n await this.#replicateMutation({\n ...pending,\n phase: 'writing',\n ...(await this.#authorizeMutation(mutation)),\n receipts: [],\n });\n });\n }\n\n async #authorizeMutation(\n mutation: Mutation,\n ): Promise<\n Pick<WritingPendingOperation, 'authControllerToken' | 'approvedIdentifiers'>\n > {\n // The lease outlives the approval, so no write lands after another\n // operation can take the lease.\n await this.#acquireLease();\n const { approval, identifiers } =\n await this.#authProvider.authorizeRecoveryRequest({\n requestHash: mutation.requestHash,\n audiences: this.#escrows.map((escrow) => escrow.authAudience),\n requireTwoFactor: true,\n });\n return { authControllerToken: approval, approvedIdentifiers: identifiers };\n }\n\n async #repairPendingMutation(): Promise<void> {\n const pending = await this.#loadPending();\n if (!pending) {\n return;\n }\n\n if (pending.phase === 'authorizing') {\n await this.#assertEscrowsAvailable(this.#escrows);\n await this.#replicateMutation({\n ...pending,\n phase: 'writing',\n ...(await this.#authorizeMutation(pending.mutation)),\n receipts: [],\n });\n return;\n }\n\n // writing phase. Renewing would only prompt for MFA again.\n if (await this.#isUnapplied(pending)) {\n await this.#clearPending();\n throw new MutationRejectedError(\n 'No escrow applied the mutation before its approval expired',\n );\n }\n await this.#replicateMutation(pending);\n }\n\n async #replicateMutation(pending: WritingPendingOperation): Promise<void> {\n const { mutation } = pending;\n const remainingEscrows = await this.#getRemainingEscrows(pending);\n if (remainingEscrows.length === 0) {\n await this.#clearPending();\n return;\n }\n\n await this.#assertEscrowsAvailable(remainingEscrows);\n\n const claims = decodeAuthControllerToken(pending.authControllerToken);\n const writing =\n claims && claims.exp > this.#now()\n ? pending\n : { ...pending, ...(await this.#authorizeMutation(mutation)) };\n await this.#assertPending(writing);\n const authorizations = await this.#authorizeEscrows(\n writing,\n remainingEscrows,\n );\n const payloads = await Promise.all(\n remainingEscrows.map(async (escrow) =>\n this.#payloadForEscrow(writing, escrow),\n ),\n );\n\n await this.#persistPending(writing);\n const results = await Promise.allSettled(\n remainingEscrows.map((escrow, index) =>\n escrow.applyMutation(\n mutation,\n writing.authControllerToken,\n authorizations[index],\n payloads[index],\n writing.approvedIdentifiers,\n ),\n ),\n );\n\n const { receipts, hasInvalidReceipt } = await this.#collectMutationReceipts(\n results,\n remainingEscrows,\n mutation,\n writing.receipts,\n );\n const rejection = unanimousMutationRejection(results, writing.receipts);\n if (rejection) {\n await this.#clearPending();\n throw rejection;\n }\n await this.#persistPending({ ...writing, receipts });\n\n if (hasInvalidReceipt) {\n throw new MfaRecoveryError('Invalid mutation receipt', 'invalid_receipt');\n }\n\n if (\n new Set(receipts.map((receipt) => receipt.escrowId)).size !==\n this.#escrows.length\n ) {\n throw new IncompleteMutationError(mutation.id);\n }\n await this.#clearPending();\n }\n\n async #assertEscrowsAvailable(\n escrows: RecoveryEscrowProvider[],\n ): Promise<void> {\n const availableEscrows = await this.#getAvailableEscrows(escrows);\n // Do we want to wait for all escrows to be available?\n if (availableEscrows.length !== escrows.length) {\n throw new MfaRecoveryError(\n 'All configured escrows are required for mutation',\n 'escrow_unavailable',\n );\n }\n }\n\n async #getRemainingEscrows(\n pending: WritingPendingOperation,\n ): Promise<RecoveryEscrowProvider[]> {\n const { mutation } = pending;\n const remainingEscrows: RecoveryEscrowProvider[] = [];\n for (const escrow of this.#escrows) {\n const receipt = pending.receipts.find(\n (item) => item.escrowId === escrow.id,\n );\n if (receipt === undefined) {\n remainingEscrows.push(escrow);\n continue;\n }\n if (!(await verifyMutationReceipt(receipt, mutation, escrow))) {\n throw new MfaRecoveryError(\n 'Invalid mutation receipt',\n 'invalid_receipt',\n );\n }\n }\n if (\n remainingEscrows.length + pending.receipts.length !==\n this.#escrows.length\n ) {\n throw new MfaRecoveryError(\n 'Receipt escrow is not configured',\n 'unknown_receipt_escrow',\n );\n }\n return remainingEscrows;\n }\n\n async #collectMutationReceipts(\n results: PromiseSettledResult<MutationReceipt>[],\n escrows: RecoveryEscrowProvider[],\n mutation: Mutation,\n existingReceipts: MutationReceipt[],\n ): Promise<{ receipts: MutationReceipt[]; hasInvalidReceipt: boolean }> {\n const receipts = [...existingReceipts];\n let hasInvalidReceipt = false;\n for (const [index, result] of results.entries()) {\n if (!isFulfilledResult(result)) {\n continue;\n }\n const escrow = escrows[index];\n if (\n !isMutationReceipt(result.value) ||\n !(await verifyMutationReceipt(result.value, mutation, escrow))\n ) {\n hasInvalidReceipt = true;\n continue;\n }\n receipts.push(result.value);\n }\n return { receipts, hasInvalidReceipt };\n }\n\n /**\n * Proves the update's enrolled identifier and each SIWE identifier the\n * escrows have not enrolled, all against one challenge per escrow.\n *\n * @param writing - Writing pending mutation.\n * @param escrows - Escrows to authorize.\n * @returns Each escrow's identifier authorizations, in `escrows` order.\n */\n async #authorizeEscrows(\n writing: WritingPendingOperation,\n escrows: RecoveryEscrowProvider[],\n ): Promise<IdentifierAuthorization[][]> {\n const identifiers = [\n ...(writing.identifier ? [writing.identifier] : []),\n ...(await this.#findNewSiweIdentifiers(writing, escrows)),\n ];\n if (identifiers.length === 0) {\n return escrows.map(() => []);\n }\n const credentials: KeyBoundCredential[] = [];\n for (const identifier of identifiers) {\n getIdentifierAuthMode(identifier.type);\n const { token, proofPrivateKey } = await requestIdentifierLogin({\n identifier,\n requestHash: writing.mutation.requestHash,\n identifierAuthProvider: this.#identifierAuthProvider,\n });\n // Writes authorize registered/enrolled identifiers, so the subject must\n // match exactly; only reads may discover it from an empty value.\n if (token.identifier.value !== identifier.value) {\n throw new MfaRecoveryError(\n 'Identifier token is not bound to this request',\n 'invalid_identifier_token',\n );\n }\n credentials.push({ token, proofPrivateKey });\n }\n const authorized = await authorizeEscrowsWithToken({\n escrows,\n credentials,\n authControllerToken: writing.authControllerToken,\n });\n if (authorized.length !== escrows.length) {\n throw new MfaRecoveryError(\n 'Unable to authorize every escrow',\n 'identifier_auth_failed',\n );\n }\n return authorized.map(({ authorizations }) => authorizations);\n }\n\n // SIWE identifiers some escrow has not enrolled. Escrows that already\n // applied the mutation replay their receipt and ignore the extra proofs.\n async #findNewSiweIdentifiers(\n { mutation, payload, authControllerToken }: WritingPendingOperation,\n escrows: RecoveryEscrowProvider[],\n ): Promise<Identifier[]> {\n const siweIdentifiers = pendingPayloadHasIdentifiers(payload)\n ? payload.identifiers.filter(({ type }) => type === 'siwe')\n : [];\n if (mutation.operation === 'register' || siweIdentifiers.length === 0) {\n return siweIdentifiers;\n }\n const responses = await Promise.all(\n escrows.map((escrow) => escrow.getIdentifiers(authControllerToken)),\n );\n const enrolledPerEscrow = responses.map(({ identifiers }) => identifiers);\n // Escrows compare SIWE addresses case-insensitively.\n const isEnrolledInEveryEscrow = ({\n namespace,\n value,\n }: Identifier): boolean =>\n enrolledPerEscrow.every((enrolled) =>\n enrolled.some(\n (other) =>\n other.type === 'siwe' &&\n other.namespace === namespace &&\n other.value.toLowerCase() === value.toLowerCase(),\n ),\n );\n return siweIdentifiers.filter(\n (identifier) => !isEnrolledInEveryEscrow(identifier),\n );\n }\n\n async #payloadForEscrow(\n pending: WritingPendingOperation,\n escrow: RecoveryEscrowProvider,\n ): Promise<MutationPayload> {\n const { payload } = pending;\n if (!pendingPayloadHasRecoverySecret(payload)) {\n return {\n identifiers: payload.identifiers,\n };\n }\n const recoverySecret = await this.#wrapRecoverySecret(\n hexToBytes(payload.recoverySecret),\n escrow.wrapPublicKey,\n );\n if (pendingPayloadHasIdentifiers(payload)) {\n return {\n identifiers: payload.identifiers,\n recoverySecret,\n };\n }\n return { recoverySecret };\n }\n\n #resolveCurrentRecoveryVersion(epoch: number): number {\n if (!Number.isInteger(epoch) || epoch < 0) {\n throw new MfaRecoveryError('Invalid epoch', 'invalid_epoch');\n }\n return epoch;\n }\n\n async #getAvailableEscrows(\n escrows: RecoveryEscrowProvider[] = this.#escrows,\n ): Promise<RecoveryEscrowProvider[]> {\n const flags = await Promise.allSettled(\n escrows.map(async (escrow) => ({\n escrow,\n available: await escrow.isAvailable(),\n })),\n );\n return flags.flatMap((result) =>\n isFulfilledResult(result) && result.value.available\n ? [result.value.escrow]\n : [],\n );\n }\n\n #assertValidIdentifiers(identifiers: Identifier[]): void {\n for (const identifier of identifiers) {\n getIdentifierAuthMode(identifier.type);\n if (\n identifier.type === 'siwe' &&\n (!isHexAddress(identifier.value.toLowerCase()) ||\n identifier.namespace !== getSiweNamespace(identifier))\n ) {\n throw new MfaRecoveryError(\n 'SIWE value must be an address and namespace the verifier domain:chainId',\n 'invalid_identifier',\n );\n }\n }\n }\n\n #assertIdentifierSet(identifiers: Identifier[]): void {\n const distinct = countDistinctIdentifiers(identifiers);\n if (distinct < MIN_IDENTIFIERS) {\n throw new MfaRecoveryError(\n `Requires at least ${MIN_IDENTIFIERS} identifiers`,\n 'too_few_identifiers',\n );\n }\n if (distinct !== identifiers.length) {\n throw new MfaRecoveryError(\n 'Duplicate identifier',\n 'duplicate_identifier',\n );\n }\n if (identifiers.length > MAX_IDENTIFIERS) {\n throw new MfaRecoveryError(\n `Supports at most ${MAX_IDENTIFIERS} identifiers`,\n 'too_many_identifiers',\n );\n }\n }\n\n async #wrapRecoverySecret(\n plaintext: Uint8Array,\n wrapPublicKey: Uint8Array,\n ): Promise<WrappedSecret> {\n const ephemeral = await generateWrapKey();\n return {\n pkE: ephemeral.publicKey,\n ciphertext: await encryptToPublic(\n ephemeral.privateKey,\n wrapPublicKey,\n plaintext,\n ),\n };\n }\n\n async #loadPending(): Promise<PendingOperation | null> {\n const { pendingOperation } = this.state;\n if (pendingOperation === null) {\n return null;\n }\n const pending = (await this.#encryptor.decrypt(\n pendingOperation,\n )) as unknown;\n await this.#assertPending(pending);\n return pending as PendingOperation;\n }\n\n async #persistPending(operation: PendingOperation): Promise<void> {\n await this.#assertPending(operation);\n const encrypted = await this.#encryptor.encrypt(operation);\n this.update((state) => {\n state.pendingOperation = encrypted;\n });\n }\n\n async #assertPending(pending: unknown): Promise<void> {\n await assertValidPendingOperation(\n pending,\n this.#escrows.map((escrow) => escrow.id),\n );\n }\n\n async #clearPending(): Promise<void> {\n this.update((state) => {\n state.pendingOperation = null;\n });\n }\n\n async #acquireLease(): Promise<void> {\n const lockId = this.state.lockId ?? randomId();\n this.update((state) => {\n state.lockId = lockId;\n });\n try {\n await this.#lockProvider.acquire(lockId);\n } catch (error) {\n // A conflict means another ID holds the lease. Other failures may have\n // acquired it, so keep the ID for a retry.\n if (\n error instanceof MfaRecoveryError &&\n error.code === 'recovery_lock_conflict'\n ) {\n this.update((state) => {\n state.lockId = null;\n });\n }\n throw error;\n }\n }\n\n async #withLock<ReturnValue>(\n fn: () => Promise<ReturnValue>,\n ): Promise<ReturnValue> {\n const run = this.#lock.then(fn, fn);\n this.#lock = run.then(\n () => undefined,\n () => undefined,\n );\n return await run;\n }\n}\n\n/**\n * Every remaining escrow refused the mutation, and none has a receipt.\n *\n * @param results - Settled apply results for the remaining escrows.\n * @param existingReceipts - Receipts already stored for this mutation.\n * @returns The first refusal, or `null` when the write may have been applied.\n */\nfunction unanimousMutationRejection(\n results: PromiseSettledResult<MutationReceipt>[],\n existingReceipts: MutationReceipt[],\n): MutationRejectedError | null {\n if (existingReceipts.length > 0 || results.length === 0) {\n return null;\n }\n let rejection: MutationRejectedError | null = null;\n for (const result of results) {\n if (\n result.status !== 'rejected' ||\n !(result.reason instanceof MutationRejectedError)\n ) {\n return null;\n }\n rejection ??= result.reason;\n }\n return rejection;\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
export { MfaRecoveryController, getDefaultMfaRecoveryControllerState, } from './MfaRecoveryController.js';
|
|
2
2
|
export type { MfaRecoveryControllerActions, MfaRecoveryControllerEvents, MfaRecoveryControllerGetStateAction, MfaRecoveryControllerMessenger, MfaRecoveryControllerOptions, MfaRecoveryControllerState, MfaRecoveryControllerStateChangedEvent, } from './MfaRecoveryController.js';
|
|
3
|
-
export type { MfaRecoveryControllerAbortAction, MfaRecoveryControllerAuthenticateIdentifierAction, MfaRecoveryControllerGetIdentifiersAction, MfaRecoveryControllerGetPhaseAction, MfaRecoveryControllerGetRecoverySecretAction, MfaRecoveryControllerRegisterAction, MfaRecoveryControllerResumeAction, MfaRecoveryControllerUpdateIdentifiersAction, MfaRecoveryControllerUpdateRecoverySecretAction, } from './MfaRecoveryController-method-action-types.js';
|
|
3
|
+
export type { MfaRecoveryControllerAbortAction, MfaRecoveryControllerAcquireLockAction, MfaRecoveryControllerAuthenticateIdentifierAction, MfaRecoveryControllerGetIdentifiersAction, MfaRecoveryControllerGetPhaseAction, MfaRecoveryControllerGetRecoverySecretAction, MfaRecoveryControllerRegisterAction, MfaRecoveryControllerReleaseLockAction, MfaRecoveryControllerResumeAction, MfaRecoveryControllerUpdateIdentifiersAction, MfaRecoveryControllerUpdateRecoverySecretAction, } from './MfaRecoveryController-method-action-types.js';
|
|
4
4
|
export { CubistEscrowProvider } from './escrow-providers/cubist-escrow-provider.js';
|
|
5
5
|
export type { CubistEscrowProviderOptions } from './escrow-providers/cubist-escrow-provider.js';
|
|
6
6
|
export { AuthApiRecoveryAuthProvider } from './auth-api-recovery-provider.js';
|
|
7
7
|
export type { AuthApiRecoveryAuthProviderMessenger, AuthApiRecoveryAuthProviderOptions, } from './auth-api-recovery-provider.js';
|
|
8
|
+
export { RecoveryRegistrationLockProvider } from './recovery-registration-lock-provider.js';
|
|
9
|
+
export type { RecoveryRegistrationLockProviderMessenger, RecoveryRegistrationLockProviderOptions, } from './recovery-registration-lock-provider.js';
|
|
8
10
|
export { IncompleteMutationError, MfaRecoveryError, MutationRejectedError, } from './errors.js';
|
|
9
11
|
export { IDENTIFIER_AUTH_MODES, MIN_IDENTIFIERS, expectedSeedlessAuthConnection, getIdentifierAuthMode, } from './identifier-auth.js';
|
|
10
|
-
export type { AuthControllerToken, EncryptedPendingOperation, GetIdentifiersResponse, Identifier, IdentifierAuthorization, IdentifierSession, KeyBoundIdentifierLogin, KeyBoundIdentifierToken, KeyBoundIdentifierTokenRequest, Mutation, MutationPayload, MutationReceipt, PendingMutationPayload, PendingOperation, PendingOperationEncryptor, PendingRecoverySecretHex, PendingRegisterPayload, PendingUpdateIdentifiersPayload, PendingUpdateRecoverySecretPayload, RecoveryApproval, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryIdentifiers, RecoveryPhase, RecoveredSecret, SeedlessAuthData, WrappedSecret, WrappedSecretOutput, } from './types.js';
|
|
12
|
+
export type { AuthControllerToken, EncryptedPendingOperation, GetIdentifiersResponse, Identifier, IdentifierAuthorization, IdentifierSession, KeyBoundIdentifierLogin, KeyBoundIdentifierToken, KeyBoundIdentifierTokenRequest, Mutation, MutationPayload, MutationReceipt, PendingMutationPayload, PendingOperation, PendingOperationEncryptor, PendingRecoverySecretHex, PendingRegisterPayload, PendingUpdateIdentifiersPayload, PendingUpdateRecoverySecretPayload, RecoveryApproval, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryIdentifiers, RecoveryLockProvider, RecoveryPhase, RecoveredSecret, SeedlessAuthData, WrappedSecret, WrappedSecretOutput, } from './types.js';
|
|
11
13
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,YAAY,EACV,4BAA4B,EAC5B,2BAA2B,EAC3B,mCAAmC,EACnC,8BAA8B,EAC9B,4BAA4B,EAC5B,0BAA0B,EAC1B,sCAAsC,GACvC,MAAM,4BAA4B,CAAC;AACpC,YAAY,EACV,gCAAgC,EAChC,iDAAiD,EACjD,yCAAyC,EACzC,mCAAmC,EACnC,4CAA4C,EAC5C,mCAAmC,EACnC,iCAAiC,EACjC,4CAA4C,EAC5C,+CAA+C,GAChD,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,8CAA8C,CAAC;AACpF,YAAY,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAChG,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAC9E,YAAY,EACV,oCAAoC,EACpC,kCAAkC,GACnC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,mBAAmB,EACnB,yBAAyB,EACzB,sBAAsB,EACtB,UAAU,EACV,uBAAuB,EACvB,iBAAiB,EACjB,uBAAuB,EACvB,uBAAuB,EACvB,8BAA8B,EAC9B,QAAQ,EACR,eAAe,EACf,eAAe,EACf,sBAAsB,EACtB,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,+BAA+B,EAC/B,kCAAkC,EAClC,gBAAgB,EAChB,oBAAoB,EACpB,sBAAsB,EACtB,8BAA8B,EAC9B,mBAAmB,EACnB,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,aAAa,EACb,mBAAmB,GACpB,MAAM,YAAY,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,YAAY,EACV,4BAA4B,EAC5B,2BAA2B,EAC3B,mCAAmC,EACnC,8BAA8B,EAC9B,4BAA4B,EAC5B,0BAA0B,EAC1B,sCAAsC,GACvC,MAAM,4BAA4B,CAAC;AACpC,YAAY,EACV,gCAAgC,EAChC,sCAAsC,EACtC,iDAAiD,EACjD,yCAAyC,EACzC,mCAAmC,EACnC,4CAA4C,EAC5C,mCAAmC,EACnC,sCAAsC,EACtC,iCAAiC,EACjC,4CAA4C,EAC5C,+CAA+C,GAChD,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,8CAA8C,CAAC;AACpF,YAAY,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAChG,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAC9E,YAAY,EACV,oCAAoC,EACpC,kCAAkC,GACnC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,gCAAgC,EAAE,MAAM,0CAA0C,CAAC;AAC5F,YAAY,EACV,yCAAyC,EACzC,uCAAuC,GACxC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,mBAAmB,EACnB,yBAAyB,EACzB,sBAAsB,EACtB,UAAU,EACV,uBAAuB,EACvB,iBAAiB,EACjB,uBAAuB,EACvB,uBAAuB,EACvB,8BAA8B,EAC9B,QAAQ,EACR,eAAe,EACf,eAAe,EACf,sBAAsB,EACtB,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,+BAA+B,EAC/B,kCAAkC,EAClC,gBAAgB,EAChB,oBAAoB,EACpB,sBAAsB,EACtB,8BAA8B,EAC9B,mBAAmB,EACnB,oBAAoB,EACpB,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,aAAa,EACb,mBAAmB,GACpB,MAAM,YAAY,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { MfaRecoveryController, getDefaultMfaRecoveryControllerState, } from './MfaRecoveryController.js';
|
|
2
2
|
export { CubistEscrowProvider } from './escrow-providers/cubist-escrow-provider.js';
|
|
3
3
|
export { AuthApiRecoveryAuthProvider } from './auth-api-recovery-provider.js';
|
|
4
|
+
export { RecoveryRegistrationLockProvider } from './recovery-registration-lock-provider.js';
|
|
4
5
|
export { IncompleteMutationError, MfaRecoveryError, MutationRejectedError, } from './errors.js';
|
|
5
6
|
export { IDENTIFIER_AUTH_MODES, MIN_IDENTIFIERS, expectedSeedlessAuthConnection, getIdentifierAuthMode, } from './identifier-auth.js';
|
|
6
7
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AAuBpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,8CAA8C,CAAC;AAEpF,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAK9E,OAAO,EAAE,gCAAgC,EAAE,MAAM,0CAA0C,CAAC;AAK5F,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,sBAAsB,CAAC","sourcesContent":["export {\n MfaRecoveryController,\n getDefaultMfaRecoveryControllerState,\n} from './MfaRecoveryController.js';\nexport type {\n MfaRecoveryControllerActions,\n MfaRecoveryControllerEvents,\n MfaRecoveryControllerGetStateAction,\n MfaRecoveryControllerMessenger,\n MfaRecoveryControllerOptions,\n MfaRecoveryControllerState,\n MfaRecoveryControllerStateChangedEvent,\n} from './MfaRecoveryController.js';\nexport type {\n MfaRecoveryControllerAbortAction,\n MfaRecoveryControllerAcquireLockAction,\n MfaRecoveryControllerAuthenticateIdentifierAction,\n MfaRecoveryControllerGetIdentifiersAction,\n MfaRecoveryControllerGetPhaseAction,\n MfaRecoveryControllerGetRecoverySecretAction,\n MfaRecoveryControllerRegisterAction,\n MfaRecoveryControllerReleaseLockAction,\n MfaRecoveryControllerResumeAction,\n MfaRecoveryControllerUpdateIdentifiersAction,\n MfaRecoveryControllerUpdateRecoverySecretAction,\n} from './MfaRecoveryController-method-action-types.js';\nexport { CubistEscrowProvider } from './escrow-providers/cubist-escrow-provider.js';\nexport type { CubistEscrowProviderOptions } from './escrow-providers/cubist-escrow-provider.js';\nexport { AuthApiRecoveryAuthProvider } from './auth-api-recovery-provider.js';\nexport type {\n AuthApiRecoveryAuthProviderMessenger,\n AuthApiRecoveryAuthProviderOptions,\n} from './auth-api-recovery-provider.js';\nexport { RecoveryRegistrationLockProvider } from './recovery-registration-lock-provider.js';\nexport type {\n RecoveryRegistrationLockProviderMessenger,\n RecoveryRegistrationLockProviderOptions,\n} from './recovery-registration-lock-provider.js';\nexport {\n IncompleteMutationError,\n MfaRecoveryError,\n MutationRejectedError,\n} from './errors.js';\nexport {\n IDENTIFIER_AUTH_MODES,\n MIN_IDENTIFIERS,\n expectedSeedlessAuthConnection,\n getIdentifierAuthMode,\n} from './identifier-auth.js';\nexport type {\n AuthControllerToken,\n EncryptedPendingOperation,\n GetIdentifiersResponse,\n Identifier,\n IdentifierAuthorization,\n IdentifierSession,\n KeyBoundIdentifierLogin,\n KeyBoundIdentifierToken,\n KeyBoundIdentifierTokenRequest,\n Mutation,\n MutationPayload,\n MutationReceipt,\n PendingMutationPayload,\n PendingOperation,\n PendingOperationEncryptor,\n PendingRecoverySecretHex,\n PendingRegisterPayload,\n PendingUpdateIdentifiersPayload,\n PendingUpdateRecoverySecretPayload,\n RecoveryApproval,\n RecoveryAuthProvider,\n RecoveryEscrowProvider,\n RecoveryIdentifierAuthProvider,\n RecoveryIdentifiers,\n RecoveryLockProvider,\n RecoveryPhase,\n RecoveredSecret,\n SeedlessAuthData,\n WrappedSecret,\n WrappedSecretOutput,\n} from './types.js';\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Messenger } from '@metamask/messenger';
|
|
2
|
+
import type { AuthenticationControllerGetBearerTokenAction, AuthenticationControllerRefreshCanonicalProfileIdAction } from '@metamask/profile-sync-controller/auth';
|
|
3
|
+
import type { RecoveryLockProvider } from './types.js';
|
|
4
|
+
export type RecoveryRegistrationLockProviderMessenger = Messenger<'RecoveryRegistrationLockProvider', AuthenticationControllerGetBearerTokenAction | AuthenticationControllerRefreshCanonicalProfileIdAction>;
|
|
5
|
+
export type RecoveryRegistrationLockProviderOptions = {
|
|
6
|
+
/** Recovery registration service origin. */
|
|
7
|
+
baseUrl: string;
|
|
8
|
+
messenger: RecoveryRegistrationLockProviderMessenger;
|
|
9
|
+
fetch: typeof globalThis.fetch;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Holds the recovery lease in the registration service, which keys it by the
|
|
13
|
+
* bearer token's `sub`.
|
|
14
|
+
*/
|
|
15
|
+
export declare class RecoveryRegistrationLockProvider implements RecoveryLockProvider {
|
|
16
|
+
#private;
|
|
17
|
+
/**
|
|
18
|
+
* @param options - Provider options.
|
|
19
|
+
* @param options.baseUrl - Recovery registration service origin.
|
|
20
|
+
* @param options.messenger - Messenger with the AuthenticationController
|
|
21
|
+
* actions.
|
|
22
|
+
* @param options.fetch - Fetch implementation.
|
|
23
|
+
*/
|
|
24
|
+
constructor(options: RecoveryRegistrationLockProviderOptions);
|
|
25
|
+
/** @param lockId - Persisted lease ID; reuse it when retrying. */
|
|
26
|
+
acquire(lockId: string): Promise<void>;
|
|
27
|
+
/** @param lockId - Held lease. */
|
|
28
|
+
release(lockId: string): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=recovery-registration-lock-provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recovery-registration-lock-provider.d.ts","sourceRoot":"","sources":["../src/recovery-registration-lock-provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EACV,4CAA4C,EAC5C,uDAAuD,EACxD,MAAM,wCAAwC,CAAC;AAGhD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAEvD,MAAM,MAAM,yCAAyC,GAAG,SAAS,CAC/D,kCAAkC,EAChC,4CAA4C,GAC5C,uDAAuD,CAC1D,CAAC;AAEF,MAAM,MAAM,uCAAuC,GAAG;IACpD,4CAA4C;IAC5C,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,yCAAyC,CAAC;IACrD,KAAK,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CAChC,CAAC;AAEF;;;GAGG;AACH,qBAAa,gCAAiC,YAAW,oBAAoB;;IAO3E;;;;;;OAMG;IACH,YAAY,OAAO,EAAE,uCAAuC,EAI3D;IAED,kEAAkE;IAC5D,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAM3C;IAED,kCAAkC;IAC5B,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAE3C;CA8BF"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { MfaRecoveryError } from './errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* Holds the recovery lease in the registration service, which keys it by the
|
|
4
|
+
* bearer token's `sub`.
|
|
5
|
+
*/
|
|
6
|
+
export class RecoveryRegistrationLockProvider {
|
|
7
|
+
#baseUrl;
|
|
8
|
+
#messenger;
|
|
9
|
+
#fetch;
|
|
10
|
+
/**
|
|
11
|
+
* @param options - Provider options.
|
|
12
|
+
* @param options.baseUrl - Recovery registration service origin.
|
|
13
|
+
* @param options.messenger - Messenger with the AuthenticationController
|
|
14
|
+
* actions.
|
|
15
|
+
* @param options.fetch - Fetch implementation.
|
|
16
|
+
*/
|
|
17
|
+
constructor(options) {
|
|
18
|
+
this.#baseUrl = options.baseUrl.replace(/\/$/u, '');
|
|
19
|
+
this.#messenger = options.messenger;
|
|
20
|
+
this.#fetch = options.fetch;
|
|
21
|
+
}
|
|
22
|
+
/** @param lockId - Persisted lease ID; reuse it when retrying. */
|
|
23
|
+
async acquire(lockId) {
|
|
24
|
+
// Re-login so the bearer `sub` is the current canonical profile.
|
|
25
|
+
await this.#messenger.call('AuthenticationController:refreshCanonicalProfileId');
|
|
26
|
+
await this.#request('POST', '', { lock_id: lockId });
|
|
27
|
+
}
|
|
28
|
+
/** @param lockId - Held lease. */
|
|
29
|
+
async release(lockId) {
|
|
30
|
+
await this.#request('DELETE', `/${encodeURIComponent(lockId)}`);
|
|
31
|
+
}
|
|
32
|
+
async #request(method, path, body) {
|
|
33
|
+
const token = await this.#messenger.call('AuthenticationController:getBearerToken');
|
|
34
|
+
const response = await this.#fetch(`${this.#baseUrl}/recovery/lock${path}`, {
|
|
35
|
+
method,
|
|
36
|
+
headers: {
|
|
37
|
+
Authorization: `Bearer ${token}`,
|
|
38
|
+
'Content-Type': 'application/json',
|
|
39
|
+
},
|
|
40
|
+
...(body ? { body: JSON.stringify(body) } : {}),
|
|
41
|
+
});
|
|
42
|
+
if (!response.ok) {
|
|
43
|
+
throw new MfaRecoveryError(`Recovery lock returned ${response.status}`, response.status === 409
|
|
44
|
+
? 'recovery_lock_conflict'
|
|
45
|
+
: 'recovery_lock_unavailable');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=recovery-registration-lock-provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recovery-registration-lock-provider.js","sourceRoot":"","sources":["../src/recovery-registration-lock-provider.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAgB/C;;;GAGG;AACH,MAAM,OAAO,gCAAgC;IAClC,QAAQ,CAAS;IAEjB,UAAU,CAA4C;IAEtD,MAAM,CAA0B;IAEzC;;;;;;OAMG;IACH,YAAY,OAAgD;QAC1D,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACpD,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;QACpC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC;IAC9B,CAAC;IAED,kEAAkE;IAClE,KAAK,CAAC,OAAO,CAAC,MAAc;QAC1B,iEAAiE;QACjE,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CACxB,oDAAoD,CACrD,CAAC;QACF,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;IACvD,CAAC;IAED,kCAAkC;IAClC,KAAK,CAAC,OAAO,CAAC,MAAc;QAC1B,MAAM,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,kBAAkB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAClE,CAAC;IAED,KAAK,CAAC,QAAQ,CACZ,MAAyB,EACzB,IAAY,EACZ,IAA0B;QAE1B,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CACtC,yCAAyC,CAC1C,CAAC;QACF,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAChC,GAAG,IAAI,CAAC,QAAQ,iBAAiB,IAAI,EAAE,EACvC;YACE,MAAM;YACN,OAAO,EAAE;gBACP,aAAa,EAAE,UAAU,KAAK,EAAE;gBAChC,cAAc,EAAE,kBAAkB;aACnC;YACD,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAChD,CACF,CAAC;QACF,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,gBAAgB,CACxB,0BAA0B,QAAQ,CAAC,MAAM,EAAE,EAC3C,QAAQ,CAAC,MAAM,KAAK,GAAG;gBACrB,CAAC,CAAC,wBAAwB;gBAC1B,CAAC,CAAC,2BAA2B,CAChC,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { Messenger } from '@metamask/messenger';\nimport type {\n AuthenticationControllerGetBearerTokenAction,\n AuthenticationControllerRefreshCanonicalProfileIdAction,\n} from '@metamask/profile-sync-controller/auth';\n\nimport { MfaRecoveryError } from './errors.js';\nimport type { RecoveryLockProvider } from './types.js';\n\nexport type RecoveryRegistrationLockProviderMessenger = Messenger<\n 'RecoveryRegistrationLockProvider',\n | AuthenticationControllerGetBearerTokenAction\n | AuthenticationControllerRefreshCanonicalProfileIdAction\n>;\n\nexport type RecoveryRegistrationLockProviderOptions = {\n /** Recovery registration service origin. */\n baseUrl: string;\n messenger: RecoveryRegistrationLockProviderMessenger;\n fetch: typeof globalThis.fetch;\n};\n\n/**\n * Holds the recovery lease in the registration service, which keys it by the\n * bearer token's `sub`.\n */\nexport class RecoveryRegistrationLockProvider implements RecoveryLockProvider {\n readonly #baseUrl: string;\n\n readonly #messenger: RecoveryRegistrationLockProviderMessenger;\n\n readonly #fetch: typeof globalThis.fetch;\n\n /**\n * @param options - Provider options.\n * @param options.baseUrl - Recovery registration service origin.\n * @param options.messenger - Messenger with the AuthenticationController\n * actions.\n * @param options.fetch - Fetch implementation.\n */\n constructor(options: RecoveryRegistrationLockProviderOptions) {\n this.#baseUrl = options.baseUrl.replace(/\\/$/u, '');\n this.#messenger = options.messenger;\n this.#fetch = options.fetch;\n }\n\n /** @param lockId - Persisted lease ID; reuse it when retrying. */\n async acquire(lockId: string): Promise<void> {\n // Re-login so the bearer `sub` is the current canonical profile.\n await this.#messenger.call(\n 'AuthenticationController:refreshCanonicalProfileId',\n );\n await this.#request('POST', '', { lock_id: lockId });\n }\n\n /** @param lockId - Held lease. */\n async release(lockId: string): Promise<void> {\n await this.#request('DELETE', `/${encodeURIComponent(lockId)}`);\n }\n\n async #request(\n method: 'POST' | 'DELETE',\n path: string,\n body?: { lock_id: string },\n ): Promise<void> {\n const token = await this.#messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n const response = await this.#fetch(\n `${this.#baseUrl}/recovery/lock${path}`,\n {\n method,\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n ...(body ? { body: JSON.stringify(body) } : {}),\n },\n );\n if (!response.ok) {\n throw new MfaRecoveryError(\n `Recovery lock returned ${response.status}`,\n response.status === 409\n ? 'recovery_lock_conflict'\n : 'recovery_lock_unavailable',\n );\n }\n }\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -259,6 +259,14 @@ export type RecoveryAuthProvider = {
|
|
|
259
259
|
requireTwoFactor?: boolean;
|
|
260
260
|
}) => Promise<RecoveryApproval>;
|
|
261
261
|
};
|
|
262
|
+
/**
|
|
263
|
+
* Per-profile recovery lease. It must outlive the approvals requested right
|
|
264
|
+
* after acquiring it. Acquiring a held lease again extends it.
|
|
265
|
+
*/
|
|
266
|
+
export type RecoveryLockProvider = {
|
|
267
|
+
acquire: (lockId: string) => Promise<void>;
|
|
268
|
+
release: (lockId: string) => Promise<void>;
|
|
269
|
+
};
|
|
262
270
|
/**
|
|
263
271
|
* Obtains a key-bound identifier assertion from an IdP (OIDC, Passkey, SIWE).
|
|
264
272
|
*/
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAEjF,YAAY,EAAE,gBAAgB,EAAE,CAAC;AAEjC,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG,WAAW,CAAC;AAE7C,MAAM,MAAM,uBAAuB,GAAG;IACpC,UAAU,EAAE,UAAU,CAAC;IACvB;;OAEG;IACH,cAAc,EAAE,UAAU,CAAC;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,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mappings":"AAAA;;GAEG","sourcesContent":["/**\n * MFA recovery protocol types from the recovery ADR.\n */\n\nimport type { SeedlessAuthData } from '@metamask/seedless-onboarding-controller';\n\nexport type { SeedlessAuthData };\n\nexport type Identifier = {\n type: string;\n namespace: string;\n value: string;\n verifier?: unknown;\n};\n\nexport type PoPChallenge = {\n id: string;\n escrowId: string;\n /**\n * Unix time in seconds.\n */\n expiresAt: number;\n};\n\nexport type IdentifierAuthMode = 'key-bound';\n\nexport type KeyBoundIdentifierToken = {\n identifier: Identifier;\n /**\n * Raw 32-byte Ed25519 public key of the ephemeral proof key.\n */\n proofPublicKey: Uint8Array;\n requestHash: string;\n providerAssertion: unknown;\n};\n\nexport type ProofOfPossession = {\n challengeId: string;\n requestHash: string;\n signature: string;\n};\n\n/**\n * Identifier proof presented to an escrow. Only key-bound proofs are wired;\n * escrow-challenge grants land with MFA-605 / MFA-606 / MFA-568.\n */\nexport type IdentifierAuthorization = {\n kind: 'key-bound';\n token: KeyBoundIdentifierToken;\n proof: ProofOfPossession;\n};\n\nexport type MutationOperation =\n | 'register'\n | 'updateRecoverySecret'\n | 'updateIdentifiers';\n\nexport type Mutation = {\n id: string;\n profileId: string;\n operation: MutationOperation;\n expectedVersion: number;\n newVersion: number;\n payloadHash: string;\n audiences: string[];\n requestHash: string;\n};\n\n/**\n * Auth API approval (compact JWT). Its `ext` claims bind it to one mutation:\n * `aal`, `request_hash`, and `identifiers_hash`.\n */\nexport type AuthControllerToken = string;\n\nexport type RecoveryApproval = {\n approval: AuthControllerToken;\n identifiers: Identifier[];\n};\n\nexport type MutationReceipt = {\n mutationId: string;\n requestHash: string;\n escrowId: string;\n version: number;\n /**\n * SHA-256 of the raw 32-byte Ed25519 receipt public key, as `0x` hex.\n */\n receiptKeyId: string;\n signature: string;\n};\n\n/**\n * Key-bound identifier credential: the IdP token and the private key that\n * proves possession of it. Ephemeral; keep only in memory.\n */\nexport type KeyBoundCredential = {\n token: KeyBoundIdentifierToken;\n /**\n * Raw 32-byte Ed25519 private key of the ephemeral proof key.\n */\n proofPrivateKey: Uint8Array;\n};\n\n/**\n * Parameters for requesting a key-bound identifier token from an IdP.\n */\nexport type KeyBoundIdentifierTokenRequest = {\n identifier: Identifier;\n /**\n * Raw 32-byte Ed25519 public key to bind into the token.\n */\n proofPublicKey: Uint8Array;\n requestHash: string;\n};\n\n/**\n * Result of one identifier login. `token` is the key-bound recovery material\n * presented to escrows (its `providerAssertion` carries the provider ID token\n * or assertion). `seedlessAuthData` is present when the IdP issued seedless\n * auth-server tokens in the same exchange (social logins); passkey / SIWE\n * omit it.\n */\nexport type KeyBoundIdentifierLogin = {\n token: KeyBoundIdentifierToken;\n seedlessAuthData?: SeedlessAuthData;\n};\n\n/**\n * Result of first-factor identifier authentication from\n * `authenticateIdentifier`, and the input to `getRecoverySecret`.\n *\n * `proofPrivateKey` signs escrow challenges. `ephemeralPrivateKey` is the\n * private half of `pkE` and decrypts the recovery secret. Keep both in\n * memory only.\n *\n * `seedlessAuthData` is present when the same login also completed a seedless\n * auth-server exchange. Use it for `SeedlessOnboardingController.authenticate`,\n * then drop it before holding the session for a later `getRecoverySecret`.\n * Escrow paths use only the key-bound credential fields.\n */\nexport type IdentifierSession = KeyBoundCredential & {\n requestId: string;\n /**\n * Raw 32-byte X25519 private key matching `pkE`.\n */\n ephemeralPrivateKey: Uint8Array;\n /**\n * Raw 32-byte X25519 public key, the client's one-time read key.\n */\n pkE: Uint8Array;\n seedlessAuthData?: SeedlessAuthData;\n};\n\n/**\n * Recovery secret wrapped to one escrow wrap key for transit.\n */\nexport type WrappedSecret = {\n /**\n * Raw 32-byte X25519 public key of the sender's ephemeral key.\n */\n pkE: Uint8Array;\n /**\n * Raw bytes of `iv || AES-256-GCM(ciphertext+tag)`.\n */\n ciphertext: Uint8Array;\n};\n\nexport type WrappedSecretOutput = {\n /**\n * Raw bytes of `iv || AES-256-GCM(ciphertext+tag)`.\n */\n ciphertext: Uint8Array;\n};\n\nexport type RegisterPayload = {\n recoverySecret: WrappedSecret;\n identifiers: Identifier[];\n};\n\nexport type UpdateRecoverySecretPayload = Pick<\n RegisterPayload,\n 'recoverySecret'\n>;\n\nexport type UpdateIdentifiersPayload = Pick<RegisterPayload, 'identifiers'>;\n\n/**\n * Escrow `applyMutation` body. Recovery secrets are wrapped to that escrow's\n * wrap key; do not confuse with {@link PendingMutationPayload}.\n */\nexport type MutationPayload =\n | RegisterPayload\n | UpdateRecoverySecretPayload\n | UpdateIdentifiersPayload;\n\n/**\n * 0x-hex of a plaintext recovery secret. Encrypted pending state stores this\n * logical value; each escrow receives a {@link WrappedSecret} only at apply.\n */\nexport type PendingRecoverySecretHex = string;\n\n/**\n * Logical register payload stored in encrypted pending state.\n */\nexport type PendingRegisterPayload = {\n identifiers: Identifier[];\n recoverySecret: PendingRecoverySecretHex;\n};\n\n/**\n * Logical secret-update payload stored in encrypted pending state.\n */\nexport type PendingUpdateRecoverySecretPayload = Pick<\n PendingRegisterPayload,\n 'recoverySecret'\n>;\n\n/**\n * Logical identifier-update payload stored in encrypted pending state.\n */\nexport type PendingUpdateIdentifiersPayload = Pick<\n PendingRegisterPayload,\n 'identifiers'\n>;\n\n/**\n * Logical mutation payload persisted in encrypted pending state. Distinct from\n * {@link MutationPayload}, which is the per-escrow apply body.\n */\nexport type PendingMutationPayload =\n | PendingRegisterPayload\n | PendingUpdateRecoverySecretPayload\n | PendingUpdateIdentifiersPayload;\n\ntype PendingOperationBase = {\n mutation: Mutation;\n identifier: Identifier | null;\n payload: PendingMutationPayload;\n};\n\nexport type AuthorizingPendingOperation = PendingOperationBase & {\n phase: 'authorizing';\n};\n\nexport type WritingPendingOperation = PendingOperationBase & {\n phase: 'writing';\n authControllerToken: AuthControllerToken;\n /**\n * The approval's identifiers, in Auth API order, bound by its\n * `identifiers_hash`.\n */\n approvedIdentifiers: Identifier[];\n receipts: MutationReceipt[];\n};\n\nexport type PendingOperation =\n | AuthorizingPendingOperation\n | WritingPendingOperation;\n\nexport type RecoveryPhase = 'idle' | PendingOperation['phase'];\n\n/**\n * Encoded ciphertext of {@link PendingOperation}. Wallet secure storage\n * encrypts this blob (including any hex recovery secret). A raw recovery\n * secret is never persisted in BaseController state.\n *\n * The recovery spec's pseudocode represents this as `Uint8Array`, but the\n * controller stores the encoded ciphertext as a string so BaseController state\n * persistence and serialization preserve it without binary coercion.\n */\nexport type EncryptedPendingOperation = string;\n\nexport type GetRecoverySecretResponse = {\n recoverySecret: WrappedSecretOutput;\n version: number;\n lastMutationId: string;\n wrapKeyId: string;\n};\n\n/**\n * Recovery secret plus the version to use as `epoch` on later mutations.\n */\nexport type RecoveredSecret = {\n recoverySecret: Uint8Array;\n epoch: number;\n};\n\n/**\n * One escrow's enrolled identifiers and record version.\n */\nexport type GetIdentifiersResponse = {\n identifiers: Identifier[];\n version: number;\n};\n\n/**\n * Enrolled identifiers and `epoch`, plus Auth's current identifiers to build\n * an `updateIdentifiers` set from.\n */\nexport type RecoveryIdentifiers = {\n identifiers: Identifier[];\n epoch: number;\n authIdentifiers: Identifier[];\n};\n\n/**\n * Authenticates the MetaMask profile and issues request-bound attestations.\n */\nexport type RecoveryAuthProvider = {\n getAuthenticatedProfileId: () => Promise<string>;\n /**\n * Returns the Auth API's approval and current recovery identifiers.\n * `requireTwoFactor` requests recent AAL2 authentication.\n */\n authorizeRecoveryRequest: (params: {\n requestHash: string;\n audiences: string[];\n requireTwoFactor?: boolean;\n }) => Promise<RecoveryApproval>;\n};\n\n/**\n * Obtains a key-bound identifier assertion from an IdP (OIDC, Passkey, SIWE).\n */\nexport type RecoveryIdentifierAuthProvider = {\n /**\n * One identifier login. Returns the key-bound token, bound to the requested\n * `proofPublicKey` and `requestHash`, and any seedless auth-server tokens\n * from the same exchange. Omit `seedlessAuthData` when the IdP does not\n * issue it (e.g. passkey). Every controller path calls this method and uses\n * only the parts it needs.\n */\n getKeyBoundIdentifierLogin: (\n params: KeyBoundIdentifierTokenRequest,\n ) => Promise<KeyBoundIdentifierLogin>;\n};\n\n/**\n * One recovery escrow replica. Implementations may talk to different backends.\n */\nexport type RecoveryEscrowProvider = {\n readonly id: string;\n /**\n * Audience the AuthController token must carry for this escrow to accept it.\n * Independent of `id`.\n */\n readonly authAudience: string;\n /**\n * Raw 32-byte X25519 wrap public key. Mutation payloads are encrypted to this\n * key; `getSecret` responses are encrypted to the request's ephemeral key\n * using the corresponding wrap private key.\n */\n readonly wrapPublicKey: Uint8Array;\n isAvailable: () => Promise<boolean>;\n generateChallenge: (\n authControllerToken: AuthControllerToken,\n ) => Promise<PoPChallenge>;\n getIdentifiers: (\n authControllerToken: AuthControllerToken,\n ) => Promise<GetIdentifiersResponse>;\n getSecret: (\n authControllerToken: AuthControllerToken,\n authorization: IdentifierAuthorization,\n requestId: string,\n pkE: Uint8Array,\n ) => Promise<GetRecoverySecretResponse>;\n /**\n * On first application, `identifierAuthorizations` share one challenge: one\n * proof per SIWE identifier the escrow has not enrolled, plus one\n * enrolled-identifier proof for updates.\n *\n * An escrow that already applied the mutation returns its matching stored\n * receipt before validating proofs, which may include SIWE identifiers still\n * missing from other escrows.\n */\n applyMutation: (\n mutation: Mutation,\n authControllerToken: AuthControllerToken,\n identifierAuthorizations: IdentifierAuthorization[],\n payload: MutationPayload,\n approvedIdentifiers: Identifier[],\n ) => Promise<MutationReceipt>;\n /**\n * Verifies a receipt cryptographically using the build-pinned receipt key\n * and confirms it targets the expected escrow.\n *\n * @param receipt - Receipt returned by an escrow.\n * @param mutation - Mutation acknowledged by the receipt.\n * @param expectedEscrowId - Escrow identity expected by the caller.\n */\n verifyReceipt: (\n receipt: MutationReceipt,\n mutation: Mutation,\n expectedEscrowId: string,\n ) => Promise<boolean>;\n};\n\n/**\n * Encrypts pending mutation state using wallet secure storage.\n */\nexport type PendingOperationEncryptor = {\n encrypt: (operation: PendingOperation) => Promise<EncryptedPendingOperation>;\n decrypt: (ciphertext: EncryptedPendingOperation) => Promise<PendingOperation>;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG","sourcesContent":["/**\n * MFA recovery protocol types from the recovery ADR.\n */\n\nimport type { SeedlessAuthData } from '@metamask/seedless-onboarding-controller';\n\nexport type { SeedlessAuthData };\n\nexport type Identifier = {\n type: string;\n namespace: string;\n value: string;\n verifier?: unknown;\n};\n\nexport type PoPChallenge = {\n id: string;\n escrowId: string;\n /**\n * Unix time in seconds.\n */\n expiresAt: number;\n};\n\nexport type IdentifierAuthMode = 'key-bound';\n\nexport type KeyBoundIdentifierToken = {\n identifier: Identifier;\n /**\n * Raw 32-byte Ed25519 public key of the ephemeral proof key.\n */\n proofPublicKey: Uint8Array;\n requestHash: string;\n providerAssertion: unknown;\n};\n\nexport type ProofOfPossession = {\n challengeId: string;\n requestHash: string;\n signature: string;\n};\n\n/**\n * Identifier proof presented to an escrow. Only key-bound proofs are wired;\n * escrow-challenge grants land with MFA-605 / MFA-606 / MFA-568.\n */\nexport type IdentifierAuthorization = {\n kind: 'key-bound';\n token: KeyBoundIdentifierToken;\n proof: ProofOfPossession;\n};\n\nexport type MutationOperation =\n | 'register'\n | 'updateRecoverySecret'\n | 'updateIdentifiers';\n\nexport type Mutation = {\n id: string;\n profileId: string;\n operation: MutationOperation;\n expectedVersion: number;\n newVersion: number;\n payloadHash: string;\n audiences: string[];\n requestHash: string;\n};\n\n/**\n * Auth API approval (compact JWT). Its `ext` claims bind it to one mutation:\n * `aal`, `request_hash`, and `identifiers_hash`.\n */\nexport type AuthControllerToken = string;\n\nexport type RecoveryApproval = {\n approval: AuthControllerToken;\n identifiers: Identifier[];\n};\n\nexport type MutationReceipt = {\n mutationId: string;\n requestHash: string;\n escrowId: string;\n version: number;\n /**\n * SHA-256 of the raw 32-byte Ed25519 receipt public key, as `0x` hex.\n */\n receiptKeyId: string;\n signature: string;\n};\n\n/**\n * Key-bound identifier credential: the IdP token and the private key that\n * proves possession of it. Ephemeral; keep only in memory.\n */\nexport type KeyBoundCredential = {\n token: KeyBoundIdentifierToken;\n /**\n * Raw 32-byte Ed25519 private key of the ephemeral proof key.\n */\n proofPrivateKey: Uint8Array;\n};\n\n/**\n * Parameters for requesting a key-bound identifier token from an IdP.\n */\nexport type KeyBoundIdentifierTokenRequest = {\n identifier: Identifier;\n /**\n * Raw 32-byte Ed25519 public key to bind into the token.\n */\n proofPublicKey: Uint8Array;\n requestHash: string;\n};\n\n/**\n * Result of one identifier login. `token` is the key-bound recovery material\n * presented to escrows (its `providerAssertion` carries the provider ID token\n * or assertion). `seedlessAuthData` is present when the IdP issued seedless\n * auth-server tokens in the same exchange (social logins); passkey / SIWE\n * omit it.\n */\nexport type KeyBoundIdentifierLogin = {\n token: KeyBoundIdentifierToken;\n seedlessAuthData?: SeedlessAuthData;\n};\n\n/**\n * Result of first-factor identifier authentication from\n * `authenticateIdentifier`, and the input to `getRecoverySecret`.\n *\n * `proofPrivateKey` signs escrow challenges. `ephemeralPrivateKey` is the\n * private half of `pkE` and decrypts the recovery secret. Keep both in\n * memory only.\n *\n * `seedlessAuthData` is present when the same login also completed a seedless\n * auth-server exchange. Use it for `SeedlessOnboardingController.authenticate`,\n * then drop it before holding the session for a later `getRecoverySecret`.\n * Escrow paths use only the key-bound credential fields.\n */\nexport type IdentifierSession = KeyBoundCredential & {\n requestId: string;\n /**\n * Raw 32-byte X25519 private key matching `pkE`.\n */\n ephemeralPrivateKey: Uint8Array;\n /**\n * Raw 32-byte X25519 public key, the client's one-time read key.\n */\n pkE: Uint8Array;\n seedlessAuthData?: SeedlessAuthData;\n};\n\n/**\n * Recovery secret wrapped to one escrow wrap key for transit.\n */\nexport type WrappedSecret = {\n /**\n * Raw 32-byte X25519 public key of the sender's ephemeral key.\n */\n pkE: Uint8Array;\n /**\n * Raw bytes of `iv || AES-256-GCM(ciphertext+tag)`.\n */\n ciphertext: Uint8Array;\n};\n\nexport type WrappedSecretOutput = {\n /**\n * Raw bytes of `iv || AES-256-GCM(ciphertext+tag)`.\n */\n ciphertext: Uint8Array;\n};\n\nexport type RegisterPayload = {\n recoverySecret: WrappedSecret;\n identifiers: Identifier[];\n};\n\nexport type UpdateRecoverySecretPayload = Pick<\n RegisterPayload,\n 'recoverySecret'\n>;\n\nexport type UpdateIdentifiersPayload = Pick<RegisterPayload, 'identifiers'>;\n\n/**\n * Escrow `applyMutation` body. Recovery secrets are wrapped to that escrow's\n * wrap key; do not confuse with {@link PendingMutationPayload}.\n */\nexport type MutationPayload =\n | RegisterPayload\n | UpdateRecoverySecretPayload\n | UpdateIdentifiersPayload;\n\n/**\n * 0x-hex of a plaintext recovery secret. Encrypted pending state stores this\n * logical value; each escrow receives a {@link WrappedSecret} only at apply.\n */\nexport type PendingRecoverySecretHex = string;\n\n/**\n * Logical register payload stored in encrypted pending state.\n */\nexport type PendingRegisterPayload = {\n identifiers: Identifier[];\n recoverySecret: PendingRecoverySecretHex;\n};\n\n/**\n * Logical secret-update payload stored in encrypted pending state.\n */\nexport type PendingUpdateRecoverySecretPayload = Pick<\n PendingRegisterPayload,\n 'recoverySecret'\n>;\n\n/**\n * Logical identifier-update payload stored in encrypted pending state.\n */\nexport type PendingUpdateIdentifiersPayload = Pick<\n PendingRegisterPayload,\n 'identifiers'\n>;\n\n/**\n * Logical mutation payload persisted in encrypted pending state. Distinct from\n * {@link MutationPayload}, which is the per-escrow apply body.\n */\nexport type PendingMutationPayload =\n | PendingRegisterPayload\n | PendingUpdateRecoverySecretPayload\n | PendingUpdateIdentifiersPayload;\n\ntype PendingOperationBase = {\n mutation: Mutation;\n identifier: Identifier | null;\n payload: PendingMutationPayload;\n};\n\nexport type AuthorizingPendingOperation = PendingOperationBase & {\n phase: 'authorizing';\n};\n\nexport type WritingPendingOperation = PendingOperationBase & {\n phase: 'writing';\n authControllerToken: AuthControllerToken;\n /**\n * The approval's identifiers, in Auth API order, bound by its\n * `identifiers_hash`.\n */\n approvedIdentifiers: Identifier[];\n receipts: MutationReceipt[];\n};\n\nexport type PendingOperation =\n | AuthorizingPendingOperation\n | WritingPendingOperation;\n\nexport type RecoveryPhase = 'idle' | PendingOperation['phase'];\n\n/**\n * Encoded ciphertext of {@link PendingOperation}. Wallet secure storage\n * encrypts this blob (including any hex recovery secret). A raw recovery\n * secret is never persisted in BaseController state.\n *\n * The recovery spec's pseudocode represents this as `Uint8Array`, but the\n * controller stores the encoded ciphertext as a string so BaseController state\n * persistence and serialization preserve it without binary coercion.\n */\nexport type EncryptedPendingOperation = string;\n\nexport type GetRecoverySecretResponse = {\n recoverySecret: WrappedSecretOutput;\n version: number;\n lastMutationId: string;\n wrapKeyId: string;\n};\n\n/**\n * Recovery secret plus the version to use as `epoch` on later mutations.\n */\nexport type RecoveredSecret = {\n recoverySecret: Uint8Array;\n epoch: number;\n};\n\n/**\n * One escrow's enrolled identifiers and record version.\n */\nexport type GetIdentifiersResponse = {\n identifiers: Identifier[];\n version: number;\n};\n\n/**\n * Enrolled identifiers and `epoch`, plus Auth's current identifiers to build\n * an `updateIdentifiers` set from.\n */\nexport type RecoveryIdentifiers = {\n identifiers: Identifier[];\n epoch: number;\n authIdentifiers: Identifier[];\n};\n\n/**\n * Authenticates the MetaMask profile and issues request-bound attestations.\n */\nexport type RecoveryAuthProvider = {\n getAuthenticatedProfileId: () => Promise<string>;\n /**\n * Returns the Auth API's approval and current recovery identifiers.\n * `requireTwoFactor` requests recent AAL2 authentication.\n */\n authorizeRecoveryRequest: (params: {\n requestHash: string;\n audiences: string[];\n requireTwoFactor?: boolean;\n }) => Promise<RecoveryApproval>;\n};\n\n/**\n * Per-profile recovery lease. It must outlive the approvals requested right\n * after acquiring it. Acquiring a held lease again extends it.\n */\nexport type RecoveryLockProvider = {\n acquire: (lockId: string) => Promise<void>;\n release: (lockId: string) => Promise<void>;\n};\n\n/**\n * Obtains a key-bound identifier assertion from an IdP (OIDC, Passkey, SIWE).\n */\nexport type RecoveryIdentifierAuthProvider = {\n /**\n * One identifier login. Returns the key-bound token, bound to the requested\n * `proofPublicKey` and `requestHash`, and any seedless auth-server tokens\n * from the same exchange. Omit `seedlessAuthData` when the IdP does not\n * issue it (e.g. passkey). Every controller path calls this method and uses\n * only the parts it needs.\n */\n getKeyBoundIdentifierLogin: (\n params: KeyBoundIdentifierTokenRequest,\n ) => Promise<KeyBoundIdentifierLogin>;\n};\n\n/**\n * One recovery escrow replica. Implementations may talk to different backends.\n */\nexport type RecoveryEscrowProvider = {\n readonly id: string;\n /**\n * Audience the AuthController token must carry for this escrow to accept it.\n * Independent of `id`.\n */\n readonly authAudience: string;\n /**\n * Raw 32-byte X25519 wrap public key. Mutation payloads are encrypted to this\n * key; `getSecret` responses are encrypted to the request's ephemeral key\n * using the corresponding wrap private key.\n */\n readonly wrapPublicKey: Uint8Array;\n isAvailable: () => Promise<boolean>;\n generateChallenge: (\n authControllerToken: AuthControllerToken,\n ) => Promise<PoPChallenge>;\n getIdentifiers: (\n authControllerToken: AuthControllerToken,\n ) => Promise<GetIdentifiersResponse>;\n getSecret: (\n authControllerToken: AuthControllerToken,\n authorization: IdentifierAuthorization,\n requestId: string,\n pkE: Uint8Array,\n ) => Promise<GetRecoverySecretResponse>;\n /**\n * On first application, `identifierAuthorizations` share one challenge: one\n * proof per SIWE identifier the escrow has not enrolled, plus one\n * enrolled-identifier proof for updates.\n *\n * An escrow that already applied the mutation returns its matching stored\n * receipt before validating proofs, which may include SIWE identifiers still\n * missing from other escrows.\n */\n applyMutation: (\n mutation: Mutation,\n authControllerToken: AuthControllerToken,\n identifierAuthorizations: IdentifierAuthorization[],\n payload: MutationPayload,\n approvedIdentifiers: Identifier[],\n ) => Promise<MutationReceipt>;\n /**\n * Verifies a receipt cryptographically using the build-pinned receipt key\n * and confirms it targets the expected escrow.\n *\n * @param receipt - Receipt returned by an escrow.\n * @param mutation - Mutation acknowledged by the receipt.\n * @param expectedEscrowId - Escrow identity expected by the caller.\n */\n verifyReceipt: (\n receipt: MutationReceipt,\n mutation: Mutation,\n expectedEscrowId: string,\n ) => Promise<boolean>;\n};\n\n/**\n * Encrypts pending mutation state using wallet secure storage.\n */\nexport type PendingOperationEncryptor = {\n encrypt: (operation: PendingOperation) => Promise<EncryptedPendingOperation>;\n decrypt: (ciphertext: EncryptedPendingOperation) => Promise<PendingOperation>;\n};\n"]}
|