@metamask/passkey-controller 2.0.1 → 3.0.0

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 (41) hide show
  1. package/CHANGELOG.md +52 -1
  2. package/README.md +83 -20
  3. package/dist/PasskeyController-method-action-types.cjs +7 -0
  4. package/dist/PasskeyController-method-action-types.cjs.map +1 -0
  5. package/dist/PasskeyController-method-action-types.d.cts +204 -0
  6. package/dist/PasskeyController-method-action-types.d.cts.map +1 -0
  7. package/dist/PasskeyController-method-action-types.d.mts +204 -0
  8. package/dist/PasskeyController-method-action-types.d.mts.map +1 -0
  9. package/dist/PasskeyController-method-action-types.mjs +6 -0
  10. package/dist/PasskeyController-method-action-types.mjs.map +1 -0
  11. package/dist/PasskeyController.cjs +341 -163
  12. package/dist/PasskeyController.cjs.map +1 -1
  13. package/dist/PasskeyController.d.cts +88 -49
  14. package/dist/PasskeyController.d.cts.map +1 -1
  15. package/dist/PasskeyController.d.mts +88 -49
  16. package/dist/PasskeyController.d.mts.map +1 -1
  17. package/dist/PasskeyController.mjs +341 -163
  18. package/dist/PasskeyController.mjs.map +1 -1
  19. package/dist/constants.cjs +4 -0
  20. package/dist/constants.cjs.map +1 -1
  21. package/dist/constants.d.cts +5 -1
  22. package/dist/constants.d.cts.map +1 -1
  23. package/dist/constants.d.mts +5 -1
  24. package/dist/constants.d.mts.map +1 -1
  25. package/dist/constants.mjs +4 -0
  26. package/dist/constants.mjs.map +1 -1
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +2 -2
  29. package/dist/index.d.cts.map +1 -1
  30. package/dist/index.d.mts +2 -2
  31. package/dist/index.d.mts.map +1 -1
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/types.cjs +1 -0
  34. package/dist/types.cjs.map +1 -1
  35. package/dist/types.d.cts +38 -0
  36. package/dist/types.d.cts.map +1 -1
  37. package/dist/types.d.mts +38 -0
  38. package/dist/types.d.mts.map +1 -1
  39. package/dist/types.mjs +1 -1
  40. package/dist/types.mjs.map +1 -1
  41. package/package.json +11 -4
@@ -9,9 +9,10 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _PasskeyController_instances, _PasskeyController_ceremonyManager, _PasskeyController_expectedRPIDs, _PasskeyController_rpId, _PasskeyController_rpName, _PasskeyController_expectedOrigin, _PasskeyController_userName, _PasskeyController_userDisplayName, _PasskeyController_requireEnrolled, _PasskeyController_getChallengeFromClientData, _PasskeyController_verifyAuthenticationResponse;
12
+ var _PasskeyController_instances, _PasskeyController_ceremonyManager, _PasskeyController_expectedRPIDs, _PasskeyController_rpId, _PasskeyController_rpName, _PasskeyController_expectedOrigin, _PasskeyController_userName, _PasskeyController_userDisplayName, _PasskeyController_getIsOnboardingCompleted, _PasskeyController_operationMutex, _PasskeyController_protectVaultKeyWithPasskey, _PasskeyController_retrieveVaultKeyWithPasskey, _PasskeyController_verifyPasskeyAuthentication, _PasskeyController_renewVaultKeyProtection, _PasskeyController_changePasswordWithPasskeyVerification, _PasskeyController_removePasskeyWithPasskeyVerification, _PasskeyController_removePasskeyWithPasswordVerification, _PasskeyController_verifyAuthenticationResponse, _PasskeyController_withOperationLock, _PasskeyController_assertEnrollmentAllowed, _PasskeyController_requireEnrolled, _PasskeyController_getChallengeFromClientData, _PasskeyController_removePasskey;
13
13
  import { BaseController } from "@metamask/base-controller";
14
14
  import { areUint8ArraysEqual, stringToBytes } from "@metamask/utils";
15
+ import { Mutex } from "async-mutex";
15
16
  import { WEBAUTHN_TIMEOUT_MS, CeremonyManager } from "./ceremony-manager.mjs";
16
17
  import { controllerName, PasskeyControllerErrorCode, PasskeyControllerErrorMessage } from "./constants.mjs";
17
18
  import { PasskeyControllerError } from "./errors.mjs";
@@ -50,6 +51,24 @@ const log = createModuleLogger(projectLogger, controllerName);
50
51
  export const passkeyControllerSelectors = {
51
52
  selectIsPasskeyEnrolled: (state) => state.passkeyRecord !== null,
52
53
  };
