@metamask-previews/mfa-recovery-controller 0.0.0-preview-d4ac59b6e → 0.0.0-preview-c3d36da85

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 CHANGED
@@ -9,10 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Added
11
11
 
12
- - `authenticateIdentifier` can return optional seedless auth-server data beside a key-bound recovery `session` from one social login (passkey / SIWE omit it); callers can require a complete set including `revokeToken` for the seedless password unlock path and still reuse `session` with `getRecoverySecret` ([#11224](https://github.com/MetaMask/core/pull/11224))
13
- - Uses one identifier request helper; prefers optional `getKeyBoundIdentifierLogin` when present, otherwise `getKeyBoundIdentifierToken`.
14
- - Validates that the key-bound token matches the requested identifier, proof key, and request hash.
15
- - Validates that `seedlessAuthData.authConnection` matches the social identifier's issuer namespace.
16
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))
17
13
  - Requires recent, request-bound AAL2 approvals for writes and reads.
18
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))
package/README.md CHANGED
@@ -22,47 +22,6 @@ included): the controller rejects any other identifier before writing, and the
22
22
  mutation can then be aborted. Set `CubistEscrowProviderOptions.authAudience` to the escrow's
23
23
  `AUTH_CONTROLLER_AUDIENCE`.
24
24
 
25
- ## Seedless password unlock
26
-
27
- `authenticateIdentifier` always goes through one helper
28
- (`requestKeyBoundIdentifierToken`). That helper prefers optional
29
- `RecoveryIdentifierAuthProvider.getKeyBoundIdentifierLogin` when present, and
30
- otherwise uses `getKeyBoundIdentifierToken`.
31
-
32
- `seedlessAuthData` on the result is **optional**: passkey / SIWE logins omit
33
- it; only seedless social password unlock needs it. For that path, implement
34
- `getKeyBoundIdentifierLogin` to perform one AAL1 social login and return the
35
- key-bound recovery token plus the auth-server token set, then call:
36
-
37
- ```typescript
38
- const { session, seedlessAuthData } =
39
- await mfaRecoveryController.authenticateIdentifier(identifier, {
40
- requireSeedlessAuthData: true,
41
- });
42
-
43
- const { authConnection, ...seedlessAuthFields } = seedlessAuthData;
44
- await seedlessOnboardingController.authenticate({
45
- ...seedlessAuthFields,
46
- // Values match `AuthConnection`; cast if your TS treats string enums nominally.
47
- authConnection: authConnection as AuthConnection,
48
- });
49
- // Prompt for the password, evaluate TOPRF, and decrypt the vault.
50
- // Keep `session` only if a later getRecoverySecret is needed; drop seedlessAuthData.
51
- ```
52
-
53
- With `requireSeedlessAuthData: true`, the result always includes
54
- `seedlessAuthData` (including `revokeToken`) beside a key-bound `session`.
55
- Without that flag (default), missing seedless data is fine — e.g. passkey.
56
- `authConnection` must match the social identifier's issuer namespace and uses
57
- the same string values as seedless `AuthConnection`. Cast to `AuthConnection`
58
- if TypeScript treats that enum nominally. Pass only `session` to
59
- `getRecoverySecret(session)` later — do not keep auth-server tokens on the
60
- session object.
61
-
62
- The seedless auth data comes only from the AAL1 social login and is never sent
63
- to recovery escrows. `getRecoverySecret` separately requests its AAL2
64
- approval when a recovery-secret read is needed.
65
-
66
25
  ## Installation
67
26
 
68
27
  `yarn add @metamask/mfa-recovery-controller`
@@ -38,18 +38,10 @@ export type MfaRecoveryControllerUpdateIdentifiersAction = {
38
38
  handler: MfaRecoveryController['updateIdentifiers'];
39
39
  };
40
40
  /**
41
- * Authenticates an identifier with a single login. Returns an ephemeral
42
- * `session` for {@link getRecoverySecret} and, for seedless social logins,
43
- * `seedlessAuthData` for `SeedlessOnboardingController.authenticate`.
44
- * Callers should drop `seedlessAuthData` after seedless authenticate and
45
- * keep only `session` for recovery reads.
41
+ * Authenticates an identifier for a subsequent recovery-secret read.
46
42
  *
47
43
  * @param identifier - Identifier to authenticate.
48
- * @param options - Authentication options.
49
- * @param options.requireSeedlessAuthData - Fail unless the login returns
50
- * complete seedless auth data (including `revokeToken`). Set for the
51
- * seedless password unlock path.
52
- * @returns Session for recovery reads, plus seedless auth data when present.
44
+ * @returns Ephemeral session data required by {@link getRecoverySecret}.
53
45
  */
