@metamask-previews/passkey-controller 2.1.0-preview-789f7f935 → 2.1.0-preview-eade524

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