54
+ const MESSENGER_EXPOSED_METHODS = [
55
+ 'isPasskeyEnrolled',
56
+ 'generateRegistrationOptions',
57
+ 'generatePostRegistrationAuthenticationOptions',
58
+ 'generateAuthenticationOptions',
59
+ 'protectVaultKeyWithPasskey',
60
+ 'retrieveVaultKeyWithPasskey',
61
+ 'unlockWithPasskey',
62
+ 'verifyPasskeyAuthentication',
63
+ 'renewVaultKeyProtection',
64
+ 'changePasswordWithPasskeyVerification',
65
+ 'exportSeedPhraseWithPasskey',
66
+ 'exportAccountsWithPasskey',
67
+ 'removePasskeyWithPasskeyVerification',
68
+ 'removePasskeyWithPasswordVerification',
69
+ 'clearState',
70
+ 'destroy',
71
+ ];
53
72
  /**
54
73
  * Controller that enrolls a WebAuthn passkey and uses it to protect and unlock
55
74
  * the vault encryption key.
@@ -58,20 +77,18 @@ export class PasskeyController extends BaseController {
58
77
  /**
59
78
  * Creates a passkey controller with WebAuthn relying-party settings.
60
79
  *
61
- * @param args - Constructor options.
62
- * @param args.messenger - Controller messenger.
63
- * @param args.state - Partial initial state; merged with {@link getDefaultPasskeyControllerState}.
64
- * @param args.expectedRPID - Relying party ID(s) for verification (SHA-256 hash match in
65
- * authenticator data). Pass a string or array of strings; an empty array skips RP ID
66
- * allowlist checks in {@link verifyRegistrationResponse} / {@link verifyAuthenticationResponse}.
67
- * @param args.rpId - When set, included as `rp.id` on registration options and `rpId` on
68
- * authentication options. When omitted, those fields are left unset (client default RP ID).
69
- * @param args.rpName - Relying party name shown in the platform passkey UI.
70
- * @param args.expectedOrigin - Allowed value(s) for the WebAuthn client origin.
71
- * @param args.userName - Optional passkey user name; defaults to `rpName`.
72
- * @param args.userDisplayName - Optional display name; defaults to `rpName`.
80
+ * @param options - Constructor options.
81
+ * @param options.messenger - The messenger to use for communication.
82
+ * @param options.state - The initial state of the controller.
83
+ * @param options.rpId - The relying party ID to use for the passkey.
84
+ * @param options.expectedRPID - The expected relying party ID to use for the passkey.
85
+ * @param options.rpName - The relying party name to use for the passkey.
86
+ * @param options.expectedOrigin - The expected origin to use for the passkey.
87
+ * @param options.userName - The user name to use for the passkey.
88
+ * @param options.userDisplayName - The user display name to use for the passkey.
89
+ * @param options.getIsOnboardingCompleted - The callback to use to check if onboarding is complete.
73
90
  */
