@metamask-previews/mfa-recovery-controller 0.0.0-preview-2c49dc768 → 0.0.0-preview-3e99b509d

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,6 +9,10 @@ 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; `authenticateIdentifier` prefers optional `getKeyBoundIdentifierLogin` when present, otherwise `getKeyBoundIdentifierToken`. Mutation writes always use `getKeyBoundIdentifierToken` so seedless tokens are not minted and dropped.
14
+ - Validates that the key-bound token matches the requested identifier, proof key, and request hash. Empty request `identifier.value` (provider-discovered subject) is allowed only on `authenticateIdentifier`, not on mutation writes.
15
+ - Validates that `seedlessAuthData.authConnection` matches the social identifier's issuer namespace (provider check only; subject / `userId` are not compared).
12
16
  - Initial release of `MfaRecoveryController`, which manages MFA recovery flows and persists in-flight operations in its state ([#10022](https://github.com/MetaMask/core/pull/10022))
13
17
  - Requires recent, request-bound AAL2 approvals for writes and reads.
14
18
  - 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,6 +22,51 @@ 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` goes through `requestKeyBoundIdentifierToken` with
28
+ seedless-login enabled: that helper prefers optional
29
+ `RecoveryIdentifierAuthProvider.getKeyBoundIdentifierLogin` when present, and
30
+ otherwise uses `getKeyBoundIdentifierToken`. Mutation writes
31
+ (`updateRecoverySecret` / `updateIdentifiers`) call the same helper **without**
32
+ seedless-login, so they always use `getKeyBoundIdentifierToken` and never mint
33
+ auth-server tokens that would be dropped.
34
+
35
+ `seedlessAuthData` on the result is **optional**: passkey / SIWE logins omit
36
+ it; only seedless social password unlock needs it. For that path, implement
37
+ `getKeyBoundIdentifierLogin` to perform one AAL1 social login and return the
38
+ key-bound recovery token plus the auth-server token set, then call:
39
+
40
+ ```typescript
41
+ const { session, seedlessAuthData } =
42
+ await mfaRecoveryController.authenticateIdentifier(identifier, {
43
+ requireSeedlessAuthData: true,
44
+ });
45
+
46
+ const { authConnection, ...seedlessAuthFields } = seedlessAuthData;
47
+ await seedlessOnboardingController.authenticate({
48
+ ...seedlessAuthFields,
49
+ // Values match `AuthConnection`; cast if your TS treats string enums nominally.
50
+ authConnection: authConnection as AuthConnection,
51
+ });
52
+ // Prompt for the password, evaluate TOPRF, and decrypt the vault.
53
+ // Keep `session` only if a later getRecoverySecret is needed; drop seedlessAuthData.
54
+ ```
55
+
56
+ With `requireSeedlessAuthData: true`, the result is a
57
+ `SeedlessAuthenticateIdentifierResult`: `seedlessAuthData` (including
58
+ `revokeToken`) beside a key-bound `session`. Without that flag (default), the
59
+ result is an `AuthenticateIdentifierResult` and missing seedless data is fine
60
+ — e.g. passkey. `authConnection` is checked against the social identifier's
61
+ issuer namespace (provider match only) and uses the same string values as
62
+ seedless `AuthConnection`. Cast to `AuthConnection` if TypeScript treats that
63
+ enum nominally. Pass only `session` to `getRecoverySecret(session)` later —
64
+ do not keep auth-server tokens on the session object.
65
+
66
+ The seedless auth data comes only from the AAL1 social login and is never sent
67
+ to recovery escrows. `getRecoverySecret` separately requests its AAL2
68
+ approval when a recovery-secret read is needed.
69
+
25
70
  ## Installation
26
71
 
27
72
  `yarn add @metamask/mfa-recovery-controller`
@@ -38,10 +38,18 @@ export type MfaRecoveryControllerUpdateIdentifiersAction = {
38
38
  handler: MfaRecoveryController['updateIdentifiers'];
39
39
  };
40
40
  /**
41
- * Authenticates an identifier for a subsequent recovery-secret read.
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.
42
46
  *
43
47
  * @param identifier - Identifier to authenticate.
44
- * @returns Ephemeral session data required by {@link getRecoverySecret}.
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.
45
53
  */
46
54
  export type MfaRecoveryControllerAuthenticateIdentifierAction = {
47
55
  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;;;;;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
+ {"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,GAA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-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"]}
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"]}
@@ -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 { Identifier, IdentifierSession, PendingOperationEncryptor, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryPhase, RecoveredSecret } from './types.js';
5
+ import type { AuthenticateIdentifierOptions, AuthenticateIdentifierResult, Identifier, IdentifierSession, PendingOperationEncryptor, RecoveryAuthProvider, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, RecoveryPhase, RecoveredSecret, SeedlessAuthenticateIdentifierResult } from './types.js';
6
6
  declare const CONTROLLER_NAME = "MfaRecoveryController";
7
7
  export type MfaRecoveryControllerState = {
8
8
  /**
@@ -86,12 +86,23 @@ 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 for a subsequent recovery-secret read.
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.
90
94
  *
91
95
  * @param identifier - Identifier to authenticate.
92
- * @returns Ephemeral session data required by {@link getRecoverySecret}.
93
- */
94
- authenticateIdentifier(identifier: Identifier): Promise<IdentifierSession>;
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>;
95
106
  /**
96
107
  * Reads the recovery secret from available escrows and returns the highest
97
108
  * 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,UAAU,EACV,iBAAiB,EAKjB,yBAAyB,EAIzB,oBAAoB,EACpB,sBAAsB,EACtB,8BAA8B,EAC9B,aAAa,EACb,eAAe,EAGhB,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,e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B;IAED;;;;;;OAMG;IACG,QAAQ,CACZ,cAAc,EAAE,UAAU,EAC1B,WAAW,EAAE,UAAU,EAAE,GACxB,OAAO,CAAC,IAAI,CAAC,CAYf;IAED;;;;;;OAMG;IACG,oBAAoB,CACxB,UAAU,EAAE,UAAU,EACtB,cAAc,EAAE,UAAU,EAC1B,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAUf;IAED;;;;;;;OAOG;IACG,iBAAiB,CACrB,UAAU,EAAE,UAAU,EACtB,WAAW,EAAE,UAAU,EAAE,EACzB,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CASf;IAED;;;;;;;;;;;;;OAaG;IACG,sBAAsB,CAC1B,UAAU,EAAE,UAAU,EACtB,OAAO,EAAE,6BAA6B,GAAG;QACvC,uBAAuB,EAAE,IAAI,CAAC;KAC/B,GACA,OAAO,CAAC,oCAAoC,CAAC,CAAC;IAE3C,sBAAsB,CAC1B,UAAU,EAAE,UAAU,EACtB,OAAO,CAAC,EAAE,6BAA6B,GACtC,OAAO,CAAC,4BAA4B,CAAC,CAAC;IAqCzC;;;;;;;;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,13 +122,7 @@ export class MfaRecoveryController extends BaseController {
122
122
  epoch,
123
123
  });
124
124
  }
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) {
125
+ async authenticateIdentifier(identifier, { requireSeedlessAuthData = false } = {}) {
132
126
  this.#assertKnownIdentifierTypes([identifier]);
133
127
  const requestId = randomId();
134
128
  const ephemeral = await generateWrapKey();
@@ -138,17 +132,25 @@ export class MfaRecoveryController extends BaseController {
138
132
  requestId,
139
133
  pkE,
140
134
  });
141
- const credential = await requestKeyBoundIdentifierToken({
135
+ const { seedlessAuthData, ...credential } = await requestKeyBoundIdentifierToken({
142
136
  identifier,
143
137
  requestHash,
144
138
  identifierAuthProvider: this.#identifierAuthProvider,
139
+ requireSeedlessAuthData,
140
+ // Seedless login + empty-value subject discovery are authenticate-only.
141
+ // Mutation writes omit these flags (token path + exact value match).
142
+ allowSeedlessLogin: true,
143
+ allowEmptyIdentifierValue: true,
145
144
  });
146
- return {
145
+ const session = {
147
146
  ...credential,
148
147
  requestId,
149
148
  ephemeralPrivateKey: ephemeral.privateKey,
150
149
  pkE,
151
150
  };
151
+ return seedlessAuthData === undefined
152
+ ? { session }
153
+ : { session, seedlessAuthData };
152
154
  }
153
155
  /**
154
156
  * 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,EACz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AAO,EACP,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,CACzC,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,aAAa;QACjB,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAChC,CAAC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,SAAS,CACb,EAA8B;QAE9B,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QACpC,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CACnB,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;QACF,OAAO,MAAM,GAAG,CAAC;IACnB,CAAC;CACF;AAED;;;;;;GAMG;AACH,SAAS,0BAA0B,CACjC,OAAgD,EAChD,gBAAmC;IAEnC,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,SAAS,GAAiC,IAAI,CAAC;IACnD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IACE,MAAM,CAAC,MAAM,KAAK,UAAU;YAC5B,CAAC,CAAC,MAAM,CAAC,MAAM,YAAY,qBAAqB,CAAC,EACjD,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,SAAS,KAAK,MAAM,CAAC,MAAM,CAAC;IAC9B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport { bytesToHex, hexToBytes } 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
+ {"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,MAA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C,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 // Seedless login + empty-value subject discovery are authenticate-only.\n // Mutation writes omit these flags (token path + exact value match).\n allowSeedlessLogin: true,\n allowEmptyIdentifierValue: true,\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,4 +1,4 @@
1
- import type { Identifier, IdentifierAuthMode, IdentifierAuthorization, KeyBoundCredential, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider } from './types.js';
1
+ import type { Identifier, IdentifierAuthMode, IdentifierAuthorization, KeyBoundCredential, RecoveryEscrowProvider, RecoveryIdentifierAuthProvider, SeedlessAuthConnection, SeedlessAuthData } from './types.js';
2
2
  /**
3
3
  * Minimum identifier count for register and updateIdentifiers.
4
4
  */
@@ -23,20 +23,54 @@ export type AuthorizedEscrow = {
23
23
  authorization: IdentifierAuthorization;
24
24
  };
25
25
  /**
26
- * Requests a key-bound identifier token and returns the private key used to
27
- * prove possession of it.
26
+ * Requests a key-bound identifier credential (and optional seedless auth data)
27
+ * from one provider call.
28
+ *
29
+ * Mutation write paths leave `allowSeedlessLogin` false and only call
30
+ * `getKeyBoundIdentifierToken`, so providers never mint seedless tokens that
31
+ * would be discarded. `authenticateIdentifier` sets `allowSeedlessLogin` so a
32
+ * social login can return seedless auth-server tokens beside the recovery
33
+ * token via `getKeyBoundIdentifierLogin` when implemented; otherwise it falls
34
+ * back to `getKeyBoundIdentifierToken`.
35
+ *
36
+ * `seedlessAuthData` is always optional on the success path — passkey logins
37
+ * typically omit it. Set `requireSeedlessAuthData` only for the seedless
38
+ * password-unlock path that must have a complete seedless token set.
28
39
  *
29
40
  * @param params - Identifier authorization parameters.
30
41
  * @param params.identifier - Identifier to authenticate.
31
42
  * @param params.requestHash - Request hash bound to the authorization.
32
43
  * @param params.identifierAuthProvider - Provider for key-bound assertions.
33
- * @returns Key-bound identifier token and its proof private key.
44
+ * @param params.requireSeedlessAuthData - When true, fail unless complete
45
+ * seedless auth data (including `revokeToken`) is returned.
46
+ * @param params.allowSeedlessLogin - When true, prefer
47
+ * `getKeyBoundIdentifierLogin` if the provider implements it. Only
48
+ * `authenticateIdentifier` sets this; mutation writes leave it false.
49
+ * @param params.allowEmptyIdentifierValue - When true, an empty request
50
+ * `identifier.value` may bind to a non-empty provider-discovered subject.
51
+ * Only `authenticateIdentifier` sets this; mutation writes leave it false.
52
+ * @returns Key-bound credential and optional seedless auth data.
53
+ * @throws If the returned token is not bound to this identifier and request,
54
+ * or seedless auth data is required but missing / incomplete.
34
55
  */
35
- export declare function requestKeyBoundIdentifierToken({ identifier, requestHash, identifierAuthProvider, }: {
56
+ export declare function requestKeyBoundIdentifierToken({ identifier, requestHash, identifierAuthProvider, requireSeedlessAuthData, allowSeedlessLogin, allowEmptyIdentifierValue, }: {
36
57
  identifier: Identifier;
37
58
  requestHash: string;
38
59
  identifierAuthProvider: RecoveryIdentifierAuthProvider;
39
- }): Promise<KeyBoundCredential>;
60
+ requireSeedlessAuthData?: boolean;
61
+ allowSeedlessLogin?: boolean;
62
+ allowEmptyIdentifierValue?: boolean;
63
+ }): Promise<KeyBoundCredential & {
64
+ seedlessAuthData?: SeedlessAuthData;
65
+ }>;
66
+ /**
67
+ * Expected seedless `authConnection` for a social identifier, if known.
68
+ *
69
+ * @param identifier - Authenticated identifier.
70
+ * @returns Matching connection, or `undefined` when the identifier is not a
71
+ * known social issuer.
72
+ */
73
+ export declare function expectedSeedlessAuthConnection(identifier: Identifier): SeedlessAuthConnection | undefined;
40
74
  /**
41
75
  * Presents a key-bound credential to each escrow that provides a challenge.
42
76
  *
@@ -1 +1 @@
1
- {"version":3,"file":"identifier-auth.d.ts","sourceRoot":"","sources":["../src/identifier-auth.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,UAAU,EACV,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,sBAAsB,EACtB,8BAA8B,EAC/B,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;AAEF;;;;;;;;;GASG;AACH,wBAAsB,8BAA8B,CAAC,EACnD,UAAU,EACV,WAAW,EACX,sBAAsB,GACvB,EAAE;IACD,UAAU,EAAE,UAAU,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC;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,kBAA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AgB,8BAA8B,CAC5C,UAAU,EAAE,UAAU,GACrB,sBAAsB,GAAG,SAAS,CAKpC;AAuGD;;;;;;;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,6 +1,9 @@
1
+ import { array, enums, is, optional, size, string, type as structType, } from '@metamask/superstruct';
2
+ import { areUint8ArraysEqual } from '@metamask/utils';
1
3
  import { generateSigningKey, hash, sign } from './crypto.js';
2
4
  import { MfaRecoveryError } from './errors.js';
3
5
  import { isFulfilledResult } from './escrow-utils.js';
6
+ import { SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE, SEEDLESS_AUTH_CONNECTIONS, } from './types.js';
4
7
  /**
5
8
  * Minimum identifier count for register and updateIdentifiers.
6
9
  */
@@ -26,25 +29,209 @@ export const IDENTIFIER_AUTH_MODES = {
26
29
  passkey: 'key-bound',
27
30
  siwe: 'key-bound',
28
31
  };
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
+ });
29
45
  /**
30
- * Requests a key-bound identifier token and returns the private key used to
31
- * prove possession of it.
46
+ * Requests a key-bound identifier credential (and optional seedless auth data)
47
+ * from one provider call.
48
+ *
49
+ * Mutation write paths leave `allowSeedlessLogin` false and only call
50
+ * `getKeyBoundIdentifierToken`, so providers never mint seedless tokens that
51
+ * would be discarded. `authenticateIdentifier` sets `allowSeedlessLogin` so a
52
+ * social login can return seedless auth-server tokens beside the recovery
53
+ * token via `getKeyBoundIdentifierLogin` when implemented; otherwise it falls
54
+ * back to `getKeyBoundIdentifierToken`.
55
+ *
56
+ * `seedlessAuthData` is always optional on the success path — passkey logins
57
+ * typically omit it. Set `requireSeedlessAuthData` only for the seedless
58
+ * password-unlock path that must have a complete seedless token set.
32
59
  *
33
60
  * @param params - Identifier authorization parameters.
34
61
  * @param params.identifier - Identifier to authenticate.
35
62
  * @param params.requestHash - Request hash bound to the authorization.
36
63
  * @param params.identifierAuthProvider - Provider for key-bound assertions.
37
- * @returns Key-bound identifier token and its proof private key.
64
+ * @param params.requireSeedlessAuthData - When true, fail unless complete
65
+ * seedless auth data (including `revokeToken`) is returned.
66
+ * @param params.allowSeedlessLogin - When true, prefer
67
+ * `getKeyBoundIdentifierLogin` if the provider implements it. Only
68
+ * `authenticateIdentifier` sets this; mutation writes leave it false.
69
+ * @param params.allowEmptyIdentifierValue - When true, an empty request
70
+ * `identifier.value` may bind to a non-empty provider-discovered subject.
71
+ * Only `authenticateIdentifier` sets this; mutation writes leave it false.
72
+ * @returns Key-bound credential and optional seedless auth data.
73
+ * @throws If the returned token is not bound to this identifier and request,
74
+ * or seedless auth data is required but missing / incomplete.
38
75
  */
39
- export async function requestKeyBoundIdentifierToken({ identifier, requestHash, identifierAuthProvider, }) {
76
+ export async function requestKeyBoundIdentifierToken({ identifier, requestHash, identifierAuthProvider, requireSeedlessAuthData = false, allowSeedlessLogin = false, allowEmptyIdentifierValue = false, }) {
40
77
  const proofKey = await generateSigningKey();
78
+ if (allowSeedlessLogin &&
79
+ identifierAuthProvider.getKeyBoundIdentifierLogin !== undefined) {
80
+ const login = await identifierAuthProvider.getKeyBoundIdentifierLogin({
81
+ identifier,
82
+ proofPublicKey: proofKey.publicKey,
83
+ requestHash,
84
+ });
85
+ const token = login?.token;
86
+ if (!login ||
87
+ !isTokenBoundToRequest(token, identifier, proofKey.publicKey, requestHash, allowEmptyIdentifierValue)) {
88
+ throwInvalidIdentifierToken();
89
+ }
90
+ const credential = { token, proofPrivateKey: proofKey.privateKey };
91
+ if (login.seedlessAuthData === undefined) {
92
+ if (requireSeedlessAuthData) {
93
+ throwMissingSeedlessAuthData();
94
+ }
95
+ return credential;
96
+ }
97
+ return {
98
+ ...credential,
99
+ seedlessAuthData: validateSeedlessAuthData(login.seedlessAuthData, {
100
+ identifier,
101
+ requireRevokeToken: requireSeedlessAuthData,
102
+ }),
103
+ };
104
+ }
105
+ if (requireSeedlessAuthData) {
106
+ throwMissingSeedlessAuthData();
107
+ }
41
108
  const token = await identifierAuthProvider.getKeyBoundIdentifierToken({
42
109
  identifier,
43
110
  proofPublicKey: proofKey.publicKey,
44
111
  requestHash,
45
112
  });
113
+ if (!isTokenBoundToRequest(token, identifier, proofKey.publicKey, requestHash, allowEmptyIdentifierValue)) {
114
+ throwInvalidIdentifierToken();
115
+ }
46
116
  return { token, proofPrivateKey: proofKey.privateKey };
47
117
  }
118
+ /**
119
+ * @param token - Token returned by the identifier provider.
120
+ * @param identifier - Identifier the provider was asked to authenticate.
121
+ * @param proofPublicKey - Proof public key sent to the provider.
122
+ * @param requestHash - Request hash sent to the provider.
123
+ * @param allowEmptyIdentifierValue - Whether an empty request value may bind
124
+ * to a non-empty provider-discovered subject.
125
+ * @returns Whether the token is bound to the identifier, proof key, and request.
126
+ */
127
+ function isTokenBoundToRequest(token, identifier, proofPublicKey, requestHash, allowEmptyIdentifierValue) {
128
+ if (typeof token !== 'object' || token === null) {
129
+ return false;
130
+ }
131
+ const candidate = token;
132
+ return (candidate.requestHash === requestHash &&
133
+ candidate.proofPublicKey instanceof Uint8Array &&
134
+ areUint8ArraysEqual(candidate.proofPublicKey, proofPublicKey) &&
135
+ isTokenIdentifierBoundToRequest(candidate.identifier, identifier, allowEmptyIdentifierValue));
136
+ }
137
+ /**
138
+ * Whether the token's identifier is bound to the requested identifier.
139
+ *
140
+ * Type and namespace must always match. Value must match when the request
141
+ * already knows the subject. When `allowEmptyIdentifierValue` is true (only
142
+ * `authenticateIdentifier` sets this), an empty request `value` may bind to a
143
+ * non-empty provider-discovered IdP `sub` written onto the returned token
144
+ * (see metamask-mobile OIDC identifier provider). Mutation writes leave the
145
+ * option false and require an exact value match.
146
+ *
147
+ * @param tokenIdentifier - Identifier from the token, if any.
148
+ * @param requested - Identifier requested by the controller.
149
+ * @param allowEmptyIdentifierValue - Whether empty request values may discover
150
+ * a non-empty subject.
151
+ * @returns Whether the token identifier is acceptable for this request.
152
+ */
153
+ function isTokenIdentifierBoundToRequest(tokenIdentifier, requested, allowEmptyIdentifierValue) {
154
+ if (tokenIdentifier === undefined ||
155
+ tokenIdentifier.type !== requested.type ||
156
+ tokenIdentifier.namespace !== requested.namespace) {
157
+ return false;
158
+ }
159
+ if (allowEmptyIdentifierValue && requested.value === '') {
160
+ return tokenIdentifier.value.length > 0;
161
+ }
162
+ return tokenIdentifier.value === requested.value;
163
+ }
164
+ /**
165
+ * Expected seedless `authConnection` for a social identifier, if known.
166
+ *
167
+ * @param identifier - Authenticated identifier.
168
+ * @returns Matching connection, or `undefined` when the identifier is not a
169
+ * known social issuer.
170
+ */
171
+ export function expectedSeedlessAuthConnection(identifier) {
172
+ if (identifier.type !== 'social') {
173
+ return undefined;
174
+ }
175
+ return SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE[identifier.namespace];
176
+ }
177
+ /**
178
+ * Validates seedless auth data shape, strips unknown fields, and checks that
179
+ * `authConnection` matches the expected provider for the authenticated social
180
+ * identifier's issuer namespace. It does not verify that tokens belong to the
181
+ * same subject / `userId` as the identifier value.
182
+ *
183
+ * @param data - Provider-returned seedless auth data.
184
+ * @param options - Validation options.
185
+ * @param options.identifier - Identifier that was authenticated.
186
+ * @param options.requireRevokeToken - Whether `revokeToken` must be present
187
+ * (password unlock path).
188
+ * @returns Documented seedless auth data fields only.
189
+ */
190
+ function validateSeedlessAuthData(data, { identifier, requireRevokeToken, }) {
191
+ if (!is(data, SeedlessAuthDataStruct)) {
192
+ throw new MfaRecoveryError('Incomplete seedless auth data', 'invalid_seedless_auth_data');
193
+ }
194
+ if (requireRevokeToken &&
195
+ (data.revokeToken === undefined || data.revokeToken.length === 0)) {
196
+ throw new MfaRecoveryError('Incomplete seedless auth data', 'invalid_seedless_auth_data');
197
+ }
198
+ const expectedConnection = expectedSeedlessAuthConnection(identifier);
199
+ if (expectedConnection === undefined ||
200
+ data.authConnection !== expectedConnection) {
201
+ throw new MfaRecoveryError('Seedless auth data does not match the authenticated identifier', 'invalid_seedless_auth_data');
202
+ }
203
+ return pickSeedlessAuthData(data);
204
+ }
205
+ /**
206
+ * Copies only the documented fields, so extra provider fields (for example
207
+ * `skipLock`) cannot reach `SeedlessOnboardingController.authenticate`.
208
+ *
209
+ * @param data - Validated seedless auth data.
210
+ * @returns Seedless auth data with only documented fields.
211
+ */
212
+ function pickSeedlessAuthData(data) {
213
+ const { idTokens, accessToken, metadataAccessToken, refreshToken, revokeToken, authConnection, authConnectionId, groupedAuthConnectionId, userId, socialLoginEmail, } = data;
214
+ return {
215
+ idTokens: [...idTokens],
216
+ accessToken,
217
+ metadataAccessToken,
218
+ refreshToken,
219
+ authConnection,
220
+ authConnectionId,
221
+ userId,
222
+ ...(revokeToken === undefined ? {} : { revokeToken }),
223
+ ...(groupedAuthConnectionId === undefined
224
+ ? {}
225
+ : { groupedAuthConnectionId }),
226
+ ...(socialLoginEmail === undefined ? {} : { socialLoginEmail }),
227
+ };
228
+ }
229
+ function throwMissingSeedlessAuthData() {
230
+ throw new MfaRecoveryError('Identifier login did not return seedless auth data', 'missing_seedless_auth_data');
231
+ }
232
+ function throwInvalidIdentifierToken() {
233
+ throw new MfaRecoveryError('Identifier token is not bound to this request', 'invalid_identifier_token');
234
+ }
48
235
  /**
49
236
  * Presents a key-bound credential to each escrow that provides a challenge.
50
237
  *
@@ -1 +1 @@
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;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,EACnD,UAAU,EACV,WAAW,EACX,sBAAsB,GAKvB;IACC,MAAM,QAAQ,GAAG,MAAM,kBAAkB,EAAE,CAAC;IAC5C,MAAM,KAAK,GAAG,MAAM,sBAAsB,CAAC,0BAA0B,CAAC;QACpE,UAAU;QACV,cAAc,EAAE,QAAQ,CAAC,SAAS;QAClC,WAAW;KACZ,CAAC,CAAC;IACH,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,QAAQ,CAAC,UAAU,EAAE,CAAC;AACzD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAy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,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"]}
1
+ {"version":3,"file":"identifier-auth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","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 * Mutation write paths leave `allowSeedlessLogin` false and only call\n * `getKeyBoundIdentifierToken`, so providers never mint seedless tokens that\n * would be discarded. `authenticateIdentifier` sets `allowSeedlessLogin` so a\n * social login can return seedless auth-server tokens beside the recovery\n * token via `getKeyBoundIdentifierLogin` when implemented; otherwise it falls\n * back to `getKeyBoundIdentifierToken`.\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 * @param params.allowSeedlessLogin - When true, prefer\n * `getKeyBoundIdentifierLogin` if the provider implements it. Only\n * `authenticateIdentifier` sets this; mutation writes leave it false.\n * @param params.allowEmptyIdentifierValue - When true, an empty request\n * `identifier.value` may bind to a non-empty provider-discovered subject.\n * Only `authenticateIdentifier` sets this; mutation writes leave it false.\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 allowSeedlessLogin = false,\n allowEmptyIdentifierValue = false,\n}: {\n identifier: Identifier;\n requestHash: string;\n identifierAuthProvider: RecoveryIdentifierAuthProvider;\n requireSeedlessAuthData?: boolean;\n allowSeedlessLogin?: boolean;\n allowEmptyIdentifierValue?: boolean;\n}): Promise<KeyBoundCredential & { seedlessAuthData?: SeedlessAuthData }> {\n const proofKey = await generateSigningKey();\n\n if (\n allowSeedlessLogin &&\n identifierAuthProvider.getKeyBoundIdentifierLogin !== undefined\n ) {\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(\n token,\n identifier,\n proofKey.publicKey,\n requestHash,\n allowEmptyIdentifierValue,\n )\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(\n token,\n identifier,\n proofKey.publicKey,\n requestHash,\n allowEmptyIdentifierValue,\n )\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 * @param allowEmptyIdentifierValue - Whether an empty request value may bind\n * to a non-empty provider-discovered subject.\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 allowEmptyIdentifierValue: boolean,\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(\n candidate.identifier,\n identifier,\n allowEmptyIdentifierValue,\n )\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. When `allowEmptyIdentifierValue` is true (only\n * `authenticateIdentifier` sets this), an empty request `value` may bind to a\n * non-empty provider-discovered IdP `sub` written onto the returned token\n * (see metamask-mobile OIDC identifier provider). Mutation writes leave the\n * option false and require an exact value match.\n *\n * @param tokenIdentifier - Identifier from the token, if any.\n * @param requested - Identifier requested by the controller.\n * @param allowEmptyIdentifierValue - Whether empty request values may discover\n * a non-empty subject.\n * @returns Whether the token identifier is acceptable for this request.\n */\nfunction isTokenIdentifierBoundToRequest(\n tokenIdentifier: Identifier | undefined,\n requested: Identifier,\n allowEmptyIdentifierValue: boolean,\n): boolean {\n if (\n tokenIdentifier === undefined ||\n tokenIdentifier.type !== requested.type ||\n tokenIdentifier.namespace !== requested.namespace\n ) {\n return false;\n }\n if (allowEmptyIdentifierValue && 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 checks that\n * `authConnection` matches the expected provider for the authenticated social\n * identifier's issuer namespace. It does not verify that tokens belong to the\n * same subject / `userId` as the identifier value.\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"]}
package/dist/index.d.ts CHANGED
@@ -6,6 +6,7 @@ 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, 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';
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';
11
12
  //# 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,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"}
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"}
package/dist/index.js CHANGED
@@ -2,5 +2,6 @@ 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, getIdentifierAuthMode, } from './identifier-auth.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';
6
7
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;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"]}
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"]}
package/dist/types.d.ts CHANGED
@@ -1,6 +1,24 @@
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 (`google`, `apple`,
7
+ * `telegram`). Kept as a local constant so this package does not depend on
8
+ * seedless-onboarding-controller.
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 check that `seedlessAuthData.authConnection`
18
+ * matches the authenticated identifier's IdP namespace (provider check only;
19
+ * subject / `userId` are not compared).
20
+ */
21
+ export declare const SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE: Record<string, SeedlessAuthConnection>;
4
22
  export type Identifier = {
5
23
  type: string;
6
24
  namespace: string;
@@ -81,13 +99,84 @@ export type KeyBoundCredential = {
81
99
  */
82
100
  proofPrivateKey: Uint8Array;
83
101
  };
102
+ /**
103
+ * Seedless auth-server tokens and social login details issued by the same
104
+ * login that produced a key-bound identifier token. The fields match the
105
+ * parameters of `SeedlessOnboardingController.authenticate` (without
106
+ * `skipLock`), so the password unlock path can authenticate without a second
107
+ * social prompt.
108
+ *
109
+ * These tokens come from the AAL1 social login exchange, never from an AAL2
110
+ * recovery approval. They are never sent to escrows. Keep in memory only.
111
+ */
112
+ export type SeedlessAuthData = {
113
+ /**
114
+ * ID token(s) verified by the TOPRF nodes.
115
+ */
116
+ idTokens: string[];
117
+ accessToken: string;
118
+ metadataAccessToken: string;
119
+ refreshToken: string;
120
+ /**
121
+ * Required when `authenticateIdentifier` is called with
122
+ * `requireSeedlessAuthData: true` (password unlock / vault path). Optional
123
+ * when seedless auth data is returned without that requirement.
124
+ */
125
+ revokeToken?: string;
126
+ /**
127
+ * Social login provider. Values match `SeedlessOnboardingController`'s
128
+ * `AuthConnection` enum (`google`, `apple`, `telegram`). Validated against
129
+ * the authenticated social identifier's issuer namespace (provider match
130
+ * only; not subject / `userId`).
131
+ */
132
+ authConnection: SeedlessAuthConnection;
133
+ authConnectionId: string;
134
+ groupedAuthConnectionId?: string;
135
+ /**
136
+ * User email or id from the social login.
137
+ */
138
+ userId: string;
139
+ socialLoginEmail?: string;
140
+ };
141
+ /**
142
+ * Parameters for requesting a key-bound identifier token from an IdP.
143
+ */
144
+ export type KeyBoundIdentifierTokenRequest = {
145
+ identifier: Identifier;
146
+ /**
147
+ * Raw 32-byte Ed25519 public key to bind into the token.
148
+ */
149
+ proofPublicKey: Uint8Array;
150
+ requestHash: string;
151
+ };
152
+ /**
153
+ * Result of one identifier login. `token` is the key-bound recovery material
154
+ * presented to escrows (its `providerAssertion` carries the provider ID token
155
+ * or assertion). `seedlessAuthData` is optional — social password-unlock may
156
+ * include it from the same exchange; passkey / SIWE typically omit it.
157
+ */
158
+ export type KeyBoundIdentifierLogin = {
159
+ token: KeyBoundIdentifierToken;
160
+ seedlessAuthData?: SeedlessAuthData;
161
+ };
162
+ /**
163
+ * Options for `MfaRecoveryController.authenticateIdentifier`.
164
+ */
165
+ export type AuthenticateIdentifierOptions = {
166
+ /**
167
+ * Fail unless the login returns complete {@link SeedlessAuthData}. Set for
168
+ * the seedless password unlock path.
169
+ */
170
+ requireSeedlessAuthData?: boolean;
171
+ };
84
172
  /**
85
173
  * Result of first-factor identifier authentication, consumed by
86
174
  * `getRecoverySecret`.
87
175
  *
88
176
  * `proofPrivateKey` signs escrow challenges. `ephemeralPrivateKey` is the
89
177
  * private half of `pkE` and decrypts the recovery secret. Keep both in
90
- * memory only.
178
+ * memory only. Does not carry seedless auth-server tokens — those are
179
+ * returned beside the session from {@link AuthenticateIdentifierResult}.
91
180
  */
92
181
  export type IdentifierSession = KeyBoundCredential & {
93
182
  requestId: string;
@@ -100,6 +189,23 @@ export type IdentifierSession = KeyBoundCredential & {
100
189
  */
101
190
  pkE: Uint8Array;
102
191
  };
192
+ /**
193
+ * Result of `authenticateIdentifier`. `seedlessAuthData` is present when the
194
+ * login also completed a seedless auth-server exchange. Callers should use it
195
+ * for `SeedlessOnboardingController.authenticate` and then drop it; keep only
196
+ * `session` for a later `getRecoverySecret`.
197
+ */
198
+ export type AuthenticateIdentifierResult = {
199
+ session: IdentifierSession;
200
+ seedlessAuthData?: SeedlessAuthData;
201
+ };
202
+ /**
203
+ * `AuthenticateIdentifierResult` when seedless auth data was required.
204
+ */
205
+ export type SeedlessAuthenticateIdentifierResult = {
206
+ session: IdentifierSession;
207
+ seedlessAuthData: SeedlessAuthData;
208
+ };
103
209
  /**
104
210
  * Recovery secret wrapped to one escrow wrap key for transit.
105
211
  */
@@ -215,16 +321,25 @@ export type RecoveryAuthProvider = {
215
321
  };
216
322
  /**
217
323
  * Obtains a key-bound identifier assertion from an IdP (OIDC, Passkey, SIWE).
324
+ *
325
+ * Implement `getKeyBoundIdentifierToken` for every provider. Optionally also
326
+ * implement `getKeyBoundIdentifierLogin` when one social login should return
327
+ * seedless auth-server tokens beside the recovery token for
328
+ * `authenticateIdentifier`; `seedlessAuthData` on that result stays optional
329
+ * (passkey providers omit it). Mutation writes always use
330
+ * {@link getKeyBoundIdentifierToken} and never call this method.
218
331
  */
219
332
  export type RecoveryIdentifierAuthProvider = {
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>;
333
+ getKeyBoundIdentifierToken: (params: KeyBoundIdentifierTokenRequest) => Promise<KeyBoundIdentifierToken>;
334
+ /**
335
+ * Optional. One identifier login that returns the key-bound token and, when
336
+ * available, seedless auth-server tokens from the same exchange. Used only by
337
+ * `authenticateIdentifier` when present; mutation writes always use
338
+ * {@link getKeyBoundIdentifierToken} instead. The returned token must be
339
+ * bound to the requested `proofPublicKey` and `requestHash`. Omit
340
+ * `seedlessAuthData` when the IdP does not issue it (e.g. passkey).
341
+ */
342
+ getKeyBoundIdentifierLogin?: (params: KeyBoundIdentifierTokenRequest) => Promise<KeyBoundIdentifierLogin>;
228
343
  };
229
344
  /**
230
345
  * 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,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG,WAAW,CAAC;AAE7C,MAAM,MAAM,uBAAuB,GAAG;IACpC,UAAU,EAAE,UAAU,CAAC;IACvB;;OAEG;IACH,cAAc,EAAE,UAAU,CAAC;IAC3B,WAAW,EA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Q,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B;;;;OAIG;IACH,QAAQ,CAAC,aAAa,EAAE,UAAU,CAAC;IACnC,WAAW,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IACpC,iBAAiB,EAAE,MAAM,OAAO,CAAC,YAAY,CAAC,CAAC;IAC/C,SAAS,EAAE,CACT,mBAAmB,EAAE,mBAAmB,EACxC,aAAa,EAAE,uBAAuB,EACtC,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,UAAU,KACZ,OAAO,CAAC,yBAAyB,CAAC,CAAC;IACxC,aAAa,EAAE,CACb,QAAQ,EAAE,QAAQ,EAClB,mBAAmB,EAAE,mBAAmB,EACxC,uBAAuB,EAAE,uBAAuB,GAAG,IAAI,EACvD,OAAO,EAAE,eAAe,EACxB,mBAAmB,EAAE,UAAU,EAAE,KAC9B,OAAO,CAAC,eAAe,CAAC,CAAC;IAC9B;;;;;;;OAOG;IACH,aAAa,EAAE,CACb,OAAO,EAAE,eAAe,EACxB,QAAQ,EAAE,QAAQ,EAClB,gBAAgB,EAAE,MAAM,KACrB,OAAO,CAAC,OAAO,CAAC,CAAC;CACvB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC,OAAO,EAAE,CAAC,SAAS,EAAE,gBAAgB,KAAK,OAAO,CAAC,yBAAyB,CAAC,CAAC;IAC7E,OAAO,EAAE,CAAC,UAAU,EAAE,yBAAyB,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAAC;CAC/E,CAAC"}
package/dist/types.js CHANGED
@@ -1,5 +1,26 @@
1
1
  /**
2
2
  * MFA recovery protocol types from the recovery ADR.
3
3
  */
4
- export {};
4
+ /**
5
+ * Social login providers accepted by seedless authenticate. Values match
6
+ * `SeedlessOnboardingController`'s `AuthConnection` enum (`google`, `apple`,
7
+ * `telegram`). Kept as a local constant so this package does not depend on
8
+ * seedless-onboarding-controller.
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 check that `seedlessAuthData.authConnection`
18
+ * matches the authenticated identifier's IdP namespace (provider check only;
19
+ * subject / `userId` are not compared).
20
+ */
21
+ export const SEEDLESS_AUTH_CONNECTION_BY_NAMESPACE = {
22
+ 'https://accounts.google.com': 'google',
23
+ 'https://appleid.apple.com': 'apple',
24
+ 'https://oauth.telegram.org': 'telegram',
25
+ };
5
26
  //# 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","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"]}
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;;;;;GAKG;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 (`google`, `apple`,\n * `telegram`). Kept as a local constant so this package does not depend on\n * seedless-onboarding-controller.\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 check that `seedlessAuthData.authConnection`\n * matches the authenticated identifier's IdP namespace (provider check only;\n * subject / `userId` are not compared).\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`). Validated against\n * the authenticated social identifier's issuer namespace (provider match\n * only; not subject / `userId`).\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 for\n * `authenticateIdentifier`; `seedlessAuthData` on that result stays optional\n * (passkey providers omit it). Mutation writes always use\n * {@link getKeyBoundIdentifierToken} and never call this method.\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. Used only by\n * `authenticateIdentifier` when present; mutation writes always use\n * {@link getKeyBoundIdentifierToken} instead. The returned token must be\n * bound to the requested `proofPublicKey` and `requestHash`. Omit\n * `seedlessAuthData` when the IdP does not issue it (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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/mfa-recovery-controller",
3
- "version": "0.0.0-preview-2c49dc768",
3
+ "version": "0.0.0-preview-3e99b509d",
4
4
  "description": "Manages MFA recovery flows across MetaMask clients",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -32,14 +32,13 @@
32
32
  "registry": "https://registry.npmjs.org/"
33
33
  },
