@metamask-previews/mfa-recovery-controller 0.0.0-preview-406090321 → 0.0.0-preview-979919367

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.
Files changed (34) hide show
  1. package/CHANGELOG.md +0 -3
  2. package/README.md +8 -21
  3. package/dist/MfaRecoveryController.d.ts.map +1 -1
  4. package/dist/MfaRecoveryController.js +16 -18
  5. package/dist/MfaRecoveryController.js.map +1 -1
  6. package/dist/auth-controller-token.d.ts +5 -3
  7. package/dist/auth-controller-token.d.ts.map +1 -1
  8. package/dist/auth-controller-token.js +1 -1
  9. package/dist/auth-controller-token.js.map +1 -1
  10. package/dist/crypto.d.ts +18 -0
  11. package/dist/crypto.d.ts.map +1 -1
  12. package/dist/crypto.js +37 -0
  13. package/dist/crypto.js.map +1 -1
  14. package/dist/escrow-providers/cubist-escrow-provider.d.ts +4 -11
  15. package/dist/escrow-providers/cubist-escrow-provider.d.ts.map +1 -1
  16. package/dist/escrow-providers/cubist-escrow-provider.js +4 -9
  17. package/dist/escrow-providers/cubist-escrow-provider.js.map +1 -1
  18. package/dist/identifier-auth.js +1 -1
  19. package/dist/identifier-auth.js.map +1 -1
  20. package/dist/index.d.ts +1 -3
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +0 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/pending-operation-validation.d.ts.map +1 -1
  25. package/dist/pending-operation-validation.js +6 -21
  26. package/dist/pending-operation-validation.js.map +1 -1
  27. package/dist/types.d.ts +6 -18
  28. package/dist/types.d.ts.map +1 -1
  29. package/dist/types.js.map +1 -1
  30. package/package.json +1 -2
  31. package/dist/auth-api-recovery-provider.d.ts +0 -33
  32. package/dist/auth-api-recovery-provider.d.ts.map +0 -1
  33. package/dist/auth-api-recovery-provider.js +0 -38
  34. package/dist/auth-api-recovery-provider.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -10,10 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
10
10
  ### Added
11
11
 
12
12
  - Initial release of `MfaRecoveryController`, which manages MFA recovery flows and persists in-flight operations in its state ([#10022](https://github.com/MetaMask/core/pull/10022))
13
- - Requires recent, request-bound AAL2 approvals for writes and reads.
14
- - Sends the approval's identifiers to escrows as `approvedIdentifiers` with `register` and `updateIdentifiers` mutations, and rejects payload identifiers that are not exactly among them before writing ([#10883](https://github.com/MetaMask/core/pull/10883))
15
13
  - Exports `MfaRecoveryController`, `getDefaultMfaRecoveryControllerState`, and the controller's action, event, messenger, state, and options types.
16
- - Exports `AuthApiRecoveryAuthProvider`, `AuthApiRecoveryAuthProviderOptions` and `AuthApiRecoveryAuthProviderMessenger` for requesting approvals through `AuthenticationController:requestMfaApproval`, using the profile id from `AuthenticationController:refreshCanonicalProfileId` ([#10883](https://github.com/MetaMask/core/pull/10883))
17
14
  - Exports `CubistEscrowProvider` and `CubistEscrowProviderOptions` for storing recovery secrets with CubeSigner.
18
15
  - Exports `MfaRecoveryError`, `IncompleteMutationError`, and `MutationRejectedError`.
19
16
  - Exports `MIN_IDENTIFIERS`, `IDENTIFIER_AUTH_MODES`, and `getIdentifierAuthMode` for identifier authentication.
package/README.md CHANGED
@@ -1,26 +1,13 @@
1
1
  # `@metamask/mfa-recovery-controller`
2
2
 
3
- Coordinates MFA recovery through injected auth and escrow providers.
4
-
5
- Pending mutations are encrypted in controller state. `resume()` completes them;
6
- `abort()` is allowed only before writing. See [Architecture](ARCHITECTURE.md).
7
-
8
- ## Auth API Integration
9
-
10
- Configure `AuthApiRecoveryAuthProvider` with a messenger that can call
11
- `AuthenticationController:refreshCanonicalProfileId` and
12
- `AuthenticationController:requestMfaApproval`. It resolves the current canonical
13
- profile id for each mutation and requests approvals from `/api/v2/mfa/approvals`. Writes and reads require a
14
- request-bound AAL2 approval; updates and reads also require an identifier proof.
15
- Without a recent MFA verification, approvals reject with `StepUpRequiredError`:
16
- verify, then call `resume()` or retry the read.
17
-
18
- `register` and `updateIdentifiers` send the approval's `identifiers` to each
19
- escrow as `approvedIdentifiers`; the escrow rejects payload identifiers outside
20
- that list. Build payload identifiers from those entries unchanged (verifier
21
- included): the controller rejects any other identifier before writing, and the
22
- mutation can then be aborted. Set `CubistEscrowProviderOptions.authAudience` to the escrow's
23
- `AUTH_CONTROLLER_AUDIENCE`.
3
+ Manages MFA recovery flows across MetaMask clients. Auth and escrow storage are
4
+ injected so the same controller can run against different identity providers and
5
+ escrow backends.
6
+
7
+ Pending mutations are persisted as encoded encrypted `authorizing` / `writing`
8
+ state so a crash can `resume()` the same mutation. `abort()` drops `authorizing`
9
+ only; `writing` must `resume()`. The encoded ciphertext is stored as a string so
10
+ BaseController state serialization preserves the encrypted value.
24
11
 
25
12
  ## Installation
26
13
 
@@ -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,eAAe,EACtB,0BAA0B,C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AAW,EAAE,UAAU,EAAE,GACxB,OAAO,CAAC,IAAI,CAAC,CAYf;IAED;;;;;;OAMG;IACG,oBAAoB,CACxB,UAAU,EAAE,UAAU,EACtB,cAAc,EAAE,UAAU,EAC1B,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAUf;IAED;;;;;;;OAOG;IACG,iBAAiB,CACrB,UAAU,EAAE,UAAU,EACtB,WAAW,EAAE,UAAU,EAAE,EACzB,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CASf;IAED;;;;;OAKG;IACG,sBAAsB,CAC1B,UAAU,EAAE,UAAU,GACrB,OAAO,CAAC,iBAAiB,CAAC,CAqB5B;IAED;;;;;;;;OAQG;IACG,iBAAiB,CACrB,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,eAAe,CAAC,CAyD1B;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;CAwXF"}
@@ -175,17 +175,12 @@ export class MfaRecoveryController extends BaseController {
175
175
  if (available.length === 0) {
176
176
  throw new MfaRecoveryError('No escrow is available', 'no_available_escrow');
177
177
  }
178
- const { approval } = await this.#authProvider.authorizeRecoveryRequest({
179
- requestHash,
180
- audiences: available.map((escrow) => escrow.authAudience),
181
- requireTwoFactor: true,
182
- });
183
178
  const authorizedEscrows = await authorizeEscrowsWithToken({
184
179
  escrows: available,
185
180
  credential: session,
186
181
  });
187
182
  const results = await Promise.allSettled(authorizedEscrows.map(async ({ escrow, authorization }) => {
188
- const response = await escrow.getSecret(approval, authorization, requestId, pkE);
183
+ const response = await escrow.getSecret(authorization, requestId, pkE);
189
184
  if (response.wrapKeyId !== (await wrapKeyId(escrow.wrapPublicKey))) {
190
185
  throw new MfaRecoveryError('Unexpected wrap key', 'wrap_key_mismatch');
191
186
  }
@@ -260,21 +255,24 @@ export class MfaRecoveryController extends BaseController {
260
255
  identifier,
261
256
  };
262
257
  await this.#persistPending(pending);
258
+ const authControllerToken = await this.#authorizeMutation(mutation, payload);
263
259
  await this.#replicateMutation({
264
260
  ...pending,
265
261
  phase: 'writing',
266
- ...(await this.#authorizeMutation(mutation)),
262
+ authControllerToken,
267
263
  receipts: [],
268
264
  });
269
265
  });
270
266
  }
271
- async #authorizeMutation(mutation) {
272
- const { approval, identifiers } = await this.#authProvider.authorizeRecoveryRequest({
267
+ async #authorizeMutation(mutation, payload) {
268
+ return await this.#authProvider.authorizeRecoveryRequest({
273
269
  requestHash: mutation.requestHash,
274
270
  audiences: this.#escrows.map((escrow) => escrow.authAudience),
275
- requireTwoFactor: true,
271
+ ...(mutation.operation === 'register' ? {} : { requireTwoFactor: true }),
272
+ ...(pendingPayloadHasIdentifiers(payload)
273
+ ? { identifiers: payload.identifiers }
274
+ : {}),
276
275
  });