74
- constructor({ messenger, state = {}, rpId, expectedRPID, rpName, expectedOrigin, userName, userDisplayName, }) {
91
+ constructor({ messenger, state = {}, rpId, expectedRPID, rpName, expectedOrigin, userName, userDisplayName, getIsOnboardingCompleted, }) {
75
92
  super({
76
93
  messenger,
77
94
  metadata: passkeyControllerMetadata,
@@ -86,6 +103,8 @@ export class PasskeyController extends BaseController {
86
103
  _PasskeyController_expectedOrigin.set(this, void 0);
87
104
  _PasskeyController_userName.set(this, void 0);
88
105
  _PasskeyController_userDisplayName.set(this, void 0);
106
+ _PasskeyController_getIsOnboardingCompleted.set(this, void 0);
107
+ _PasskeyController_operationMutex.set(this, new Mutex());
89
108
  const expectedRPIDs = Array.isArray(expectedRPID)
90
109
  ? expectedRPID
91
110
  : [expectedRPID];
@@ -95,6 +114,8 @@ export class PasskeyController extends BaseController {
95
114
  __classPrivateFieldSet(this, _PasskeyController_expectedOrigin, expectedOrigin, "f");
96
115
  __classPrivateFieldSet(this, _PasskeyController_userName, userName ?? rpName, "f");
97
116
  __classPrivateFieldSet(this, _PasskeyController_userDisplayName, userDisplayName ?? rpName, "f");
117
+ __classPrivateFieldSet(this, _PasskeyController_getIsOnboardingCompleted, getIsOnboardingCompleted, "f");
118
+ this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
98
119
  }
99
120
  /**
100
121
  * Whether a passkey is enrolled and vault key material is stored.
@@ -239,113 +260,72 @@ export class PasskeyController extends BaseController {
239
260
  * Verifies registration and post-registration authentication, then stores the
240
261
  * vault key encrypted under the new passkey.
241
262
  *
263
+ * Fetches the current vault encryption key from KeyringController before wrapping.
264
+ * When onboarding is complete, requires `password` for step-up verification first.
265
+ *
242
266
  * @param params - Enrollment completion inputs.
243
267
  * @param params.registrationResponse - Result of `navigator.credentials.create()`.
244
268
  * @param params.authenticationResponse - Result of `navigator.credentials.get()` after {@link generatePostRegistrationAuthenticationOptions}.
245
- * @param params.vaultKey - Vault encryption key to encrypt and persist.
269
+ * @param params.password - Wallet password when onboarding is complete (step-up).
270
+ * @returns Resolves when enrollment completes.
246
271
  */
247
272
  async protectVaultKeyWithPasskey(params) {
248
- if (this.isPasskeyEnrolled()) {
249
- throw new PasskeyControllerError(PasskeyControllerErrorMessage.AlreadyEnrolled, { code: PasskeyControllerErrorCode.AlreadyEnrolled });
250
- }
251
- const { registrationResponse, authenticationResponse, vaultKey } = params;
252
- // get registration ceremony
253
- const challenge = __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_getChallengeFromClientData).call(this, registrationResponse.response.clientDataJSON);
254
- const registrationCeremony = __classPrivateFieldGet(this, _PasskeyController_ceremonyManager, "f").getRegistrationCeremony(challenge);
255
- if (!registrationCeremony) {
256
- log('No active passkey registration ceremony for challenge');
257
- throw new PasskeyControllerError(PasskeyControllerErrorMessage.NoRegistrationCeremony, { code: PasskeyControllerErrorCode.NoRegistrationCeremony });
258
- }
259
- try {
260
- // verify registration response
261
- const { verified, registrationInfo } = await verifyRegistrationResponse({
262
- response: registrationResponse,
263
- expectedChallenge: registrationCeremony.challenge,
264
- expectedOrigin: __classPrivateFieldGet(this, _PasskeyController_expectedOrigin, "f"),
265
- expectedRPIDs: __classPrivateFieldGet(this, _PasskeyController_expectedRPIDs, "f"),
266
- requireUserVerification: true,
267
- }).catch((error) => {
268
- log('Error verifying passkey registration response', error);
269
- throw new PasskeyControllerError(PasskeyControllerErrorMessage.RegistrationVerificationFailed, {
270
- code: PasskeyControllerErrorCode.RegistrationVerificationFailed,
271
- cause: error instanceof Error ? error : new Error(String(error)),
272
- });
273
- });
274
- if (!verified || !registrationInfo) {
275
- log('Passkey registration verification returned unverified or missing registration info');
276
- throw new PasskeyControllerError(PasskeyControllerErrorMessage.RegistrationVerificationFailed, { code: PasskeyControllerErrorCode.RegistrationVerificationFailed });
277
- }
278
- // verify authentication response
279
- const credential = {
280
- id: registrationInfo.credentialId,
281
- publicKey: bytesToBase64URL(registrationInfo.publicKey),
282
- counter: registrationInfo.counter,
283
- transports: registrationInfo.transports,
284
- aaguid: registrationInfo.aaguid,
285
- };
286
- const { newCounter } = await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_verifyAuthenticationResponse).call(this, authenticationResponse, credential);
287
- // determine key derivation method
288
- const prfFirst = authenticationResponse.clientExtensionResults?.prf?.results?.first;
289
- const authHasPrfOutput = typeof prfFirst === 'string' && prfFirst.length > 0;
290
- const keyDerivation = authHasPrfOutput && registrationCeremony.prfSalt
291
- ? { method: 'prf', prfSalt: registrationCeremony.prfSalt }
292
- : { method: 'userHandle' };
293
- if (keyDerivation.method === 'userHandle' &&
294
- authenticationResponse.response.userHandle !==
295
- registrationCeremony.userHandle) {
296
- log('Post-registration assertion userHandle does not match registration ceremony');
297
- throw new PasskeyControllerError(PasskeyControllerErrorMessage.AuthenticationVerificationFailed, { code: PasskeyControllerErrorCode.AuthenticationVerificationFailed });
298
- }
299
- // derive key and encrypt vault key
300
- const encKey = deriveKeyFromAuthenticationResponse(authenticationResponse, { credential, keyDerivation });
301
- const { ciphertext, iv } = encryptWithKey(vaultKey, encKey);
302
- // persist passkey record
303
- this.update((state) => {
304
- state.passkeyRecord = {
305
- credential: {
306
- ...credential,
307
- counter: Math.max(newCounter, credential.counter),
308
- },
309
- encryptedVaultKey: { ciphertext, iv },
310
- keyDerivation,
311
- };
312
- });
313
- }
314
- finally {
315
- // delete registration ceremony
316
- __classPrivateFieldGet(this, _PasskeyController_ceremonyManager, "f").deleteRegistrationCeremony(challenge);
317
- }
273
+ return __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_withOperationLock).call(this, () => __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_protectVaultKeyWithPasskey).call(this, params));
318
274
  }
319
275
  /**
320
276
  * Verifies an authentication assertion and returns the decrypted vault key.
321
277
  *
278
+ * Prefer orchestrated methods ({@link unlockWithPasskey},
279
+ * {@link exportSeedPhraseWithPasskey}, {@link exportAccountsWithPasskey}) for product
280
+ * flows instead of calling KeyringController with the returned key manually.
281
+ *
322
282
  * @param authenticationResponse - Result of `navigator.credentials.get()`.
323
283
  * @returns The plaintext vault encryption key.
324
284
  */
325
285
  async retrieveVaultKeyWithPasskey(authenticationResponse) {
326
- const passkeyRecord = __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_requireEnrolled).call(this);
327
- // verify authentication response and update counter
328
- const { newCounter } = await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_verifyAuthenticationResponse).call(this, authenticationResponse, passkeyRecord.credential);
329
- this.update((state) => {
330
- if (!state.passkeyRecord) {
331
- throw new PasskeyControllerError(PasskeyControllerErrorMessage.NotEnrolled, { code: PasskeyControllerErrorCode.NotEnrolled });
286
+ return __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_withOperationLock).call(this, () => __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_retrieveVaultKeyWithPasskey).call(this, authenticationResponse));
287
+ }
288
+ /**
289
+ * Unlocks the keyring using a passkey authentication assertion.
290
+ *
291
+ * @param authenticationResponse - Result of `navigator.credentials.get()`.
292
+ * @returns Resolves when the keyring is unlocked.
293
+ */
294
+ async unlockWithPasskey(authenticationResponse) {
295
+ return __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_withOperationLock).call(this, async () => {
296
+ const vaultKey = await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_retrieveVaultKeyWithPasskey).call(this, authenticationResponse);
297
+ await this.messenger.call('KeyringController:submitEncryptionKey', vaultKey);
298
+ });
299
+ }
300
+ /**
301
+ * Exports the seed phrase after passkey step-up authentication.
302
+ *
303
+ * @param authenticationResponse - Result of `navigator.credentials.get()`.
304
+ * @param keyringId - Optional keyring id; defaults to the primary HD keyring.
305
+ * @returns Raw seed phrase bytes from KeyringController.
306
+ */
307
+ async exportSeedPhraseWithPasskey(authenticationResponse, keyringId) {
308
+ return __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_withOperationLock).call(this, async () => {
309
+ const vaultKey = await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_retrieveVaultKeyWithPasskey).call(this, authenticationResponse);
310
+ return await this.messenger.call('KeyringController:exportSeedPhrase', { encryptionKey: vaultKey }, keyringId);
311
+ });
312
+ }
313
+ /**
314
+ * Exports private keys for the given addresses after passkey step-up authentication.
315
+ *
316
+ * @param authenticationResponse - Result of `navigator.credentials.get()`.
317
+ * @param addresses - Account addresses to export.
318
+ * @returns Private keys in the same order as `addresses`.
319
+ */
320
+ async exportAccountsWithPasskey(authenticationResponse, addresses) {
321
+ return __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_withOperationLock).call(this, async () => {
322
+ const vaultKey = await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_retrieveVaultKeyWithPasskey).call(this, authenticationResponse);
323
+ const privateKeys = [];
324
+ for (const address of addresses) {
325
+ privateKeys.push(await this.messenger.call('KeyringController:exportAccount', { encryptionKey: vaultKey }, address));
332
326
  }
333
- state.passkeyRecord.credential.counter = Math.max(newCounter, state.passkeyRecord.credential.counter);
327
+ return privateKeys;
334
328
  });