54
46
  export type MfaRecoveryControllerAuthenticateIdentifierAction = {
55
47
  type: `MfaRecoveryController:authenticateIdentifier`;
@@ -1 +1 @@
1
- {"version":3,"file":"MfaRecoveryController-method-action-types.d.ts","sourceRoot":"","sources":["../src/MfaRecoveryController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAExE;;;;;;GAMG;AACH,MAAM,MAAM,mCAAmC,GAAG;IAChD,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,qBAAqB,CAAC,UAAU,CAAC,CAAC;CAC5C,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,+CAA+C,GAAG;IAC5D,IAAI,EAAE,4CAA4C,CAAC;IACnD,OAAO,EAAE,qBAAqB,CAAC,sBAAsB,CAAC,CAAC;CACxD,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,4CAA4C,GAAG;IACzD,IAAI,EAAE,yCAAyC,CAAC;IAChD,OAAO,EAAE,qBAAqB,CAAC,mBAAmB,CAAC,CAAC;CACrD,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,iDAAiD,GAAG;IAC9D,IAAI,EAAE,8CAA8C,CAAC;IACrD,OAAO,EAAE,qBAAqB,CAAC,wBAAwB,CAAC,CAAC;CAC1D,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,4CAA4C,GAAG;IACzD,IAAI,EAAE,yCAAyC,CAAC;IAChD,OAAO,EAAE,qBAAqB,CAAC,mBAAmB,CAAC,CAAC;CACrD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,qBAAqB,CAAC,QAAQ,CAAC,CAAC;CAC1C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C,IAAI,EAAE,6BAA6B,CAAC;IACpC,OAAO,EAAE,qBAAqB,CAAC,OAAO,CAAC,CAAC;CACzC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,mCAAmC,GAAG;IAChD,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,qBAAqB,CAAC,UAAU,CAAC,CAAC;CAC5C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kCAAkC,GAC1C,mCAAmC,GACnC,+CAA+C,GAC/C,4CAA4C,GAC5C,iDAAiD,GACjD,4CAA4C,GAC5C,iCAAiC,GACjC,gCAAgC,GAChC,mCAAmC,CAAC"}
1
+ {"version":3,"file":"MfaRecoveryController-method-action-types.d.ts","sourceRoot":"","sources":["../src/MfaRecoveryController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAExE;;;;;;GAMG;AACH,MAAM,MAAM,mCAAmC,GAAG;IAChD,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,qBAAqB,CAAC,UAAU,CAAC,CAAC;CAC5C,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,+CAA+C,GAAG;IAC5D,IAAI,EAAE,4CAA4C,CAAC;IACnD,OAAO,EAAE,qBAAqB,CAAC,sBAAsB,CAAC,CAAC;CACxD,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,4CAA4C,GAAG;IACzD,IAAI,EAAE,yCAAyC,CAAC;IAChD,OAAO,EAAE,qBAAqB,CAAC,mBAAmB,CAAC,CAAC;CACrD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,iDAAiD,GAAG;IAC9D,IAAI,EAAE,8CAA8C,CAAC;IACrD,OAAO,EAAE,qBAAqB,CAAC,wBAAwB,CAAC,CAAC;CAC1D,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,4CAA4C,GAAG;IACzD,IAAI,EAAE,yCAAyC,CAAC;IAChD,OAAO,EAAE,qBAAqB,CAAC,mBAAmB,CAAC,CAAC;CACrD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,qBAAqB,CAAC,QAAQ,CAAC,CAAC;CAC1C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C,IAAI,EAAE,6BAA6B,CAAC;IACpC,OAAO,EAAE,qBAAqB,CAAC,OAAO,CAAC,CAAC;CACzC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,mCAAmC,GAAG;IAChD,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,qBAAqB,CAAC,UAAU,CAAC,CAAC;CAC5C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kCAAkC,GAC1C,mCAAmC,GACnC,+CAA+C,GAC/C,4CAA4C,GAC5C,iDAAiD,GACjD,4CAA4C,GAC5C,iCAAiC,GACjC,gCAAgC,GAChC,mCAAmC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"MfaRecoveryController-method-action-types.js","sourceRoot":"","sources":["../src/MfaRecoveryController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { MfaRecoveryController } from './MfaRecoveryController.js';\n\n/**\n * Creates version 1 of a recovery record.\n *\n * @param recoverySecret - Secret replicated in full to every escrow.\n * @param identifiers - Ownership-approved identifier set. Must contain at\n * least two identifiers.\n */\nexport type MfaRecoveryControllerRegisterAction = {\n type: `MfaRecoveryController:register`;\n handler: MfaRecoveryController['register'];\n};\n\n/**\n * Replaces the recovery secret.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param recoverySecret - New secret.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\nexport type MfaRecoveryControllerUpdateRecoverySecretAction = {\n type: `MfaRecoveryController:updateRecoverySecret`;\n handler: MfaRecoveryController['updateRecoverySecret'];\n};\n\n/**\n * Replaces the complete identifier set.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param identifiers - New identifier set. Must contain at least two\n * identifiers.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\nexport type MfaRecoveryControllerUpdateIdentifiersAction = {\n type: `MfaRecoveryController:updateIdentifiers`;\n handler: MfaRecoveryController['updateIdentifiers'];\n};\n\n/**\n * Authenticates an identifier with a single login. Returns an ephemeral\n * `session` for {@link getRecoverySecret} and, for seedless social logins,\n * `seedlessAuthData` for `SeedlessOnboardingController.authenticate`.\n * Callers should drop `seedlessAuthData` after seedless authenticate and\n * keep only `session` for recovery reads.\n *\n * @param identifier - Identifier to authenticate.\n * @param options - Authentication options.\n * @param options.requireSeedlessAuthData - Fail unless the login returns\n * complete seedless auth data (including `revokeToken`). Set for the\n * seedless password unlock path.\n * @returns Session for recovery reads, plus seedless auth data when present.\n */\nexport type MfaRecoveryControllerAuthenticateIdentifierAction = {\n type: `MfaRecoveryController:authenticateIdentifier`;\n handler: MfaRecoveryController['authenticateIdentifier'];\n};\n\n/**\n * Reads the recovery secret from available escrows and returns the highest\n * consistent version. `epoch` is the current recovery version and is required\n * by later mutations. Does not wait for a pending mutation to be repaired.\n *\n * @param session - Identifier authentication session used to authorize the\n * read.\n * @returns Recovered secret bytes and the selected epoch.\n */\nexport type MfaRecoveryControllerGetRecoverySecretAction = {\n type: `MfaRecoveryController:getRecoverySecret`;\n handler: MfaRecoveryController['getRecoverySecret'];\n};\n\n/**\n * Completes a persisted pending mutation, if any.\n */\nexport type MfaRecoveryControllerResumeAction = {\n type: `MfaRecoveryController:resume`;\n handler: MfaRecoveryController['resume'];\n};\n\n/**\n * Drops `authorizing` pending. `writing` must be finished with {@link resume}.\n */\nexport type MfaRecoveryControllerAbortAction = {\n type: `MfaRecoveryController:abort`;\n handler: MfaRecoveryController['abort'];\n};\n\n/**\n * @returns Current recovery phase.\n */\nexport type MfaRecoveryControllerGetPhaseAction = {\n type: `MfaRecoveryController:getPhase`;\n handler: MfaRecoveryController['getPhase'];\n};\n\n/**\n * Union of all MfaRecoveryController action types.\n */\nexport type MfaRecoveryControllerMethodActions =\n | MfaRecoveryControllerRegisterAction\n | MfaRecoveryControllerUpdateRecoverySecretAction\n | MfaRecoveryControllerUpdateIdentifiersAction\n | MfaRecoveryControllerAuthenticateIdentifierAction\n | MfaRecoveryControllerGetRecoverySecretAction\n | MfaRecoveryControllerResumeAction\n | MfaRecoveryControllerAbortAction\n | MfaRecoveryControllerGetPhaseAction;\n"]}
1
+ {"version":3,"file":"MfaRecoveryController-method-action-types.js","sourceRoot":"","sources":["../src/MfaRecoveryController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { MfaRecoveryController } from './MfaRecoveryController.js';\n\n/**\n * Creates version 1 of a recovery record.\n *\n * @param recoverySecret - Secret replicated in full to every escrow.\n * @param identifiers - Ownership-approved identifier set. Must contain at\n * least two identifiers.\n */\nexport type MfaRecoveryControllerRegisterAction = {\n type: `MfaRecoveryController:register`;\n handler: MfaRecoveryController['register'];\n};\n\n/**\n * Replaces the recovery secret.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param recoverySecret - New secret.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\nexport type MfaRecoveryControllerUpdateRecoverySecretAction = {\n type: `MfaRecoveryController:updateRecoverySecret`;\n handler: MfaRecoveryController['updateRecoverySecret'];\n};\n\n/**\n * Replaces the complete identifier set.\n *\n * @param identifier - Currently registered identifier used to authorize.\n * @param identifiers - New identifier set. Must contain at least two\n * identifiers.\n * @param epoch - Current recovery version, used as `expectedVersion`.\n */\nexport type MfaRecoveryControllerUpdateIdentifiersAction = {\n type: `MfaRecoveryController:updateIdentifiers`;\n handler: MfaRecoveryController['updateIdentifiers'];\n};\n\n/**\n * Authenticates an identifier for a subsequent recovery-secret read.\n *\n * @param identifier - Identifier to authenticate.\n * @returns Ephemeral session data required by {@link getRecoverySecret}.\n */\nexport type MfaRecoveryControllerAuthenticateIdentifierAction = {\n type: `MfaRecoveryController:authenticateIdentifier`;\n handler: MfaRecoveryController['authenticateIdentifier'];\n};\n\n/**\n * Reads the recovery secret from available escrows and returns the highest\n * consistent version. `epoch` is the current recovery version and is required\n * by later mutations. Does not wait for a pending mutation to be repaired.\n *\n * @param session - Identifier authentication session used to authorize the\n * read.\n * @returns Recovered secret bytes and the selected epoch.\n */\nexport type MfaRecoveryControllerGetRecoverySecretAction = {\n type: `MfaRecoveryController:getRecoverySecret`;\n handler: MfaRecoveryController['getRecoverySecret'];\n};\n\n/**\n * Completes a persisted pending mutation, if any.\n */\nexport type MfaRecoveryControllerResumeAction = {\n type: `MfaRecoveryController:resume`;\n handler: MfaRecoveryController['resume'];\n};\n\n/**\n * Drops `authorizing` pending. `writing` must be finished with {@link resume}.\n */\nexport type MfaRecoveryControllerAbortAction = {\n type: `MfaRecoveryController:abort`;\n handler: MfaRecoveryController['abort'];\n};\n\n/**\n * @returns Current recovery phase.\n */\nexport type MfaRecoveryControllerGetPhaseAction = {\n type: `MfaRecoveryController:getPhase`;\n handler: MfaRecoveryController['getPhase'];\n};\n\n/**\n * Union of all MfaRecoveryController action types.\n */\nexport type MfaRecoveryControllerMethodActions =\n | MfaRecoveryControllerRegisterAction\n | MfaRecoveryControllerUpdateRecoverySecretAction\n | MfaRecoveryControllerUpdateIdentifiersAction\n | MfaRecoveryControllerAuthenticateIdentifierAction\n | MfaRecoveryControllerGetRecoverySecretAction\n | MfaRecoveryControllerResumeAction\n | MfaRecoveryControllerAbortAction\n | MfaRecoveryControllerGetPhaseAction;\n"]}
@@ -2,7 +2,7 @@ import type { ControllerGetStateAction, ControllerStateChangedEvent } from '@met
2
2
  import { BaseController } from '@metamask/base-controller';
3
3
  import type { Messenger } from '@metamask/messenger';
4
4
  import type { MfaRecoveryControllerMethodActions } from './MfaRecoveryController-method-action-types.js';
5
- import type { AuthenticateIdentifierOptions, AuthenticateIdentifierResult, Identifier, IdentifierSession, PendingOperationEncryptor, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryPhase, RecoveredSecret, SeedlessAuthenticateIdentifierResult } from './types.js';
5
+ import type { Identifier, IdentifierSession, PendingOperationEncryptor, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryPhase, RecoveredSecret } from './types.js';
6
6
  declare const CONTROLLER_NAME = "MfaRecoveryController";
7
7
  export type MfaRecoveryControllerState = {
8
8
  /**
@@ -86,23 +86,12 @@ export declare class MfaRecoveryController extends BaseController<typeof CONTROL
86
86
  */
87
87
  updateIdentifiers(identifier: Identifier, identifiers: Identifier[], epoch: number): Promise<void>;
88
88
  /**
89
- * Authenticates an identifier with a single login. Returns an ephemeral
90
- * `session` for {@link getRecoverySecret} and, for seedless social logins,
91
- * `seedlessAuthData` for `SeedlessOnboardingController.authenticate`.
92
- * Callers should drop `seedlessAuthData` after seedless authenticate and
93
- * keep only `session` for recovery reads.
89
+ * Authenticates an identifier for a subsequent recovery-secret read.
94
90
  *
95
91
  * @param identifier - Identifier to authenticate.
96
- * @param options - Authentication options.
97
- * @param options.requireSeedlessAuthData - Fail unless the login returns
98
- * complete seedless auth data (including `revokeToken`). Set for the
99
- * seedless password unlock path.
100
- * @returns Session for recovery reads, plus seedless auth data when present.
101
- */
102
- authenticateIdentifier(identifier: Identifier, options: AuthenticateIdentifierOptions & {
103
- requireSeedlessAuthData: true;
104
- }): Promise<SeedlessAuthenticateIdentifierResult>;
105
- authenticateIdentifier(identifier: Identifier, options?: AuthenticateIdentifierOptions): Promise<AuthenticateIdentifierResult>;
92
+ * @returns Ephemeral session data required by {@link getRecoverySecret}.
93
+ */
94
+ authenticateIdentifier(identifier: Identifier): Promise<IdentifierSession>;
106
95
  /**
107
96
  * Reads the recovery secret from available escrows and returns the highest
108
97
  * consistent version. `epoch` is the current recovery version and is required
@@ -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,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAgCrD,OAAO,KAAK,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AAOzG,OAAO,KAAK,EACV,6BAA6B,EAC7B,4BAA4B,EAC5B,UAAU,EACV,iBAAiB,EAKjB,yBAAyB,EAIzB,oBAAoB,EACpB,sBAAsB,EACtB,8BAA8B,EAC9B,aAAa,EACb,eAAe,EACf,oCAAoC,EAGrC,MAAM,YAAY,CAAC;AAEpB,QAAA,MAAM,eAAe,0BAA0B,CAAC;AAahD,MAAM,MAAM,0BAA0B,GAAG;IACvC;;OAEG;IACH,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;CACjC,CAAC;AAWF;;GAEG;AACH,wBAAgB,oCAAoC,IAAI,0BAA0B,CAEjF;AAED,MAAM,MAAM,mCAAmC,GAAG,wBAAwB,CACxE,OAAO,eAAe,EACtB,0BAA0B,CAC3B,CAAC;AAEF,MAAM,MAAM,4BAA4B,GACpC,mCAAmC,GACnC,kCAAkC,CAAC;AAEvC,KAAK,cAAc,GAAG,KAAK,CAAC;AAE5B,MAAM,MAAM,sCAAsC,GAChD,2BAA2B,CACzB,OAAO,eAAe,EACtB,0BAA0B,CAC3B,CAAC;AAEJ,MAAM,MAAM,2BAA2B,GACrC,sCAAsC,CAAC;AAEzC,KAAK,aAAa,GAAG,KAAK,CAAC;AAE3B,MAAM,MAAM,8BAA8B,GAAG,SAAS,CAC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AU,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,CA+D1B;IAED;;OAEG;IACG,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAI5B;IAED;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAQ3B;IAED;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,aAAa,CAAC,CAIvC;CAkXF"}
@@ -122,7 +122,13 @@ export class MfaRecoveryController extends BaseController {
122
122
  epoch,
123
123
  });
124
124
  }
125
- async authenticateIdentifier(identifier, { requireSeedlessAuthData = false } = {}) {
125
+ /**
126
+ * Authenticates an identifier for a subsequent recovery-secret read.
127
+ *
128
+ * @param identifier - Identifier to authenticate.
129
+ * @returns Ephemeral session data required by {@link getRecoverySecret}.
130
+ */
131
+ async authenticateIdentifier(identifier) {
126
132
  this.#assertKnownIdentifierTypes([identifier]);
127
133
  const requestId = randomId();
128
134
  const ephemeral = await generateWrapKey();
@@ -132,21 +138,17 @@ export class MfaRecoveryController extends BaseController {
132
138
  requestId,
133
139
  pkE,
134
140
  });
135
- const { seedlessAuthData, ...credential } = await requestKeyBoundIdentifierToken({
141
+ const credential = await requestKeyBoundIdentifierToken({
136
142
  identifier,
137
143
  requestHash,
138
144
  identifierAuthProvider: this.#identifierAuthProvider,
139
- requireSeedlessAuthData,
140
145
  });
141
- const session = {
146
+ return {
142
147
  ...credential,
143
148
  requestId,
144
149
  ephemeralPrivateKey: ephemeral.privateKey,
145
150
  pkE,
146
151
  };
147
- return seedlessAuthData === undefined
148
- ? { session }
149
- : { session, seedlessAuthData };
150
152
  }
151
153
  /**
152
154
  * Reads the recovery secret from available escrows and returns the highest
@@ -1 +1 @@
1
- {"version":3,"file":"MfaRecoveryController.js","sourceRoot":"","sources":["../src/MfaRecoveryController.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAEzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,eAAe,EACf,IAAI,EACJ,QAAQ,EACR,OAAO,EACP,SAAS,GACV,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,yBAAyB,EACzB,wBAAwB,EACxB,qBAAqB,EACrB,eAAe,EACf,8BAA8B,GAC/B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,EAC5B,+BAA+B,GAChC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAwB1E,MAAM,eAAe,GAAG,uBAAuB,CAAC;AAEhD,MAAM,yBAAyB,GAAG;IAChC,UAAU;IACV,sBAAsB;IACtB,mBAAmB;IACnB,wBAAwB;IACxB,mBAAmB;IACnB,QAAQ;IACR,OAAO;IACP,UAAU;CACF,CAAC;AASX,MAAM,6BAA6B,GAAG;IACpC,gBAAgB,EAAE;QAChB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE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C;IAED,KAAK,CAAC,SAAS,CACb,EAA8B;QAE9B,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QACpC,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CACnB,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;QACF,OAAO,MAAM,GAAG,CAAC;IACnB,CAAC;CACF;AAED;;;;;;GAMG;AACH,SAAS,0BAA0B,CACjC,OAAgD,EAChD,gBAAmC;IAEnC,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,SAAS,GAAiC,IAAI,CAAC;IACnD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IACE,MAAM,CAAC,MAAM,KAAK,UAAU;YAC5B,CAAC,CAAC,MAAM,CAAC,MAAM,YAAY,qBAAqB,CAAC,EACjD,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,SAAS,KAAK,MAAM,CAAC,MAAM,CAAC;IAC9B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport { bytesToHex, hexToBytes } 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 MIN_IDENTIFIERS,\n requestKeyBoundIdentifierToken,\n} from './identifier-auth.js';\nimport type { AuthorizedEscrow } 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 { assertAbortAllowed, getRecoveryPhase } from './state-machine.js';\nimport type {\n AuthenticateIdentifierOptions,\n AuthenticateIdentifierResult,\n Identifier,\n IdentifierSession,\n Mutation,\n MutationPayload,\n MutationReceipt,\n PendingOperation,\n PendingOperationEncryptor,\n PendingRegisterPayload,\n PendingUpdateIdentifiersPayload,\n PendingUpdateRecoverySecretPayload,\n RecoveryAuthProvider,\n RecoveryEscrowProvider,\n RecoveryIdentifierAuthProvider,\n RecoveryPhase,\n RecoveredSecret,\n SeedlessAuthenticateIdentifierResult,\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 '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.#assertKnownIdentifierTypes(identifiers);\n this.#assertMinIdentifiers(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.#assertKnownIdentifierTypes([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.#assertKnownIdentifierTypes([identifier, ...identifiers]);\n this.#assertMinIdentifiers(identifiers);\n await this.#mutate({\n operation: 'updateIdentifiers',\n payload: { identifiers },\n identifier,\n epoch,\n });\n }\n\n /**\n * Authenticates an identifier with a single login. Returns an ephemeral\n * `session` for {@link getRecoverySecret} and, for seedless social logins,\n * `seedlessAuthData` for `SeedlessOnboardingController.authenticate`.\n * Callers should drop `seedlessAuthData` after seedless authenticate and\n * keep only `session` for recovery reads.\n *\n * @param identifier - Identifier to authenticate.\n * @param options - Authentication options.\n * @param options.requireSeedlessAuthData - Fail unless the login returns\n * complete seedless auth data (including `revokeToken`). Set for the\n * seedless password unlock path.\n * @returns Session for recovery reads, plus seedless auth data when present.\n */\n async authenticateIdentifier(\n identifier: Identifier,\n options: AuthenticateIdentifierOptions & {\n requireSeedlessAuthData: true;\n },\n ): Promise<SeedlessAuthenticateIdentifierResult>;\n\n async authenticateIdentifier(\n identifier: Identifier,\n options?: AuthenticateIdentifierOptions,\n ): Promise<AuthenticateIdentifierResult>;\n\n async authenticateIdentifier(\n identifier: Identifier,\n { requireSeedlessAuthData = false }: AuthenticateIdentifierOptions = {},\n ): Promise<AuthenticateIdentifierResult> {\n this.#assertKnownIdentifierTypes([identifier]);\n const requestId = randomId();\n const ephemeral = await generateWrapKey();\n const pkE = ephemeral.publicKey;\n const requestHash = await hash({\n operation: 'getRecoverySecret',\n requestId,\n pkE,\n });\n const { seedlessAuthData, ...credential } =\n await requestKeyBoundIdentifierToken({\n identifier,\n requestHash,\n identifierAuthProvider: this.#identifierAuthProvider,\n requireSeedlessAuthData,\n });\n const session: IdentifierSession = {\n ...credential,\n requestId,\n ephemeralPrivateKey: ephemeral.privateKey,\n pkE,\n };\n return seedlessAuthData === undefined\n ? { session }\n : { session, seedlessAuthData };\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.#assertKnownIdentifierTypes([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 credential: session,\n });\n const results = await Promise.allSettled(\n authorizedEscrows.map(async ({ escrow, authorization }) => {\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 * Completes a persisted pending mutation, if any.\n */\n async resume(): Promise<void> {\n await this.#withLock(async () => {\n await this.#repairPendingMutation();\n });\n }\n\n /**\n * Drops `authorizing` pending. `writing` must be finished with {@link resume}.\n */\n async abort(): Promise<void> {\n await this.#withLock(async () => {\n const pending = await this.#loadPending();\n assertAbortAllowed(pending);\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 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\n await this.#replicateMutation(pending);\n }\n\n async #replicateMutation(pending: WritingPendingOperation): Promise<void> {\n const { mutation, identifier } = 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 authorizedEscrows =\n mutation.operation === 'register'\n ? null\n : await this.#authorizeEscrows({\n escrows: remainingEscrows,\n identifier: identifier as Identifier,\n requestHash: mutation.requestHash,\n });\n if (\n authorizedEscrows !== null &&\n authorizedEscrows.length !== remainingEscrows.length\n ) {\n throw new MfaRecoveryError(\n 'Unable to authorize every escrow',\n 'identifier_auth_failed',\n );\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 authorizedEscrows?.[index]?.authorization ?? null,\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 async #authorizeEscrows({\n escrows,\n identifier,\n requestHash,\n }: {\n escrows: RecoveryEscrowProvider[];\n identifier: Identifier;\n requestHash: string;\n }): Promise<AuthorizedEscrow[]> {\n getIdentifierAuthMode(identifier.type);\n const credential = await requestKeyBoundIdentifierToken({\n identifier,\n requestHash,\n identifierAuthProvider: this.#identifierAuthProvider,\n });\n return await authorizeEscrowsWithToken({ escrows, credential });\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 #assertKnownIdentifierTypes(identifiers: Identifier[]): void {\n for (const identifier of identifiers) {\n getIdentifierAuthMode(identifier.type);\n }\n }\n\n #assertMinIdentifiers(identifiers: Identifier[]): void {\n if (countDistinctIdentifiers(identifiers) < MIN_IDENTIFIERS) {\n throw new MfaRecoveryError(\n `Requires at least ${MIN_IDENTIFIERS} identifiers`,\n 'too_few_identifiers',\n );\n }\n }\n\n async #wrapRecoverySecret(\n plaintext: Uint8Array,\n wrapPublicKey: Uint8Array,\n ): Promise<WrappedSecret> {\n const ephemeral = await generateWrapKey();\n return {\n pkE: ephemeral.publicKey,\n ciphertext: await encryptToPublic(\n ephemeral.privateKey,\n wrapPublicKey,\n plaintext,\n ),\n };\n }\n\n async #loadPending(): Promise<PendingOperation | null> {\n const { pendingOperation } = this.state;\n if (pendingOperation === null) {\n return null;\n }\n const pending = (await this.#encryptor.decrypt(\n pendingOperation,\n )) as unknown;\n await this.#assertPending(pending);\n return pending as PendingOperation;\n }\n\n async #persistPending(operation: PendingOperation): Promise<void> {\n await this.#assertPending(operation);\n const encrypted = await this.#encryptor.encrypt(operation);\n this.update((state) => {\n state.pendingOperation = encrypted;\n });\n }\n\n async #assertPending(pending: unknown): Promise<void> {\n await assertValidPendingOperation(\n pending,\n this.#escrows.map((escrow) => escrow.id),\n );\n }\n\n async #clearPending(): Promise<void> {\n this.update((state) => {\n state.pendingOperation = null;\n });\n }\n\n async #withLock<ReturnValue>(\n fn: () => Promise<ReturnValue>,\n ): Promise<ReturnValue> {\n const run = this.#lock.then(fn, fn);\n this.#lock = run.then(\n () => undefined,\n () => undefined,\n );\n return await run;\n }\n}\n\n/**\n * Every remaining escrow refused the mutation, and none has a receipt.\n *\n * @param results - Settled apply results for the remaining escrows.\n * @param existingReceipts - Receipts already stored for this mutation.\n * @returns The first refusal, or `null` when the write may have been applied.\n */\nfunction unanimousMutationRejection(\n results: PromiseSettledResult<MutationReceipt>[],\n existingReceipts: MutationReceipt[],\n): MutationRejectedError | null {\n if (existingReceipts.length > 0 || results.length === 0) {\n return null;\n }\n let rejection: MutationRejectedError | null = null;\n for (const result of results) {\n if (\n result.status !== 'rejected' ||\n !(result.reason instanceof MutationRejectedError)\n ) {\n return null;\n }\n rejection ??= result.reason;\n }\n return rejection;\n}\n"]}
1
+ {"version":3,"file":"MfaRecoveryController.js","sourceRoot":"","sources":["../src/MfaRecoveryController.ts"],"names":[],"mappings":"AAKA,OAA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C;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 } 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 MIN_IDENTIFIERS,\n requestKeyBoundIdentifierToken,\n} from './identifier-auth.js';\nimport type { AuthorizedEscrow } 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 { assertAbortAllowed, getRecoveryPhase } from './state-machine.js';\nimport type {\n Identifier,\n IdentifierSession,\n Mutation,\n MutationPayload,\n MutationReceipt,\n PendingOperation,\n PendingOperationEncryptor,\n PendingRegisterPayload,\n PendingUpdateIdentifiersPayload,\n PendingUpdateRecoverySecretPayload,\n RecoveryAuthProvider,\n RecoveryEscrowProvider,\n RecoveryIdentifierAuthProvider,\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 '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.#assertKnownIdentifierTypes(identifiers);\n this.#assertMinIdentifiers(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.#assertKnownIdentifierTypes([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.#assertKnownIdentifierTypes([identifier, ...identifiers]);\n this.#assertMinIdentifiers(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.#assertKnownIdentifierTypes([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.#assertKnownIdentifierTypes([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 credential: session,\n });\n const results = await Promise.allSettled(\n authorizedEscrows.map(async ({ escrow, authorization }) => {\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 * Completes a persisted pending mutation, if any.\n */\n async resume(): Promise<void> {\n await this.#withLock(async () => {\n await this.#repairPendingMutation();\n });\n }\n\n /**\n * Drops `authorizing` pending. `writing` must be finished with {@link resume}.\n */\n async abort(): Promise<void> {\n await this.#withLock(async () => {\n const pending = await this.#loadPending();\n assertAbortAllowed(pending);\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 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\n await this.#replicateMutation(pending);\n }\n\n async #replicateMutation(pending: WritingPendingOperation): Promise<void> {\n const { mutation, identifier } = 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 authorizedEscrows =\n mutation.operation === 'register'\n ? null\n : await this.#authorizeEscrows({\n escrows: remainingEscrows,\n identifier: identifier as Identifier,\n requestHash: mutation.requestHash,\n });\n if (\n authorizedEscrows !== null &&\n authorizedEscrows.length !== remainingEscrows.length\n ) {\n throw new MfaRecoveryError(\n 'Unable to authorize every escrow',\n 'identifier_auth_failed',\n );\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 authorizedEscrows?.[index]?.authorization ?? null,\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 async #authorizeEscrows({\n escrows,\n identifier,\n requestHash,\n }: {\n escrows: RecoveryEscrowProvider[];\n identifier: Identifier;\n requestHash: string;\n }): Promise<AuthorizedEscrow[]> {\n getIdentifierAuthMode(identifier.type);\n const credential = await requestKeyBoundIdentifierToken({\n identifier,\n requestHash,\n identifierAuthProvider: this.#identifierAuthProvider,\n });\n return await authorizeEscrowsWithToken({ escrows, credential });\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 #assertKnownIdentifierTypes(identifiers: Identifier[]): void {\n for (const identifier of identifiers) {\n getIdentifierAuthMode(identifier.type);\n }\n }\n\n #assertMinIdentifiers(identifiers: Identifier[]): void {\n if (countDistinctIdentifiers(identifiers) < MIN_IDENTIFIERS) {\n throw new MfaRecoveryError(\n `Requires at least ${MIN_IDENTIFIERS} identifiers`,\n 'too_few_identifiers',\n );\n }\n }\n\n async #wrapRecoverySecret(\n plaintext: Uint8Array,\n wrapPublicKey: Uint8Array,\n ): Promise<WrappedSecret> {\n const ephemeral = await generateWrapKey();\n return {\n pkE: ephemeral.publicKey,\n ciphertext: await encryptToPublic(\n ephemeral.privateKey,\n wrapPublicKey,\n plaintext,\n ),\n };\n }\n\n async #loadPending(): Promise<PendingOperation | null> {\n const { pendingOperation } = this.state;\n if (pendingOperation === null) {\n return null;\n }\n const pending = (await this.#encryptor.decrypt(\n pendingOperation,\n )) as unknown;\n await this.#assertPending(pending);\n return pending as PendingOperation;\n }\n\n async #persistPending(operation: PendingOperation): Promise<void> {\n await this.#assertPending(operation);\n const encrypted = await this.#encryptor.encrypt(operation);\n this.update((state) => {\n state.pendingOperation = encrypted;\n });\n }\n\n async #assertPending(pending: unknown): Promise<void> {\n await assertValidPendingOperation(\n pending,\n this.#escrows.map((escrow) => escrow.id),\n );\n }\n\n async #clearPending(): Promise<void> {\n this.update((state) => {\n state.pendingOperation = null;\n });\n }\n\n async #withLock<ReturnValue>(\n fn: () => Promise<ReturnValue>,\n ): Promise<ReturnValue> {\n const run = this.#lock.then(fn, fn);\n this.#lock = run.then(\n () => undefined,\n () => undefined,\n );\n return await run;\n }\n}\n\n/**\n * Every remaining escrow refused the mutation, and none has a receipt.\n *\n * @param results - Settled apply results for the remaining escrows.\n * @param existingReceipts - Receipts already stored for this mutation.\n * @returns The first refusal, or `null` when the write may have been applied.\n */\nfunction unanimousMutationRejection(\n results: PromiseSettledResult<MutationReceipt>[],\n existingReceipts: MutationReceipt[],\n): MutationRejectedError | null {\n if (existingReceipts.length > 0 || results.length === 0) {\n return null;\n }\n let rejection: MutationRejectedError | null = null;\n for (const result of results) {\n if (\n result.status !== 'rejected' ||\n !(result.reason instanceof MutationRejectedError)\n ) {\n return null;\n }\n rejection ??= result.reason;\n }\n return rejection;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { Identifier, IdentifierAuthMode, IdentifierAuthorization, KeyBoundCredential, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, SeedlessAuthConnection, SeedlessAuthData } from './types.js';
1
+ import type { Identifier, IdentifierAuthMode, IdentifierAuthorization, KeyBoundCredential, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider } from './types.js';
2
2
  /**
3
3
  * Minimum identifier count for register and updateIdentifiers.
4
4
  */
@@ -23,44 +23,20 @@ export type AuthorizedEscrow = {
23
23
  authorization: IdentifierAuthorization;
24
24
  };
25
25
  /**
26
- * Requests a key-bound identifier credential (and optional seedless auth data)
27
- * from one provider call.
28
- *
29
- * Prefers `getKeyBoundIdentifierLogin` when the provider implements it so a
30
- * social login can return seedless auth-server tokens beside the recovery
31
- * token. Otherwise falls back to `getKeyBoundIdentifierToken` (passkey / SIWE /
32
- * providers that do not return seedless data).
33
- *
34
- * `seedlessAuthData` is always optional on the success path — passkey logins
35
- * typically omit it. Set `requireSeedlessAuthData` only for the seedless
36
- * password-unlock path that must have a complete seedless token set.
26
+ * Requests a key-bound identifier token and returns the private key used to
27
+ * prove possession of it.
37
28
  *
38
29
  * @param params - Identifier authorization parameters.
39
30
  * @param params.identifier - Identifier to authenticate.
40
31
  * @param params.requestHash - Request hash bound to the authorization.
41
32
  * @param params.identifierAuthProvider - Provider for key-bound assertions.
42
- * @param params.requireSeedlessAuthData - When true, fail unless complete
43
- * seedless auth data (including `revokeToken`) is returned.
44
- * @returns Key-bound credential and optional seedless auth data.
45
- * @throws If the returned token is not bound to this identifier and request,
46
- * or seedless auth data is required but missing / incomplete.
33
+ * @returns Key-bound identifier token and its proof private key.
47
34
  */
48
- export declare function requestKeyBoundIdentifierToken({ identifier, requestHash, identifierAuthProvider, requireSeedlessAuthData, }: {
35
+ export declare function requestKeyBoundIdentifierToken({ identifier, requestHash, identifierAuthProvider, }: {
49
36
  identifier: Identifier;
50
37
  requestHash: string;
51
38
  identifierAuthProvider: RecoveryIdentifierAuthProvider;
52
- requireSeedlessAuthData?: boolean;
53
- }): Promise<KeyBoundCredential & {
54
- seedlessAuthData?: SeedlessAuthData;
55
- }>;
56
- /**
57
- * Expected seedless `authConnection` for a social identifier, if known.
58
- *
59
- * @param identifier - Authenticated identifier.
60
- * @returns Matching connection, or `undefined` when the identifier is not a
61
- * known social issuer.
62
- */
63
- export declare function expectedSeedlessAuthConnection(identifier: Identifier): SeedlessAuthConnection | undefined;
39
+ }): Promise<KeyBoundCredential>;
64
40
  /**
65
41
  * Presents a key-bound credential to each escrow that provides a challenge.
66
42
  *
@@ -1 +1 @@
1
- {"version":3,"file":"identifier-auth.d.ts","sourceRoot":"","sources":["../src/identifier-auth.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EACV,UAAU,EACV,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAGlB,sBAAsB,EACtB,8BAA8B,EAC9B,sBAAsB,EACtB,gBAAgB,EACjB,MAAM,YAAY,CAAC;AAEpB;;GAEG;AACH,eAAO,MAAM,eAAe,IAAI,CAAC;AAEjC;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,UAAU,EAAE,GAAG,MAAM,CAM1E;AAED;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAIpE,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,MAAM,EAAE,sBAAsB,CAAC;IAC/B,aAAa,EAAE,uBAAuB,CAAC;CACxC,CAAC;AAiBF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAsB,8BAA8B,CAAC,EACnD,UAAU,EACV,WAAW,EACX,sBAAsB,EACtB,uBAA+B,GAChC,EAAE;IACD,UAAU,EAAE,UAAU,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,sBAAsB,EAAE,8BAA8B,CA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C;IACpB,sBAAsB,EAAE,8BAA8B,CAAC;CACxD,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAQ9B;AAED;;;;;;;GAOG;AACH,wBAAsB,yBAAyB,CAAC,EAC9C,OAAO,EACP,UAAU,GACX,EAAE;IACD,OAAO,EAAE,sBAAsB,EAAE,CAAC;IAClC,UAAU,EAAE,kBAAkB,CAAC;CAChC,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CA8B9B;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,CAStE"}
@@ -1,9 +1,6 @@
1
- import { array, enums, is, optional, size, string, type as structType, } from '@metamask/superstruct';
2
- import { areUint8ArraysEqual } from '@metamask/utils';
3
1
  import { generateSigningKey, hash, sign } from './crypto.js';
4
2
  import { MfaRecoveryError } from './errors.js';
5
3
  import { isFulfilledResult } from './escrow-utils.js';
6
- import { SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE, SEEDLESS_AUTH_CONNECTIONS, } from './types.js';
7
4
  /**
8
5
  * Minimum identifier count for register and updateIdentifiers.
9
6
  */
@@ -29,192 +26,25 @@ export const IDENTIFIER_AUTH_MODES = {
29
26
  passkey: 'key-bound',
30
27
  siwe: 'key-bound',
31
28
  };
32
- const NonEmptyStringStruct = size(string(), 1, Infinity);
33
- const SeedlessAuthDataStruct = structType({
34
- idTokens: size(array(NonEmptyStringStruct), 1, Infinity),
35
- accessToken: NonEmptyStringStruct,
36
- metadataAccessToken: NonEmptyStringStruct,
37
- refreshToken: NonEmptyStringStruct,
38
- revokeToken: optional(NonEmptyStringStruct),
39
- authConnection: enums([...SEEDLESS_AUTH_CONNECTIONS]),
40
- authConnectionId: NonEmptyStringStruct,
41
- groupedAuthConnectionId: optional(string()),
42
- userId: NonEmptyStringStruct,
43
- socialLoginEmail: optional(string()),
44
- });
45
29
  /**
46
- * Requests a key-bound identifier credential (and optional seedless auth data)
47
- * from one provider call.
48
- *
49
- * Prefers `getKeyBoundIdentifierLogin` when the provider implements it so a
50
- * social login can return seedless auth-server tokens beside the recovery
51
- * token. Otherwise falls back to `getKeyBoundIdentifierToken` (passkey / SIWE /
52
- * providers that do not return seedless data).
53
- *
54
- * `seedlessAuthData` is always optional on the success path — passkey logins
55
- * typically omit it. Set `requireSeedlessAuthData` only for the seedless
56
- * password-unlock path that must have a complete seedless token set.
30
+ * Requests a key-bound identifier token and returns the private key used to
31
+ * prove possession of it.
57
32
  *
58
33
  * @param params - Identifier authorization parameters.
59
34
  * @param params.identifier - Identifier to authenticate.
60
35
  * @param params.requestHash - Request hash bound to the authorization.
61
36
  * @param params.identifierAuthProvider - Provider for key-bound assertions.
62
- * @param params.requireSeedlessAuthData - When true, fail unless complete
63
- * seedless auth data (including `revokeToken`) is returned.
64
- * @returns Key-bound credential and optional seedless auth data.
65
- * @throws If the returned token is not bound to this identifier and request,
66
- * or seedless auth data is required but missing / incomplete.
37
+ * @returns Key-bound identifier token and its proof private key.
67
38
  */
68
- export async function requestKeyBoundIdentifierToken({ identifier, requestHash, identifierAuthProvider, requireSeedlessAuthData = false, }) {
39
+ export async function requestKeyBoundIdentifierToken({ identifier, requestHash, identifierAuthProvider, }) {
69
40
  const proofKey = await generateSigningKey();
70
- if (identifierAuthProvider.getKeyBoundIdentifierLogin !== undefined) {
71
- const login = await identifierAuthProvider.getKeyBoundIdentifierLogin({
72
- identifier,
73
- proofPublicKey: proofKey.publicKey,
74
- requestHash,
75
- });
76
- const token = login?.token;
77
- if (!login ||
78
- !isTokenBoundToRequest(token, identifier, proofKey.publicKey, requestHash)) {
79
- throwInvalidIdentifierToken();
80
- }
81
- const credential = { token, proofPrivateKey: proofKey.privateKey };
82
- if (login.seedlessAuthData === undefined) {
83
- if (requireSeedlessAuthData) {
84
- throwMissingSeedlessAuthData();
85
- }
86
- return credential;
87
- }
88
- return {
89
- ...credential,
90
- seedlessAuthData: validateSeedlessAuthData(login.seedlessAuthData, {
91
- identifier,
92
- requireRevokeToken: requireSeedlessAuthData,
93
- }),
94
- };
95
- }
96
- if (requireSeedlessAuthData) {
97
- throwMissingSeedlessAuthData();
98
- }
99
41
  const token = await identifierAuthProvider.getKeyBoundIdentifierToken({
100
42
  identifier,
101
43
  proofPublicKey: proofKey.publicKey,
102
44
  requestHash,
103
45
  });
104
- if (!isTokenBoundToRequest(token, identifier, proofKey.publicKey, requestHash)) {
105
- throwInvalidIdentifierToken();
106
- }
107
46
  return { token, proofPrivateKey: proofKey.privateKey };
108
47
  }
109
- /**
110
- * @param token - Token returned by the identifier provider.
111
- * @param identifier - Identifier the provider was asked to authenticate.
112
- * @param proofPublicKey - Proof public key sent to the provider.
113
- * @param requestHash - Request hash sent to the provider.
114
- * @returns Whether the token is bound to the identifier, proof key, and request.
115
- */
116
- function isTokenBoundToRequest(token, identifier, proofPublicKey, requestHash) {
117
- if (typeof token !== 'object' || token === null) {
118
- return false;
119
- }
120
- const candidate = token;
121
- return (candidate.requestHash === requestHash &&
122
- candidate.proofPublicKey instanceof Uint8Array &&
123
- areUint8ArraysEqual(candidate.proofPublicKey, proofPublicKey) &&
124
- isTokenIdentifierBoundToRequest(candidate.identifier, identifier));
125
- }
126
- /**
127
- * Whether the token's identifier is bound to the requested identifier.
128
- *
129
- * Type and namespace must always match. Value must match when the request
130
- * already knows the subject. An empty request `value` is allowed for password
131
- * unlock: mobile discovers the IdP `sub` from the provider ID token and writes
132
- * it onto the returned token (see metamask-mobile OIDC identifier provider).
133
- *
134
- * @param tokenIdentifier - Identifier from the token, if any.
135
- * @param requested - Identifier requested by the controller.
136
- * @returns Whether the token identifier is acceptable for this request.
137
- */
138
- function isTokenIdentifierBoundToRequest(tokenIdentifier, requested) {
139
- if (tokenIdentifier === undefined ||
140
- tokenIdentifier.type !== requested.type ||
141
- tokenIdentifier.namespace !== requested.namespace) {
142
- return false;
143
- }
144
- if (requested.value === '') {
145
- return tokenIdentifier.value.length > 0;
146
- }
147
- return tokenIdentifier.value === requested.value;
148
- }
149
- /**
150
- * Expected seedless `authConnection` for a social identifier, if known.
151
- *
152
- * @param identifier - Authenticated identifier.
153
- * @returns Matching connection, or `undefined` when the identifier is not a
154
- * known social issuer.
155
- */
156
- export function expectedSeedlessAuthConnection(identifier) {
157
- if (identifier.type !== 'social') {
158
- return undefined;
159
- }
160
- return SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE[identifier.namespace];
161
- }
162
- /**
163
- * Validates seedless auth data shape, strips unknown fields, and ensures it
164
- * belongs to the authenticated social identifier.
165
- *
166
- * @param data - Provider-returned seedless auth data.
167
- * @param options - Validation options.
168
- * @param options.identifier - Identifier that was authenticated.
169
- * @param options.requireRevokeToken - Whether `revokeToken` must be present
170
- * (password unlock path).
171
- * @returns Documented seedless auth data fields only.
172
- */
173
- function validateSeedlessAuthData(data, { identifier, requireRevokeToken, }) {
174
- if (!is(data, SeedlessAuthDataStruct)) {
175
- throw new MfaRecoveryError('Incomplete seedless auth data', 'invalid_seedless_auth_data');
176
- }
177
- if (requireRevokeToken &&
178
- (data.revokeToken === undefined || data.revokeToken.length === 0)) {
179
- throw new MfaRecoveryError('Incomplete seedless auth data', 'invalid_seedless_auth_data');
180
- }
181
- const expectedConnection = expectedSeedlessAuthConnection(identifier);
182
- if (expectedConnection === undefined ||
183
- data.authConnection !== expectedConnection) {
184
- throw new MfaRecoveryError('Seedless auth data does not match the authenticated identifier', 'invalid_seedless_auth_data');
185
- }
186
- return pickSeedlessAuthData(data);
187
- }
188
- /**
189
- * Copies only the documented fields, so extra provider fields (for example
190
- * `skipLock`) cannot reach `SeedlessOnboardingController.authenticate`.
191
- *
192
- * @param data - Validated seedless auth data.
193
- * @returns Seedless auth data with only documented fields.
194
- */
195
- function pickSeedlessAuthData(data) {
196
- const { idTokens, accessToken, metadataAccessToken, refreshToken, revokeToken, authConnection, authConnectionId, groupedAuthConnectionId, userId, socialLoginEmail, } = data;
197
- return {
198
- idTokens: [...idTokens],
199
- accessToken,
200
- metadataAccessToken,
201
- refreshToken,
202
- authConnection,
203
- authConnectionId,
204
- userId,
205
- ...(revokeToken === undefined ? {} : { revokeToken }),
206
- ...(groupedAuthConnectionId === undefined
207
- ? {}
208
- : { groupedAuthConnectionId }),
209
- ...(socialLoginEmail === undefined ? {} : { socialLoginEmail }),
210
- };
211
- }
212
- function throwMissingSeedlessAuthData() {
213
- throw new MfaRecoveryError('Identifier login did not return seedless auth data', 'missing_seedless_auth_data');
214
- }
215
- function throwInvalidIdentifierToken() {
216
- throw new MfaRecoveryError('Identifier token is not bound to this request', 'invalid_identifier_token');
217
- }
218
48
  /**
219
49
  * Presents a key-bound credential to each escrow that provides a challenge.
220
50
  *
@@ -1 +1 @@
1
- {"version":3,"file":"identifier-auth.js","sourceRoot":"","sources":["../src/identifier-auth.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,KAAK,EACL,EAAE,EACF,QAAQ,EACR,IAAI,EACJ,MAAM,EACN,IAAI,IAAI,UAAU,GACnB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEtD,OAAO,EAAE,kBAAkB,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EACL,qCAAqC,EACrC,yBAAyB,GAC1B,MAAM,YAAY,CAAC;AAcpB;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAC;AAEjC;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CAAC,WAAyB;IAChE,OAAO,IAAI,GAAG,CACZ,WAAW,CAAC,GAAG,CACb,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,GAAG,IAAI,KAAK,SAAS,KAAK,KAAK,EAAE,CAClE,CACF,CAAC,IAAI,CAAC;AACT,CAAC;AAED;;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AMG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,MAAM,IAAI,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;IACzC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,MAAM,IAAI,gBAAgB,CACxB,4BAA4B,IAAI,EAAE,EAClC,yBAAyB,CAC1B,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import {\n array,\n enums,\n is,\n optional,\n size,\n string,\n type as structType,\n} from '@metamask/superstruct';\nimport { areUint8ArraysEqual } from '@metamask/utils';\n\nimport { generateSigningKey, hash, sign } from './crypto.js';\nimport { MfaRecoveryError } from './errors.js';\nimport { isFulfilledResult } from './escrow-utils.js';\nimport {\n SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE,\n SEEDLESS_AUTH_CONNECTIONS,\n} from './types.js';\nimport type {\n Identifier,\n IdentifierAuthMode,\n IdentifierAuthorization,\n KeyBoundCredential,\n KeyBoundIdentifierLogin,\n KeyBoundIdentifierToken,\n RecoveryEscrowProvider,\n RecoveryIdentifierAuthProvider,\n SeedlessAuthConnection,\n SeedlessAuthData,\n} from './types.js';\n\n/**\n * Minimum identifier count for register and updateIdentifiers.\n */\nexport const MIN_IDENTIFIERS = 2;\n\n/**\n * Distinct identifier identities (`type` + `namespace` + `value`).\n *\n * @param identifiers - Identifier list.\n * @returns Distinct identity count.\n */\nexport function countDistinctIdentifiers(identifiers: Identifier[]): number {\n return new Set(\n identifiers.map(\n ({ type, namespace, value }) => `${type}\\0${namespace}\\0${value}`,\n ),\n ).size;\n}\n\n/**\n * Trusted identifier-type registry. Escrows and the controller derive the\n * authentication mode from this table, never from a client-selected flag.\n *\n * TODO: MFA-605 / MFA-606 / MFA-568 — add `emailOtp` / `smsOtp` as\n * `escrow-challenge` once escrow OTP commands exist.\n */\nexport const IDENTIFIER_AUTH_MODES: Record<string, IdentifierAuthMode> = {\n social: 'key-bound',\n passkey: 'key-bound',\n siwe: 'key-bound',\n};\n\nexport type AuthorizedEscrow = {\n escrow: RecoveryEscrowProvider;\n authorization: IdentifierAuthorization;\n};\n\nconst NonEmptyStringStruct = size(string(), 1, Infinity);\n\nconst SeedlessAuthDataStruct = structType({\n idTokens: size(array(NonEmptyStringStruct), 1, Infinity),\n accessToken: NonEmptyStringStruct,\n metadataAccessToken: NonEmptyStringStruct,\n refreshToken: NonEmptyStringStruct,\n revokeToken: optional(NonEmptyStringStruct),\n authConnection: enums([...SEEDLESS_AUTH_CONNECTIONS]),\n authConnectionId: NonEmptyStringStruct,\n groupedAuthConnectionId: optional(string()),\n userId: NonEmptyStringStruct,\n socialLoginEmail: optional(string()),\n});\n\n/**\n * Requests a key-bound identifier credential (and optional seedless auth data)\n * from one provider call.\n *\n * Prefers `getKeyBoundIdentifierLogin` when the provider implements it so a\n * social login can return seedless auth-server tokens beside the recovery\n * token. Otherwise falls back to `getKeyBoundIdentifierToken` (passkey / SIWE /\n * providers that do not return seedless data).\n *\n * `seedlessAuthData` is always optional on the success path — passkey logins\n * typically omit it. Set `requireSeedlessAuthData` only for the seedless\n * password-unlock path that must have a complete seedless token set.\n *\n * @param params - Identifier authorization parameters.\n * @param params.identifier - Identifier to authenticate.\n * @param params.requestHash - Request hash bound to the authorization.\n * @param params.identifierAuthProvider - Provider for key-bound assertions.\n * @param params.requireSeedlessAuthData - When true, fail unless complete\n * seedless auth data (including `revokeToken`) is returned.\n * @returns Key-bound credential and optional seedless auth data.\n * @throws If the returned token is not bound to this identifier and request,\n * or seedless auth data is required but missing / incomplete.\n */\nexport async function requestKeyBoundIdentifierToken({\n identifier,\n requestHash,\n identifierAuthProvider,\n requireSeedlessAuthData = false,\n}: {\n identifier: Identifier;\n requestHash: string;\n identifierAuthProvider: RecoveryIdentifierAuthProvider;\n requireSeedlessAuthData?: boolean;\n}): Promise<KeyBoundCredential & { seedlessAuthData?: SeedlessAuthData }> {\n const proofKey = await generateSigningKey();\n\n if (identifierAuthProvider.getKeyBoundIdentifierLogin !== undefined) {\n const login: Partial<KeyBoundIdentifierLogin> | null | undefined =\n await identifierAuthProvider.getKeyBoundIdentifierLogin({\n identifier,\n proofPublicKey: proofKey.publicKey,\n requestHash,\n });\n const token: unknown = login?.token;\n if (\n !login ||\n !isTokenBoundToRequest(token, identifier, proofKey.publicKey, requestHash)\n ) {\n throwInvalidIdentifierToken();\n }\n const credential = { token, proofPrivateKey: proofKey.privateKey };\n\n if (login.seedlessAuthData === undefined) {\n if (requireSeedlessAuthData) {\n throwMissingSeedlessAuthData();\n }\n return credential;\n }\n return {\n ...credential,\n seedlessAuthData: validateSeedlessAuthData(login.seedlessAuthData, {\n identifier,\n requireRevokeToken: requireSeedlessAuthData,\n }),\n };\n }\n\n if (requireSeedlessAuthData) {\n throwMissingSeedlessAuthData();\n }\n\n const token = await identifierAuthProvider.getKeyBoundIdentifierToken({\n identifier,\n proofPublicKey: proofKey.publicKey,\n requestHash,\n });\n if (\n !isTokenBoundToRequest(token, identifier, proofKey.publicKey, requestHash)\n ) {\n throwInvalidIdentifierToken();\n }\n return { token, proofPrivateKey: proofKey.privateKey };\n}\n\n/**\n * @param token - Token returned by the identifier provider.\n * @param identifier - Identifier the provider was asked to authenticate.\n * @param proofPublicKey - Proof public key sent to the provider.\n * @param requestHash - Request hash sent to the provider.\n * @returns Whether the token is bound to the identifier, proof key, and request.\n */\nfunction isTokenBoundToRequest(\n token: unknown,\n identifier: Identifier,\n proofPublicKey: Uint8Array,\n requestHash: string,\n): token is KeyBoundIdentifierToken {\n if (typeof token !== 'object' || token === null) {\n return false;\n }\n const candidate = token as Partial<KeyBoundIdentifierToken>;\n return (\n candidate.requestHash === requestHash &&\n candidate.proofPublicKey instanceof Uint8Array &&\n areUint8ArraysEqual(candidate.proofPublicKey, proofPublicKey) &&\n isTokenIdentifierBoundToRequest(candidate.identifier, identifier)\n );\n}\n\n/**\n * Whether the token's identifier is bound to the requested identifier.\n *\n * Type and namespace must always match. Value must match when the request\n * already knows the subject. An empty request `value` is allowed for password\n * unlock: mobile discovers the IdP `sub` from the provider ID token and writes\n * it onto the returned token (see metamask-mobile OIDC identifier provider).\n *\n * @param tokenIdentifier - Identifier from the token, if any.\n * @param requested - Identifier requested by the controller.\n * @returns Whether the token identifier is acceptable for this request.\n */\nfunction isTokenIdentifierBoundToRequest(\n tokenIdentifier: Identifier | undefined,\n requested: Identifier,\n): boolean {\n if (\n tokenIdentifier === undefined ||\n tokenIdentifier.type !== requested.type ||\n tokenIdentifier.namespace !== requested.namespace\n ) {\n return false;\n }\n if (requested.value === '') {\n return tokenIdentifier.value.length > 0;\n }\n return tokenIdentifier.value === requested.value;\n}\n\n/**\n * Expected seedless `authConnection` for a social identifier, if known.\n *\n * @param identifier - Authenticated identifier.\n * @returns Matching connection, or `undefined` when the identifier is not a\n * known social issuer.\n */\nexport function expectedSeedlessAuthConnection(\n identifier: Identifier,\n): SeedlessAuthConnection | undefined {\n if (identifier.type !== 'social') {\n return undefined;\n }\n return SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE[identifier.namespace];\n}\n\n/**\n * Validates seedless auth data shape, strips unknown fields, and ensures it\n * belongs to the authenticated social identifier.\n *\n * @param data - Provider-returned seedless auth data.\n * @param options - Validation options.\n * @param options.identifier - Identifier that was authenticated.\n * @param options.requireRevokeToken - Whether `revokeToken` must be present\n * (password unlock path).\n * @returns Documented seedless auth data fields only.\n */\nfunction validateSeedlessAuthData(\n data: unknown,\n {\n identifier,\n requireRevokeToken,\n }: {\n identifier: Identifier;\n requireRevokeToken: boolean;\n },\n): SeedlessAuthData {\n if (!is(data, SeedlessAuthDataStruct)) {\n throw new MfaRecoveryError(\n 'Incomplete seedless auth data',\n 'invalid_seedless_auth_data',\n );\n }\n if (\n requireRevokeToken &&\n (data.revokeToken === undefined || data.revokeToken.length === 0)\n ) {\n throw new MfaRecoveryError(\n 'Incomplete seedless auth data',\n 'invalid_seedless_auth_data',\n );\n }\n const expectedConnection = expectedSeedlessAuthConnection(identifier);\n if (\n expectedConnection === undefined ||\n data.authConnection !== expectedConnection\n ) {\n throw new MfaRecoveryError(\n 'Seedless auth data does not match the authenticated identifier',\n 'invalid_seedless_auth_data',\n );\n }\n return pickSeedlessAuthData(data);\n}\n\n/**\n * Copies only the documented fields, so extra provider fields (for example\n * `skipLock`) cannot reach `SeedlessOnboardingController.authenticate`.\n *\n * @param data - Validated seedless auth data.\n * @returns Seedless auth data with only documented fields.\n */\nfunction pickSeedlessAuthData(data: SeedlessAuthData): SeedlessAuthData {\n const {\n idTokens,\n accessToken,\n metadataAccessToken,\n refreshToken,\n revokeToken,\n authConnection,\n authConnectionId,\n groupedAuthConnectionId,\n userId,\n socialLoginEmail,\n } = data;\n return {\n idTokens: [...idTokens],\n accessToken,\n metadataAccessToken,\n refreshToken,\n authConnection,\n authConnectionId,\n userId,\n ...(revokeToken === undefined ? {} : { revokeToken }),\n ...(groupedAuthConnectionId === undefined\n ? {}\n : { groupedAuthConnectionId }),\n ...(socialLoginEmail === undefined ? {} : { socialLoginEmail }),\n };\n}\n\nfunction throwMissingSeedlessAuthData(): never {\n throw new MfaRecoveryError(\n 'Identifier login did not return seedless auth data',\n 'missing_seedless_auth_data',\n );\n}\n\nfunction throwInvalidIdentifierToken(): never {\n throw new MfaRecoveryError(\n 'Identifier token is not bound to this request',\n 'invalid_identifier_token',\n );\n}\n\n/**\n * Presents a key-bound credential to each escrow that provides a challenge.\n *\n * @param params - Escrow authorization parameters.\n * @param params.escrows - Escrows to authorize.\n * @param params.credential - Key-bound identifier credential.\n * @returns Successful escrow authorizations.\n */\nexport async function authorizeEscrowsWithToken({\n escrows,\n credential,\n}: {\n escrows: RecoveryEscrowProvider[];\n credential: KeyBoundCredential;\n}): Promise<AuthorizedEscrow[]> {\n const { token, proofPrivateKey } = credential;\n const challengeResults = await Promise.allSettled(\n escrows.map((escrow) => escrow.generateChallenge()),\n );\n const challenges = challengeResults.flatMap((result, index) =>\n isFulfilledResult(result)\n ? [{ escrow: escrows[index], challenge: result.value }]\n : [],\n );\n const authorizationResults = await Promise.allSettled(\n challenges.map(async ({ escrow, challenge }) => {\n const message = await hash([token, challenge.id, token.requestHash]);\n return {\n escrow,\n authorization: {\n kind: 'key-bound' as const,\n token,\n proof: {\n challengeId: challenge.id,\n requestHash: token.requestHash,\n signature: await sign(proofPrivateKey, message),\n },\n },\n };\n }),\n );\n return authorizationResults\n .filter(isFulfilledResult)\n .map((result) => result.value);\n}\n\n/**\n * Returns the auth mode for an identifier type.\n *\n * @param type - Identifier type.\n * @returns Auth mode.\n * @throws If the type is not in the trusted registry.\n */\nexport function getIdentifierAuthMode(type: string): IdentifierAuthMode {\n const mode = IDENTIFIER_AUTH_MODES[type];\n if (mode === undefined) {\n throw new MfaRecoveryError(\n `Unknown identifier type: ${type}`,\n 'unknown_identifier_type',\n );\n }\n return mode;\n}\n"]}
1
+ {"version":3,"file":"identifier-auth.js","sourceRoot":"","sources":["../src/identifier-auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAUtD;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAC;AAEjC;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CAAC,WAAyB;IAChE,OAAO,IAAI,GAAG,CACZ,WAAW,CAAC,GAAG,CACb,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,GAAG,IAAI,KAAK,SAAS,KAAK,KAAK,EAAE,CAClE,CACF,CAAC,IAAI,CAAC;AACT,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAuC;IACvE,MAAM,EAAE,WAAW;IACnB,OAAO,EAAE,WAAW;IACpB,IAAI,EAAE,WAAW;CAClB,CAAC;AAOF;;;;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Aa,EAAE;gBACb,IAAI,EAAE,WAAoB;gBAC1B,KAAK;gBACL,KAAK,EAAE;oBACL,WAAW,EAAE,SAAS,CAAC,EAAE;oBACzB,WAAW,EAAE,KAAK,CAAC,WAAW;oBAC9B,SAAS,EAAE,MAAM,IAAI,CAAC,eAAe,EAAE,OAAO,CAAC;iBAChD;aACF;SACF,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;IACF,OAAO,oBAAoB;SACxB,MAAM,CAAC,iBAAiB,CAAC;SACzB,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACnC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,MAAM,IAAI,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;IACzC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,MAAM,IAAI,gBAAgB,CACxB,4BAA4B,IAAI,EAAE,EAClC,yBAAyB,CAC1B,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { generateSigningKey, hash, sign } from './crypto.js';\nimport { MfaRecoveryError } from './errors.js';\nimport { isFulfilledResult } from './escrow-utils.js';\nimport type {\n Identifier,\n IdentifierAuthMode,\n IdentifierAuthorization,\n KeyBoundCredential,\n RecoveryEscrowProvider,\n RecoveryIdentifierAuthProvider,\n} from './types.js';\n\n/**\n * Minimum identifier count for register and updateIdentifiers.\n */\nexport const MIN_IDENTIFIERS = 2;\n\n/**\n * Distinct identifier identities (`type` + `namespace` + `value`).\n *\n * @param identifiers - Identifier list.\n * @returns Distinct identity count.\n */\nexport function countDistinctIdentifiers(identifiers: Identifier[]): number {\n return new Set(\n identifiers.map(\n ({ type, namespace, value }) => `${type}\\0${namespace}\\0${value}`,\n ),\n ).size;\n}\n\n/**\n * Trusted identifier-type registry. Escrows and the controller derive the\n * authentication mode from this table, never from a client-selected flag.\n *\n * TODO: MFA-605 / MFA-606 / MFA-568 — add `emailOtp` / `smsOtp` as\n * `escrow-challenge` once escrow OTP commands exist.\n */\nexport const IDENTIFIER_AUTH_MODES: Record<string, IdentifierAuthMode> = {\n social: 'key-bound',\n passkey: 'key-bound',\n siwe: 'key-bound',\n};\n\nexport type AuthorizedEscrow = {\n escrow: RecoveryEscrowProvider;\n authorization: IdentifierAuthorization;\n};\n\n/**\n * Requests a key-bound identifier token and returns the private key used to\n * prove possession of it.\n *\n * @param params - Identifier authorization parameters.\n * @param params.identifier - Identifier to authenticate.\n * @param params.requestHash - Request hash bound to the authorization.\n * @param params.identifierAuthProvider - Provider for key-bound assertions.\n * @returns Key-bound identifier token and its proof private key.\n */\nexport async function requestKeyBoundIdentifierToken({\n identifier,\n requestHash,\n identifierAuthProvider,\n}: {\n identifier: Identifier;\n requestHash: string;\n identifierAuthProvider: RecoveryIdentifierAuthProvider;\n}): Promise<KeyBoundCredential> {\n const proofKey = await generateSigningKey();\n const token = await identifierAuthProvider.getKeyBoundIdentifierToken({\n identifier,\n proofPublicKey: proofKey.publicKey,\n requestHash,\n });\n return { token, proofPrivateKey: proofKey.privateKey };\n}\n\n/**\n * Presents a key-bound credential to each escrow that provides a challenge.\n *\n * @param params - Escrow authorization parameters.\n * @param params.escrows - Escrows to authorize.\n * @param params.credential - Key-bound identifier credential.\n * @returns Successful escrow authorizations.\n */\nexport async function authorizeEscrowsWithToken({\n escrows,\n credential,\n}: {\n escrows: RecoveryEscrowProvider[];\n credential: KeyBoundCredential;\n}): Promise<AuthorizedEscrow[]> {\n const { token, proofPrivateKey } = credential;\n const challengeResults = await Promise.allSettled(\n escrows.map((escrow) => escrow.generateChallenge()),\n );\n const challenges = challengeResults.flatMap((result, index) =>\n isFulfilledResult(result)\n ? [{ escrow: escrows[index], challenge: result.value }]\n : [],\n );\n const authorizationResults = await Promise.allSettled(\n challenges.map(async ({ escrow, challenge }) => {\n const message = await hash([token, challenge.id, token.requestHash]);\n return {\n escrow,\n authorization: {\n kind: 'key-bound' as const,\n token,\n proof: {\n challengeId: challenge.id,\n requestHash: token.requestHash,\n signature: await sign(proofPrivateKey, message),\n },\n },\n };\n }),\n );\n return authorizationResults\n .filter(isFulfilledResult)\n .map((result) => result.value);\n}\n\n/**\n * Returns the auth mode for an identifier type.\n *\n * @param type - Identifier type.\n * @returns Auth mode.\n * @throws If the type is not in the trusted registry.\n */\nexport function getIdentifierAuthMode(type: string): IdentifierAuthMode {\n const mode = IDENTIFIER_AUTH_MODES[type];\n if (mode === undefined) {\n throw new MfaRecoveryError(\n `Unknown identifier type: ${type}`,\n 'unknown_identifier_type',\n );\n }\n return mode;\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -6,7 +6,6 @@ export type { CubistEscrowProviderOptions } from './escrow-providers/cubist-escr
6
6
  export { AuthApiRecoveryAuthProvider } from './auth-api-recovery-provider.js';
7
7
  export type { AuthApiRecoveryAuthProviderMessenger, AuthApiRecoveryAuthProviderOptions, } from './auth-api-recovery-provider.js';
8
8
  export { IncompleteMutationError, MfaRecoveryError, MutationRejectedError, } from './errors.js';
9
- export { IDENTIFIER_AUTH_MODES, MIN_IDENTIFIERS, expectedSeedlessAuthConnection, getIdentifierAuthMode, } from './identifier-auth.js';
10
- export { SEEDLESS_AUTH_CONNECTIONS, SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE, } from './types.js';
11
- export type { AuthControllerToken, AuthenticateIdentifierOptions, AuthenticateIdentifierResult, EncryptedPendingOperation, Identifier, IdentifierAuthorization, IdentifierSession, KeyBoundIdentifierLogin, KeyBoundIdentifierToken, KeyBoundIdentifierTokenRequest, Mutation, MutationPayload, MutationReceipt, PendingMutationPayload, PendingOperation, PendingOperationEncryptor, PendingRecoverySecretHex, PendingRegisterPayload, PendingUpdateIdentifiersPayload, PendingUpdateRecoverySecretPayload, RecoveryApproval, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryPhase, RecoveredSecret, SeedlessAuthConnection, SeedlessAuthData, SeedlessAuthenticateIdentifierResult, WrappedSecret, WrappedSecretOutput, } from './types.js';
9
+ export { IDENTIFIER_AUTH_MODES, MIN_IDENTIFIERS, getIdentifierAuthMode, } from './identifier-auth.js';
10
+ export type { AuthControllerToken, EncryptedPendingOperation, Identifier, IdentifierAuthorization, IdentifierSession, Mutation, MutationPayload, MutationReceipt, PendingMutationPayload, PendingOperation, PendingOperationEncryptor, PendingRecoverySecretHex, PendingRegisterPayload, PendingUpdateIdentifiersPayload, PendingUpdateRecoverySecretPayload, RecoveryApproval, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryPhase, RecoveredSecret, WrappedSecret, WrappedSecretOutput, } from './types.js';
12
11
  //# sourceMappingURL=index.d.ts.map
@@ -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,mCAAmC,EACnC,4CAA4C,EAC5C,mCAAmC,EACnC,iCAAiC,EACjC,4CAA4C,EAC5C,+CAA+C,GAChD,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,8CAA8C,CAAC;AACpF,YAAY,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAChG,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAC9E,YAAY,EACV,oCAAoC,EACpC,kCAAkC,GACnC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,yBAAyB,EACzB,qCAAqC,GACtC,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,mBAAmB,EACnB,6BAA6B,EAC7B,4BAA4B,EAC5B,yBAAyB,EACzB,UAAU,EACV,uBAAuB,EACvB,iBAAiB,EACjB,uBAAuB,EACvB,uBAAuB,EACvB,8BAA8B,EAC9B,QAAQ,EACR,eAAe,EACf,eAAe,EACf,sBAAsB,EACtB,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,+BAA+B,EAC/B,kCAAkC,EAClC,gBAAgB,EAChB,oBAAoB,EACpB,sBAAsB,EACtB,8BAA8B,EAC9B,aAAa,EACb,eAAe,EACf,sBAAsB,EACtB,gBAAgB,EAChB,oCAAoC,EACpC,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,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,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,aAAa,EACb,eAAe,EACf,aAAa,EACb,mBAAmB,GACpB,MAAM,YAAY,CAAC"}
package/dist/index.js CHANGED
@@ -2,6 +2,5 @@ export { MfaRecoveryController, getDefaultMfaRecoveryControllerState, } from './
2
2
  export { CubistEscrowProvider } from './escrow-providers/cubist-escrow-provider.js';
3
3
  export { AuthApiRecoveryAuthProvider } from './auth-api-recovery-provider.js';
4
4
  export { IncompleteMutationError, MfaRecoveryError, MutationRejectedError, } from './errors.js';
5
- export { IDENTIFIER_AUTH_MODES, MIN_IDENTIFIERS, expectedSeedlessAuthConnection, getIdentifierAuthMode, } from './identifier-auth.js';
6
- export { SEEDLESS_AUTH_CONNECTIONS, SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE, } from './types.js';
5
+ export { IDENTIFIER_AUTH_MODES, MIN_IDENTIFIERS, getIdentifierAuthMode, } from './identifier-auth.js';
7
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;AAoBpC,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,8BAA8B,EAC9B,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,yBAAyB,EACzB,qCAAqC,GACtC,MAAM,YAAY,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 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 expectedSeedlessAuthConnection,\n getIdentifierAuthMode,\n} from './identifier-auth.js';\nexport {\n SEEDLESS_AUTH_CONNECTIONS,\n SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE,\n} from './types.js';\nexport type {\n AuthControllerToken,\n AuthenticateIdentifierOptions,\n AuthenticateIdentifierResult,\n EncryptedPendingOperation,\n Identifier,\n IdentifierAuthorization,\n IdentifierSession,\n KeyBoundIdentifierLogin,\n KeyBoundIdentifierToken,\n KeyBoundIdentifierTokenRequest,\n Mutation,\n MutationPayload,\n MutationReceipt,\n PendingMutationPayload,\n PendingOperation,\n PendingOperationEncryptor,\n PendingRecoverySecretHex,\n PendingRegisterPayload,\n PendingUpdateIdentifiersPayload,\n PendingUpdateRecoverySecretPayload,\n RecoveryApproval,\n RecoveryAuthProvider,\n RecoveryEscrowProvider,\n RecoveryIdentifierAuthProvider,\n RecoveryPhase,\n RecoveredSecret,\n SeedlessAuthConnection,\n SeedlessAuthData,\n SeedlessAuthenticateIdentifierResult,\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;AAoBpC,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 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 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 RecoveryPhase,\n RecoveredSecret,\n WrappedSecret,\n WrappedSecretOutput,\n} from './types.js';\n"]}
package/dist/types.d.ts CHANGED
@@ -1,23 +1,6 @@
1
1
  /**
2
2
  * MFA recovery protocol types from the recovery ADR.
3
3
  */
4
- /**
5
- * Social login providers accepted by seedless authenticate. Values match
6
- * `SeedlessOnboardingController`'s `AuthConnection` enum. Kept as a local
7
- * constant so this package does not depend on seedless-onboarding-controller
8
- * at runtime; a unit test asserts the two stay in sync.
9
- */
10
- export declare const SEEDLESS_AUTH_CONNECTIONS: readonly ['google', 'apple', 'telegram'];
11
- /**
12
- * Social login provider for {@link SeedlessAuthData}.
13
- */
14
- export type SeedlessAuthConnection = (typeof SEEDLESS_AUTH_CONNECTIONS)[number];
15
- /**
16
- * OIDC issuer namespaces for {@link Identifier} `type: 'social'`, mapped to
17
- * {@link SeedlessAuthConnection}. Used to ensure seedless auth data belongs to
18
- * the same IdP that was authenticated.
19
- */
20
- export declare const SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE: Record<string, SeedlessAuthConnection>;
21
4
  export type Identifier = {
22
5
  type: string;
23
6
  namespace: string;
@@ -98,83 +81,13 @@ export type KeyBoundCredential = {
98
81
  */
99
82
  proofPrivateKey: Uint8Array;
100
83
  };
101
- /**
102
- * Seedless auth-server tokens and social login details issued by the same
103
- * login that produced a key-bound identifier token. The fields match the
104
- * parameters of `SeedlessOnboardingController.authenticate` (without
105
- * `skipLock`), so the password unlock path can authenticate without a second
106
- * social prompt.
107
- *
108
- * These tokens come from the AAL1 social login exchange, never from an AAL2
109
- * recovery approval. They are never sent to escrows. Keep in memory only.
110
- */
111
- export type SeedlessAuthData = {
112
- /**
113
- * ID token(s) verified by the TOPRF nodes.
114
- */
115
- idTokens: string[];
116
- accessToken: string;
117
- metadataAccessToken: string;
118
- refreshToken: string;
119
- /**
120
- * Required when `authenticateIdentifier` is called with
121
- * `requireSeedlessAuthData: true` (password unlock / vault path). Optional
122
- * when seedless auth data is returned without that requirement.
123
- */
124
- revokeToken?: string;
125
- /**
126
- * Social login provider. Values match `SeedlessOnboardingController`'s
127
- * `AuthConnection` enum (`google`, `apple`, `telegram`). Must match the
128
- * authenticated social identifier's issuer namespace.
129
- */
130
- authConnection: SeedlessAuthConnection;
131
- authConnectionId: string;
132
- groupedAuthConnectionId?: string;
133
- /**
134
- * User email or id from the social login.
135
- */
136
- userId: string;
137
- socialLoginEmail?: string;
138
- };
139
- /**
140
- * Parameters for requesting a key-bound identifier token from an IdP.
141
- */
142
- export type KeyBoundIdentifierTokenRequest = {
143
- identifier: Identifier;
144
- /**
145
- * Raw 32-byte Ed25519 public key to bind into the token.
146
- */
147
- proofPublicKey: Uint8Array;
148
- requestHash: string;
149
- };
150
- /**
151
- * Result of one identifier login. `token` is the key-bound recovery material
152
- * presented to escrows (its `providerAssertion` carries the provider ID token
153
- * or assertion). `seedlessAuthData` is optional — social password-unlock may
154
- * include it from the same exchange; passkey / SIWE typically omit it.
155
- */
156
- export type KeyBoundIdentifierLogin = {
157
- token: KeyBoundIdentifierToken;
158
- seedlessAuthData?: SeedlessAuthData;
159
- };
160
- /**
161
- * Options for `MfaRecoveryController.authenticateIdentifier`.
162
- */
163
- export type AuthenticateIdentifierOptions = {
164
- /**
165
- * Fail unless the login returns complete {@link SeedlessAuthData}. Set for
166
- * the seedless password unlock path.
167
- */
168
- requireSeedlessAuthData?: boolean;
169
- };
170
84
  /**
171
85
  * Result of first-factor identifier authentication, consumed by
172
86
  * `getRecoverySecret`.
173
87
  *
174
88
  * `proofPrivateKey` signs escrow challenges. `ephemeralPrivateKey` is the
175
89
  * private half of `pkE` and decrypts the recovery secret. Keep both in
176
- * memory only. Does not carry seedless auth-server tokens — those are
177
- * returned beside the session from {@link AuthenticateIdentifierResult}.
90
+ * memory only.
178
91
  */
179
92
  export type IdentifierSession = KeyBoundCredential & {
180
93
  requestId: string;
@@ -187,23 +100,6 @@ export type IdentifierSession = KeyBoundCredential & {
187
100
  */
188
101
  pkE: Uint8Array;
189
102
  };
190
- /**
191
- * Result of `authenticateIdentifier`. `seedlessAuthData` is present when the
192
- * login also completed a seedless auth-server exchange. Callers should use it
193
- * for `SeedlessOnboardingController.authenticate` and then drop it; keep only
194
- * `session` for a later `getRecoverySecret`.
195
- */
196
- export type AuthenticateIdentifierResult = {
197
- session: IdentifierSession;
198
- seedlessAuthData?: SeedlessAuthData;
199
- };
200
- /**
201
- * `AuthenticateIdentifierResult` when seedless auth data was required.
202
- */
203
- export type SeedlessAuthenticateIdentifierResult = {
204
- session: IdentifierSession;
205
- seedlessAuthData: SeedlessAuthData;
206
- };
207
103
  /**
208
104
  * Recovery secret wrapped to one escrow wrap key for transit.
209
105
  */
@@ -319,23 +215,16 @@ export type RecoveryAuthProvider = {
319
215
  };
320
216
  /**
321
217
  * Obtains a key-bound identifier assertion from an IdP (OIDC, Passkey, SIWE).
322
- *
323
- * Implement `getKeyBoundIdentifierToken` for every provider. Optionally also
324
- * implement `getKeyBoundIdentifierLogin` when one social login should return
325
- * seedless auth-server tokens beside the recovery token; `seedlessAuthData`
326
- * on that result stays optional (passkey providers omit it).
327
218
  */
328
219
  export type RecoveryIdentifierAuthProvider = {
329
- getKeyBoundIdentifierToken: (params: KeyBoundIdentifierTokenRequest) => Promise<KeyBoundIdentifierToken>;
330
- /**
331
- * Optional. One identifier login that returns the key-bound token and, when
332
- * available, seedless auth-server tokens from the same exchange. When
333
- * present, the controller prefers this over {@link getKeyBoundIdentifierToken}.
334
- * The returned token must be bound to the requested `proofPublicKey` and
335
- * `requestHash`. Omit `seedlessAuthData` when the IdP does not issue it
336
- * (e.g. passkey).
337
- */
338
- getKeyBoundIdentifierLogin?: (params: KeyBoundIdentifierTokenRequest) => Promise<KeyBoundIdentifierLogin>;
220
+ getKeyBoundIdentifierToken: (params: {
221
+ identifier: Identifier;
222
+ /**
223
+ * Raw 32-byte Ed25519 public key to bind into the token.
224
+ */
225
+ proofPublicKey: Uint8Array;
226
+ requestHash: string;
227
+ }) => Promise<KeyBoundIdentifierToken>;
339
228
  };
340
229
  /**
341
230
  * One recovery escrow replica. Implementations may talk to different backends.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,YACpC,QAAQ,EACR,OAAO,EACP,UAAU,CACF,CAAC;AAEX;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG,CAAC,OAAO,y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CAAC,CAAC;IAC7E,OAAO,EAAE,CAAC,UAAU,EAAE,yBAAyB,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAAC;CAC/E,CAAC"}
package/dist/types.js CHANGED
@@ -1,25 +1,5 @@
1
1
  /**
2
2
  * MFA recovery protocol types from the recovery ADR.
3
3
  */
4
- /**
5
- * Social login providers accepted by seedless authenticate. Values match
6
- * `SeedlessOnboardingController`'s `AuthConnection` enum. Kept as a local
7
- * constant so this package does not depend on seedless-onboarding-controller
8
- * at runtime; a unit test asserts the two stay in sync.
9
- */
10
- export const SEEDLESS_AUTH_CONNECTIONS = [
11
- 'google',
12
- 'apple',
13
- 'telegram',
14
- ];
15
- /**
16
- * OIDC issuer namespaces for {@link Identifier} `type: 'social'`, mapped to
17
- * {@link SeedlessAuthConnection}. Used to ensure seedless auth data belongs to
18
- * the same IdP that was authenticated.
19
- */
20
- export const SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE = {
21
- 'https://accounts.google.com': 'google',
22
- 'https://appleid.apple.com': 'apple',
23
- 'https://oauth.telegram.org': 'telegram',
24
- };
4
+ export {};
25
5
  //# sourceMappingURL=types.js.map
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;GAKG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACvC,QAAQ;IACR,OAAO;IACP,UAAU;CACF,CAAC;AAOX;;;;GAIG;AACH,MAAM,CAAC,MAAM,qCAAqC,GAG9C;IACF,6BAA6B,EAAE,QAAQ;IACvC,2BAA2B,EAAE,OAAO;IACpC,4BAA4B,EAAE,UAAU;CACzC,CAAC","sourcesContent":["/**\n * MFA recovery protocol types from the recovery ADR.\n */\n\n/**\n * Social login providers accepted by seedless authenticate. Values match\n * `SeedlessOnboardingController`'s `AuthConnection` enum. Kept as a local\n * constant so this package does not depend on seedless-onboarding-controller\n * at runtime; a unit test asserts the two stay in sync.\n */\nexport const SEEDLESS_AUTH_CONNECTIONS = [\n 'google',\n 'apple',\n 'telegram',\n] as const;\n\n/**\n * Social login provider for {@link SeedlessAuthData}.\n */\nexport type SeedlessAuthConnection = (typeof SEEDLESS_AUTH_CONNECTIONS)[number];\n\n/**\n * OIDC issuer namespaces for {@link Identifier} `type: 'social'`, mapped to\n * {@link SeedlessAuthConnection}. Used to ensure seedless auth data belongs to\n * the same IdP that was authenticated.\n */\nexport const SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE: Record<\n string,\n SeedlessAuthConnection\n> = {\n 'https://accounts.google.com': 'google',\n 'https://appleid.apple.com': 'apple',\n 'https://oauth.telegram.org': 'telegram',\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 * Seedless auth-server tokens and social login details issued by the same\n * login that produced a key-bound identifier token. The fields match the\n * parameters of `SeedlessOnboardingController.authenticate` (without\n * `skipLock`), so the password unlock path can authenticate without a second\n * social prompt.\n *\n * These tokens come from the AAL1 social login exchange, never from an AAL2\n * recovery approval. They are never sent to escrows. Keep in memory only.\n */\nexport type SeedlessAuthData = {\n /**\n * ID token(s) verified by the TOPRF nodes.\n */\n idTokens: string[];\n accessToken: string;\n metadataAccessToken: string;\n refreshToken: string;\n /**\n * Required when `authenticateIdentifier` is called with\n * `requireSeedlessAuthData: true` (password unlock / vault path). Optional\n * when seedless auth data is returned without that requirement.\n */\n revokeToken?: string;\n /**\n * Social login provider. Values match `SeedlessOnboardingController`'s\n * `AuthConnection` enum (`google`, `apple`, `telegram`). Must match the\n * authenticated social identifier's issuer namespace.\n */\n authConnection: SeedlessAuthConnection;\n authConnectionId: string;\n groupedAuthConnectionId?: string;\n /**\n * User email or id from the social login.\n */\n userId: string;\n socialLoginEmail?: string;\n};\n\n/**\n * Parameters for requesting a key-bound identifier token from an IdP.\n */\nexport type KeyBoundIdentifierTokenRequest = {\n identifier: Identifier;\n /**\n * Raw 32-byte Ed25519 public key to bind into the token.\n */\n proofPublicKey: Uint8Array;\n requestHash: string;\n};\n\n/**\n * Result of one identifier login. `token` is the key-bound recovery material\n * presented to escrows (its `providerAssertion` carries the provider ID token\n * or assertion). `seedlessAuthData` is optional — social password-unlock may\n * include it from the same exchange; passkey / SIWE typically omit it.\n */\nexport type KeyBoundIdentifierLogin = {\n token: KeyBoundIdentifierToken;\n seedlessAuthData?: SeedlessAuthData;\n};\n\n/**\n * Options for `MfaRecoveryController.authenticateIdentifier`.\n */\nexport type AuthenticateIdentifierOptions = {\n /**\n * Fail unless the login returns complete {@link SeedlessAuthData}. Set for\n * the seedless password unlock path.\n */\n requireSeedlessAuthData?: boolean;\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. Does not carry seedless auth-server tokens — those are\n * returned beside the session from {@link AuthenticateIdentifierResult}.\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 * Result of `authenticateIdentifier`. `seedlessAuthData` is present when the\n * login also completed a seedless auth-server exchange. Callers should use it\n * for `SeedlessOnboardingController.authenticate` and then drop it; keep only\n * `session` for a later `getRecoverySecret`.\n */\nexport type AuthenticateIdentifierResult = {\n session: IdentifierSession;\n seedlessAuthData?: SeedlessAuthData;\n};\n\n/**\n * `AuthenticateIdentifierResult` when seedless auth data was required.\n */\nexport type SeedlessAuthenticateIdentifierResult = {\n session: IdentifierSession;\n seedlessAuthData: SeedlessAuthData;\n};\n\n/**\n * Recovery secret wrapped to one escrow wrap key for transit.\n */\nexport type WrappedSecret = {\n /**\n * Raw 32-byte X25519 public key of the sender's ephemeral key.\n */\n pkE: Uint8Array;\n /**\n * Raw bytes of `iv || AES-256-GCM(ciphertext+tag)`.\n */\n ciphertext: Uint8Array;\n};\n\nexport type WrappedSecretOutput = {\n /**\n * Raw bytes of `iv || AES-256-GCM(ciphertext+tag)`.\n */\n ciphertext: Uint8Array;\n};\n\nexport type RegisterPayload = {\n recoverySecret: WrappedSecret;\n identifiers: Identifier[];\n};\n\nexport type UpdateRecoverySecretPayload = Pick<\n RegisterPayload,\n 'recoverySecret'\n>;\n\nexport type UpdateIdentifiersPayload = Pick<RegisterPayload, 'identifiers'>;\n\n/**\n * Escrow `applyMutation` body. Recovery secrets are wrapped to that escrow's\n * wrap key; do not confuse with {@link PendingMutationPayload}.\n */\nexport type MutationPayload =\n | RegisterPayload\n | UpdateRecoverySecretPayload\n | UpdateIdentifiersPayload;\n\n/**\n * 0x-hex of a plaintext recovery secret. Encrypted pending state stores this\n * logical value; each escrow receives a {@link WrappedSecret} only at apply.\n */\nexport type PendingRecoverySecretHex = string;\n\n/**\n * Logical register payload stored in encrypted pending state.\n */\nexport type PendingRegisterPayload = {\n identifiers: Identifier[];\n recoverySecret: PendingRecoverySecretHex;\n};\n\n/**\n * Logical secret-update payload stored in encrypted pending state.\n */\nexport type PendingUpdateRecoverySecretPayload = Pick<\n PendingRegisterPayload,\n 'recoverySecret'\n>;\n\n/**\n * Logical identifier-update payload stored in encrypted pending state.\n */\nexport type PendingUpdateIdentifiersPayload = Pick<\n PendingRegisterPayload,\n 'identifiers'\n>;\n\n/**\n * Logical mutation payload persisted in encrypted pending state. Distinct from\n * {@link MutationPayload}, which is the per-escrow apply body.\n */\nexport type PendingMutationPayload =\n | PendingRegisterPayload\n | PendingUpdateRecoverySecretPayload\n | PendingUpdateIdentifiersPayload;\n\ntype PendingOperationBase = {\n mutation: Mutation;\n identifier: Identifier | null;\n payload: PendingMutationPayload;\n};\n\nexport type AuthorizingPendingOperation = PendingOperationBase & {\n phase: 'authorizing';\n};\n\nexport type WritingPendingOperation = PendingOperationBase & {\n phase: 'writing';\n authControllerToken: AuthControllerToken;\n /**\n * The approval's identifiers, in Auth API order, bound by its\n * `identifiers_hash`.\n */\n approvedIdentifiers: Identifier[];\n receipts: MutationReceipt[];\n};\n\nexport type PendingOperation =\n | AuthorizingPendingOperation\n | WritingPendingOperation;\n\nexport type RecoveryPhase = 'idle' | PendingOperation['phase'];\n\n/**\n * Encoded ciphertext of {@link PendingOperation}. Wallet secure storage\n * encrypts this blob (including any hex recovery secret). A raw recovery\n * secret is never persisted in BaseController state.\n *\n * The recovery spec's pseudocode represents this as `Uint8Array`, but the\n * controller stores the encoded ciphertext as a string so BaseController state\n * persistence and serialization preserve it without binary coercion.\n */\nexport type EncryptedPendingOperation = string;\n\nexport type GetRecoverySecretResponse = {\n recoverySecret: WrappedSecretOutput;\n version: number;\n lastMutationId: string;\n wrapKeyId: string;\n};\n\n/**\n * Recovery secret plus the version to use as `epoch` on later mutations.\n */\nexport type RecoveredSecret = {\n recoverySecret: Uint8Array;\n epoch: number;\n};\n\n/**\n * 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 *\n * Implement `getKeyBoundIdentifierToken` for every provider. Optionally also\n * implement `getKeyBoundIdentifierLogin` when one social login should return\n * seedless auth-server tokens beside the recovery token; `seedlessAuthData`\n * on that result stays optional (passkey providers omit it).\n */\nexport type RecoveryIdentifierAuthProvider = {\n getKeyBoundIdentifierToken: (\n params: KeyBoundIdentifierTokenRequest,\n ) => Promise<KeyBoundIdentifierToken>;\n /**\n * Optional. One identifier login that returns the key-bound token and, when\n * available, seedless auth-server tokens from the same exchange. When\n * present, the controller prefers this over {@link getKeyBoundIdentifierToken}.\n * The returned token must be bound to the requested `proofPublicKey` and\n * `requestHash`. Omit `seedlessAuthData` when the IdP does not issue it\n * (e.g. passkey).\n */\n getKeyBoundIdentifierLogin?: (\n params: KeyBoundIdentifierTokenRequest,\n ) => Promise<KeyBoundIdentifierLogin>;\n};\n\n/**\n * One recovery escrow replica. Implementations may talk to different backends.\n */\nexport type RecoveryEscrowProvider = {\n readonly id: string;\n /**\n * Audience the AuthController token must carry for this escrow to accept it.\n * Independent of `id`.\n */\n readonly authAudience: string;\n /**\n * Raw 32-byte X25519 wrap public key. Mutation payloads are encrypted to this\n * key; `getSecret` responses are encrypted to the request's ephemeral key\n * using the corresponding wrap private key.\n */\n readonly wrapPublicKey: Uint8Array;\n isAvailable: () => Promise<boolean>;\n generateChallenge: () => Promise<PoPChallenge>;\n getSecret: (\n authControllerToken: AuthControllerToken,\n authorization: IdentifierAuthorization,\n requestId: string,\n pkE: Uint8Array,\n ) => Promise<GetRecoverySecretResponse>;\n applyMutation: (\n mutation: Mutation,\n authControllerToken: AuthControllerToken,\n identifierAuthorization: IdentifierAuthorization | null,\n payload: MutationPayload,\n approvedIdentifiers: Identifier[],\n ) => Promise<MutationReceipt>;\n /**\n * Verifies a receipt cryptographically using the build-pinned receipt key\n * and confirms it targets the expected escrow.\n *\n * @param receipt - Receipt returned by an escrow.\n * @param mutation - Mutation acknowledged by the receipt.\n * @param expectedEscrowId - Escrow identity expected by the caller.\n */\n verifyReceipt: (\n receipt: MutationReceipt,\n mutation: Mutation,\n expectedEscrowId: string,\n ) => Promise<boolean>;\n};\n\n/**\n * Encrypts pending mutation state using wallet secure storage.\n */\nexport type PendingOperationEncryptor = {\n encrypt: (operation: PendingOperation) => Promise<EncryptedPendingOperation>;\n decrypt: (ciphertext: EncryptedPendingOperation) => Promise<PendingOperation>;\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG","sourcesContent":["/**\n * MFA recovery protocol types from the recovery ADR.\n */\n\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 * 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: () => Promise<PoPChallenge>;\n getSecret: (\n authControllerToken: AuthControllerToken,\n authorization: IdentifierAuthorization,\n requestId: string,\n pkE: Uint8Array,\n ) => Promise<GetRecoverySecretResponse>;\n applyMutation: (\n mutation: Mutation,\n authControllerToken: AuthControllerToken,\n identifierAuthorization: IdentifierAuthorization | null,\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-d4ac59b6e",
3
+ "version": "0.0.0-preview-c3d36da85",
4
4
  "description": "Manages MFA recovery flows across MetaMask clients",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -38,7 +38,7 @@
38
38
  "build:docs": "typedoc",
39
39
  "build:only-clean": "rimraf './dist' './tsconfig.build.tsbuildinfo'",
40
40
  "changelog:update": "../../scripts/update-changelog.sh @metamask/mfa-recovery-controller",
41
- "changelog:validate": "../../scripts/validate-changelog.sh @metamask/mfa-recovery-controller",
41
+ "changelog:validate": "../../scripts/validate-changelog.sh",
42
42
  "cubesigner:invoke-escrow": "tsx scripts/invoke-escrow.ts",
43
43
  "cubesigner:register": "tsx scripts/register-with-controller.ts",
44
44
  "lint:tsconfigs": "node --import ../../scripts/resolver/register.ts ../../scripts/lint-tsconfigs/lint-tsconfigs.ts",
@@ -48,6 +48,7 @@
48
48
  "since-latest-release": "../../scripts/since-latest-release.sh",
49
49
  "test": "vitest",
50
50
  "test:clean": "vitest --clearCache",
51
+ "test:coverage": "vitest --coverage",
51
52
  "test:verbose": "vitest --reporter=verbose",
52
53
  "test:watch": "vitest --watch"
53
54
  },
@@ -63,14 +64,14 @@
63
64
  },
64
65
  "devDependencies": {
65
66
  "@cubist-labs/cubesigner-sdk-fs-storage": "^0.4.284",
66
- "@metamask/auto-changelog": "^6.2.1",
67
+ "@metamask/auto-changelog": "^7.1.0",
67
68
  "@typescript/native": "npm:typescript@^7.0.2",
68
69
  "rimraf": "^6.1.3",
69
70
  "tsx": "^4.20.5",
70
71
  "typedoc": "^0.28.20",
71
72
  "typedoc-plugin-missing-exports": "^4.1.4",
72
73
  "typescript": "npm:@typescript/typescript6@^6.0.2",
73
- "vitest": "^5.0.0"
74
+ "vitest": "5.0.3"
74
75
  },
75
76
  "engines": {
76
77
  "node": "^22.14.0 || ^24 || ^26"