277
- return { authControllerToken: approval, approvedIdentifiers: identifiers };
278
276
  }
279
277
  async #repairPendingMutation() {
280
278
  const pending = await this.#loadPending();
@@ -286,7 +284,7 @@ export class MfaRecoveryController extends BaseController {
286
284
  await this.#replicateMutation({
287
285
  ...pending,
288
286
  phase: 'writing',
289
- ...(await this.#authorizeMutation(pending.mutation)),
287
+ authControllerToken: await this.#authorizeMutation(pending.mutation, pending.payload),
290
288
  receipts: [],
291
289
  });
292
290
  return;
@@ -295,7 +293,7 @@ export class MfaRecoveryController extends BaseController {
295
293
  await this.#replicateMutation(pending);
296
294
  }
297
295
  async #replicateMutation(pending) {
298
- const { mutation, identifier } = pending;
296
+ const { mutation, payload, identifier } = pending;
299
297
  const remainingEscrows = await this.#getRemainingEscrows(pending);
300
298
  if (remainingEscrows.length === 0) {
301
299
  await this.#clearPending();
@@ -303,10 +301,10 @@ export class MfaRecoveryController extends BaseController {
303
301
  }
304
302
  await this.#assertEscrowsAvailable(remainingEscrows);
305
303
  const claims = decodeAuthControllerToken(pending.authControllerToken);
306
- const writing = claims && claims.exp > this.#now()
307
- ? pending
308
- : { ...pending, ...(await this.#authorizeMutation(mutation)) };
309
- await this.#assertPending(writing);
304
+ const authControllerToken = claims && claims.exp > this.#now()
305
+ ? pending.authControllerToken
306
+ : await this.#authorizeMutation(mutation, payload);
307
+ const writing = { ...pending, authControllerToken };
310
308
  const authorizedEscrows = mutation.operation === 'register'
311
309
  ? null
312
310
  : await this.#authorizeEscrows({
@@ -320,7 +318,7 @@ export class MfaRecoveryController extends BaseController {
320
318
  }
321
319
  const payloads = await Promise.all(remainingEscrows.map(async (escrow) => this.#payloadForEscrow(writing, escrow)));
322
320
  await this.#persistPending(writing);
323
- const results = await Promise.allSettled(remainingEscrows.map((escrow, index) => escrow.applyMutation(mutation, writing.authControllerToken, authorizedEscrows?.[index]?.authorization ?? null, payloads[index], writing.approvedIdentifiers)));
321
+ const results = await Promise.allSettled(remainingEscrows.map((escrow, index) => escrow.applyMutation(mutation, writing.authControllerToken, authorizedEscrows?.[index]?.authorization ?? null, payloads[index])));
324
322
  const { receipts, hasInvalidReceipt } = await this.#collectMutationReceipts(results, remainingEscrows, mutation, writing.receipts);
325
323
  const rejection = unanimousMutationRejection(results, writing.receipts);
326
324
  if (rejection) {
@@ -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,MA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ent":["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,E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,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 AuthControllerToken,\n Identifier,\n IdentifierSession,\n Mutation,\n MutationPayload,\n MutationReceipt,\n PendingMutationPayload,\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 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 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 const authControllerToken = await this.#authorizeMutation(\n mutation,\n payload,\n );\n await this.#replicateMutation({\n ...pending,\n phase: 'writing',\n authControllerToken,\n receipts: [],\n });\n });\n }\n\n async #authorizeMutation(\n mutation: Mutation,\n payload: PendingMutationPayload,\n ): Promise<AuthControllerToken> {\n return await this.#authProvider.authorizeRecoveryRequest({\n requestHash: mutation.requestHash,\n audiences: this.#escrows.map((escrow) => escrow.authAudience),\n ...(mutation.operation === 'register' ? {} : { requireTwoFactor: true }),\n ...(pendingPayloadHasIdentifiers(payload)\n ? { identifiers: payload.identifiers }\n : {}),\n });\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 authControllerToken: await this.#authorizeMutation(\n pending.mutation,\n pending.payload,\n ),\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, payload, 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 authControllerToken =\n claims && claims.exp > this.#now()\n ? pending.authControllerToken\n : await this.#authorizeMutation(mutation, payload);\n const writing = { ...pending, authControllerToken };\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 ),\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,5 +1,7 @@
1
1
  /**
2
- * Claims read from an Auth API approval, with camelCase field names.
2
+ * The claims the controller reads from an AuthController (Hydra) access token,
3
+ * in the token's shape with camelCase names. The Auth API token hook adds the
4
+ * step-up bindings under `ext`; a token that did not step up has none of them.
3
5
  */
4
6
  export type AuthControllerTokenClaims = {
5
7
  /**
@@ -15,9 +17,9 @@ export type AuthControllerTokenClaims = {
15
17
  /**
16
18
  * Authentication assurance level.
17
19
  */
18
- aal: number;
20
+ aal?: number;
19
21
  /**
20
- * Hash of the Auth API's recovery identifiers.
22
+ * Only present when the step-up was bound to a payload's identifiers.
21
23
  */
22
24
  identifiersHash?: string;
23
25
  };
@@ -1 +1 @@
1
- {"version":3,"file":"auth-controller-token.d.ts","sourceRoot":"","sources":["../src/auth-controller-token.ts"],"names":[],"mappings":"AAIA;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE;QACH,WAAW,EAAE,MAAM,CAAC;QACpB;;WAEG;QACH,GAAG,EAAE,MAAM,CAAC;QACZ;;WAEG;QACH,eAAe,CAAC,EAAE,MAAM,CAAC;KAC1B,CAAC;CACH,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,OAAO,GACb,yBAAyB,GAAG,SAAS,CA+BvC"}
1
+ {"version":3,"file":"auth-controller-token.d.ts","sourceRoot":"","sources":["../src/auth-controller-token.ts"],"names":[],"mappings":"AAIA;;;;GAIG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE;QACH,WAAW,EAAE,MAAM,CAAC;QACpB;;WAEG;QACH,GAAG,CAAC,EAAE,MAAM,CAAC;QACb;;WAEG;QACH,eAAe,CAAC,EAAE,MAAM,CAAC;KAC1B,CAAC;CACH,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,OAAO,GACb,yBAAyB,GAAG,SAAS,CA+BvC"}
@@ -27,7 +27,7 @@ export function decodeAuthControllerToken(token) {
27
27
  if (typeof sub !== 'string' ||
28
28
  typeof exp !== 'number' ||
29
29
  typeof requestHash !== 'string' ||
30
- typeof aal !== 'number' ||
30
+ (aal !== undefined && typeof aal !== 'number') ||
31
31
  (identifiersHash !== undefined && typeof identifiersHash !== 'string')) {
32
32
  return undefined;
33
33
  }
@@ -1 +1 @@
1
- {"version":3,"file":"auth-controller-token.js","sourceRoot":"","sources":["../src/auth-controller-token.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE1D,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AA2B5C;;;;;;;GAOG;AACH,MAAM,UAAU,yBAAyB,CACvC,KAAc;IAEd,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,MAAe,CAAC;IACpB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CACjB,aAAa,CAAC,aAAa,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CACxD,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/C,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,MAAM,CAAC;IACjC,MAAM,EACJ,GAAG,EACH,YAAY,EAAE,WAAW,EACzB,gBAAgB,EAAE,eAAe,GAClC,GAAG,GAAG,CAAC;IACR,IACE,OAAO,GAAG,KAAK,QAAQ;QACvB,OAAO,GAAG,KAAK,QAAQ;QACvB,OAAO,WAAW,KAAK,QAAQ;QAC/B,OAAO,GAAG,KAAK,QAAQ;QACvB,CAAC,eAAe,KAAK,SAAS,IAAI,OAAO,eAAe,KAAK,QAAQ,CAAC,EACtE,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,WAAW,EAAE,GAAG,EAAE,eAAe,EAAE,EAAE,CAAC;AAClE,CAAC","sourcesContent":["import { bytesToString, isObject } from '@metamask/utils';\n\nimport { fromBase64Url } from './crypto.js';\n\n/**\n * Claims read from an Auth API approval, with camelCase field names.\n */\nexport type AuthControllerTokenClaims = {\n /**\n * The profile id.\n */\n sub: string;\n /**\n * Unix time in seconds.\n */\n exp: number;\n ext: {\n requestHash: string;\n /**\n * Authentication assurance level.\n */\n aal: number;\n /**\n * Hash of the Auth API's recovery identifiers.\n */\n identifiersHash?: string;\n };\n};\n\n/**\n * Decodes the claims of an AuthController token without verifying its\n * signature; the escrow verifies the token. Required claims must be present;\n * optional ones may be absent but, when present, must have the right type.\n *\n * @param token - Compact JWT.\n * @returns The claims, or `undefined` if the token is malformed.\n */\nexport function decodeAuthControllerToken(\n token: unknown,\n): AuthControllerTokenClaims | undefined {\n if (typeof token !== 'string') {\n return undefined;\n }\n let claims: unknown;\n try {\n claims = JSON.parse(\n bytesToString(fromBase64Url(token.split('.')[1] ?? '')),\n );\n } catch {\n return undefined;\n }\n if (!isObject(claims) || !isObject(claims.ext)) {\n return undefined;\n }\n const { sub, exp, ext } = claims;\n const {\n aal,\n request_hash: requestHash,\n identifiers_hash: identifiersHash,\n } = ext;\n if (\n typeof sub !== 'string' ||\n typeof exp !== 'number' ||\n typeof requestHash !== 'string' ||\n typeof aal !== 'number' ||\n (identifiersHash !== undefined && typeof identifiersHash !== 'string')\n ) {\n return undefined;\n }\n return { sub, exp, ext: { requestHash, aal, identifiersHash } };\n}\n"]}
1
+ {"version":3,"file":"auth-controller-token.js","sourceRoot":"","sources":["../src/auth-controller-token.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;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\n/**\n * The claims the controller reads from an AuthController (Hydra) access token,\n * in the token's shape with camelCase names. The Auth API token hook adds the\n * step-up bindings under `ext`; a token that did not step up has none of them.\n */\nexport type AuthControllerTokenClaims = {\n /**\n * The profile id.\n */\n sub: string;\n /**\n * Unix time in seconds.\n */\n exp: number;\n ext: {\n requestHash: string;\n /**\n * Authentication assurance level.\n */\n aal?: number;\n /**\n * Only present when the step-up was bound to a payload's identifiers.\n */\n identifiersHash?: string;\n };\n};\n\n/**\n * Decodes the claims of an AuthController token without verifying its\n * signature; the escrow verifies the token. Required claims must be present;\n * optional ones may be absent but, when present, must have the right type.\n *\n * @param token - Compact JWT.\n * @returns The claims, or `undefined` if the token is malformed.\n */\nexport function decodeAuthControllerToken(\n token: unknown,\n): AuthControllerTokenClaims | undefined {\n if (typeof token !== 'string') {\n return undefined;\n }\n let claims: unknown;\n try {\n claims = JSON.parse(\n bytesToString(fromBase64Url(token.split('.')[1] ?? '')),\n );\n } catch {\n return undefined;\n }\n if (!isObject(claims) || !isObject(claims.ext)) {\n return undefined;\n }\n const { sub, exp, ext } = claims;\n const {\n aal,\n request_hash: requestHash,\n identifiers_hash: identifiersHash,\n } = ext;\n if (\n typeof sub !== 'string' ||\n typeof exp !== 'number' ||\n typeof requestHash !== 'string' ||\n (aal !== undefined && typeof aal !== 'number') ||\n (identifiersHash !== undefined && typeof identifiersHash !== 'string')\n ) {\n return undefined;\n }\n return { sub, exp, ext: { requestHash, aal, identifiersHash } };\n}\n"]}
package/dist/crypto.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { KeyPair } from '@metamask/cryptography';
2
2
  import type { Hex } from '@metamask/utils';
3
+ import type { Identifier } from './types.js';
3
4
  /**
4
5
  * Recursively sorts object keys so hashes are independent of property order.
5
6
  *
@@ -14,6 +15,23 @@ export declare function canonicalize(value: unknown): string;
14
15
  * @returns Hex digest.
15
16
  */
16
17
  export declare function hash(value: unknown): Promise<Hex>;
18
+ /**
19
+ * Orders two strings by their UTF-8 bytes. The escrow sorts identifiers the same
20
+ * way (Rust `String` ordering), so this must not be locale or UTF-16 aware.
21
+ *
22
+ * @param left - First string.
23
+ * @param right - Second string.
24
+ * @returns Negative, zero, or positive like `Array.prototype.sort` expects.
25
+ */
26
+ export declare function compareUtf8(left: string, right: string): number;
27
+ /**
28
+ * Canonical identifier list bound into AuthController `identifiersHash`.
29
+ *
30
+ * @param identifiers - Identifier set.
31
+ * @returns Identifier records including verifier material, sorted by the UTF-8
32
+ * bytes of their canonical JSON.
33
+ */
34
+ export declare function canonicalizeIdentifiers(identifiers: Identifier[]): unknown;
17
35
  /**
18
36
  * @returns A random 0x-prefixed id.
19
37
  */
@@ -1 +1 @@
1
- {"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAqBtD,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAM3C;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAKnD;AAED;;;;;GAKG;AACH,wBAAsB,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAEvD;AAED;;GAEG;AACH,wBAAgB,QAAQ,IAAI,GAAG,CAE9B;AAED;;;;GAIG;AACH,wBAAgB,OAAO,IAAI,MAAM,CAEhC;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,OAAO,CAAC,CAE3D;AAED;;;;GAIG;AACH,wBAAsB,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC,CAExD;AAED;;;;;;;GAOG;AACH,wBAAsB,IAAI,CACxB,UAAU,EAAE,UAAU,EACtB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,GAAG,CAAC,CAOd;AAED;;;;;;;;;GASG;AACH,wBAAsB,eAAe,CACnC,SAAS,EAAE,UAAU,EACrB,SAAS,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CAAC,CAE7E;AAED;;;;;;;GAOG;AACH,wBAAsB,eAAe,CACnC,UAAU,EAAE,UAAU,EACtB,SAAS,EAAE,UAAU,EACrB,SAAS,EAAE,UAAU,GACpB,OAAO,CAAC,UAAU,CAAC,CAIrB;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CACrC,UAAU,EAAE,UAAU,EACtB,SAAS,EAAE,UAAU,EACrB,UAAU,EAAE,UAAU,GACrB,OAAO,CAAC,UAAU,CAAC,CAOrB;AAcD;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAOvD"}
package/dist/crypto.js CHANGED
@@ -28,6 +28,43 @@ export function canonicalize(value) {
28
28
  export async function hash(value) {
29
29
  return bytesToHex(await sha256(stringToBytes(canonicalize(value))));
30
30
  }
31
+ /**
32
+ * Orders two strings by their UTF-8 bytes. The escrow sorts identifiers the same
33
+ * way (Rust `String` ordering), so this must not be locale or UTF-16 aware.
34
+ *
35
+ * @param left - First string.
36
+ * @param right - Second string.
37
+ * @returns Negative, zero, or positive like `Array.prototype.sort` expects.
38
+ */
39
+ export function compareUtf8(left, right) {
40
+ const leftBytes = stringToBytes(left);
41
+ const rightBytes = stringToBytes(right);
42
+ const shared = Math.min(leftBytes.length, rightBytes.length);
43
+ for (let index = 0; index < shared; index += 1) {
44
+ const difference = leftBytes[index] - rightBytes[index];
45
+ if (difference !== 0) {
46
+ return difference;
47
+ }
48
+ }
49
+ return leftBytes.length - rightBytes.length;
50
+ }
51
+ /**
52
+ * Canonical identifier list bound into AuthController `identifiersHash`.
53
+ *
54
+ * @param identifiers - Identifier set.
55
+ * @returns Identifier records including verifier material, sorted by the UTF-8
56
+ * bytes of their canonical JSON.
57
+ */
58
+ export function canonicalizeIdentifiers(identifiers) {
59
+ return [...identifiers]
60
+ .map((identifier) => ({
61
+ namespace: identifier.namespace,
62
+ type: identifier.type,
63
+ value: identifier.value,
64
+ verifier: identifier.verifier,
65
+ }))
66
+ .sort((left, right) => compareUtf8(canonicalize(left), canonicalize(right)));
67
+ }
31
68
  /**
32
69
  * @returns A random 0x-prefixed id.
33
70
  */
@@ -1 +1 @@
1
- {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,gCAAgC,CAAC;AAC7E,OAAO,EACL,eAAe,IAAI,sBAAsB,EACzC,IAAI,IAAI,WAAW,EACnB,MAAM,IAAI,aAAa,GACxB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACpD,OAAO,EACL,eAAe,IAAI,qBAAqB,EACxC,eAAe,GAChB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,aAAa,EACb,UAAU,EACV,WAAW,EACX,UAAU,EACV,aAAa,GACd,MAAM,iBAAiB,CAAC;AAEzB,OAAO,eAAe,MAAM,uBAAuB,CAAC;AAEpD,MAAM,SAAS,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAC7D,MAAM,YAAY,GAAG,EAAE,CAAC;AAExB;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,KAAc;IACzC,OAAO,eAAe,CAAC,KAAK,EAAE;QAC5B,QAAQ,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CACvB,IAAI,YAAY,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI;KACvD,CAAW,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,IAAI,CAAC,KAAc;IACvC,OAAO,UAAU,CAAC,MAAM,MAAM,CAAC,aAAa,CAAC,YAAY,CAAC,KAA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,CAAC,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,SAAS,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC;AAC7E,CAAC;AAED,KAAK,UAAU,kBAAkB,CAC/B,UAAsB,EACtB,SAAqB;IAErB,0EAA0E;IAC1E,MAAM,MAAM,GAAG,MAAM,eAAe,CAClC,IAAI,UAAU,CAAC,UAAU,CAAC,EAC1B,IAAI,UAAU,CAAC,SAAS,CAAC,CAC1B,CAAC;IACF,OAAO,UAAU,CAAC,MAAM,EAAE,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,YAAY,CAAC,CAAC;AACxE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,OAAO,aAAa,CAClB,KAAK;SACF,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAC9D,CAAC;AACJ,CAAC","sourcesContent":["import type { KeyPair } from '@metamask/cryptography';\nimport { getRandomBytes } from '@metamask/cryptography';\nimport { decrypt, encrypt, IV_LENGTH } from '@metamask/cryptography/aes-gcm';\nimport {\n generateKeyPair as generateEd25519KeyPair,\n sign as ed25519Sign,\n verify as ed25519Verify,\n} from '@metamask/cryptography/ed25519';\nimport { hkdfSha256 } from '@metamask/cryptography/hkdf';\nimport { sha256 } from '@metamask/cryptography/sha';\nimport {\n generateKeyPair as generateX25519KeyPair,\n getSharedSecret,\n} from '@metamask/cryptography/x25519';\nimport {\n base64ToBytes,\n bytesToHex,\n concatBytes,\n hexToBytes,\n stringToBytes,\n} from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\nimport stableStringify from 'json-stable-stringify';\n\nconst WRAP_INFO = new TextEncoder().encode('escrow-wrap-v1');\nconst WRAP_KEY_LEN = 32;\n\n/**\n * Recursively sorts object keys so hashes are independent of property order.\n *\n * @param value - JSON-compatible value.\n * @returns A canonical JSON string.\n */\nexport function canonicalize(value: unknown): string {\n return stableStringify(value, {\n replacer: (_key, node) =>\n node instanceof Uint8Array ? bytesToHex(node) : node,\n }) as string;\n}\n\n/**\n * SHA-256 of the canonical JSON form of `value`, as a 0x-prefixed hex string.\n *\n * @param value - Value to hash.\n * @returns Hex digest.\n */\nexport async function hash(value: unknown): Promise<Hex> {\n return bytesToHex(await sha256(stringToBytes(canonicalize(value))));\n}\n\n/**\n * @returns A random 0x-prefixed id.\n */\nexport function randomId(): Hex {\n return bytesToHex(getRandomBytes(16));\n}\n\n/**\n * Unix time in seconds. AuthController tokens and PoP challenges use this unit.\n *\n * @returns Seconds since the Unix epoch.\n */\nexport function unixNow(): number {\n return Math.floor(Date.now() / 1000);\n}\n\n/**\n * Generates an ephemeral Ed25519 proof key pair for key-bound identifier PoP.\n *\n * @returns Raw 32-byte Ed25519 public and private keys.\n */\nexport async function generateSigningKey(): Promise<KeyPair> {\n return await generateEd25519KeyPair();\n}\n\n/**\n * Generates an X25519 wrap key pair.\n *\n * @returns Raw 32-byte X25519 public and private keys.\n */\nexport async function generateWrapKey(): Promise<KeyPair> {\n return await generateX25519KeyPair();\n}\n\n/**\n * Signs a message with an Ed25519 private key.\n *\n * @param privateKey - Raw 32-byte Ed25519 private key.\n * @param message - Message string; signed as its UTF-8 bytes without a\n * pre-hash, since Ed25519 hashes internally.\n * @returns 0x-prefixed hex of the 64-byte Ed25519 signature.\n */\nexport async function sign(\n privateKey: Uint8Array,\n message: string,\n): Promise<Hex> {\n return bytesToHex(\n await ed25519Sign(\n new Uint8Array(privateKey),\n new Uint8Array(stringToBytes(message)),\n ),\n );\n}\n\n/**\n * Verifies an Ed25519 signature against a public key. Never throws: malformed\n * keys or signatures yield `false`.\n *\n * @param publicKey - Raw 32-byte Ed25519 public key.\n * @param signature - Hex of the 64-byte signature, with or without a 0x prefix.\n * @param message - Message string; verified as its UTF-8 bytes without a\n * pre-hash.\n * @returns Whether the signature is valid.\n */\nexport async function verifySignature(\n publicKey: Uint8Array,\n signature: string,\n message: string,\n): Promise<boolean> {\n try {\n return await ed25519Verify(\n new Uint8Array(publicKey),\n new Uint8Array(hexToBytes(signature)),\n new Uint8Array(stringToBytes(message)),\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Unsigned mutation-receipt digest. SHA-256 of canonical JSON of the receipt\n * fields excluding `signature`.\n *\n * @param receipt - Receipt fields covered by the signature.\n * @param receipt.escrowId - Escrow that issued the receipt.\n * @param receipt.mutationId - Mutation id.\n * @param receipt.receiptKeyId - SHA-256 of the raw 32-byte Ed25519 receipt public key.\n * @param receipt.requestHash - Mutation request hash.\n * @param receipt.version - Applied version.\n * @returns Hex digest.\n */\nexport async function hashMutationReceipt(receipt: {\n escrowId: string;\n mutationId: string;\n receiptKeyId: string;\n requestHash: string;\n version: number;\n}): Promise<Hex> {\n return hash({\n escrowId: receipt.escrowId,\n mutationId: receipt.mutationId,\n receiptKeyId: receipt.receiptKeyId,\n requestHash: receipt.requestHash,\n version: receipt.version,\n });\n}\n\n/**\n * SHA-256 of the raw 32-byte X25519 wrap public key, as `0x` hex.\n *\n * @param wrapPublicKey - Raw 32-byte X25519 wrap public key.\n * @returns Key id matching cubist `wrapKeyId`.\n */\nexport async function wrapKeyId(wrapPublicKey: Uint8Array): Promise<Hex> {\n return bytesToHex(await sha256(new Uint8Array(wrapPublicKey)));\n}\n\n/**\n * SHA-256 of the raw 32-byte Ed25519 receipt public key, as `0x` hex.\n *\n * @param receiptPublicKey - Raw 32-byte Ed25519 receipt public key.\n * @returns Key id matching cubist `receiptKeyId`.\n */\nexport async function receiptKeyId(receiptPublicKey: Uint8Array): Promise<Hex> {\n return bytesToHex(await sha256(new Uint8Array(receiptPublicKey)));\n}\n\n/**\n * Encrypts plaintext to an X25519 public key using escrow-wrap-v1.\n *\n * @param privateKey - Sender raw 32-byte X25519 private key.\n * @param publicKey - Recipient raw 32-byte X25519 public key.\n * @param plaintext - Bytes to encrypt.\n * @returns `iv || ciphertext+tag` bytes.\n */\nexport async function encryptToPublic(\n privateKey: Uint8Array,\n publicKey: Uint8Array,\n plaintext: Uint8Array,\n): Promise<Uint8Array> {\n const key = await deriveTransportKey(privateKey, publicKey);\n const { iv, ciphertext } = await encrypt(key, new Uint8Array(plaintext));\n return concatBytes([iv, ciphertext]);\n}\n\n/**\n * Decrypts escrow-wrap-v1 ciphertext produced by {@link encryptToPublic}.\n *\n * @param privateKey - Recipient raw 32-byte X25519 private key.\n * @param publicKey - Sender raw 32-byte X25519 public key.\n * @param ciphertext - `iv || ciphertext+tag` bytes.\n * @returns Plaintext bytes.\n */\nexport async function decryptFromPublic(\n privateKey: Uint8Array,\n publicKey: Uint8Array,\n ciphertext: Uint8Array,\n): Promise<Uint8Array> {\n const key = await deriveTransportKey(privateKey, publicKey);\n const blob = new Uint8Array(ciphertext);\n if (blob.length < IV_LENGTH) {\n throw new Error('Wrapped secret is truncated');\n }\n return decrypt(key, blob.subarray(0, IV_LENGTH), blob.subarray(IV_LENGTH));\n}\n\nasync function deriveTransportKey(\n privateKey: Uint8Array,\n publicKey: Uint8Array,\n): Promise<Uint8Array<ArrayBuffer>> {\n // WebCrypto rejects the all-zero shared secret of a low-order public key.\n const shared = await getSharedSecret(\n new Uint8Array(privateKey),\n new Uint8Array(publicKey),\n );\n return hkdfSha256(shared, new Uint8Array(0), WRAP_INFO, WRAP_KEY_LEN);\n}\n\n/**\n * Decodes unpadded base64url, as used by JWT segments.\n *\n * @param value - Base64url string.\n * @returns Raw bytes.\n */\nexport function fromBase64Url(value: string): Uint8Array {\n return base64ToBytes(\n value\n .replace(/-/gu, '+')\n .replace(/_/gu, '/')\n .padEnd(value.length + ((4 - (value.length % 4)) % 4), '='),\n );\n}\n"]}
1
+ {"version":3,"file":"cryp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U,CAAC,EAC1B,IAAI,UAAU,CAAC,SAAS,CAAC,CAC1B,CAAC;IACF,OAAO,UAAU,CAAC,MAAM,EAAE,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,YAAY,CAAC,CAAC;AACxE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,OAAO,aAAa,CAClB,KAAK;SACF,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAC9D,CAAC;AACJ,CAAC","sourcesContent":["import type { KeyPair } from '@metamask/cryptography';\nimport { getRandomBytes } from '@metamask/cryptography';\nimport { decrypt, encrypt, IV_LENGTH } from '@metamask/cryptography/aes-gcm';\nimport {\n generateKeyPair as generateEd25519KeyPair,\n sign as ed25519Sign,\n verify as ed25519Verify,\n} from '@metamask/cryptography/ed25519';\nimport { hkdfSha256 } from '@metamask/cryptography/hkdf';\nimport { sha256 } from '@metamask/cryptography/sha';\nimport {\n generateKeyPair as generateX25519KeyPair,\n getSharedSecret,\n} from '@metamask/cryptography/x25519';\nimport {\n base64ToBytes,\n bytesToHex,\n concatBytes,\n hexToBytes,\n stringToBytes,\n} from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\nimport stableStringify from 'json-stable-stringify';\n\nimport type { Identifier } from './types.js';\n\nconst WRAP_INFO = new TextEncoder().encode('escrow-wrap-v1');\nconst WRAP_KEY_LEN = 32;\n\n/**\n * Recursively sorts object keys so hashes are independent of property order.\n *\n * @param value - JSON-compatible value.\n * @returns A canonical JSON string.\n */\nexport function canonicalize(value: unknown): string {\n return stableStringify(value, {\n replacer: (_key, node) =>\n node instanceof Uint8Array ? bytesToHex(node) : node,\n }) as string;\n}\n\n/**\n * SHA-256 of the canonical JSON form of `value`, as a 0x-prefixed hex string.\n *\n * @param value - Value to hash.\n * @returns Hex digest.\n */\nexport async function hash(value: unknown): Promise<Hex> {\n return bytesToHex(await sha256(stringToBytes(canonicalize(value))));\n}\n\n/**\n * Orders two strings by their UTF-8 bytes. The escrow sorts identifiers the same\n * way (Rust `String` ordering), so this must not be locale or UTF-16 aware.\n *\n * @param left - First string.\n * @param right - Second string.\n * @returns Negative, zero, or positive like `Array.prototype.sort` expects.\n */\nexport function compareUtf8(left: string, right: string): number {\n const leftBytes = stringToBytes(left);\n const rightBytes = stringToBytes(right);\n const shared = Math.min(leftBytes.length, rightBytes.length);\n for (let index = 0; index < shared; index += 1) {\n const difference = leftBytes[index] - rightBytes[index];\n if (difference !== 0) {\n return difference;\n }\n }\n return leftBytes.length - rightBytes.length;\n}\n\n/**\n * Canonical identifier list bound into AuthController `identifiersHash`.\n *\n * @param identifiers - Identifier set.\n * @returns Identifier records including verifier material, sorted by the UTF-8\n * bytes of their canonical JSON.\n */\nexport function canonicalizeIdentifiers(identifiers: Identifier[]): unknown {\n return [...identifiers]\n .map((identifier) => ({\n namespace: identifier.namespace,\n type: identifier.type,\n value: identifier.value,\n verifier: identifier.verifier,\n }))\n .sort((left, right) =>\n compareUtf8(canonicalize(left), canonicalize(right)),\n );\n}\n\n/**\n * @returns A random 0x-prefixed id.\n */\nexport function randomId(): Hex {\n return bytesToHex(getRandomBytes(16));\n}\n\n/**\n * Unix time in seconds. AuthController tokens and PoP challenges use this unit.\n *\n * @returns Seconds since the Unix epoch.\n */\nexport function unixNow(): number {\n return Math.floor(Date.now() / 1000);\n}\n\n/**\n * Generates an ephemeral Ed25519 proof key pair for key-bound identifier PoP.\n *\n * @returns Raw 32-byte Ed25519 public and private keys.\n */\nexport async function generateSigningKey(): Promise<KeyPair> {\n return await generateEd25519KeyPair();\n}\n\n/**\n * Generates an X25519 wrap key pair.\n *\n * @returns Raw 32-byte X25519 public and private keys.\n */\nexport async function generateWrapKey(): Promise<KeyPair> {\n return await generateX25519KeyPair();\n}\n\n/**\n * Signs a message with an Ed25519 private key.\n *\n * @param privateKey - Raw 32-byte Ed25519 private key.\n * @param message - Message string; signed as its UTF-8 bytes without a\n * pre-hash, since Ed25519 hashes internally.\n * @returns 0x-prefixed hex of the 64-byte Ed25519 signature.\n */\nexport async function sign(\n privateKey: Uint8Array,\n message: string,\n): Promise<Hex> {\n return bytesToHex(\n await ed25519Sign(\n new Uint8Array(privateKey),\n new Uint8Array(stringToBytes(message)),\n ),\n );\n}\n\n/**\n * Verifies an Ed25519 signature against a public key. Never throws: malformed\n * keys or signatures yield `false`.\n *\n * @param publicKey - Raw 32-byte Ed25519 public key.\n * @param signature - Hex of the 64-byte signature, with or without a 0x prefix.\n * @param message - Message string; verified as its UTF-8 bytes without a\n * pre-hash.\n * @returns Whether the signature is valid.\n */\nexport async function verifySignature(\n publicKey: Uint8Array,\n signature: string,\n message: string,\n): Promise<boolean> {\n try {\n return await ed25519Verify(\n new Uint8Array(publicKey),\n new Uint8Array(hexToBytes(signature)),\n new Uint8Array(stringToBytes(message)),\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Unsigned mutation-receipt digest. SHA-256 of canonical JSON of the receipt\n * fields excluding `signature`.\n *\n * @param receipt - Receipt fields covered by the signature.\n * @param receipt.escrowId - Escrow that issued the receipt.\n * @param receipt.mutationId - Mutation id.\n * @param receipt.receiptKeyId - SHA-256 of the raw 32-byte Ed25519 receipt public key.\n * @param receipt.requestHash - Mutation request hash.\n * @param receipt.version - Applied version.\n * @returns Hex digest.\n */\nexport async function hashMutationReceipt(receipt: {\n escrowId: string;\n mutationId: string;\n receiptKeyId: string;\n requestHash: string;\n version: number;\n}): Promise<Hex> {\n return hash({\n escrowId: receipt.escrowId,\n mutationId: receipt.mutationId,\n receiptKeyId: receipt.receiptKeyId,\n requestHash: receipt.requestHash,\n version: receipt.version,\n });\n}\n\n/**\n * SHA-256 of the raw 32-byte X25519 wrap public key, as `0x` hex.\n *\n * @param wrapPublicKey - Raw 32-byte X25519 wrap public key.\n * @returns Key id matching cubist `wrapKeyId`.\n */\nexport async function wrapKeyId(wrapPublicKey: Uint8Array): Promise<Hex> {\n return bytesToHex(await sha256(new Uint8Array(wrapPublicKey)));\n}\n\n/**\n * SHA-256 of the raw 32-byte Ed25519 receipt public key, as `0x` hex.\n *\n * @param receiptPublicKey - Raw 32-byte Ed25519 receipt public key.\n * @returns Key id matching cubist `receiptKeyId`.\n */\nexport async function receiptKeyId(receiptPublicKey: Uint8Array): Promise<Hex> {\n return bytesToHex(await sha256(new Uint8Array(receiptPublicKey)));\n}\n\n/**\n * Encrypts plaintext to an X25519 public key using escrow-wrap-v1.\n *\n * @param privateKey - Sender raw 32-byte X25519 private key.\n * @param publicKey - Recipient raw 32-byte X25519 public key.\n * @param plaintext - Bytes to encrypt.\n * @returns `iv || ciphertext+tag` bytes.\n */\nexport async function encryptToPublic(\n privateKey: Uint8Array,\n publicKey: Uint8Array,\n plaintext: Uint8Array,\n): Promise<Uint8Array> {\n const key = await deriveTransportKey(privateKey, publicKey);\n const { iv, ciphertext } = await encrypt(key, new Uint8Array(plaintext));\n return concatBytes([iv, ciphertext]);\n}\n\n/**\n * Decrypts escrow-wrap-v1 ciphertext produced by {@link encryptToPublic}.\n *\n * @param privateKey - Recipient raw 32-byte X25519 private key.\n * @param publicKey - Sender raw 32-byte X25519 public key.\n * @param ciphertext - `iv || ciphertext+tag` bytes.\n * @returns Plaintext bytes.\n */\nexport async function decryptFromPublic(\n privateKey: Uint8Array,\n publicKey: Uint8Array,\n ciphertext: Uint8Array,\n): Promise<Uint8Array> {\n const key = await deriveTransportKey(privateKey, publicKey);\n const blob = new Uint8Array(ciphertext);\n if (blob.length < IV_LENGTH) {\n throw new Error('Wrapped secret is truncated');\n }\n return decrypt(key, blob.subarray(0, IV_LENGTH), blob.subarray(IV_LENGTH));\n}\n\nasync function deriveTransportKey(\n privateKey: Uint8Array,\n publicKey: Uint8Array,\n): Promise<Uint8Array<ArrayBuffer>> {\n // WebCrypto rejects the all-zero shared secret of a low-order public key.\n const shared = await getSharedSecret(\n new Uint8Array(privateKey),\n new Uint8Array(publicKey),\n );\n return hkdfSha256(shared, new Uint8Array(0), WRAP_INFO, WRAP_KEY_LEN);\n}\n\n/**\n * Decodes unpadded base64url, as used by JWT segments.\n *\n * @param value - Base64url string.\n * @returns Raw bytes.\n */\nexport function fromBase64Url(value: string): Uint8Array {\n return base64ToBytes(\n value\n .replace(/-/gu, '+')\n .replace(/_/gu, '/')\n .padEnd(value.length + ((4 - (value.length % 4)) % 4), '='),\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { CubeSignerClient, Version } from '@cubist-labs/cubesigner-sdk';
2
- import type { AuthControllerToken, GetRecoverySecretResponse, Identifier, IdentifierAuthorization, Mutation, MutationPayload, MutationReceipt, PoPChallenge, RecoveryEscrowProvider } from '../types.js';
2
+ import type { AuthControllerToken, GetRecoverySecretResponse, IdentifierAuthorization, Mutation, MutationPayload, MutationReceipt, PoPChallenge, RecoveryEscrowProvider } from '../types.js';
3
3
  /**
4
4
  * CubeSigner C2F client for the Cubist recovery escrow.
5
5
  *
@@ -13,10 +13,6 @@ export type CubistEscrowProviderOptions = {
13
13
  * Authenticated CubeSigner client used to invoke the escrow C2F.
14
14
  */
15
15
  client: CubeSignerClient;
16
- /**
17
- * Must match the escrow's AUTH_CONTROLLER_AUDIENCE configuration.
18
- */
19
- authAudience: string;
20
16
  /**
21
17
  * C2F name or named-policy id. Defaults to `cubist_secret_escrow`.
22
18
  */
@@ -37,7 +33,7 @@ export type CubistEscrowProviderOptions = {
37
33
  export declare class CubistEscrowProvider implements RecoveryEscrowProvider {
38
34
  #private;
39
35
  readonly id = "cubist";
40
- readonly authAudience: string;
36
+ readonly authAudience = "cubist";
41
37
  readonly wrapPublicKey: Uint8Array;
42
38
  /**
43
39
  * @param options - CubeSigner client, pinned keys, and optional C2F id/version.
@@ -52,23 +48,20 @@ export declare class CubistEscrowProvider implements RecoveryEscrowProvider {
52
48
  */
53
49
  generateChallenge(): Promise<PoPChallenge>;
54
50
  /**
55
- * @param authControllerToken - Request-bound approval for this read.
56
51
  * @param authorization - Identifier proof for this read.
57
52
  * @param requestId - Client request id bound into the read hash.
58
53
  * @param pkE - Ephemeral wrap public key for the response.
59
54
  * @returns The wrapped recovery secret and its version.
60
55
  */
61
- getSecret(authControllerToken: AuthControllerToken, authorization: IdentifierAuthorization, requestId: string, pkE: Uint8Array): Promise<GetRecoverySecretResponse>;
56
+ getSecret(authorization: IdentifierAuthorization, requestId: string, pkE: Uint8Array): Promise<GetRecoverySecretResponse>;
62
57
  /**
63
58
  * @param mutation - Mutation to apply.
64
59
  * @param authControllerToken - Request-bound AuthController token.
65
60
  * @param identifierAuthorization - Identifier proof. `null` for register.
66
61
  * @param payload - Per-escrow mutation payload.
67
- * @param approvedIdentifiers - The approval's identifiers, which payload
68
- * identifiers must be drawn from.
69
62
  * @returns The escrow's mutation receipt.
70
63
  */
71
- applyMutation(mutation: Mutation, authControllerToken: AuthControllerToken, identifierAuthorization: IdentifierAuthorization | null, payload: MutationPayload, approvedIdentifiers: Identifier[]): Promise<MutationReceipt>;
64
+ applyMutation(mutation: Mutation, authControllerToken: AuthControllerToken, identifierAuthorization: IdentifierAuthorization | null, payload: MutationPayload): Promise<MutationReceipt>;
72
65
  /**
73
66
  * Verifies a receipt with the pinned receipt public key.
74
67
  *
@@ -1 +1 @@
1
- {"version":3,"file":"cubist-escrow-provider.d.ts","sourceRoot":"","sources":["../../src/escrow-providers/cubist-escrow-provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAEhB,OAAO,EACR,MAAM,6BAA6B,CAAC;AAgBrC,OAAO,KAAK,EACV,mBAAmB,EACnB,yBAAyB,EACzB,UAAU,EACV,uBAAuB,EACvB,QAAQ,EACR,eAAe,EACf,eAAe,EACf,YAAY,EACZ,sBAAsB,EACvB,MAAM,aAAa,CAA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