335
- // derive key
336
- const encKey = deriveKeyFromAuthenticationResponse(authenticationResponse, passkeyRecord);
337
- // decrypt vault key
338
- try {
339
- const vaultKey = decryptWithKey(passkeyRecord.encryptedVaultKey.ciphertext, passkeyRecord.encryptedVaultKey.iv, encKey);
340
- return vaultKey;
341
- }
342
- catch (cause) {
343
- log('Error decrypting vault key with passkey', cause instanceof Error ? cause : new Error(String(cause)));
344
- throw new PasskeyControllerError(PasskeyControllerErrorMessage.VaultKeyDecryptionFailed, {
345
- code: PasskeyControllerErrorCode.VaultKeyDecryptionFailed,
346
- cause: cause instanceof Error ? cause : new Error(String(cause)),
347
- });
348
- }
349
329
  }
350
330
  /**
351
331
  * Checks whether the given authentication assertion is valid for the enrolled passkey.
@@ -357,16 +337,7 @@ export class PasskeyController extends BaseController {
357
337
  * @returns `true` if verification succeeds, otherwise `false`.
358
338
  */
359
339
  async verifyPasskeyAuthentication(authenticationResponse) {
360
- try {
361
- await this.retrieveVaultKeyWithPasskey(authenticationResponse);
362
- return true;
363
- }
364
- catch (error) {
365
- if (error instanceof PasskeyControllerError && error.code !== undefined) {
366
- return false;
367
- }
368
- throw error;
369
- }
340
+ return __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_withOperationLock).call(this, () => __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_verifyPasskeyAuthentication).call(this, authenticationResponse));
370
341
  }
371
342
  /**
372
343
  * Re-wraps the vault key after rotation. Updates persisted `encryptedVaultKey` on success.
@@ -376,59 +347,62 @@ export class PasskeyController extends BaseController {
376
347
  * pass the same `authenticationResponse` you just verified (e.g. from
377
348
  * {@link retrieveVaultKeyWithPasskey} / {@link verifyPasskeyAuthentication}).
378
349
  *
350
+ * For password change with passkey step-up, prefer
351
+ * {@link changePasswordWithPasskeyVerification}, which orchestrates keyring export,
352
+ * `changePassword`, and re-wrap in one call.
353
+ *
379
354
  * @param params - Re-wrap inputs.
380
355
  * @param params.authenticationResponse - Used to derive the wrapping key.
381
356
  * @param params.oldVaultKey - Expected current vault key.
382
357
  * @param params.newVaultKey - New vault key to encrypt under the passkey.
358
+ * @returns Resolves when the passkey record is updated.
383
359
  */
