@metamask-previews/mfa-recovery-controller 0.0.0-preview-8df707a0a → 0.0.0-preview-e1e83cae0
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 +5 -8
- package/README.md +6 -3
- package/dist/MfaRecoveryController.d.ts +11 -17
- package/dist/MfaRecoveryController.d.ts.map +1 -1
- package/dist/MfaRecoveryController.js +14 -50
- package/dist/MfaRecoveryController.js.map +1 -1
- package/dist/auth-api-recovery-provider.d.ts +33 -0
- package/dist/auth-api-recovery-provider.d.ts.map +1 -0
- package/dist/auth-api-recovery-provider.js +38 -0
- package/dist/auth-api-recovery-provider.js.map +1 -0
- package/dist/escrow-providers/cubist-escrow-provider.d.ts +1 -4
- package/dist/escrow-providers/cubist-escrow-provider.d.ts.map +1 -1
- package/dist/escrow-providers/cubist-escrow-provider.js +3 -19
- package/dist/escrow-providers/cubist-escrow-provider.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +30 -17
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -1
- package/package.json +1 -2
package/CHANGELOG.md
CHANGED
|
@@ -9,8 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
### Added
|
|
11
11
|
|
|
12
|
-
- Initial release of `MfaRecoveryController`, which manages MFA recovery flows and persists in-flight operations in its state ([#10022](https://github.com/MetaMask/core/pull/10022))
|
|
13
|
-
- Requires recent, request-bound AAL2 approvals for writes and reads.
|
|
12
|
+
- Initial release of `MfaRecoveryController`, which manages MFA recovery flows and persists in-flight operations in its state ([#10022](https://github.com/MetaMask/core/pull/10022), [#11280](https://github.com/MetaMask/core/pull/11280))
|
|
13
|
+
- Requires recent, request-bound AAL2 approvals for writes and reads.
|
|
14
14
|
- Sends the approval's identifiers to escrows as `approvedIdentifiers` with `register` and `updateIdentifiers` mutations, and rejects payload identifiers that are not exactly among them before writing ([#10883](https://github.com/MetaMask/core/pull/10883))
|
|
15
15
|
- Adds `getIdentifiers`, which returns the enrolled identifiers at the highest escrow version as `epoch` along with Auth's identifiers, for building `updateIdentifiers` calls ([#11149](https://github.com/MetaMask/core/pull/11149))
|
|
16
16
|
- Passes the operation's AuthController token to `RecoveryEscrowProvider.generateChallenge`, and requires `RecoveryEscrowProvider.getIdentifiers` ([#11149](https://github.com/MetaMask/core/pull/11149))
|
|
@@ -19,10 +19,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
19
19
|
- Rejects duplicate identifiers with `duplicate_identifier` and more than 16 identifiers with `too_many_identifiers` ([#11151](https://github.com/MetaMask/core/pull/11151))
|
|
20
20
|
- 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))
|
|
21
21
|
- Exports `MfaRecoveryController`, `getDefaultMfaRecoveryControllerState`, and the controller's action, event, messenger, state, and options types.
|
|
22
|
-
- Exports `
|
|
22
|
+
- 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))
|
|
23
|
+
- 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))
|
|
23
24
|
- Exports `MfaRecoveryError`, `IncompleteMutationError`, and `MutationRejectedError`.
|
|
24
25
|
- Exports `MIN_IDENTIFIERS`, `IDENTIFIER_AUTH_MODES`, and `getIdentifierAuthMode` for identifier authentication.
|
|
25
|
-
- Exports types for the recovery providers (`RecoveryIdentifierAuthProvider`, `RecoveryEscrowProvider`) and
|
|
26
|
+
- Exports types for the recovery providers (`RecoveryAuthProvider`, `RecoveryIdentifierAuthProvider`, `RecoveryEscrowProvider`) and the pending operation encryptor (`PendingOperationEncryptor`), along with the related identifier, mutation, and recovery phase types, including `GetIdentifiersResponse` and `RecoveryIdentifiers` ([#11149](https://github.com/MetaMask/core/pull/11149))
|
|
26
27
|
- Add support for Node.js 26 ([#10981](https://github.com/MetaMask/core/pull/10981))
|
|
27
28
|
|
|
28
29
|
### Changed
|
|
@@ -30,8 +31,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
30
31
|
- Bump `@metamask/utils` from `^12.0.0` to `^12.0.1` ([#11107](https://github.com/MetaMask/core/pull/11107))
|
|
31
32
|
- Bump `@metamask/profile-sync-controller` from `^36.0.0` to `^36.1.1` ([#11396](https://github.com/MetaMask/core/pull/11396), [#11419](https://github.com/MetaMask/core/pull/11419))
|
|
32
33
|
|
|
33
|
-
### Fixed
|
|
34
|
-
|
|
35
|
-
- Propagate errors thrown by `RecoveryEscrowProvider.isAvailable`, such as `feature_disabled` or a failed registration, instead of treating them as an unavailable escrow ([#11280](https://github.com/MetaMask/core/pull/11280))
|
|
36
|
-
|
|
37
34
|
[Unreleased]: https://github.com/MetaMask/core/
|
package/README.md
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
# `@metamask/mfa-recovery-controller`
|
|
2
2
|
|
|
3
|
-
Coordinates MFA recovery through
|
|
3
|
+
Coordinates MFA recovery through injected auth and escrow providers.
|
|
4
4
|
|
|
5
|
-
Pending mutations are encrypted in controller state
|
|
5
|
+
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
9
|
## Auth API Integration
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
Configure `AuthApiRecoveryAuthProvider` with a messenger that can call
|
|
12
|
+
`AuthenticationController:refreshCanonicalProfileId` and
|
|
13
|
+
`AuthenticationController:requestMfaApproval`. It resolves the current canonical
|
|
14
|
+
profile id for each mutation and requests approvals from `/api/v2/mfa/approvals`. Writes and reads require a
|
|
12
15
|
request-bound AAL2 approval; updates and reads also require an identifier proof.
|
|
13
16
|
Without a recent MFA verification, approvals reject with `StepUpRequiredError`:
|
|
14
17
|
verify, then call `resume()` or retry the read.
|
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import type { ControllerGetStateAction, ControllerStateChangedEvent } from '@metamask/base-controller';
|
|
2
2
|
import { BaseController } from '@metamask/base-controller';
|
|
3
|
-
import type { EncryptionResultConstraint } from '@metamask/keyring-controller';
|
|
4
3
|
import type { Messenger } from '@metamask/messenger';
|
|
5
|
-
import type { AuthenticationControllerRefreshCanonicalProfileIdAction, AuthenticationControllerRequestMfaApprovalAction } from '@metamask/profile-sync-controller/auth';
|
|
6
4
|
import type { MfaRecoveryControllerMethodActions } from './MfaRecoveryController-method-action-types.js';
|
|
7
|
-
import type {
|
|
5
|
+
import type { Identifier, IdentifierSession, PendingOperationEncryptor, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryIdentifiers, RecoveryPhase, RecoveredSecret } from './types.js';
|
|
8
6
|
declare const CONTROLLER_NAME = "MfaRecoveryController";
|
|
9
7
|
export type MfaRecoveryControllerState = {
|
|
10
8
|
/**
|
|
@@ -18,12 +16,12 @@ export type MfaRecoveryControllerState = {
|
|
|
18
16
|
export declare function getDefaultMfaRecoveryControllerState(): MfaRecoveryControllerState;
|
|
19
17
|
export type MfaRecoveryControllerGetStateAction = ControllerGetStateAction<typeof CONTROLLER_NAME, MfaRecoveryControllerState>;
|
|
20
18
|
export type MfaRecoveryControllerActions = MfaRecoveryControllerGetStateAction | MfaRecoveryControllerMethodActions;
|
|
21
|
-
type AllowedActions =
|
|
19
|
+
type AllowedActions = never;
|
|
22
20
|
export type MfaRecoveryControllerStateChangedEvent = ControllerStateChangedEvent<typeof CONTROLLER_NAME, MfaRecoveryControllerState>;
|
|
23
21
|
export type MfaRecoveryControllerEvents = MfaRecoveryControllerStateChangedEvent;
|
|
24
22
|
type AllowedEvents = never;
|
|
25
23
|
export type MfaRecoveryControllerMessenger = Messenger<typeof CONTROLLER_NAME, MfaRecoveryControllerActions | AllowedActions, MfaRecoveryControllerEvents | AllowedEvents>;
|
|
26
|
-
export type MfaRecoveryControllerOptions
|
|
24
|
+
export type MfaRecoveryControllerOptions = {
|
|
27
25
|
/**
|
|
28
26
|
* The messenger suited for this controller.
|
|
29
27
|
*/
|
|
@@ -33,6 +31,10 @@ export type MfaRecoveryControllerOptions<EncryptionKey = DefaultEncryptionKey, E
|
|
|
33
31
|
* properties will be filled in with defaults.
|
|
34
32
|
*/
|
|
35
33
|
state?: Partial<MfaRecoveryControllerState>;
|
|
34
|
+
/**
|
|
35
|
+
* Authenticates the MetaMask profile and issues request-bound attestations.
|
|
36
|
+
*/
|
|
37
|
+
authProvider: RecoveryAuthProvider;
|
|
36
38
|
/**
|
|
37
39
|
* Obtains key-bound identifier tokens from an IdP.
|
|
38
40
|
*/
|
|
@@ -43,17 +45,9 @@ export type MfaRecoveryControllerOptions<EncryptionKey = DefaultEncryptionKey, E
|
|
|
43
45
|
*/
|
|
44
46
|
escrows: RecoveryEscrowProvider[];
|
|
45
47
|
/**
|
|
46
|
-
*
|
|
47
|
-
* mutation state with it. Pass the same instance given to KeyringController.
|
|
48
|
-
*/
|
|
49
|
-
encryptor: PendingOperationEncryptor<EncryptionKey, EncryptionResult>;
|
|
50
|
-
/**
|
|
51
|
-
* Returns the serialized key that encrypts `pendingOperation`, or `null` if
|
|
52
|
-
* none exists. The key must be importable by `encryptor` and kept in
|
|
53
|
-
* host-owned secret storage, independent of controller state and the vault.
|
|
54
|
-
* The controller never creates or persists it.
|
|
48
|
+
* Encrypts pending mutation state using wallet secure storage.
|
|
55
49
|
*/
|
|
56
|
-
|
|
50
|
+
pendingOperationEncryptor: PendingOperationEncryptor;
|
|
57
51
|
/**
|
|
58
52
|
* Clock used for AuthController token expiry checks. Unix seconds.
|
|
59
53
|
* Defaults to {@link unixNow}.
|
|
@@ -63,9 +57,9 @@ export type MfaRecoveryControllerOptions<EncryptionKey = DefaultEncryptionKey, E
|
|
|
63
57
|
/**
|
|
64
58
|
* Coordinates MFA recovery secret replication across independent escrows.
|
|
65
59
|
*/
|
|
66
|
-
export declare class MfaRecoveryController
|
|
60
|
+
export declare class MfaRecoveryController extends BaseController<typeof CONTROLLER_NAME, MfaRecoveryControllerState, MfaRecoveryControllerMessenger> {
|
|
67
61
|
#private;
|
|
68
|
-
constructor({ messenger, state, identifierAuthProvider, escrows,
|
|
62
|
+
constructor({ messenger, state, authProvider, identifierAuthProvider, escrows, pendingOperationEncryptor, now, }: MfaRecoveryControllerOptions);
|
|
69
63
|
/**
|
|
70
64
|
* Creates version 1 of a recovery record.
|
|
71
65
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MfaRecoveryController.d.ts","sourceRoot":"","sources":["../src/MfaRecoveryController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,2BAA2B,EAE5B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"MfaRecoveryController.d.ts","sourceRoot":"","sources":["../src/MfaRecoveryController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,2BAA2B,EAE5B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAiCrD,OAAO,KAAK,EAAE,kCAAkC,EAAE,MAA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,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB,CAAC;AAsBF;;GAEG;AACH,qBAAa,qBAAsB,SAAQ,cAAc,CACvD,OAAO,eAAe,EACtB,0BAA0B,EAC1B,8BAA8B,CAC/B;;IAaC,YAAY,EACV,SAAS,EACT,KAAK,EACL,YAAY,EACZ,sBAAsB,EACtB,OAAO,EACP,yBAAyB,EACzB,GAAa,GACd,EAAE,4BAA4B,EAgC9B;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;;;;;OAKG;IACG,sBAAsB,CAC1B,UAAU,EAAE,UAAU,GACrB,OAAO,CAAC,iBAAiB,CAAC,CAqB5B;IAED;;;;;;;;OAQG;IACG,iBAAiB,CACrB,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,eAAe,CAAC,CAiE1B;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;CAieF"}
|
|
@@ -37,15 +37,13 @@ export function getDefaultMfaRecoveryControllerState() {
|
|
|
37
37
|
* Coordinates MFA recovery secret replication across independent escrows.
|
|
38
38
|
*/
|
|
39
39
|
export class MfaRecoveryController extends BaseController {
|
|
40
|
+
#authProvider;
|
|
40
41
|
#identifierAuthProvider;
|
|
41
42
|
#escrows;
|
|
42
43
|
#encryptor;
|
|
43
|
-
#getPendingOperationKey;
|
|
44
44
|
#now;
|
|
45
|
-
// Shared by concurrent callers so the key is fetched and imported once.
|
|
46
|
-
#encryptionKey = null;
|
|
47
45
|
#lock = Promise.resolve();
|
|
48
|
-
constructor({ messenger, state, identifierAuthProvider, escrows,
|
|
46
|
+
constructor({ messenger, state, authProvider, identifierAuthProvider, escrows, pendingOperationEncryptor, now = unixNow, }) {
|
|
49
47
|
if (escrows.length === 0) {
|
|
50
48
|
throw new MfaRecoveryError('At least one escrow is required', 'empty_escrow_set');
|
|
51
49
|
}
|
|
@@ -62,10 +60,10 @@ export class MfaRecoveryController extends BaseController {
|
|
|
62
60
|
...state,
|
|
63
61
|
},
|
|
64
62
|
});
|
|
63
|
+
this.#authProvider = authProvider;
|
|
65
64
|
this.#identifierAuthProvider = identifierAuthProvider;
|
|
66
65
|
this.#escrows = [...escrows];
|
|
67
|
-
this.#encryptor =
|
|
68
|
-
this.#getPendingOperationKey = getPendingOperationKey;
|
|
66
|
+
this.#encryptor = pendingOperationEncryptor;
|
|
69
67
|
this.#now = now;
|
|
70
68
|
this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
|
|
71
69
|
}
|
|
@@ -178,7 +176,7 @@ export class MfaRecoveryController extends BaseController {
|
|
|
178
176
|
if (available.length === 0) {
|
|
179
177
|
throw new MfaRecoveryError('No escrow is available', 'no_available_escrow');
|
|
180
178
|
}
|
|
181
|
-
const { approval } = await this.#authorizeRecoveryRequest({
|
|
179
|
+
const { approval } = await this.#authProvider.authorizeRecoveryRequest({
|
|
182
180
|
requestHash,
|
|
183
181
|
audiences: available.map((escrow) => escrow.authAudience),
|
|
184
182
|
requireTwoFactor: true,
|
|
@@ -281,7 +279,7 @@ export class MfaRecoveryController extends BaseController {
|
|
|
281
279
|
}
|
|
282
280
|
// Read approvals need no 2FA.
|
|
283
281
|
async #authorizeAndReadIdentifiers(escrows) {
|
|
284
|
-
const { approval, identifiers } = await this.#authorizeRecoveryRequest({
|
|
282
|
+
const { approval, identifiers } = await this.#authProvider.authorizeRecoveryRequest({
|
|
285
283
|
requestHash: await hash({ operation: 'getIdentifiers' }),
|
|
286
284
|
audiences: escrows.map((escrow) => escrow.authAudience),
|
|
287
285
|
});
|
|
@@ -295,7 +293,7 @@ export class MfaRecoveryController extends BaseController {
|
|
|
295
293
|
throw new MfaRecoveryError('A pending mutation must be resumed or aborted first', 'pending_mutation');
|
|
296
294
|
}
|
|
297
295
|
await this.#assertEscrowsAvailable(this.#escrows);
|
|
298
|
-
const profileId = await this.
|
|
296
|
+
const profileId = await this.#authProvider.getAuthenticatedProfileId();
|
|
299
297
|
const audiences = this.#escrows.map((escrow) => escrow.id);
|
|
300
298
|
const currentVersion = this.#resolveCurrentRecoveryVersion(epoch);
|
|
301
299
|
const payloadHash = await hash(payload);
|
|
@@ -328,23 +326,13 @@ export class MfaRecoveryController extends BaseController {
|
|
|
328
326
|
});
|
|
329
327
|
}
|
|
330
328
|
async #authorizeMutation(mutation) {
|
|
331
|
-
const { approval, identifiers } = await this.#authorizeRecoveryRequest({
|
|
329
|
+
const { approval, identifiers } = await this.#authProvider.authorizeRecoveryRequest({
|
|
332
330
|
requestHash: mutation.requestHash,
|
|
333
331
|
audiences: this.#escrows.map((escrow) => escrow.authAudience),
|
|
334
332
|
requireTwoFactor: true,
|
|
335
333
|
});
|
|
336
334
|
return { authControllerToken: approval, approvedIdentifiers: identifiers };
|
|
337
335
|
}
|
|
338
|
-
async #authorizeRecoveryRequest({ requestHash, audiences, requireTwoFactor, }) {
|
|
339
|
-
const { approval, identifiers } = await this.messenger.call('AuthenticationController:requestMfaApproval', {
|
|
340
|
-
requestHash,
|
|
341
|
-
audiences,
|
|
342
|
-
requireVerification: requireTwoFactor === true,
|
|
343
|
-
includeIdentifiers: true,
|
|
344
|
-
reason: { operation: 'mfa_recovery' },
|
|
345
|
-
});
|
|
346
|
-
return { approval, identifiers: identifiers ?? [] };
|
|
347
|
-
}
|
|
348
336
|
async #repairPendingMutation() {
|
|
349
337
|
const pending = await this.#loadPending();
|
|
350
338
|
if (!pending) {
|
|
@@ -518,11 +506,13 @@ export class MfaRecoveryController extends BaseController {
|
|
|
518
506
|
return epoch;
|
|
519
507
|
}
|
|
520
508
|
async #getAvailableEscrows(escrows = this.#escrows) {
|
|
521
|
-
const flags = await Promise.
|
|
509
|
+
const flags = await Promise.allSettled(escrows.map(async (escrow) => ({
|
|
522
510
|
escrow,
|
|
523
511
|
available: await escrow.isAvailable(),
|
|
524
512
|
})));
|
|
525
|
-
return flags.flatMap((
|
|
513
|
+
return flags.flatMap((result) => isFulfilledResult(result) && result.value.available
|
|
514
|
+
? [result.value.escrow]
|
|
515
|
+
: []);
|
|
526
516
|
}
|
|
527
517
|
#assertValidIdentifiers(identifiers) {
|
|
528
518
|
for (const identifier of identifiers) {
|
|
@@ -558,43 +548,17 @@ export class MfaRecoveryController extends BaseController {
|
|
|
558
548
|
if (pendingOperation === null) {
|
|
559
549
|
return null;
|
|
560
550
|
}
|
|
561
|
-
const pending = await this.#
|
|
551
|
+
const pending = (await this.#encryptor.decrypt(pendingOperation));
|
|
562
552
|
await this.#assertPending(pending);
|
|
563
553
|
return pending;
|
|
564
554
|
}
|
|
565
555
|
async #persistPending(operation) {
|
|
566
556
|
await this.#assertPending(operation);
|
|
567
|
-
const encrypted = await this.#
|
|
557
|
+
const encrypted = await this.#encryptor.encrypt(operation);
|
|
568
558
|
this.update((state) => {
|
|
569
559
|
state.pendingOperation = encrypted;
|
|
570
560
|
});
|
|
571
561
|
}
|
|
572
|
-
async #getEncryptionKey() {
|
|
573
|
-
if (!this.#encryptionKey) {
|
|
574
|
-
const key = this.#loadEncryptionKey();
|
|
575
|
-
this.#encryptionKey = key;
|
|
576
|
-
key.catch(() => {
|
|
577
|
-
this.#encryptionKey = null;
|
|
578
|
-
});
|
|
579
|
-
}
|
|
580
|
-
return await this.#encryptionKey;
|
|
581
|
-
}
|
|
582
|
-
async #loadEncryptionKey() {
|
|
583
|
-
const serialized = await this.#getPendingOperationKey();
|
|
584
|
-
if (!serialized) {
|
|
585
|
-
throw new MfaRecoveryError('Pending operation encryption key is unavailable', 'missing_encryption_key');
|
|
586
|
-
}
|
|
587
|
-
return await this.#encryptor.importKey(serialized);
|
|
588
|
-
}
|
|
589
|
-
async #encryptPending(operation) {
|
|
590
|
-
const key = await this.#getEncryptionKey();
|
|
591
|
-
return JSON.stringify(await this.#encryptor.encryptWithKey(key, operation));
|
|
592
|
-
}
|
|
593
|
-
// Unvalidated; callers assert the result with #assertPending.
|
|
594
|
-
async #decryptPending(ciphertext) {
|
|
595
|
-
const key = await this.#getEncryptionKey();
|
|
596
|
-
return await this.#encryptor.decryptWithKey(key, JSON.parse(ciphertext));
|
|
597
|
-
}
|
|
598
562
|
async #assertPending(pending) {
|
|
599
563
|
await assertValidPendingOperation(pending, this.#escrows.map((escrow) => escrow.id));
|
|
600
564
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MfaRecoveryController.js","sourceRoot":"","sources":["../src/MfaRecoveryController.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAO3D,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAGvE,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,EA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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 { EncryptionResultConstraint } from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n AuthenticationControllerRefreshCanonicalProfileIdAction,\n AuthenticationControllerRequestMfaApprovalAction,\n} from '@metamask/profile-sync-controller/auth';\nimport { bytesToHex, hexToBytes, isHexAddress } from '@metamask/utils';\nimport type { Json } 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 requestKeyBoundIdentifierToken,\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 DefaultEncryptionKey,\n DefaultEncryptionResult,\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 RecoveryApproval,\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 =\n | AuthenticationControllerRefreshCanonicalProfileIdAction\n | AuthenticationControllerRequestMfaApprovalAction;\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 EncryptionKey = DefaultEncryptionKey,\n EncryptionResult extends EncryptionResultConstraint<unknown> =\n DefaultEncryptionResult,\n> = {\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 * 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 * Imports the key returned by `getPendingOperationKey` and encrypts pending\n * mutation state with it. Pass the same instance given to KeyringController.\n */\n encryptor: PendingOperationEncryptor<EncryptionKey, EncryptionResult>;\n\n /**\n * Returns the serialized key that encrypts `pendingOperation`, or `null` if\n * none exists. The key must be importable by `encryptor` and kept in\n * host-owned secret storage, independent of controller state and the vault.\n * The controller never creates or persists it.\n */\n getPendingOperationKey: () => Promise<string | null>;\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<\n EncryptionKey = DefaultEncryptionKey,\n EncryptionResult extends EncryptionResultConstraint<unknown> =\n DefaultEncryptionResult,\n> extends BaseController<\n typeof CONTROLLER_NAME,\n MfaRecoveryControllerState,\n MfaRecoveryControllerMessenger\n> {\n readonly #identifierAuthProvider: RecoveryIdentifierAuthProvider;\n\n readonly #escrows: RecoveryEscrowProvider[];\n\n readonly #encryptor: PendingOperationEncryptor<\n EncryptionKey,\n EncryptionResult\n >;\n\n readonly #getPendingOperationKey: () => Promise<string | null>;\n\n readonly #now: () => number;\n\n // Shared by concurrent callers so the key is fetched and imported once.\n #encryptionKey: Promise<EncryptionKey> | null = null;\n\n #lock: Promise<void> = Promise.resolve();\n\n constructor({\n messenger,\n state,\n identifierAuthProvider,\n escrows,\n encryptor,\n getPendingOperationKey,\n now = unixNow,\n }: MfaRecoveryControllerOptions<EncryptionKey, EncryptionResult>) {\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.#identifierAuthProvider = identifierAuthProvider;\n this.#escrows = [...escrows];\n this.#encryptor = encryptor;\n this.#getPendingOperationKey = getPendingOperationKey;\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 for a subsequent recovery-secret read.\n *\n * @param identifier - Identifier to authenticate.\n * @returns Ephemeral session data required by {@link getRecoverySecret}.\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 credential = await requestKeyBoundIdentifierToken({\n identifier,\n requestHash,\n identifierAuthProvider: this.#identifierAuthProvider,\n });\n return {\n ...credential,\n requestId,\n ephemeralPrivateKey: ephemeral.privateKey,\n pkE,\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.#authorizeRecoveryRequest({\n requestHash,\n audiences: available.map((escrow) => escrow.authAudience),\n requireTwoFactor: true,\n });\n const authorizedEscrows = await authorizeEscrowsWithToken({\n escrows: available,\n credentials: [session],\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 } = await this.#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.messenger.call(\n 'AuthenticationController:refreshCanonicalProfileId',\n );\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 } = await this.#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 #authorizeRecoveryRequest({\n requestHash,\n audiences,\n requireTwoFactor,\n }: {\n requestHash: string;\n audiences: string[];\n requireTwoFactor?: boolean;\n }): Promise<RecoveryApproval> {\n const { approval, identifiers } = await this.messenger.call(\n 'AuthenticationController:requestMfaApproval',\n {\n requestHash,\n audiences,\n requireVerification: requireTwoFactor === true,\n includeIdentifiers: true,\n reason: { operation: 'mfa_recovery' },\n },\n );\n return { approval, identifiers: 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 credentials.push(\n await requestKeyBoundIdentifierToken({\n identifier,\n requestHash: writing.mutation.requestHash,\n identifierAuthProvider: this.#identifierAuthProvider,\n }),\n );\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.all(\n escrows.map(async (escrow) => ({\n escrow,\n available: await escrow.isAvailable(),\n })),\n );\n return flags.flatMap(({ escrow, available }) =>\n available ? [escrow] : [],\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.#decryptPending(pendingOperation);\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.#encryptPending(operation);\n this.update((state) => {\n state.pendingOperation = encrypted;\n });\n }\n\n async #getEncryptionKey(): Promise<EncryptionKey> {\n if (!this.#encryptionKey) {\n const key = this.#loadEncryptionKey();\n this.#encryptionKey = key;\n key.catch(() => {\n this.#encryptionKey = null;\n });\n }\n return await this.#encryptionKey;\n }\n\n async #loadEncryptionKey(): Promise<EncryptionKey> {\n const serialized = await this.#getPendingOperationKey();\n if (!serialized) {\n throw new MfaRecoveryError(\n 'Pending operation encryption key is unavailable',\n 'missing_encryption_key',\n );\n }\n return await this.#encryptor.importKey(serialized);\n }\n\n async #encryptPending(operation: PendingOperation): Promise<string> {\n const key = await this.#getEncryptionKey();\n return JSON.stringify(\n await this.#encryptor.encryptWithKey(key, operation as Json),\n );\n }\n\n // Unvalidated; callers assert the result with #assertPending.\n async #decryptPending(ciphertext: string): Promise<unknown> {\n const key = await this.#getEncryptionKey();\n return await this.#encryptor.decryptWithKey(\n key,\n JSON.parse(ciphertext) as EncryptionResult,\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,aAA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C,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 requestKeyBoundIdentifierToken,\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 for a subsequent recovery-secret read.\n *\n * @param identifier - Identifier to authenticate.\n * @returns Ephemeral session data required by {@link getRecoverySecret}.\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 credential = await requestKeyBoundIdentifierToken({\n identifier,\n requestHash,\n identifierAuthProvider: this.#identifierAuthProvider,\n });\n return {\n ...credential,\n requestId,\n ephemeralPrivateKey: ephemeral.privateKey,\n pkE,\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: [session],\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 credentials.push(\n await requestKeyBoundIdentifierToken({\n identifier,\n requestHash: writing.mutation.requestHash,\n identifierAuthProvider: this.#identifierAuthProvider,\n }),\n );\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"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Messenger } from '@metamask/messenger';
|
|
2
|
+
import type { AuthenticationControllerRefreshCanonicalProfileIdAction, AuthenticationControllerRequestMfaApprovalAction } from '@metamask/profile-sync-controller/auth';
|
|
3
|
+
import type { RecoveryApproval, RecoveryAuthProvider } from './types.js';
|
|
4
|
+
export type AuthApiRecoveryAuthProviderMessenger = Messenger<'AuthApiRecoveryAuthProvider', AuthenticationControllerRefreshCanonicalProfileIdAction | AuthenticationControllerRequestMfaApprovalAction>;
|
|
5
|
+
export type AuthApiRecoveryAuthProviderOptions = {
|
|
6
|
+
messenger: AuthApiRecoveryAuthProviderMessenger;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Requests Auth API approvals through `AuthenticationController`. A missing or
|
|
10
|
+
* stale MFA verification rejects with its `StepUpRequiredError`.
|
|
11
|
+
*/
|
|
12
|
+
export declare class AuthApiRecoveryAuthProvider implements RecoveryAuthProvider {
|
|
13
|
+
#private;
|
|
14
|
+
/**
|
|
15
|
+
* @param options - Provider options.
|
|
16
|
+
* @param options.messenger - Messenger with the AuthenticationController
|
|
17
|
+
* actions.
|
|
18
|
+
*/
|
|
19
|
+
constructor({ messenger }: AuthApiRecoveryAuthProviderOptions);
|
|
20
|
+
/**
|
|
21
|
+
* Resolves the canonical profile id from the server, since the cached one
|
|
22
|
+
* can be stale after pairing on another device.
|
|
23
|
+
*
|
|
24
|
+
* @returns The canonical profile id, which approvals use as `sub`.
|
|
25
|
+
*/
|
|
26
|
+
getAuthenticatedProfileId(): Promise<string>;
|
|
27
|
+
/**
|
|
28
|
+
* @param params - Request hash, audiences, and MFA requirement.
|
|
29
|
+
* @returns The approval and current recovery identifiers.
|
|
30
|
+
*/
|
|
31
|
+
authorizeRecoveryRequest(params: Parameters<RecoveryAuthProvider['authorizeRecoveryRequest']>[0]): Promise<RecoveryApproval>;
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=auth-api-recovery-provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-api-recovery-provider.d.ts","sourceRoot":"","sources":["../src/auth-api-recovery-provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EACV,uDAAuD,EACvD,gDAAgD,EACjD,MAAM,wCAAwC,CAAC;AAEhD,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAEzE,MAAM,MAAM,oCAAoC,GAAG,SAAS,CAC1D,6BAA6B,EAC3B,uDAAuD,GACvD,gDAAgD,CACnD,CAAC;AAEF,MAAM,MAAM,kCAAkC,GAAG;IAC/C,SAAS,EAAE,oCAAoC,CAAC;CACjD,CAAC;AAEF;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,oBAAoB;;IAGtE;;;;OAIG;IACH,YAAY,EAAE,SAAS,EAAE,EAAE,kCAAkC,EAE5D;IAED;;;;;OAKG;IACG,yBAAyB,IAAI,OAAO,CAAC,MAAM,CAAC,CAIjD;IAED;;;OAGG;IACG,wBAAwB,CAC5B,MAAM,EAAE,UAAU,CAAC,oBAAoB,CAAC,0BAA0B,CAAC,CAAC,CAAC,CAAC,CAAC,GACtE,OAAO,CAAC,gBAAgB,CAAC,CAW3B;CACF"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Requests Auth API approvals through `AuthenticationController`. A missing or
|
|
3
|
+
* stale MFA verification rejects with its `StepUpRequiredError`.
|
|
4
|
+
*/
|
|
5
|
+
export class AuthApiRecoveryAuthProvider {
|
|
6
|
+
#messenger;
|
|
7
|
+
/**
|
|
8
|
+
* @param options - Provider options.
|
|
9
|
+
* @param options.messenger - Messenger with the AuthenticationController
|
|
10
|
+
* actions.
|
|
11
|
+
*/
|
|
12
|
+
constructor({ messenger }) {
|
|
13
|
+
this.#messenger = messenger;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Resolves the canonical profile id from the server, since the cached one
|
|
17
|
+
* can be stale after pairing on another device.
|
|
18
|
+
*
|
|
19
|
+
* @returns The canonical profile id, which approvals use as `sub`.
|
|
20
|
+
*/
|
|
21
|
+
async getAuthenticatedProfileId() {
|
|
22
|
+
return await this.#messenger.call('AuthenticationController:refreshCanonicalProfileId');
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* @param params - Request hash, audiences, and MFA requirement.
|
|
26
|
+
* @returns The approval and current recovery identifiers.
|
|
27
|
+
*/
|
|
28
|
+
async authorizeRecoveryRequest(params) {
|
|
29
|
+
const { approval, identifiers = [] } = await this.#messenger.call('AuthenticationController:requestMfaApproval', {
|
|
30
|
+
requestHash: params.requestHash,
|
|
31
|
+
audiences: params.audiences,
|
|
32
|
+
requireVerification: params.requireTwoFactor === true,
|
|
33
|
+
reason: { operation: 'mfa_recovery' },
|
|
34
|
+
});
|
|
35
|
+
return { approval, identifiers };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=auth-api-recovery-provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-api-recovery-provider.js","sourceRoot":"","sources":["../src/auth-api-recovery-provider.ts"],"names":[],"mappings":"AAkBA;;;GAGG;AACH,MAAM,OAAO,2BAA2B;IAC7B,UAAU,CAAuC;IAE1D;;;;OAIG;IACH,YAAY,EAAE,SAAS,EAAsC;QAC3D,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9B,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,yBAAyB;QAC7B,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAC/B,oDAAoD,CACrD,CAAC;IACJ,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,wBAAwB,CAC5B,MAAuE;QAEvE,MAAM,EAAE,QAAQ,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAC/D,6CAA6C,EAC7C;YACE,WAAW,EAAE,MAAM,CAAC,WAAW;YAC/B,SAAS,EAAE,MAAM,CAAC,SAAS;YAC3B,mBAAmB,EAAE,MAAM,CAAC,gBAAgB,KAAK,IAAI;YACrD,MAAM,EAAE,EAAE,SAAS,EAAE,cAAc,EAAE;SACtC,CACF,CAAC;QACF,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;IACnC,CAAC;CACF","sourcesContent":["import type { Messenger } from '@metamask/messenger';\nimport type {\n AuthenticationControllerRefreshCanonicalProfileIdAction,\n AuthenticationControllerRequestMfaApprovalAction,\n} from '@metamask/profile-sync-controller/auth';\n\nimport type { RecoveryApproval, RecoveryAuthProvider } from './types.js';\n\nexport type AuthApiRecoveryAuthProviderMessenger = Messenger<\n 'AuthApiRecoveryAuthProvider',\n | AuthenticationControllerRefreshCanonicalProfileIdAction\n | AuthenticationControllerRequestMfaApprovalAction\n>;\n\nexport type AuthApiRecoveryAuthProviderOptions = {\n messenger: AuthApiRecoveryAuthProviderMessenger;\n};\n\n/**\n * Requests Auth API approvals through `AuthenticationController`. A missing or\n * stale MFA verification rejects with its `StepUpRequiredError`.\n */\nexport class AuthApiRecoveryAuthProvider implements RecoveryAuthProvider {\n readonly #messenger: AuthApiRecoveryAuthProviderMessenger;\n\n /**\n * @param options - Provider options.\n * @param options.messenger - Messenger with the AuthenticationController\n * actions.\n */\n constructor({ messenger }: AuthApiRecoveryAuthProviderOptions) {\n this.#messenger = messenger;\n }\n\n /**\n * Resolves the canonical profile id from the server, since the cached one\n * can be stale after pairing on another device.\n *\n * @returns The canonical profile id, which approvals use as `sub`.\n */\n async getAuthenticatedProfileId(): Promise<string> {\n return await this.#messenger.call(\n 'AuthenticationController:refreshCanonicalProfileId',\n );\n }\n\n /**\n * @param params - Request hash, audiences, and MFA requirement.\n * @returns The approval and current recovery identifiers.\n */\n async authorizeRecoveryRequest(\n params: Parameters<RecoveryAuthProvider['authorizeRecoveryRequest']>[0],\n ): Promise<RecoveryApproval> {\n const { approval, identifiers = [] } = await this.#messenger.call(\n 'AuthenticationController:requestMfaApproval',\n {\n requestHash: params.requestHash,\n audiences: params.audiences,\n requireVerification: params.requireTwoFactor === true,\n reason: { operation: 'mfa_recovery' },\n },\n );\n return { approval, identifiers };\n }\n}\n"]}
|
|
@@ -12,7 +12,7 @@ export type CubistEscrowProviderOptions = {
|
|
|
12
12
|
/**
|
|
13
13
|
* Returns the authenticated CubeSigner client used to invoke the escrow C2F.
|
|
14
14
|
* Called for every command, so the caller owns session caching and refresh.
|
|
15
|
-
*
|
|
15
|
+
* Commands propagate its errors unchanged; `isAvailable` resolves `false`.
|
|
16
16
|
*/
|
|
17
17
|
getClient: () => Promise<CubeSignerClient>;
|
|
18
18
|
/**
|
|
@@ -47,9 +47,6 @@ export declare class CubistEscrowProvider implements RecoveryEscrowProvider {
|
|
|
47
47
|
*/
|
|
48
48
|
constructor(options: CubistEscrowProviderOptions);
|
|
49
49
|
/**
|
|
50
|
-
* Errors from `getClient` and expired sessions are rethrown so a missing or
|
|
51
|
-
* expired session is not reported as an unavailable escrow.
|
|
52
|
-
*
|
|
53
50
|
* @returns Whether a ping of the escrow C2F is allowed and reports ok.
|
|
54
51
|
*/
|
|
55
52
|
isAvailable(): Promise<boolean>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cubist-escrow-provider.d.ts","sourceRoot":"","sources":["../../src/escrow-providers/cubist-escrow-provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAEhB,OAAO,EACR,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"cubist-escrow-provider.d.ts","sourceRoot":"","sources":["../../src/escrow-providers/cubist-escrow-provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAEhB,OAAO,EACR,MAAM,6BAA6B,CAAC;AAyBrC,OAAO,KAAK,EACV,mBAAmB,EACnB,sBAAsB,EACtB,yBAAyB,EACzB,UAAU,EACV,uBAAuB,EACvB,QAAQ,EACR,eAAe,EACf,eAAe,EACf,YAAY,EACZ,sBAAsB,EACvB,MAAM,aAAa,CAAC;AAMrB;;;;;;;GAOG;AACH,MAAM,MAAM,2BAA2B,GAAG;IACxC;;;;OAIG;IACH,SAAS,EAAE,MAAM,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAC3C;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;OAEG;IACH,aAAa,EAAE,UAAU,CAAC;IAC1B;;OAEG;IACH,gBAAgB,EAAE,UAAU,CAAC;CAC9B,CAAC;AAEF,qBAAa,oBAAqB,YAAW,sBAAsB;;IACjE,QAAQ,CAAC,EAAE,YAAa;IAExB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAE9B,QAAQ,CAAC,aAAa,EAAE,UAAU,CAAC;IAUnC;;;OAGG;IACH,YAAY,OAAO,EAAE,2BAA2B,EAO/C;IAED;;OAEG;IACG,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC,CAOpC;IAED;;;OAGG;IACG,iBAAiB,CACrB,mBAAmB,EAAE,mBAAmB,GACvC,OAAO,CAAC,YAAY,CAAC,CAMvB;IAED;;;OAGG;IACG,cAAc,CAClB,mBAAmB,EAAE,mBAAmB,GACvC,OAAO,CAAC,sBAAsB,CAAC,CAMjC;IAED;;;;;;OAMG;IACG,SAAS,CACb,mBAAmB,EAAE,mBAAmB,EACxC,aAAa,EAAE,uBAAuB,EACtC,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,UAAU,GACd,OAAO,CAAC,yBAAyB,CAAC,CAWpC;IAED;;;;;;;;OAQG;IACG,aAAa,CACjB,QAAQ,EAAE,QAAQ,EAClB,mBAAmB,EAAE,mBAAmB,EACxC,wBAAwB,EAAE,uBAAuB,EAAE,EACnD,OAAO,EAAE,eAAe,EACxB,mBAAmB,EAAE,UAAU,EAAE,GAChC,OAAO,CAAC,eAAe,CAAC,CAa1B;IAED;;;;;;;OAOG;IACG,aAAa,CACjB,OAAO,EAAE,eAAe,EACxB,QAAQ,EAAE,QAAQ,EAClB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,OAAO,CAAC,CAsBlB;CA2CF"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { ErrResponse } from '@cubist-labs/cubesigner-sdk';
|
|
2
1
|
import { array, integer, is, literal, min, string, type, unknown, } from '@metamask/superstruct';
|
|
3
2
|
import { bytesToHex, bytesToString, hexToBytes, isStrictHexString, } from '@metamask/utils';
|
|
4
3
|
import { hashMutationReceipt, receiptKeyId, verifySignature, } from '../crypto.js';
|
|
@@ -28,22 +27,14 @@ export class CubistEscrowProvider {
|
|
|
28
27
|
this.#version = options.version ?? DEFAULT_VERSION;
|
|
29
28
|
}
|
|
30
29
|
/**
|
|
31
|
-
* Errors from `getClient` and expired sessions are rethrown so a missing or
|
|
32
|
-
* expired session is not reported as an unavailable escrow.
|
|
33
|
-
*
|
|
34
30
|
* @returns Whether a ping of the escrow C2F is allowed and reports ok.
|
|
35
31
|
*/
|
|
36
32
|
async isAvailable() {
|
|
37
|
-
const client = await this.#getClient();
|
|
38
33
|
try {
|
|
39
|
-
await this.#
|
|
34
|
+
await this.#invoke('ping', {}, parsePing);
|
|
40
35
|
return true;
|
|
41
36
|
}
|
|
42
|
-
catch
|
|
43
|
-
if (error instanceof MfaRecoveryError &&
|
|
44
|
-
error.code === 'session_expired') {
|
|
45
|
-
throw error;
|
|
46
|
-
}
|
|
37
|
+
catch {
|
|
47
38
|
return false;
|
|
48
39
|
}
|
|
49
40
|
}
|
|
@@ -120,19 +111,12 @@ export class CubistEscrowProvider {
|
|
|
120
111
|
}));
|
|
121
112
|
}
|
|
122
113
|
async #invoke(cmd, body, parse, denyIsRejection = false) {
|
|
123
|
-
|
|
124
|
-
}
|
|
125
|
-
async #invokeWith(client, cmd, body, parse, denyIsRejection = false) {
|
|
114
|
+
const client = await this.#getClient();
|
|
126
115
|
let invocation;
|
|
127
116
|
try {
|
|
128
117
|
invocation = await client.apiClient.policyInvoke(this.#functionId, this.#version, { request: toWire({ cmd, ...body }) });
|
|
129
118
|
}
|
|
130
119
|
catch (error) {
|
|
131
|
-
if (error instanceof ErrResponse &&
|
|
132
|
-
(error.isSessionExpiredError() ||
|
|
133
|
-
error.operation === 'signerSessionRefresh')) {
|
|
134
|
-
throw new MfaRecoveryError(error.message, 'session_expired');
|
|
135
|
-
}
|
|
136
120
|
throw new MfaRecoveryError(error instanceof Error ? error.message : 'Escrow request failed', 'escrow_request_failed');
|
|
137
121
|
}
|
|
138
122
|
const policy = invocation.response;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cubist-escrow-provider.js","sourceRoot":"","sources":["../../src/escrow-providers/cubist-escrow-provider.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EACL,KAAK,EACL,OAAO,EACP,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AAc,CAAC,UAAU,CAAC;SACxD;QACD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,KAAK,CAAC,SAAS;KAC3B,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,IAAI,CAAC,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC;QAC9B,MAAM,IAAI,gBAAgB,CACxB,0BAA0B,EAC1B,yBAAyB,CAC1B,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type {\n CubeSignerClient,\n InvokePolicyResponse,\n Version,\n} from '@cubist-labs/cubesigner-sdk';\nimport { ErrResponse } from '@cubist-labs/cubesigner-sdk';\nimport {\n array,\n integer,\n is,\n literal,\n min,\n string,\n type,\n unknown,\n} from '@metamask/superstruct';\nimport {\n bytesToHex,\n bytesToString,\n hexToBytes,\n isStrictHexString,\n} from '@metamask/utils';\n\nimport {\n hashMutationReceipt,\n receiptKeyId,\n verifySignature,\n} from '../crypto.js';\nimport { MfaRecoveryError, MutationRejectedError } from '../errors.js';\nimport { isMutationReceipt } from '../escrow-utils.js';\nimport type {\n AuthControllerToken,\n GetIdentifiersResponse,\n GetRecoverySecretResponse,\n Identifier,\n IdentifierAuthorization,\n Mutation,\n MutationPayload,\n MutationReceipt,\n PoPChallenge,\n RecoveryEscrowProvider,\n} from '../types.js';\n\nconst ESCROW_ID = 'cubist';\nconst DEFAULT_FUNCTION_ID = 'cubist_secret_escrow';\nconst DEFAULT_VERSION: Version = 'latest';\n\n/**\n * CubeSigner C2F client for the Cubist recovery escrow.\n *\n * Commands are sent with `policyInvoke` as `{ cmd, ...fields }` on\n * `cubist_secret_escrow`.\n * Escrow JSON is read from C2F stdout. Receipt signatures are checked locally\n * with the pinned receipt public key.\n */\nexport type CubistEscrowProviderOptions = {\n /**\n * Returns the authenticated CubeSigner client used to invoke the escrow C2F.\n * Called for every command, so the caller owns session caching and refresh.\n * Its errors are propagated unchanged.\n */\n getClient: () => Promise<CubeSignerClient>;\n /**\n * Must match the escrow's AUTH_CONTROLLER_AUDIENCE configuration.\n */\n authAudience: string;\n /**\n * C2F name or named-policy id. Defaults to `cubist_secret_escrow`.\n */\n functionId?: string;\n /**\n * C2F version to invoke. Defaults to `latest`.\n */\n version?: Version;\n /**\n * Raw 32-byte X25519 public key of the escrow wrap key.\n */\n wrapPublicKey: Uint8Array;\n /**\n * Raw 32-byte Ed25519 public key of the escrow receipt key.\n */\n receiptPublicKey: Uint8Array;\n};\n\nexport class CubistEscrowProvider implements RecoveryEscrowProvider {\n readonly id = ESCROW_ID;\n\n readonly authAudience: string;\n\n readonly wrapPublicKey: Uint8Array;\n\n readonly #receiptPublicKey: Uint8Array;\n\n readonly #getClient: () => Promise<CubeSignerClient>;\n\n readonly #functionId: string;\n\n readonly #version: Version;\n\n /**\n * @param options - CubeSigner client getter, pinned keys, and optional C2F\n * id/version.\n */\n constructor(options: CubistEscrowProviderOptions) {\n this.authAudience = options.authAudience;\n this.wrapPublicKey = options.wrapPublicKey;\n this.#receiptPublicKey = options.receiptPublicKey;\n this.#getClient = options.getClient;\n this.#functionId = options.functionId ?? DEFAULT_FUNCTION_ID;\n this.#version = options.version ?? DEFAULT_VERSION;\n }\n\n /**\n * Errors from `getClient` and expired sessions are rethrown so a missing or\n * expired session is not reported as an unavailable escrow.\n *\n * @returns Whether a ping of the escrow C2F is allowed and reports ok.\n */\n async isAvailable(): Promise<boolean> {\n const client = await this.#getClient();\n try {\n await this.#invokeWith(client, 'ping', {}, parsePing);\n return true;\n } catch (error) {\n if (\n error instanceof MfaRecoveryError &&\n error.code === 'session_expired'\n ) {\n throw error;\n }\n return false;\n }\n }\n\n /**\n * @param authControllerToken - Approval for the profile the challenge is for.\n * @returns A proof-of-possession challenge for this escrow.\n */\n async generateChallenge(\n authControllerToken: AuthControllerToken,\n ): Promise<PoPChallenge> {\n return await this.#invoke(\n 'generateChallenge',\n { authControllerToken },\n parseChallenge,\n );\n }\n\n /**\n * @param authControllerToken - Approval for the profile to read.\n * @returns The enrolled identifiers and record version.\n */\n async getIdentifiers(\n authControllerToken: AuthControllerToken,\n ): Promise<GetIdentifiersResponse> {\n return await this.#invoke(\n 'getIdentifiers',\n { authControllerToken },\n parseIdentifiers,\n );\n }\n\n /**\n * @param authControllerToken - Request-bound approval for this read.\n * @param authorization - Identifier proof for this read.\n * @param requestId - Client request id bound into the read hash.\n * @param pkE - Ephemeral wrap public key for the response.\n * @returns The wrapped recovery secret and its version.\n */\n async getSecret(\n authControllerToken: AuthControllerToken,\n authorization: IdentifierAuthorization,\n requestId: string,\n pkE: Uint8Array,\n ): Promise<GetRecoverySecretResponse> {\n return await this.#invoke(\n 'getSecret',\n {\n identifierAuthorization: authorization,\n requestId,\n pkE,\n authControllerToken,\n },\n parseGetSecretResponse,\n );\n }\n\n /**\n * @param mutation - Mutation to apply.\n * @param authControllerToken - Request-bound AuthController token.\n * @param identifierAuthorizations - Identifier proofs sharing one challenge.\n * @param payload - Per-escrow mutation payload.\n * @param approvedIdentifiers - The approval's identifiers, which non-SIWE\n * payload identifiers must be drawn from.\n * @returns The escrow's mutation receipt.\n */\n async applyMutation(\n mutation: Mutation,\n authControllerToken: AuthControllerToken,\n identifierAuthorizations: IdentifierAuthorization[],\n payload: MutationPayload,\n approvedIdentifiers: Identifier[],\n ): Promise<MutationReceipt> {\n return await this.#invoke(\n 'applyMutation',\n {\n mutation,\n authControllerToken,\n identifierAuthorizations,\n payload,\n approvedIdentifiers,\n },\n parseReceipt,\n true, // a policy Deny did not apply the mutation\n );\n }\n\n /**\n * Verifies a receipt with the pinned receipt public key.\n *\n * @param receipt - Receipt returned by the escrow.\n * @param mutation - Mutation the receipt must acknowledge.\n * @param expectedEscrowId - Escrow identity expected by the caller.\n * @returns Whether the receipt is valid for this escrow.\n */\n async verifyReceipt(\n receipt: MutationReceipt,\n mutation: Mutation,\n expectedEscrowId: string,\n ): Promise<boolean> {\n if (\n receipt.mutationId !== mutation.id ||\n receipt.requestHash !== mutation.requestHash ||\n receipt.escrowId !== expectedEscrowId ||\n expectedEscrowId !== this.id ||\n receipt.version !== mutation.newVersion ||\n receipt.receiptKeyId !== (await receiptKeyId(this.#receiptPublicKey))\n ) {\n return false;\n }\n return await verifySignature(\n this.#receiptPublicKey,\n receipt.signature,\n await hashMutationReceipt({\n escrowId: receipt.escrowId,\n mutationId: receipt.mutationId,\n receiptKeyId: receipt.receiptKeyId,\n requestHash: receipt.requestHash,\n version: receipt.version,\n }),\n );\n }\n\n async #invoke<Result>(\n cmd: string,\n body: Record<string, unknown>,\n parse: (value: unknown) => Result,\n denyIsRejection = false,\n ): Promise<Result> {\n return await this.#invokeWith(\n await this.#getClient(),\n cmd,\n body,\n parse,\n denyIsRejection,\n );\n }\n\n async #invokeWith<Result>(\n client: CubeSignerClient,\n cmd: string,\n body: Record<string, unknown>,\n parse: (value: unknown) => Result,\n denyIsRejection = false,\n ): Promise<Result> {\n let invocation: InvokePolicyResponse;\n try {\n invocation = await client.apiClient.policyInvoke(\n this.#functionId,\n this.#version,\n { request: toWire({ cmd, ...body }) },\n );\n } catch (error) {\n if (\n error instanceof ErrResponse &&\n (error.isSessionExpiredError() ||\n error.operation === 'signerSessionRefresh')\n ) {\n throw new MfaRecoveryError(error.message, 'session_expired');\n }\n throw new MfaRecoveryError(\n error instanceof Error ? error.message : 'Escrow request failed',\n 'escrow_request_failed',\n );\n }\n const policy = invocation.response;\n if (policy.response !== 'Allow') {\n if (denyIsRejection && policy.response === 'Deny') {\n throw new MutationRejectedError(policy.reason);\n }\n throw new MfaRecoveryError(\n policy.response === 'Deny' ? policy.reason : policy.error,\n 'escrow_request_failed',\n );\n }\n let json: unknown;\n try {\n json = JSON.parse(bytesToString(hexToBytes(invocation.stdout)));\n } catch {\n throw new MfaRecoveryError(\n 'Escrow response was not JSON',\n 'escrow_response_invalid',\n );\n }\n return parse(json);\n }\n}\n\n// `type()` is non-strict, so unknown fields are ignored. The explicit field\n// mapping below still strips them from the returned value.\nconst PingStruct = type({ ok: literal(true) });\n\nconst ChallengeStruct = type({\n id: string(),\n escrowId: literal(ESCROW_ID),\n expiresAt: integer(),\n});\n\nconst IdentifiersStruct = type({\n identifiers: array(\n type({\n type: string(),\n namespace: string(),\n value: string(),\n verifier: unknown(),\n }),\n ),\n version: min(integer(), 0),\n});\n\nconst GetSecretResponseStruct = type({\n recoverySecret: type({ ciphertext: string() }),\n version: min(integer(), 0),\n lastMutationId: string(),\n wrapKeyId: string(),\n});\n\nfunction parsePing(value: unknown): void {\n if (!is(value, PingStruct)) {\n throw new MfaRecoveryError(\n 'Invalid ping response',\n 'escrow_response_invalid',\n );\n }\n}\n\nfunction parseChallenge(value: unknown): PoPChallenge {\n if (!is(value, ChallengeStruct)) {\n throw new MfaRecoveryError(\n 'Invalid PoP challenge',\n 'escrow_response_invalid',\n );\n }\n return {\n id: value.id,\n escrowId: value.escrowId,\n expiresAt: value.expiresAt,\n };\n}\n\nfunction parseIdentifiers(value: unknown): GetIdentifiersResponse {\n if (!is(value, IdentifiersStruct)) {\n throw new MfaRecoveryError(\n 'Invalid identifiers response',\n 'escrow_response_invalid',\n );\n }\n return {\n identifiers: value.identifiers.map((identifier) => ({\n type: identifier.type,\n namespace: identifier.namespace,\n value: identifier.value,\n ...(identifier.verifier === undefined\n ? {}\n : { verifier: identifier.verifier }),\n })),\n version: value.version,\n };\n}\n\n/**\n * Encodes a request for the escrow wire: every byte field becomes a 0x-prefixed\n * hex string. Typed arrays have no `toJSON`, so the replacer sees them directly.\n *\n * @param value - Request body.\n * @returns JSON-compatible request body.\n */\nfunction toWire(value: Record<string, unknown>): Record<string, unknown> {\n return JSON.parse(\n JSON.stringify(value, (_key, node: unknown) =>\n node instanceof Uint8Array ? bytesToHex(node) : node,\n ),\n ) as Record<string, unknown>;\n}\n\nfunction parseGetSecretResponse(value: unknown): GetRecoverySecretResponse {\n if (\n !is(value, GetSecretResponseStruct) ||\n !isStrictHexString(value.recoverySecret.ciphertext)\n ) {\n throw new MfaRecoveryError(\n 'Invalid recovery secret response',\n 'escrow_response_invalid',\n );\n }\n return {\n recoverySecret: {\n ciphertext: hexToBytes(value.recoverySecret.ciphertext),\n },\n version: value.version,\n lastMutationId: value.lastMutationId,\n wrapKeyId: value.wrapKeyId,\n };\n}\n\nfunction parseReceipt(value: unknown): MutationReceipt {\n if (!isMutationReceipt(value)) {\n throw new MfaRecoveryError(\n 'Invalid mutation receipt',\n 'escrow_response_invalid',\n );\n }\n return value;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cubist-escrow-provider.js","sourceRoot":"","sources":["../../src/escrow-providers/cubist-escrow-provider.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,KAAK,EACL,OAAO,EACP,EAAE,EACF,OAAO,EACP,GAAG,EACH,MAAM,EACN,IAAI,EACJ,OAAO,GACR,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,UAAU,EACV,aAAa,EACb,UAAU,EACV,iBAAiB,GAClB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACL,mBAAmB,EACnB,YAAY,EACZ,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAcvD,MAAM,SAAS,GAAG,QAAQ,CAAC;AAC3B,MAAM,mBAAmB,GAAG,sBAAsB,CAAC;AACnD,MAAM,eAAe,GAAY,QAAQ,CAAC;AAuC1C,MAAM,OAAO,oBAAoB;IACtB,EAAE,GAAG,SAAS,CAAC;IAEf,YAAY,CAAS;IAErB,aAAa,CAAa;IAE1B,iBAAiB,CAAa;IAE9B,UAAU,CAAkC;IAE5C,WAAW,CAAS;IAEpB,QAAQ,CAAU;IAE3B;;;OAGG;IACH,YAAY,OAAoC;QAC9C,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;QACzC,IAAI,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AS;KAC3B,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,IAAI,CAAC,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC;QAC9B,MAAM,IAAI,gBAAgB,CACxB,0BAA0B,EAC1B,yBAAyB,CAC1B,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type {\n CubeSignerClient,\n InvokePolicyResponse,\n Version,\n} from '@cubist-labs/cubesigner-sdk';\nimport {\n array,\n integer,\n is,\n literal,\n min,\n string,\n type,\n unknown,\n} from '@metamask/superstruct';\nimport {\n bytesToHex,\n bytesToString,\n hexToBytes,\n isStrictHexString,\n} from '@metamask/utils';\n\nimport {\n hashMutationReceipt,\n receiptKeyId,\n verifySignature,\n} from '../crypto.js';\nimport { MfaRecoveryError, MutationRejectedError } from '../errors.js';\nimport { isMutationReceipt } from '../escrow-utils.js';\nimport type {\n AuthControllerToken,\n GetIdentifiersResponse,\n GetRecoverySecretResponse,\n Identifier,\n IdentifierAuthorization,\n Mutation,\n MutationPayload,\n MutationReceipt,\n PoPChallenge,\n RecoveryEscrowProvider,\n} from '../types.js';\n\nconst ESCROW_ID = 'cubist';\nconst DEFAULT_FUNCTION_ID = 'cubist_secret_escrow';\nconst DEFAULT_VERSION: Version = 'latest';\n\n/**\n * CubeSigner C2F client for the Cubist recovery escrow.\n *\n * Commands are sent with `policyInvoke` as `{ cmd, ...fields }` on\n * `cubist_secret_escrow`.\n * Escrow JSON is read from C2F stdout. Receipt signatures are checked locally\n * with the pinned receipt public key.\n */\nexport type CubistEscrowProviderOptions = {\n /**\n * Returns the authenticated CubeSigner client used to invoke the escrow C2F.\n * Called for every command, so the caller owns session caching and refresh.\n * Commands propagate its errors unchanged; `isAvailable` resolves `false`.\n */\n getClient: () => Promise<CubeSignerClient>;\n /**\n * Must match the escrow's AUTH_CONTROLLER_AUDIENCE configuration.\n */\n authAudience: string;\n /**\n * C2F name or named-policy id. Defaults to `cubist_secret_escrow`.\n */\n functionId?: string;\n /**\n * C2F version to invoke. Defaults to `latest`.\n */\n version?: Version;\n /**\n * Raw 32-byte X25519 public key of the escrow wrap key.\n */\n wrapPublicKey: Uint8Array;\n /**\n * Raw 32-byte Ed25519 public key of the escrow receipt key.\n */\n receiptPublicKey: Uint8Array;\n};\n\nexport class CubistEscrowProvider implements RecoveryEscrowProvider {\n readonly id = ESCROW_ID;\n\n readonly authAudience: string;\n\n readonly wrapPublicKey: Uint8Array;\n\n readonly #receiptPublicKey: Uint8Array;\n\n readonly #getClient: () => Promise<CubeSignerClient>;\n\n readonly #functionId: string;\n\n readonly #version: Version;\n\n /**\n * @param options - CubeSigner client getter, pinned keys, and optional C2F\n * id/version.\n */\n constructor(options: CubistEscrowProviderOptions) {\n this.authAudience = options.authAudience;\n this.wrapPublicKey = options.wrapPublicKey;\n this.#receiptPublicKey = options.receiptPublicKey;\n this.#getClient = options.getClient;\n this.#functionId = options.functionId ?? DEFAULT_FUNCTION_ID;\n this.#version = options.version ?? DEFAULT_VERSION;\n }\n\n /**\n * @returns Whether a ping of the escrow C2F is allowed and reports ok.\n */\n async isAvailable(): Promise<boolean> {\n try {\n await this.#invoke('ping', {}, parsePing);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * @param authControllerToken - Approval for the profile the challenge is for.\n * @returns A proof-of-possession challenge for this escrow.\n */\n async generateChallenge(\n authControllerToken: AuthControllerToken,\n ): Promise<PoPChallenge> {\n return await this.#invoke(\n 'generateChallenge',\n { authControllerToken },\n parseChallenge,\n );\n }\n\n /**\n * @param authControllerToken - Approval for the profile to read.\n * @returns The enrolled identifiers and record version.\n */\n async getIdentifiers(\n authControllerToken: AuthControllerToken,\n ): Promise<GetIdentifiersResponse> {\n return await this.#invoke(\n 'getIdentifiers',\n { authControllerToken },\n parseIdentifiers,\n );\n }\n\n /**\n * @param authControllerToken - Request-bound approval for this read.\n * @param authorization - Identifier proof for this read.\n * @param requestId - Client request id bound into the read hash.\n * @param pkE - Ephemeral wrap public key for the response.\n * @returns The wrapped recovery secret and its version.\n */\n async getSecret(\n authControllerToken: AuthControllerToken,\n authorization: IdentifierAuthorization,\n requestId: string,\n pkE: Uint8Array,\n ): Promise<GetRecoverySecretResponse> {\n return await this.#invoke(\n 'getSecret',\n {\n identifierAuthorization: authorization,\n requestId,\n pkE,\n authControllerToken,\n },\n parseGetSecretResponse,\n );\n }\n\n /**\n * @param mutation - Mutation to apply.\n * @param authControllerToken - Request-bound AuthController token.\n * @param identifierAuthorizations - Identifier proofs sharing one challenge.\n * @param payload - Per-escrow mutation payload.\n * @param approvedIdentifiers - The approval's identifiers, which non-SIWE\n * payload identifiers must be drawn from.\n * @returns The escrow's mutation receipt.\n */\n async applyMutation(\n mutation: Mutation,\n authControllerToken: AuthControllerToken,\n identifierAuthorizations: IdentifierAuthorization[],\n payload: MutationPayload,\n approvedIdentifiers: Identifier[],\n ): Promise<MutationReceipt> {\n return await this.#invoke(\n 'applyMutation',\n {\n mutation,\n authControllerToken,\n identifierAuthorizations,\n payload,\n approvedIdentifiers,\n },\n parseReceipt,\n true, // a policy Deny did not apply the mutation\n );\n }\n\n /**\n * Verifies a receipt with the pinned receipt public key.\n *\n * @param receipt - Receipt returned by the escrow.\n * @param mutation - Mutation the receipt must acknowledge.\n * @param expectedEscrowId - Escrow identity expected by the caller.\n * @returns Whether the receipt is valid for this escrow.\n */\n async verifyReceipt(\n receipt: MutationReceipt,\n mutation: Mutation,\n expectedEscrowId: string,\n ): Promise<boolean> {\n if (\n receipt.mutationId !== mutation.id ||\n receipt.requestHash !== mutation.requestHash ||\n receipt.escrowId !== expectedEscrowId ||\n expectedEscrowId !== this.id ||\n receipt.version !== mutation.newVersion ||\n receipt.receiptKeyId !== (await receiptKeyId(this.#receiptPublicKey))\n ) {\n return false;\n }\n return await verifySignature(\n this.#receiptPublicKey,\n receipt.signature,\n await hashMutationReceipt({\n escrowId: receipt.escrowId,\n mutationId: receipt.mutationId,\n receiptKeyId: receipt.receiptKeyId,\n requestHash: receipt.requestHash,\n version: receipt.version,\n }),\n );\n }\n\n async #invoke<Result>(\n cmd: string,\n body: Record<string, unknown>,\n parse: (value: unknown) => Result,\n denyIsRejection = false,\n ): Promise<Result> {\n const client = await this.#getClient();\n let invocation: InvokePolicyResponse;\n try {\n invocation = await client.apiClient.policyInvoke(\n this.#functionId,\n this.#version,\n { request: toWire({ cmd, ...body }) },\n );\n } catch (error) {\n throw new MfaRecoveryError(\n error instanceof Error ? error.message : 'Escrow request failed',\n 'escrow_request_failed',\n );\n }\n const policy = invocation.response;\n if (policy.response !== 'Allow') {\n if (denyIsRejection && policy.response === 'Deny') {\n throw new MutationRejectedError(policy.reason);\n }\n throw new MfaRecoveryError(\n policy.response === 'Deny' ? policy.reason : policy.error,\n 'escrow_request_failed',\n );\n }\n let json: unknown;\n try {\n json = JSON.parse(bytesToString(hexToBytes(invocation.stdout)));\n } catch {\n throw new MfaRecoveryError(\n 'Escrow response was not JSON',\n 'escrow_response_invalid',\n );\n }\n return parse(json);\n }\n}\n\n// `type()` is non-strict, so unknown fields are ignored. The explicit field\n// mapping below still strips them from the returned value.\nconst PingStruct = type({ ok: literal(true) });\n\nconst ChallengeStruct = type({\n id: string(),\n escrowId: literal(ESCROW_ID),\n expiresAt: integer(),\n});\n\nconst IdentifiersStruct = type({\n identifiers: array(\n type({\n type: string(),\n namespace: string(),\n value: string(),\n verifier: unknown(),\n }),\n ),\n version: min(integer(), 0),\n});\n\nconst GetSecretResponseStruct = type({\n recoverySecret: type({ ciphertext: string() }),\n version: min(integer(), 0),\n lastMutationId: string(),\n wrapKeyId: string(),\n});\n\nfunction parsePing(value: unknown): void {\n if (!is(value, PingStruct)) {\n throw new MfaRecoveryError(\n 'Invalid ping response',\n 'escrow_response_invalid',\n );\n }\n}\n\nfunction parseChallenge(value: unknown): PoPChallenge {\n if (!is(value, ChallengeStruct)) {\n throw new MfaRecoveryError(\n 'Invalid PoP challenge',\n 'escrow_response_invalid',\n );\n }\n return {\n id: value.id,\n escrowId: value.escrowId,\n expiresAt: value.expiresAt,\n };\n}\n\nfunction parseIdentifiers(value: unknown): GetIdentifiersResponse {\n if (!is(value, IdentifiersStruct)) {\n throw new MfaRecoveryError(\n 'Invalid identifiers response',\n 'escrow_response_invalid',\n );\n }\n return {\n identifiers: value.identifiers.map((identifier) => ({\n type: identifier.type,\n namespace: identifier.namespace,\n value: identifier.value,\n ...(identifier.verifier === undefined\n ? {}\n : { verifier: identifier.verifier }),\n })),\n version: value.version,\n };\n}\n\n/**\n * Encodes a request for the escrow wire: every byte field becomes a 0x-prefixed\n * hex string. Typed arrays have no `toJSON`, so the replacer sees them directly.\n *\n * @param value - Request body.\n * @returns JSON-compatible request body.\n */\nfunction toWire(value: Record<string, unknown>): Record<string, unknown> {\n return JSON.parse(\n JSON.stringify(value, (_key, node: unknown) =>\n node instanceof Uint8Array ? bytesToHex(node) : node,\n ),\n ) as Record<string, unknown>;\n}\n\nfunction parseGetSecretResponse(value: unknown): GetRecoverySecretResponse {\n if (\n !is(value, GetSecretResponseStruct) ||\n !isStrictHexString(value.recoverySecret.ciphertext)\n ) {\n throw new MfaRecoveryError(\n 'Invalid recovery secret response',\n 'escrow_response_invalid',\n );\n }\n return {\n recoverySecret: {\n ciphertext: hexToBytes(value.recoverySecret.ciphertext),\n },\n version: value.version,\n lastMutationId: value.lastMutationId,\n wrapKeyId: value.wrapKeyId,\n };\n}\n\nfunction parseReceipt(value: unknown): MutationReceipt {\n if (!isMutationReceipt(value)) {\n throw new MfaRecoveryError(\n 'Invalid mutation receipt',\n 'escrow_response_invalid',\n );\n }\n return value;\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,9 @@ export type { MfaRecoveryControllerActions, MfaRecoveryControllerEvents, MfaReco
|
|
|
3
3
|
export type { MfaRecoveryControllerAbortAction, MfaRecoveryControllerAuthenticateIdentifierAction, MfaRecoveryControllerGetIdentifiersAction, MfaRecoveryControllerGetPhaseAction, MfaRecoveryControllerGetRecoverySecretAction, MfaRecoveryControllerRegisterAction, 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
|
+
export { AuthApiRecoveryAuthProvider } from './auth-api-recovery-provider.js';
|
|
7
|
+
export type { AuthApiRecoveryAuthProviderMessenger, AuthApiRecoveryAuthProviderOptions, } from './auth-api-recovery-provider.js';
|
|
6
8
|
export { IncompleteMutationError, MfaRecoveryError, MutationRejectedError, } from './errors.js';
|
|
7
9
|
export { IDENTIFIER_AUTH_MODES, MIN_IDENTIFIERS, getIdentifierAuthMode, } from './identifier-auth.js';
|
|
8
|
-
export type { AuthControllerToken, GetIdentifiersResponse, Identifier, IdentifierAuthorization, IdentifierSession, Mutation, MutationPayload, MutationReceipt, PendingMutationPayload, PendingOperation, PendingOperationEncryptor, PendingRecoverySecretHex, PendingRegisterPayload, PendingUpdateIdentifiersPayload, PendingUpdateRecoverySecretPayload, RecoveryApproval, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryIdentifiers, RecoveryPhase, RecoveredSecret, WrappedSecret, WrappedSecretOutput, } from './types.js';
|
|
10
|
+
export type { AuthControllerToken, EncryptedPendingOperation, GetIdentifiersResponse, Identifier, IdentifierAuthorization, IdentifierSession, Mutation, MutationPayload, MutationReceipt, PendingMutationPayload, PendingOperation, PendingOperationEncryptor, PendingRecoverySecretHex, PendingRegisterPayload, PendingUpdateIdentifiersPayload, PendingUpdateRecoverySecretPayload, RecoveryApproval, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryIdentifiers, RecoveryPhase, RecoveredSecret, WrappedSecret, WrappedSecretOutput, } from './types.js';
|
|
9
11
|
//# 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,EACL,uBAAuB,EACvB,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,uBAAuB,EACvB,iBAAiB,EACjB,QAAQ,EACR,eAAe,EACf,eAAe,EACf,sBAAsB,EACtB,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,+BAA+B,EAC/B,kCAAkC,EAClC,gBAAgB,EAChB,sBAAsB,EACtB,8BAA8B,EAC9B,mBAAmB,EACnB,aAAa,EACb,eAAe,EACf,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,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,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,mBAAmB,EACnB,yBAAyB,EACzB,sBAAsB,EACtB,UAAU,EACV,uBAAuB,EACvB,iBAAiB,EACjB,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,aAAa,EACb,mBAAmB,GACpB,MAAM,YAAY,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { MfaRecoveryController, getDefaultMfaRecoveryControllerState, } from './MfaRecoveryController.js';
|
|
2
2
|
export { CubistEscrowProvider } from './escrow-providers/cubist-escrow-provider.js';
|
|
3
|
+
export { AuthApiRecoveryAuthProvider } from './auth-api-recovery-provider.js';
|
|
3
4
|
export { IncompleteMutationError, MfaRecoveryError, MutationRejectedError, } from './errors.js';
|
|
4
5
|
export { IDENTIFIER_AUTH_MODES, MIN_IDENTIFIERS, getIdentifierAuthMode, } from './identifier-auth.js';
|
|
5
6
|
//# 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;AAqBpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,8CAA8C,CAAC;AAEpF,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,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 MfaRecoveryControllerAuthenticateIdentifierAction,\n MfaRecoveryControllerGetIdentifiersAction,\n MfaRecoveryControllerGetPhaseAction,\n MfaRecoveryControllerGetRecoverySecretAction,\n MfaRecoveryControllerRegisterAction,\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 {\n IncompleteMutationError,\n MfaRecoveryError,\n MutationRejectedError,\n} from './errors.js';\nexport {\n IDENTIFIER_AUTH_MODES,\n MIN_IDENTIFIERS,\n getIdentifierAuthMode,\n} from './identifier-auth.js';\nexport type {\n AuthControllerToken,\n GetIdentifiersResponse,\n Identifier,\n IdentifierAuthorization,\n IdentifierSession,\n Mutation,\n MutationPayload,\n MutationReceipt,\n PendingMutationPayload,\n PendingOperation,\n PendingOperationEncryptor,\n PendingRecoverySecretHex,\n PendingRegisterPayload,\n PendingUpdateIdentifiersPayload,\n PendingUpdateRecoverySecretPayload,\n RecoveryApproval,\n RecoveryEscrowProvider,\n RecoveryIdentifierAuthProvider,\n RecoveryIdentifiers,\n RecoveryPhase,\n RecoveredSecret,\n WrappedSecret,\n WrappedSecretOutput,\n} from './types.js';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AAqBpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,8CAA8C,CAAC;AAEpF,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAK9E,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,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 MfaRecoveryControllerAuthenticateIdentifierAction,\n MfaRecoveryControllerGetIdentifiersAction,\n MfaRecoveryControllerGetPhaseAction,\n MfaRecoveryControllerGetRecoverySecretAction,\n MfaRecoveryControllerRegisterAction,\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 {\n IncompleteMutationError,\n MfaRecoveryError,\n MutationRejectedError,\n} from './errors.js';\nexport {\n IDENTIFIER_AUTH_MODES,\n MIN_IDENTIFIERS,\n getIdentifierAuthMode,\n} from './identifier-auth.js';\nexport type {\n AuthControllerToken,\n EncryptedPendingOperation,\n GetIdentifiersResponse,\n Identifier,\n IdentifierAuthorization,\n IdentifierSession,\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 RecoveryPhase,\n RecoveredSecret,\n WrappedSecret,\n WrappedSecretOutput,\n} from './types.js';\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { EncryptionResultConstraint, Encryptor } from '@metamask/keyring-controller';
|
|
2
1
|
/**
|
|
3
2
|
* MFA recovery protocol types from the recovery ADR.
|
|
4
3
|
*/
|
|
@@ -176,6 +175,16 @@ export type WritingPendingOperation = PendingOperationBase & {
|
|
|
176
175
|
};
|
|
177
176
|
export type PendingOperation = AuthorizingPendingOperation | WritingPendingOperation;
|
|
178
177
|
export type RecoveryPhase = 'idle' | PendingOperation['phase'];
|
|
178
|
+
/**
|
|
179
|
+
* Encoded ciphertext of {@link PendingOperation}. Wallet secure storage
|
|
180
|
+
* encrypts this blob (including any hex recovery secret). A raw recovery
|
|
181
|
+
* secret is never persisted in BaseController state.
|
|
182
|
+
*
|
|
183
|
+
* The recovery spec's pseudocode represents this as `Uint8Array`, but the
|
|
184
|
+
* controller stores the encoded ciphertext as a string so BaseController state
|
|
185
|
+
* persistence and serialization preserve it without binary coercion.
|
|
186
|
+
*/
|
|
187
|
+
export type EncryptedPendingOperation = string;
|
|
179
188
|
export type GetRecoverySecretResponse = {
|
|
180
189
|
recoverySecret: WrappedSecretOutput;
|
|
181
190
|
version: number;
|
|
@@ -205,6 +214,21 @@ export type RecoveryIdentifiers = {
|
|
|
205
214
|
epoch: number;
|
|
206
215
|
authIdentifiers: Identifier[];
|
|
207
216
|
};
|
|
217
|
+
/**
|
|
218
|
+
* Authenticates the MetaMask profile and issues request-bound attestations.
|
|
219
|
+
*/
|
|
220
|
+
export type RecoveryAuthProvider = {
|
|
221
|
+
getAuthenticatedProfileId: () => Promise<string>;
|
|
222
|
+
/**
|
|
223
|
+
* Returns the Auth API's approval and current recovery identifiers.
|
|
224
|
+
* `requireTwoFactor` requests recent AAL2 authentication.
|
|
225
|
+
*/
|
|
226
|
+
authorizeRecoveryRequest: (params: {
|
|
227
|
+
requestHash: string;
|
|
228
|
+
audiences: string[];
|
|
229
|
+
requireTwoFactor?: boolean;
|
|
230
|
+
}) => Promise<RecoveryApproval>;
|
|
231
|
+
};
|
|
208
232
|
/**
|
|
209
233
|
* Obtains a key-bound identifier assertion from an IdP (OIDC, Passkey, SIWE).
|
|
210
234
|
*/
|
|
@@ -234,10 +258,6 @@ export type RecoveryEscrowProvider = {
|
|
|
234
258
|
* using the corresponding wrap private key.
|
|
235
259
|
*/
|
|
236
260
|
readonly wrapPublicKey: Uint8Array;
|
|
237
|
-
/**
|
|
238
|
-
* Resolves `false` when this replica is down. Thrown errors, including a
|
|
239
|
-
* missing or expired session, propagate to the caller.
|
|
240
|
-
*/
|
|
241
261
|
isAvailable: () => Promise<boolean>;
|
|
242
262
|
generateChallenge: (authControllerToken: AuthControllerToken) => Promise<PoPChallenge>;
|
|
243
263
|
getIdentifiers: (authControllerToken: AuthControllerToken) => Promise<GetIdentifiersResponse>;
|
|
@@ -263,18 +283,11 @@ export type RecoveryEscrowProvider = {
|
|
|
263
283
|
verifyReceipt: (receipt: MutationReceipt, mutation: Mutation, expectedEscrowId: string) => Promise<boolean>;
|
|
264
284
|
};
|
|
265
285
|
/**
|
|
266
|
-
*
|
|
267
|
-
*/
|
|
268
|
-
export type DefaultEncryptionKey = Awaited<ReturnType<Encryptor['importKey']>>;
|
|
269
|
-
/**
|
|
270
|
-
* Encryption result type of the default KeyringController {@link Encryptor}.
|
|
271
|
-
*/
|
|
272
|
-
export type DefaultEncryptionResult = Awaited<ReturnType<Encryptor['encryptWithKey']>>;
|
|
273
|
-
/**
|
|
274
|
-
* The subset of the KeyringController {@link Encryptor} used to import the
|
|
275
|
-
* host-provided pending operation key and encrypt pending mutation state with
|
|
276
|
-
* it. Pass the same instance given to KeyringController.
|
|
286
|
+
* Encrypts pending mutation state using wallet secure storage.
|
|
277
287
|
*/
|
|
278
|
-
export type PendingOperationEncryptor
|
|
288
|
+
export type PendingOperationEncryptor = {
|
|
289
|
+
encrypt: (operation: PendingOperation) => Promise<EncryptedPendingOperation>;
|
|
290
|
+
decrypt: (ciphertext: EncryptedPendingOperation) => Promise<PendingOperation>;
|
|
291
|
+
};
|
|
279
292
|
export {};
|
|
280
293
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"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["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n EncryptionResultConstraint,\n Encryptor,\n} from '@metamask/keyring-controller';\n\n/**\n * MFA recovery protocol types from the recovery ADR.\n */\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 * Result of first-factor identifier authentication, consumed by\n * `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 */\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};\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\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 * Obtains a key-bound identifier assertion from an IdP (OIDC, Passkey, SIWE).\n */\nexport type RecoveryIdentifierAuthProvider = {\n getKeyBoundIdentifierToken: (params: {\n identifier: Identifier;\n /**\n * Raw 32-byte Ed25519 public key to bind into the token.\n */\n proofPublicKey: Uint8Array;\n requestHash: string;\n }) => Promise<KeyBoundIdentifierToken>;\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 /**\n * Resolves `false` when this replica is down. Thrown errors, including a\n * missing or expired session, propagate to the caller.\n */\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 * Encryption key type of the default KeyringController {@link Encryptor}.\n */\nexport type DefaultEncryptionKey = Awaited<ReturnType<Encryptor['importKey']>>;\n\n/**\n * Encryption result type of the default KeyringController {@link Encryptor}.\n */\nexport type DefaultEncryptionResult = Awaited<\n ReturnType<Encryptor['encryptWithKey']>\n>;\n\n/**\n * The subset of the KeyringController {@link Encryptor} used to import the\n * host-provided pending operation key and encrypt pending mutation state with\n * it. Pass the same instance given to KeyringController.\n */\nexport type PendingOperationEncryptor<\n EncryptionKey = DefaultEncryptionKey,\n EncryptionResult extends EncryptionResultConstraint<unknown> =\n DefaultEncryptionResult,\n> = Pick<\n Encryptor<EncryptionKey, unknown, EncryptionResult>,\n 'importKey' | 'encryptWithKey' | 'decryptWithKey'\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\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 * Result of first-factor identifier authentication, consumed by\n * `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 */\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};\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 getKeyBoundIdentifierToken: (params: {\n identifier: Identifier;\n /**\n * Raw 32-byte Ed25519 public key to bind into the token.\n */\n proofPublicKey: Uint8Array;\n requestHash: string;\n }) => Promise<KeyBoundIdentifierToken>;\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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/mfa-recovery-controller",
|
|
3
|
-
"version": "0.0.0-preview-
|
|
3
|
+
"version": "0.0.0-preview-e1e83cae0",
|
|
4
4
|
"description": "Manages MFA recovery flows across MetaMask clients",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -57,7 +57,6 @@
|
|
|
57
57
|
"@cubist-labs/cubesigner-sdk": "^0.4.284",
|
|
58
58
|
"@metamask/base-controller": "^10.1.0",
|
|
59
59
|
"@metamask/cryptography": "^1.1.2",
|
|
60
|
-
"@metamask/keyring-controller": "^28.2.0",
|
|
61
60
|
"@metamask/messenger": "^3.0.0",
|
|
62
61
|
"@metamask/profile-sync-controller": "^36.1.1",
|
|
63
62
|
"@metamask/superstruct": "^3.4.1",
|