34
34
  "scripts": {
35
- "allow-scripts": "yarn workspace @metamask/core-monorepo run allow-scripts",
36
35
  "build": "tsc --project tsconfig.build.json",
37
36
  "build:all": "tsc --build tsconfig.build.json --verbose",
38
37
  "build:clean": "yarn build:only-clean && yarn build",
39
38
  "build:docs": "typedoc",
40
39
  "build:only-clean": "rimraf './dist' './tsconfig.build.tsbuildinfo'",
41
40
  "changelog:update": "../../scripts/update-changelog.sh @metamask/mfa-recovery-controller",
42
- "changelog:validate": "../../scripts/validate-changelog.sh",
41
+ "changelog:validate": "../../scripts/validate-changelog.sh @metamask/mfa-recovery-controller",
43
42
  "cubesigner:invoke-escrow": "tsx scripts/invoke-escrow.ts",
44
43
  "cubesigner:register": "tsx scripts/register-with-controller.ts",
45
44
  "lint:tsconfigs": "node --import ../../scripts/resolver/register.ts ../../scripts/lint-tsconfigs/lint-tsconfigs.ts",
@@ -49,7 +48,6 @@
49
48
  "since-latest-release": "../../scripts/since-latest-release.sh",
50
49
  "test": "vitest",
51
50
  "test:clean": "vitest --clearCache",
52
- "test:coverage": "vitest --coverage",
53
51
  "test:verbose": "vitest --reporter=verbose",
54
52
  "test:watch": "vitest --watch"
55
53
  },
@@ -65,14 +63,14 @@
65
63
  },
66
64
  "devDependencies": {
67
65
  "@cubist-labs/cubesigner-sdk-fs-storage": "^0.4.284",
68
- "@metamask/auto-changelog": "^7.1.0",
66
+ "@metamask/auto-changelog": "^6.2.1",
69
67
  "@typescript/native": "npm:typescript@^7.0.2",
70
68
  "rimraf": "^6.1.3",
71
69
  "tsx": "^4.20.5",
72
70
  "typedoc": "^0.28.20",
73
71
  "typedoc-plugin-missing-exports": "^4.1.4",
74
72
  "typescript": "npm:@typescript/typescript6@^6.0.2",
75
- "vitest": "5.0.3"
73
+ "vitest": "^5.0.0"
76
74
  },
77
75
  "engines": {
78
76
  "node": "^22.14.0 || ^24 || ^26"