384
360
  async renewVaultKeyProtection(params) {
385
- const { authenticationResponse } = params;
386
- const passkeyRecord = __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_requireEnrolled).call(this);
387
- // derive key
388
- const encKey = deriveKeyFromAuthenticationResponse(authenticationResponse, passkeyRecord);
389
- // decrypt vault key
390
- let decryptedVaultKey;
391
- try {
392
- decryptedVaultKey = decryptWithKey(passkeyRecord.encryptedVaultKey.ciphertext, passkeyRecord.encryptedVaultKey.iv, encKey);
393
- }
394
- catch (error) {
395
- log('Error decrypting vault key during passkey vault key renewal', error instanceof Error ? error : new Error(String(error)));
396
- throw new PasskeyControllerError(PasskeyControllerErrorMessage.VaultKeyDecryptionFailed, {
397
- code: PasskeyControllerErrorCode.VaultKeyDecryptionFailed,
398
- cause: error instanceof Error ? error : new Error(String(error)),
399
- });
400
- }
401
- // check if vault key matches
402
- const { oldVaultKey, newVaultKey } = params;
403
- if (!areUint8ArraysEqual(stringToBytes(decryptedVaultKey), stringToBytes(oldVaultKey))) {
404
- log('Passkey renewal rejected: decrypted vault key does not match oldVaultKey');
405
- throw new PasskeyControllerError(PasskeyControllerErrorMessage.VaultKeyMismatch, { code: PasskeyControllerErrorCode.VaultKeyMismatch });
406
- }
407
- // encrypt new vault key
408
- const { ciphertext, iv } = encryptWithKey(newVaultKey, encKey);
409
- // persist passkey record (mutate current state only for vault key material)
410
- this.update((state) => {
411
- if (!state.passkeyRecord) {
412
- throw new PasskeyControllerError(PasskeyControllerErrorMessage.NotEnrolled, {
413
- code: PasskeyControllerErrorCode.NotEnrolled,
414
- });
415
- }
416
- state.passkeyRecord.encryptedVaultKey = { ciphertext, iv };
417
- });
361
+ return __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_withOperationLock).call(this, () => __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_renewVaultKeyProtection).call(this, params));
418
362
  }
419
363
  /**
420
- * Clears enrolled passkey state and in-flight ceremonies. Call only after the same
421
- * auth gate as renewal (verified passkey assertion or password).
364
+ * Changes the wallet password after passkey step-up authentication.
365
+ *
366
+ * When `renewVaultKeyProtection` is `true` (default), re-wraps the vault key under the
367
+ * passkey after rotation. When `false`, removes the passkey instead.
368
+ *
369
+ * @param params - Change-password inputs.
370
+ * @param params.newPassword - New wallet password.
371
+ * @param params.authenticationResponse - Result of `navigator.credentials.get()`.
372
+ * @param params.options - Optional flow controls.
373
+ * @param params.options.renewVaultKeyProtection - Re-wrap vault key after password change.
374
+ * @returns Resolves when the password change completes.
422
375
  */
423
- removePasskey() {
424
- this.update(() => getDefaultPasskeyControllerState());
425
- __classPrivateFieldGet(this, _PasskeyController_ceremonyManager, "f").clear();
376
+ async changePasswordWithPasskeyVerification(params) {
377
+ return __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_withOperationLock).call(this, () => __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_changePasswordWithPasskeyVerification).call(this, params));
378
+ }
379
+ /**
380
+ * Removes the enrolled passkey after verifying a passkey authentication assertion.
381
+ *
382
+ * @param authenticationResponse - Result of `navigator.credentials.get()`.
383
+ * @returns Resolves when the passkey is removed.
384
+ */
385
+ async removePasskeyWithPasskeyVerification(authenticationResponse) {
386
+ return __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_withOperationLock).call(this, () => __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_removePasskeyWithPasskeyVerification).call(this, authenticationResponse));
387
+ }
388
+ /**
389
+ * Removes the enrolled passkey after verifying the wallet password.
390
+ *
391
+ * @param password - Wallet password for step-up verification.
392
+ * @returns Resolves when the passkey is removed.
393
+ */
394
+ async removePasskeyWithPasswordVerification(password) {
395
+ return __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_withOperationLock).call(this, () => __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_removePasskeyWithPasswordVerification).call(this, password));
426
396
  }
427
397
  /**
428
398
  * Resets state and clears in-flight registration/authentication ceremonies.
399
+ *
400
+ * For user-facing passkey removal with step-up, use
401
+ * {@link removePasskeyWithPasskeyVerification} or
402
+ * {@link removePasskeyWithPasswordVerification}.
429
403
  */
430
404
  clearState() {
431
- this.removePasskey();
405
+ __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_removePasskey).call(this);
432
406
  }
433
407
  /**
434
408
  * Releases all in-flight ceremony state and tears down the messenger.
@@ -438,16 +412,188 @@ export class PasskeyController extends BaseController {
438
412
  super.destroy();
439
413
  }
440
414
  }
441
- _PasskeyController_ceremonyManager = new WeakMap(), _PasskeyController_expectedRPIDs = new WeakMap(), _PasskeyController_rpId = new WeakMap(), _PasskeyController_rpName = new WeakMap(), _PasskeyController_expectedOrigin = new WeakMap(), _PasskeyController_userName = new WeakMap(), _PasskeyController_userDisplayName = new WeakMap(), _PasskeyController_instances = new WeakSet(), _PasskeyController_requireEnrolled = function _PasskeyController_requireEnrolled() {
442
- const record = this.state.passkeyRecord;
443
- if (!record) {
444
- throw new PasskeyControllerError(PasskeyControllerErrorMessage.NotEnrolled, {
445
- code: PasskeyControllerErrorCode.NotEnrolled,
415
+ _PasskeyController_ceremonyManager = new WeakMap(), _PasskeyController_expectedRPIDs = new WeakMap(), _PasskeyController_rpId = new WeakMap(), _PasskeyController_rpName = new WeakMap(), _PasskeyController_expectedOrigin = new WeakMap(), _PasskeyController_userName = new WeakMap(), _PasskeyController_userDisplayName = new WeakMap(), _PasskeyController_getIsOnboardingCompleted = new WeakMap(), _PasskeyController_operationMutex = new WeakMap(), _PasskeyController_instances = new WeakSet(), _PasskeyController_protectVaultKeyWithPasskey = async function _PasskeyController_protectVaultKeyWithPasskey(params) {
416
+ if (this.isPasskeyEnrolled()) {
417
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.AlreadyEnrolled, { code: PasskeyControllerErrorCode.AlreadyEnrolled });
418
+ }
419
+ await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_assertEnrollmentAllowed).call(this, params.password);
420
+ const vaultKey = await this.messenger.call('KeyringController:exportEncryptionKey');
421
+ const { registrationResponse, authenticationResponse } = params;
422
+ // get registration ceremony
423
+ const challenge = __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_getChallengeFromClientData).call(this, registrationResponse.response.clientDataJSON);
424
+ const registrationCeremony = __classPrivateFieldGet(this, _PasskeyController_ceremonyManager, "f").getRegistrationCeremony(challenge);
425
+ if (!registrationCeremony) {
426
+ log('No active passkey registration ceremony for challenge');
427
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.NoRegistrationCeremony, { code: PasskeyControllerErrorCode.NoRegistrationCeremony });
428
+ }
429
+ try {
430
+ // verify registration response
431
+ const { verified, registrationInfo } = await verifyRegistrationResponse({
432
+ response: registrationResponse,
433
+ expectedChallenge: registrationCeremony.challenge,
434
+ expectedOrigin: __classPrivateFieldGet(this, _PasskeyController_expectedOrigin, "f"),
435
+ expectedRPIDs: __classPrivateFieldGet(this, _PasskeyController_expectedRPIDs, "f"),
436
+ requireUserVerification: true,
437
+ }).catch((error) => {
438
+ log('Error verifying passkey registration response', error);
439
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.RegistrationVerificationFailed, {
440
+ code: PasskeyControllerErrorCode.RegistrationVerificationFailed,
441
+ cause: error instanceof Error ? error : new Error(String(error)),
442
+ });
443
+ });
444
+ if (!verified || !registrationInfo) {
445
+ log('Passkey registration verification returned unverified or missing registration info');
446
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.RegistrationVerificationFailed, { code: PasskeyControllerErrorCode.RegistrationVerificationFailed });
447
+ }
448
+ // verify authentication response
449
+ const credential = {
450
+ id: registrationInfo.credentialId,
451
+ publicKey: bytesToBase64URL(registrationInfo.publicKey),
452
+ counter: registrationInfo.counter,
453
+ transports: registrationInfo.transports,
454
+ aaguid: registrationInfo.aaguid,
455
+ };
456
+ const { newCounter } = await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_verifyAuthenticationResponse).call(this, authenticationResponse, credential);
457
+ // determine key derivation method
458
+ const prfFirst = authenticationResponse.clientExtensionResults?.prf?.results?.first;
459
+ const authHasPrfOutput = typeof prfFirst === 'string' && prfFirst.length > 0;
460
+ const keyDerivation = authHasPrfOutput && registrationCeremony.prfSalt
461
+ ? { method: 'prf', prfSalt: registrationCeremony.prfSalt }
462
+ : { method: 'userHandle' };
463
+ if (keyDerivation.method === 'userHandle' &&
464
+ authenticationResponse.response.userHandle !==
465
+ registrationCeremony.userHandle) {
466
+ log('Post-registration assertion userHandle does not match registration ceremony');
467
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.AuthenticationVerificationFailed, { code: PasskeyControllerErrorCode.AuthenticationVerificationFailed });
468
+ }
469
+ // derive key and encrypt vault key
470
+ const encKey = deriveKeyFromAuthenticationResponse(authenticationResponse, { credential, keyDerivation });
471
+ const { ciphertext, iv } = encryptWithKey(vaultKey, encKey);
472
+ // persist passkey record
473
+ this.update((state) => {
474
+ state.passkeyRecord = {
475
+ credential: {
476
+ ...credential,
477
+ counter: Math.max(newCounter, credential.counter),
478
+ },
479
+ encryptedVaultKey: { ciphertext, iv },
480
+ keyDerivation,
481
+ };
446
482
  });
447
483
  }
448
- return record;
449
- }, _PasskeyController_getChallengeFromClientData = function _PasskeyController_getChallengeFromClientData(clientDataJSON) {
450
- return decodeClientDataJSON(clientDataJSON).challenge;
484
+ finally {
485
+ // delete registration ceremony
486
+ __classPrivateFieldGet(this, _PasskeyController_ceremonyManager, "f").deleteRegistrationCeremony(challenge);
487
+ }
488
+ }, _PasskeyController_retrieveVaultKeyWithPasskey = async function _PasskeyController_retrieveVaultKeyWithPasskey(authenticationResponse) {
489
+ const passkeyRecord = __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_requireEnrolled).call(this);
490
+ // verify authentication response and update counter
491
+ const { newCounter } = await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_verifyAuthenticationResponse).call(this, authenticationResponse, passkeyRecord.credential);
492
+ this.update((state) => {
493
+ if (!state.passkeyRecord) {
494
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.NotEnrolled, { code: PasskeyControllerErrorCode.NotEnrolled });
495
+ }
496
+ state.passkeyRecord.credential.counter = Math.max(newCounter, state.passkeyRecord.credential.counter);
497
+ });
498
+ // derive key
499
+ const encKey = deriveKeyFromAuthenticationResponse(authenticationResponse, passkeyRecord);
500
+ // decrypt vault key
501
+ try {
502
+ const vaultKey = decryptWithKey(passkeyRecord.encryptedVaultKey.ciphertext, passkeyRecord.encryptedVaultKey.iv, encKey);
503
+ return vaultKey;
504
+ }
505
+ catch (cause) {
506
+ log('Error decrypting vault key with passkey', cause instanceof Error ? cause : new Error(String(cause)));
507
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.VaultKeyDecryptionFailed, {
508
+ code: PasskeyControllerErrorCode.VaultKeyDecryptionFailed,
509
+ cause: cause instanceof Error ? cause : new Error(String(cause)),
510
+ });
511
+ }
512
+ }, _PasskeyController_verifyPasskeyAuthentication = async function _PasskeyController_verifyPasskeyAuthentication(authenticationResponse) {
513
+ try {
514
+ await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_retrieveVaultKeyWithPasskey).call(this, authenticationResponse);
515
+ return true;
516
+ }
517
+ catch (error) {
518
+ if (error instanceof PasskeyControllerError && error.code !== undefined) {
519
+ return false;
520
+ }
521
+ throw error;
522
+ }
523
+ }, _PasskeyController_renewVaultKeyProtection = async function _PasskeyController_renewVaultKeyProtection(params) {
524
+ const { authenticationResponse } = params;
525
+ const passkeyRecord = __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_requireEnrolled).call(this);
526
+ // derive key
527
+ const encKey = deriveKeyFromAuthenticationResponse(authenticationResponse, passkeyRecord);
528
+ // decrypt vault key
529
+ let decryptedVaultKey;
530
+ try {
531
+ decryptedVaultKey = decryptWithKey(passkeyRecord.encryptedVaultKey.ciphertext, passkeyRecord.encryptedVaultKey.iv, encKey);
532
+ }
533
+ catch (error) {
534
+ log('Error decrypting vault key during passkey vault key renewal', error instanceof Error ? error : new Error(String(error)));
535
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.VaultKeyDecryptionFailed, {
536
+ code: PasskeyControllerErrorCode.VaultKeyDecryptionFailed,
537
+ cause: error instanceof Error ? error : new Error(String(error)),
538
+ });
539
+ }
540
+ // check if vault key matches
541
+ const { oldVaultKey, newVaultKey } = params;
542
+ if (!areUint8ArraysEqual(stringToBytes(decryptedVaultKey), stringToBytes(oldVaultKey))) {
543
+ log('Passkey renewal rejected: decrypted vault key does not match oldVaultKey');
544
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.VaultKeyMismatch, { code: PasskeyControllerErrorCode.VaultKeyMismatch });
545
+ }
546
+ // encrypt new vault key
547
+ const { ciphertext, iv } = encryptWithKey(newVaultKey, encKey);
548
+ // persist passkey record (mutate current state only for vault key material)
549
+ this.update((state) => {
550
+ if (!state.passkeyRecord) {
551
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.NotEnrolled, {
552
+ code: PasskeyControllerErrorCode.NotEnrolled,
553
+ });
554
+ }
555
+ state.passkeyRecord.encryptedVaultKey = { ciphertext, iv };
556
+ });
557
+ }, _PasskeyController_changePasswordWithPasskeyVerification = async function _PasskeyController_changePasswordWithPasskeyVerification(params) {
558
+ __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_requireEnrolled).call(this);
559
+ const verified = await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_verifyPasskeyAuthentication).call(this, params.authenticationResponse);
560
+ if (!verified) {
561
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.AuthenticationVerificationFailed, { code: PasskeyControllerErrorCode.AuthenticationVerificationFailed });
562
+ }
563
+ const renewVaultKeyProtection = params.options?.renewVaultKeyProtection ?? true;
564
+ if (!renewVaultKeyProtection) {
565
+ await this.messenger.call('KeyringController:changePassword', params.newPassword);
566
+ __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_removePasskey).call(this);
567
+ return;
568
+ }
569
+ const vaultKeyBefore = await this.messenger.call('KeyringController:exportEncryptionKey');
570
+ await this.messenger.call('KeyringController:changePassword', params.newPassword);
571
+ try {
572
+ const vaultKeyAfter = await this.messenger.call('KeyringController:exportEncryptionKey');
573
+ await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_renewVaultKeyProtection).call(this, {
574
+ authenticationResponse: params.authenticationResponse,
575
+ oldVaultKey: vaultKeyBefore,
576
+ newVaultKey: vaultKeyAfter,
577
+ });
578
+ }
579
+ catch (error) {
580
+ __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_removePasskey).call(this);
581
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.VaultKeyRenewalFailed, {
582
+ code: PasskeyControllerErrorCode.VaultKeyRenewalFailed,
583
+ cause: error instanceof Error ? error : new Error(String(error)),
584
+ });
585
+ }
586
+ }, _PasskeyController_removePasskeyWithPasskeyVerification = async function _PasskeyController_removePasskeyWithPasskeyVerification(authenticationResponse) {
587
+ __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_requireEnrolled).call(this);
588
+ const verified = await __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_verifyPasskeyAuthentication).call(this, authenticationResponse);
589
+ if (!verified) {
590
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.AuthenticationVerificationFailed, { code: PasskeyControllerErrorCode.AuthenticationVerificationFailed });
591
+ }
592
+ __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_removePasskey).call(this);
593
+ }, _PasskeyController_removePasskeyWithPasswordVerification = async function _PasskeyController_removePasskeyWithPasswordVerification(password) {
594
+ __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_requireEnrolled).call(this);
595
+ await this.messenger.call('KeyringController:verifyPassword', password);
596
+ __classPrivateFieldGet(this, _PasskeyController_instances, "m", _PasskeyController_removePasskey).call(this);
451
597
  }, _PasskeyController_verifyAuthenticationResponse =
452
598
  /**
453
599
  * Validates a WebAuthn authentication response against stored credential data.
@@ -498,5 +644,37 @@ async function _PasskeyController_verifyAuthenticationResponse(authenticationRes
498
644
  // delete authentication ceremony
499
645
  __classPrivateFieldGet(this, _PasskeyController_ceremonyManager, "f").deleteAuthenticationCeremony(challenge);
500
646
  }
647
+ }, _PasskeyController_withOperationLock =
648
+ /**
649
+ * Serializes orchestrated passkey operations that mutate state or call KeyringController.
650
+ *
651
+ * @param callback - Operation to run while the mutex is held.
652
+ * @returns The result of the callback.
653
+ */
654
+ async function _PasskeyController_withOperationLock(callback) {
655
+ return __classPrivateFieldGet(this, _PasskeyController_operationMutex, "f").runExclusive(callback);
656
+ }, _PasskeyController_assertEnrollmentAllowed = async function _PasskeyController_assertEnrollmentAllowed(password) {
657
+ if (!__classPrivateFieldGet(this, _PasskeyController_getIsOnboardingCompleted, "f").call(this)) {
658
+ return;
659
+ }
660
+ if (!password) {
661
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.EnrollmentPasswordRequired, {
662
+ code: PasskeyControllerErrorCode.EnrollmentPasswordRequired,
663
+ });
664
+ }
665
+ await this.messenger.call('KeyringController:verifyPassword', password);
666
+ }, _PasskeyController_requireEnrolled = function _PasskeyController_requireEnrolled() {
667
+ const record = this.state.passkeyRecord;
668
+ if (!record) {
669
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.NotEnrolled, {
670
+ code: PasskeyControllerErrorCode.NotEnrolled,
671
+ });
672
+ }
673
+ return record;
674
+ }, _PasskeyController_getChallengeFromClientData = function _PasskeyController_getChallengeFromClientData(clientDataJSON) {
675
+ return decodeClientDataJSON(clientDataJSON).challenge;
676
+ }, _PasskeyController_removePasskey = function _PasskeyController_removePasskey() {
677
+ this.update(() => getDefaultPasskeyControllerState());
678
+ __classPrivateFieldGet(this, _PasskeyController_ceremonyManager, "f").clear();
501
679
  };
502
680
  //# sourceMappingURL=PasskeyController.mjs.map