@metamask/passkey-controller 3.0.0 → 4.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 (209) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/dist/{PasskeyController-method-action-types.d.mts → PasskeyController-method-action-types.d.ts} +2 -2
  3. package/dist/PasskeyController-method-action-types.d.ts.map +1 -0
  4. package/dist/{PasskeyController-method-action-types.mjs → PasskeyController-method-action-types.js} +1 -1
  5. package/dist/PasskeyController-method-action-types.js.map +1 -0
  6. package/dist/{PasskeyController.d.mts → PasskeyController.d.ts} +6 -6
  7. package/dist/PasskeyController.d.ts.map +1 -0
  8. package/dist/PasskeyController.js +680 -0
  9. package/dist/PasskeyController.js.map +1 -0
  10. package/dist/{ceremony-manager.d.cts → ceremony-manager.d.ts} +2 -2
  11. package/dist/ceremony-manager.d.ts.map +1 -0
  12. package/dist/ceremony-manager.js +135 -0
  13. package/dist/ceremony-manager.js.map +1 -0
  14. package/dist/{constants.d.mts → constants.d.ts} +12 -12
  15. package/dist/constants.d.ts.map +1 -0
  16. package/dist/{constants.mjs → constants.js} +1 -1
  17. package/dist/constants.js.map +1 -0
  18. package/dist/{errors.d.mts → errors.d.ts} +2 -2
  19. package/dist/errors.d.ts.map +1 -0
  20. package/dist/{errors.mjs → errors.js} +4 -1
  21. package/dist/errors.js.map +1 -0
  22. package/dist/{index.d.cts → index.d.ts} +8 -7
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +5 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/{key-derivation.d.cts → key-derivation.d.ts} +3 -3
  27. package/dist/key-derivation.d.ts.map +1 -0
  28. package/dist/{key-derivation.mjs → key-derivation.js} +5 -5
  29. package/dist/key-derivation.js.map +1 -0
  30. package/dist/logger.d.ts +4 -0
  31. package/dist/logger.d.ts.map +1 -0
  32. package/dist/logger.js +6 -0
  33. package/dist/logger.js.map +1 -0
  34. package/dist/{types.d.mts → types.d.ts} +6 -6
  35. package/dist/types.d.ts.map +1 -0
  36. package/dist/types.js +2 -0
  37. package/dist/types.js.map +1 -0
  38. package/dist/utils/{crypto.d.mts → crypto.d.ts} +1 -1
  39. package/dist/utils/crypto.d.ts.map +1 -0
  40. package/dist/utils/{crypto.mjs → crypto.js} +7 -7
  41. package/dist/utils/crypto.js.map +1 -0
  42. package/dist/utils/{encoding.d.cts → encoding.d.ts} +1 -1
  43. package/dist/utils/encoding.d.ts.map +1 -0
  44. package/dist/utils/{encoding.mjs → encoding.js} +2 -2
  45. package/dist/utils/encoding.js.map +1 -0
  46. package/dist/webauthn/{constants.d.mts → constants.d.ts} +1 -1
  47. package/dist/webauthn/constants.d.ts.map +1 -0
  48. package/dist/webauthn/{constants.mjs → constants.js} +1 -1
  49. package/dist/webauthn/constants.js.map +1 -0
  50. package/dist/webauthn/{decode-attestation-object.d.mts → decode-attestation-object.d.ts} +2 -2
  51. package/dist/webauthn/decode-attestation-object.d.ts.map +1 -0
  52. package/dist/webauthn/{decode-attestation-object.mjs → decode-attestation-object.js} +2 -2
  53. package/dist/webauthn/decode-attestation-object.js.map +1 -0
  54. package/dist/webauthn/{decode-client-data-json.d.cts → decode-client-data-json.d.ts} +2 -2
  55. package/dist/webauthn/decode-client-data-json.d.ts.map +1 -0
  56. package/dist/webauthn/{decode-client-data-json.mjs → decode-client-data-json.js} +2 -2
  57. package/dist/webauthn/decode-client-data-json.js.map +1 -0
  58. package/dist/webauthn/{match-expected-rp-id.d.cts → match-expected-rp-id.d.ts} +1 -1
  59. package/dist/webauthn/match-expected-rp-id.d.ts.map +1 -0
  60. package/dist/webauthn/{match-expected-rp-id.mjs → match-expected-rp-id.js} +4 -4
  61. package/dist/webauthn/match-expected-rp-id.js.map +1 -0
  62. package/dist/webauthn/{parse-authenticator-data.d.cts → parse-authenticator-data.d.ts} +2 -2
  63. package/dist/webauthn/parse-authenticator-data.d.ts.map +1 -0
  64. package/dist/webauthn/{parse-authenticator-data.mjs → parse-authenticator-data.js} +2 -2
  65. package/dist/webauthn/parse-authenticator-data.js.map +1 -0
  66. package/dist/webauthn/{types.d.mts → types.d.ts} +2 -2
  67. package/dist/webauthn/types.d.ts.map +1 -0
  68. package/dist/webauthn/types.js +2 -0
  69. package/dist/webauthn/types.js.map +1 -0
  70. package/dist/webauthn/{verify-authentication-response.d.cts → verify-authentication-response.d.ts} +3 -3
  71. package/dist/webauthn/verify-authentication-response.d.ts.map +1 -0
  72. package/dist/webauthn/{verify-authentication-response.mjs → verify-authentication-response.js} +9 -9
  73. package/dist/webauthn/verify-authentication-response.js.map +1 -0
  74. package/dist/webauthn/{verify-registration-response.d.mts → verify-registration-response.d.ts} +24 -3
  75. package/dist/webauthn/verify-registration-response.d.ts.map +1 -0
  76. package/dist/webauthn/{verify-registration-response.mjs → verify-registration-response.js} +54 -20
  77. package/dist/webauthn/verify-registration-response.js.map +1 -0
  78. package/dist/webauthn/{verify-signature.d.cts → verify-signature.d.ts} +1 -1
  79. package/dist/webauthn/verify-signature.d.ts.map +1 -0
  80. package/dist/webauthn/{verify-signature.mjs → verify-signature.js} +7 -7
  81. package/dist/webauthn/verify-signature.js.map +1 -0
  82. package/package.json +21 -26
  83. package/dist/PasskeyController-method-action-types.cjs +0 -7
  84. package/dist/PasskeyController-method-action-types.cjs.map +0 -1
  85. package/dist/PasskeyController-method-action-types.d.cts +0 -204
  86. package/dist/PasskeyController-method-action-types.d.cts.map +0 -1
  87. package/dist/PasskeyController-method-action-types.d.mts.map +0 -1
  88. package/dist/PasskeyController-method-action-types.mjs.map +0 -1
  89. package/dist/PasskeyController.cjs +0 -685
  90. package/dist/PasskeyController.cjs.map +0 -1
  91. package/dist/PasskeyController.d.cts +0 -208
  92. package/dist/PasskeyController.d.cts.map +0 -1
  93. package/dist/PasskeyController.d.mts.map +0 -1
  94. package/dist/PasskeyController.mjs +0 -680
  95. package/dist/PasskeyController.mjs.map +0 -1
  96. package/dist/ceremony-manager.cjs +0 -135
  97. package/dist/ceremony-manager.cjs.map +0 -1
  98. package/dist/ceremony-manager.d.cts.map +0 -1
  99. package/dist/ceremony-manager.d.mts +0 -72
  100. package/dist/ceremony-manager.d.mts.map +0 -1
  101. package/dist/ceremony-manager.mjs +0 -131
  102. package/dist/ceremony-manager.mjs.map +0 -1
  103. package/dist/constants.cjs +0 -39
  104. package/dist/constants.cjs.map +0 -1
  105. package/dist/constants.d.cts +0 -36
  106. package/dist/constants.d.cts.map +0 -1
  107. package/dist/constants.d.mts.map +0 -1
  108. package/dist/constants.mjs.map +0 -1
  109. package/dist/errors.cjs +0 -57
  110. package/dist/errors.cjs.map +0 -1
  111. package/dist/errors.d.cts +0 -34
  112. package/dist/errors.d.cts.map +0 -1
  113. package/dist/errors.d.mts.map +0 -1
  114. package/dist/errors.mjs.map +0 -1
  115. package/dist/index.cjs +0 -13
  116. package/dist/index.cjs.map +0 -1
  117. package/dist/index.d.cts.map +0 -1
  118. package/dist/index.d.mts +0 -7
  119. package/dist/index.d.mts.map +0 -1
  120. package/dist/index.mjs +0 -4
  121. package/dist/index.mjs.map +0 -1
  122. package/dist/key-derivation.cjs +0 -44
  123. package/dist/key-derivation.cjs.map +0 -1
  124. package/dist/key-derivation.d.cts.map +0 -1
  125. package/dist/key-derivation.d.mts +0 -20
  126. package/dist/key-derivation.d.mts.map +0 -1
  127. package/dist/key-derivation.mjs.map +0 -1
  128. package/dist/logger.cjs +0 -9
  129. package/dist/logger.cjs.map +0 -1
  130. package/dist/logger.d.cts +0 -5
  131. package/dist/logger.d.cts.map +0 -1
  132. package/dist/logger.d.mts +0 -5
  133. package/dist/logger.d.mts.map +0 -1
  134. package/dist/logger.mjs +0 -6
  135. package/dist/logger.mjs.map +0 -1
  136. package/dist/types.cjs +0 -4
  137. package/dist/types.cjs.map +0 -1
  138. package/dist/types.d.cts +0 -132
  139. package/dist/types.d.cts.map +0 -1
  140. package/dist/types.d.mts.map +0 -1
  141. package/dist/types.mjs +0 -2
  142. package/dist/types.mjs.map +0 -1
  143. package/dist/utils/crypto.cjs +0 -66
  144. package/dist/utils/crypto.cjs.map +0 -1
  145. package/dist/utils/crypto.d.cts +0 -37
  146. package/dist/utils/crypto.d.cts.map +0 -1
  147. package/dist/utils/crypto.d.mts.map +0 -1
  148. package/dist/utils/crypto.mjs.map +0 -1
  149. package/dist/utils/encoding.cjs +0 -42
  150. package/dist/utils/encoding.cjs.map +0 -1
  151. package/dist/utils/encoding.d.cts.map +0 -1
  152. package/dist/utils/encoding.d.mts +0 -22
  153. package/dist/utils/encoding.d.mts.map +0 -1
  154. package/dist/utils/encoding.mjs.map +0 -1
  155. package/dist/webauthn/constants.cjs +0 -74
  156. package/dist/webauthn/constants.cjs.map +0 -1
  157. package/dist/webauthn/constants.d.cts +0 -68
  158. package/dist/webauthn/constants.d.cts.map +0 -1
  159. package/dist/webauthn/constants.d.mts.map +0 -1
  160. package/dist/webauthn/constants.mjs.map +0 -1
  161. package/dist/webauthn/decode-attestation-object.cjs +0 -18
  162. package/dist/webauthn/decode-attestation-object.cjs.map +0 -1
  163. package/dist/webauthn/decode-attestation-object.d.cts +0 -10
  164. package/dist/webauthn/decode-attestation-object.d.cts.map +0 -1
  165. package/dist/webauthn/decode-attestation-object.d.mts.map +0 -1
  166. package/dist/webauthn/decode-attestation-object.mjs.map +0 -1
  167. package/dist/webauthn/decode-client-data-json.cjs +0 -17
  168. package/dist/webauthn/decode-client-data-json.cjs.map +0 -1
  169. package/dist/webauthn/decode-client-data-json.d.cts.map +0 -1
  170. package/dist/webauthn/decode-client-data-json.d.mts +0 -9
  171. package/dist/webauthn/decode-client-data-json.d.mts.map +0 -1
  172. package/dist/webauthn/decode-client-data-json.mjs.map +0 -1
  173. package/dist/webauthn/match-expected-rp-id.cjs +0 -26
  174. package/dist/webauthn/match-expected-rp-id.cjs.map +0 -1
  175. package/dist/webauthn/match-expected-rp-id.d.cts.map +0 -1
  176. package/dist/webauthn/match-expected-rp-id.d.mts +0 -11
  177. package/dist/webauthn/match-expected-rp-id.d.mts.map +0 -1
  178. package/dist/webauthn/match-expected-rp-id.mjs.map +0 -1
  179. package/dist/webauthn/parse-authenticator-data.cjs +0 -69
  180. package/dist/webauthn/parse-authenticator-data.cjs.map +0 -1
  181. package/dist/webauthn/parse-authenticator-data.d.cts.map +0 -1
  182. package/dist/webauthn/parse-authenticator-data.d.mts +0 -10
  183. package/dist/webauthn/parse-authenticator-data.d.mts.map +0 -1
  184. package/dist/webauthn/parse-authenticator-data.mjs.map +0 -1
  185. package/dist/webauthn/types.cjs +0 -3
  186. package/dist/webauthn/types.cjs.map +0 -1
  187. package/dist/webauthn/types.d.cts +0 -113
  188. package/dist/webauthn/types.d.cts.map +0 -1
  189. package/dist/webauthn/types.d.mts.map +0 -1
  190. package/dist/webauthn/types.mjs +0 -2
  191. package/dist/webauthn/types.mjs.map +0 -1
  192. package/dist/webauthn/verify-authentication-response.cjs +0 -133
  193. package/dist/webauthn/verify-authentication-response.cjs.map +0 -1
  194. package/dist/webauthn/verify-authentication-response.d.cts.map +0 -1
  195. package/dist/webauthn/verify-authentication-response.d.mts +0 -64
  196. package/dist/webauthn/verify-authentication-response.d.mts.map +0 -1
  197. package/dist/webauthn/verify-authentication-response.mjs.map +0 -1
  198. package/dist/webauthn/verify-registration-response.cjs +0 -207
  199. package/dist/webauthn/verify-registration-response.cjs.map +0 -1
  200. package/dist/webauthn/verify-registration-response.d.cts +0 -60
  201. package/dist/webauthn/verify-registration-response.d.cts.map +0 -1
  202. package/dist/webauthn/verify-registration-response.d.mts.map +0 -1
  203. package/dist/webauthn/verify-registration-response.mjs.map +0 -1
  204. package/dist/webauthn/verify-signature.cjs +0 -176
  205. package/dist/webauthn/verify-signature.cjs.map +0 -1
  206. package/dist/webauthn/verify-signature.d.cts.map +0 -1
  207. package/dist/webauthn/verify-signature.d.mts +0 -21
  208. package/dist/webauthn/verify-signature.d.mts.map +0 -1
  209. package/dist/webauthn/verify-signature.mjs.map +0 -1
@@ -0,0 +1,680 @@
1
+ import { BaseController } from '@metamask/base-controller';
2
+ import { areUint8ArraysEqual, stringToBytes } from '@metamask/utils';
3
+ import { Mutex } from 'async-mutex';
4
+ import { WEBAUTHN_TIMEOUT_MS, CeremonyManager } from './ceremony-manager.js';
5
+ import { controllerName, PasskeyControllerErrorCode, PasskeyControllerErrorMessage, } from './constants.js';
6
+ import { PasskeyControllerError } from './errors.js';
7
+ import { deriveKeyFromAuthenticationResponse } from './key-derivation.js';
8
+ import { createModuleLogger, projectLogger } from './logger.js';
9
+ import { decryptWithKey, encryptWithKey, randomBytesToBase64URL, } from './utils/crypto.js';
10
+ import { base64URLToBytes, bytesToBase64URL } from './utils/encoding.js';
11
+ import { COSEALG } from './webauthn/constants.js';
12
+ import { decodeClientDataJSON } from './webauthn/decode-client-data-json.js';
13
+ import { verifyAuthenticationResponse } from './webauthn/verify-authentication-response.js';
14
+ import { verifyRegistrationResponse } from './webauthn/verify-registration-response.js';
15
+ /**
16
+ * Returns the default (empty) state for {@link PasskeyController}.
17
+ *
18
+ * @returns A fresh state object with no enrolled passkey.
19
+ */
20
+ export function getDefaultPasskeyControllerState() {
21
+ return { passkeyRecord: null };
22
+ }
23
+ const passkeyControllerMetadata = {
24
+ passkeyRecord: {
25
+ persist: true,
26
+ includeInDebugSnapshot: false,
27
+ includeInStateLogs: false,
28
+ usedInUi: true,
29
+ },
30
+ };
31
+ const log = createModuleLogger(projectLogger, controllerName);
32
+ /**
33
+ * Selectors for {@link PasskeyControllerState}.
34
+ *
35
+ * Use these instead of dedicated getter methods on the controller, so that
36
+ * derived values can be consumed from Redux selectors and other places that
37
+ * only have access to a state object.
38
+ */
39
+ export const passkeyControllerSelectors = {
40
+ selectIsPasskeyEnrolled: (state) => state.passkeyRecord !== null,
41
+ };
42
+ const MESSENGER_EXPOSED_METHODS = [
43
+ 'isPasskeyEnrolled',
44
+ 'generateRegistrationOptions',
45
+ 'generatePostRegistrationAuthenticationOptions',
46
+ 'generateAuthenticationOptions',
47
+ 'protectVaultKeyWithPasskey',
48
+ 'retrieveVaultKeyWithPasskey',
49
+ 'unlockWithPasskey',
50
+ 'verifyPasskeyAuthentication',
51
+ 'renewVaultKeyProtection',
52
+ 'changePasswordWithPasskeyVerification',
53
+ 'exportSeedPhraseWithPasskey',
54
+ 'exportAccountsWithPasskey',
55
+ 'removePasskeyWithPasskeyVerification',
56
+ 'removePasskeyWithPasswordVerification',
57
+ 'clearState',
58
+ 'destroy',
59
+ ];
60
+ /**
61
+ * Controller that enrolls a WebAuthn passkey and uses it to protect and unlock
62
+ * the vault encryption key.
63
+ */
64
+ export class PasskeyController extends BaseController {
65
+ #ceremonyManager = new CeremonyManager();
66
+ #expectedRPIDs;
67
+ #rpId;
68
+ #rpName;
69
+ #expectedOrigin;
70
+ #userName;
71
+ #userDisplayName;
72
+ #getIsOnboardingCompleted;
73
+ #operationMutex = new Mutex();
74
+ /**
75
+ * Creates a passkey controller with WebAuthn relying-party settings.
76
+ *
77
+ * @param options - Constructor options.
78
+ * @param options.messenger - The messenger to use for communication.
79
+ * @param options.state - The initial state of the controller.
80
+ * @param options.rpId - The relying party ID to use for the passkey.
81
+ * @param options.expectedRPID - The expected relying party ID to use for the passkey.
82
+ * @param options.rpName - The relying party name to use for the passkey.
83
+ * @param options.expectedOrigin - The expected origin to use for the passkey.
84
+ * @param options.userName - The user name to use for the passkey.
85
+ * @param options.userDisplayName - The user display name to use for the passkey.
86
+ * @param options.getIsOnboardingCompleted - The callback to use to check if onboarding is complete.
87
+ */
88
+ constructor({ messenger, state = {}, rpId, expectedRPID, rpName, expectedOrigin, userName, userDisplayName, getIsOnboardingCompleted, }) {
89
+ super({
90
+ messenger,
91
+ metadata: passkeyControllerMetadata,
92
+ name: controllerName,
93
+ state: { ...getDefaultPasskeyControllerState(), ...state },
94
+ });
95
+ const expectedRPIDs = Array.isArray(expectedRPID)
96
+ ? expectedRPID
97
+ : [expectedRPID];
98
+ this.#expectedRPIDs = [...expectedRPIDs];
99
+ this.#rpId = rpId;
100
+ this.#rpName = rpName;
101
+ this.#expectedOrigin = expectedOrigin;
102
+ this.#userName = userName ?? rpName;
103
+ this.#userDisplayName = userDisplayName ?? rpName;
104
+ this.#getIsOnboardingCompleted = getIsOnboardingCompleted;
105
+ this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
106
+ }
107
+ /**
108
+ * Whether a passkey is enrolled and vault key material is stored.
109
+ *
110
+ * @returns `true` if enrolled, otherwise `false`.
111
+ */
112
+ isPasskeyEnrolled() {
113
+ return passkeyControllerSelectors.selectIsPasskeyEnrolled(this.state);
114
+ }
115
+ /**
116
+ * Builds WebAuthn credential creation options for passkey enrollment.
117
+ *
118
+ * @param creationOptionsConfig - Optional creation behavior.
119
+ * @param creationOptionsConfig.prfAvailable - Request the PRF extension unless `false`. Defaults to `true`.
120
+ * @returns Public key credential creation options for `navigator.credentials.create()`.
121
+ */
122
+ generateRegistrationOptions(creationOptionsConfig) {
123
+ if (this.isPasskeyEnrolled()) {
124
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.AlreadyEnrolled, { code: PasskeyControllerErrorCode.AlreadyEnrolled });
125
+ }
126
+ const includePrf = creationOptionsConfig?.prfAvailable !== false;
127
+ const prfSalt = includePrf ? randomBytesToBase64URL(32) : undefined;
128
+ const userHandle = randomBytesToBase64URL(64);
129
+ const challenge = randomBytesToBase64URL(32);
130
+ const extensions = {};
131
+ if (prfSalt) {
132
+ extensions.prf = { eval: { first: prfSalt } };
133
+ }
134
+ const options = {
135
+ rp: {
136
+ name: this.#rpName,
137
+ id: this.#rpId,
138
+ },
139
+ user: {
140
+ id: userHandle,
141
+ name: this.#userName,
142
+ displayName: this.#userDisplayName,
143
+ },
144
+ challenge,
145
+ pubKeyCredParams: [
146
+ { alg: COSEALG.EdDSA, type: 'public-key' },
147
+ { alg: COSEALG.ES256, type: 'public-key' },
148
+ { alg: COSEALG.RS256, type: 'public-key' },
149
+ ],
150
+ timeout: WEBAUTHN_TIMEOUT_MS,
151
+ authenticatorSelection: {
152
+ userVerification: 'required',
153
+ authenticatorAttachment: 'platform',
154
+ residentKey: 'preferred',
155
+ },
156
+ hints: ['client-device', 'hybrid'],
157
+ attestation: 'none',
158
+ ...(Object.keys(extensions).length > 0 ? { extensions } : {}),
159
+ };
160
+ this.#ceremonyManager.saveRegistrationCeremony(challenge, {
161
+ userHandle,
162
+ prfSalt,
163
+ challenge,
164
+ createdAt: Date.now(),
165
+ });
166
+ return options;
167
+ }
168
+ /**
169
+ * Builds WebAuthn credential request options for the post-registration
170
+ * authentication step (between `create` and {@link protectVaultKeyWithPasskey}).
171
+ *
172
+ * @param params - Input for the pending registration ceremony.
173
+ * @param params.registrationResponse - Result of `navigator.credentials.create()`.
174
+ * @returns Public key credential request options for `navigator.credentials.get()`.
175
+ */
176
+ generatePostRegistrationAuthenticationOptions(params) {
177
+ // get registration ceremony
178
+ const { registrationResponse } = params;
179
+ const regChallenge = this.#getChallengeFromClientData(registrationResponse.response.clientDataJSON);
180
+ const registrationCeremony = this.#ceremonyManager.getRegistrationCeremony(regChallenge);
181
+ if (!registrationCeremony) {
182
+ log('No active passkey registration ceremony for challenge');
183
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.NoRegistrationCeremony, { code: PasskeyControllerErrorCode.NoRegistrationCeremony });
184
+ }
185
+ // build auth options
186
+ const challenge = randomBytesToBase64URL(32);
187
+ const extensions = {};
188
+ if (registrationCeremony.prfSalt) {
189
+ extensions.prf = { eval: { first: registrationCeremony.prfSalt } };
190
+ }
191
+ const options = {
192
+ challenge,
193
+ rpId: this.#rpId,
194
+ allowCredentials: [
195
+ {
196
+ id: registrationResponse.id,
197
+ type: 'public-key',
198
+ transports: registrationResponse.response.transports,
199
+ },
200
+ ],
201
+ userVerification: 'required',
202
+ hints: ['client-device', 'hybrid'],
203
+ timeout: WEBAUTHN_TIMEOUT_MS,
204
+ extensions,
205
+ };
206
+ // save auth ceremony
207
+ this.#ceremonyManager.saveAuthenticationCeremony(challenge, {
208
+ challenge,
209
+ createdAt: Date.now(),
210
+ });
211
+ return options;
212
+ }
213
+ /**
214
+ * Builds WebAuthn credential request options for the enrolled passkey.
215
+ *
216
+ * @returns Public key credential request options for `navigator.credentials.get()`.
217
+ */
218
+ generateAuthenticationOptions() {
219
+ const record = this.#requireEnrolled();
220
+ const challenge = randomBytesToBase64URL(32);
221
+ const extensions = {};
222
+ if (record.keyDerivation.method === 'prf') {
223
+ extensions.prf = { eval: { first: record.keyDerivation.prfSalt } };
224
+ }
225
+ const options = {
226
+ challenge,
227
+ rpId: this.#rpId,
228
+ allowCredentials: [
229
+ {
230
+ id: record.credential.id,
231
+ type: 'public-key',
232
+ transports: record.credential.transports,
233
+ },
234
+ ],
235
+ userVerification: 'required',
236
+ hints: ['client-device', 'hybrid'],
237
+ timeout: WEBAUTHN_TIMEOUT_MS,
238
+ extensions,
239
+ };
240
+ this.#ceremonyManager.saveAuthenticationCeremony(challenge, {
241
+ challenge,
242
+ createdAt: Date.now(),
243
+ });
244
+ return options;
245
+ }
246
+ /**
247
+ * Verifies registration and post-registration authentication, then stores the
248
+ * vault key encrypted under the new passkey.
249
+ *
250
+ * Fetches the current vault encryption key from KeyringController before wrapping.
251
+ * When onboarding is complete, requires `password` for step-up verification first.
252
+ *
253
+ * @param params - Enrollment completion inputs.
254
+ * @param params.registrationResponse - Result of `navigator.credentials.create()`.
255
+ * @param params.authenticationResponse - Result of `navigator.credentials.get()` after {@link generatePostRegistrationAuthenticationOptions}.
256
+ * @param params.password - Wallet password when onboarding is complete (step-up).
257
+ * @returns Resolves when enrollment completes.
258
+ */
259
+ async protectVaultKeyWithPasskey(params) {
260
+ return this.#withOperationLock(() => this.#protectVaultKeyWithPasskey(params));
261
+ }
262
+ async #protectVaultKeyWithPasskey(params) {
263
+ if (this.isPasskeyEnrolled()) {
264
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.AlreadyEnrolled, { code: PasskeyControllerErrorCode.AlreadyEnrolled });
265
+ }
266
+ await this.#assertEnrollmentAllowed(params.password);
267
+ const vaultKey = await this.messenger.call('KeyringController:exportEncryptionKey');
268
+ const { registrationResponse, authenticationResponse } = params;
269
+ // get registration ceremony
270
+ const challenge = this.#getChallengeFromClientData(registrationResponse.response.clientDataJSON);
271
+ const registrationCeremony = this.#ceremonyManager.getRegistrationCeremony(challenge);
272
+ if (!registrationCeremony) {
273
+ log('No active passkey registration ceremony for challenge');
274
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.NoRegistrationCeremony, { code: PasskeyControllerErrorCode.NoRegistrationCeremony });
275
+ }
276
+ try {
277
+ // verify registration response
278
+ const { verified, registrationInfo } = await verifyRegistrationResponse({
279
+ response: registrationResponse,
280
+ expectedChallenge: registrationCeremony.challenge,
281
+ expectedOrigin: this.#expectedOrigin,
282
+ expectedRPIDs: this.#expectedRPIDs,
283
+ requireUserVerification: true,
284
+ }).catch((error) => {
285
+ log('Error verifying passkey registration response', error);
286
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.RegistrationVerificationFailed, {
287
+ code: PasskeyControllerErrorCode.RegistrationVerificationFailed,
288
+ cause: error instanceof Error ? error : new Error(String(error)),
289
+ });
290
+ });
291
+ if (!verified || !registrationInfo) {
292
+ log('Passkey registration verification returned unverified or missing registration info');
293
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.RegistrationVerificationFailed, { code: PasskeyControllerErrorCode.RegistrationVerificationFailed });
294
+ }
295
+ // verify authentication response
296
+ const credential = {
297
+ id: registrationInfo.credentialId,
298
+ publicKey: bytesToBase64URL(registrationInfo.publicKey),
299
+ counter: registrationInfo.counter,
300
+ transports: registrationInfo.transports,
301
+ aaguid: registrationInfo.aaguid,
302
+ };
303
+ const { newCounter } = await this.#verifyAuthenticationResponse(authenticationResponse, credential);
304
+ // determine key derivation method
305
+ const prfFirst = authenticationResponse.clientExtensionResults?.prf?.results?.first;
306
+ const authHasPrfOutput = typeof prfFirst === 'string' && prfFirst.length > 0;
307
+ const keyDerivation = authHasPrfOutput && registrationCeremony.prfSalt
308
+ ? { method: 'prf', prfSalt: registrationCeremony.prfSalt }
309
+ : { method: 'userHandle' };
310
+ if (keyDerivation.method === 'userHandle' &&
311
+ authenticationResponse.response.userHandle !==
312
+ registrationCeremony.userHandle) {
313
+ log('Post-registration assertion userHandle does not match registration ceremony');
314
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.AuthenticationVerificationFailed, { code: PasskeyControllerErrorCode.AuthenticationVerificationFailed });
315
+ }
316
+ // derive key and encrypt vault key
317
+ const encKey = deriveKeyFromAuthenticationResponse(authenticationResponse, { credential, keyDerivation });
318
+ const { ciphertext, iv } = encryptWithKey(vaultKey, encKey);
319
+ // persist passkey record
320
+ this.update((state) => {
321
+ state.passkeyRecord = {
322
+ credential: {
323
+ ...credential,
324
+ counter: Math.max(newCounter, credential.counter),
325
+ },
326
+ encryptedVaultKey: { ciphertext, iv },
327
+ keyDerivation,
328
+ };
329
+ });
330
+ }
331
+ finally {
332
+ // delete registration ceremony
333
+ this.#ceremonyManager.deleteRegistrationCeremony(challenge);
334
+ }
335
+ }
336
+ /**
337
+ * Verifies an authentication assertion and returns the decrypted vault key.
338
+ *
339
+ * Prefer orchestrated methods ({@link unlockWithPasskey},
340
+ * {@link exportSeedPhraseWithPasskey}, {@link exportAccountsWithPasskey}) for product
341
+ * flows instead of calling KeyringController with the returned key manually.
342
+ *
343
+ * @param authenticationResponse - Result of `navigator.credentials.get()`.
344
+ * @returns The plaintext vault encryption key.
345
+ */
346
+ async retrieveVaultKeyWithPasskey(authenticationResponse) {
347
+ return this.#withOperationLock(() => this.#retrieveVaultKeyWithPasskey(authenticationResponse));
348
+ }
349
+ async #retrieveVaultKeyWithPasskey(authenticationResponse) {
350
+ const passkeyRecord = this.#requireEnrolled();
351
+ // verify authentication response and update counter
352
+ const { newCounter } = await this.#verifyAuthenticationResponse(authenticationResponse, passkeyRecord.credential);
353
+ this.update((state) => {
354
+ if (!state.passkeyRecord) {
355
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.NotEnrolled, { code: PasskeyControllerErrorCode.NotEnrolled });
356
+ }
357
+ state.passkeyRecord.credential.counter = Math.max(newCounter, state.passkeyRecord.credential.counter);
358
+ });
359
+ // derive key
360
+ const encKey = deriveKeyFromAuthenticationResponse(authenticationResponse, passkeyRecord);
361
+ // decrypt vault key
362
+ try {
363
+ const vaultKey = decryptWithKey(passkeyRecord.encryptedVaultKey.ciphertext, passkeyRecord.encryptedVaultKey.iv, encKey);
364
+ return vaultKey;
365
+ }
366
+ catch (cause) {
367
+ log('Error decrypting vault key with passkey', cause instanceof Error ? cause : new Error(String(cause)));
368
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.VaultKeyDecryptionFailed, {
369
+ code: PasskeyControllerErrorCode.VaultKeyDecryptionFailed,
370
+ cause: cause instanceof Error ? cause : new Error(String(cause)),
371
+ });
372
+ }
373
+ }
374
+ /**
375
+ * Unlocks the keyring using a passkey authentication assertion.
376
+ *
377
+ * @param authenticationResponse - Result of `navigator.credentials.get()`.
378
+ * @returns Resolves when the keyring is unlocked.
379
+ */
380
+ async unlockWithPasskey(authenticationResponse) {
381
+ return this.#withOperationLock(async () => {
382
+ const vaultKey = await this.#retrieveVaultKeyWithPasskey(authenticationResponse);
383
+ await this.messenger.call('KeyringController:submitEncryptionKey', vaultKey);
384
+ });
385
+ }
386
+ /**
387
+ * Exports the seed phrase after passkey step-up authentication.
388
+ *
389
+ * @param authenticationResponse - Result of `navigator.credentials.get()`.
390
+ * @param keyringId - Optional keyring id; defaults to the primary HD keyring.
391
+ * @returns Raw seed phrase bytes from KeyringController.
392
+ */
393
+ async exportSeedPhraseWithPasskey(authenticationResponse, keyringId) {
394
+ return this.#withOperationLock(async () => {
395
+ const vaultKey = await this.#retrieveVaultKeyWithPasskey(authenticationResponse);
396
+ return await this.messenger.call('KeyringController:exportSeedPhrase', { encryptionKey: vaultKey }, keyringId);
397
+ });
398
+ }
399
+ /**
400
+ * Exports private keys for the given addresses after passkey step-up authentication.
401
+ *
402
+ * @param authenticationResponse - Result of `navigator.credentials.get()`.
403
+ * @param addresses - Account addresses to export.
404
+ * @returns Private keys in the same order as `addresses`.
405
+ */
406
+ async exportAccountsWithPasskey(authenticationResponse, addresses) {
407
+ return this.#withOperationLock(async () => {
408
+ const vaultKey = await this.#retrieveVaultKeyWithPasskey(authenticationResponse);
409
+ const privateKeys = [];
410
+ for (const address of addresses) {
411
+ privateKeys.push(await this.messenger.call('KeyringController:exportAccount', { encryptionKey: vaultKey }, address));
412
+ }
413
+ return privateKeys;
414
+ });
415
+ }
416
+ /**
417
+ * Checks whether the given authentication assertion is valid for the enrolled passkey.
418
+ *
419
+ * On failure, returns `false` for {@link PasskeyControllerError} with a `code`;
420
+ * other errors propagate.
421
+ *
422
+ * @param authenticationResponse - Result of `navigator.credentials.get()`.
423
+ * @returns `true` if verification succeeds, otherwise `false`.
424
+ */
425
+ async verifyPasskeyAuthentication(authenticationResponse) {
426
+ return this.#withOperationLock(() => this.#verifyPasskeyAuthentication(authenticationResponse));
427
+ }
428
+ async #verifyPasskeyAuthentication(authenticationResponse) {
429
+ try {
430
+ await this.#retrieveVaultKeyWithPasskey(authenticationResponse);
431
+ return true;
432
+ }
433
+ catch (error) {
434
+ if (error instanceof PasskeyControllerError && error.code !== undefined) {
435
+ return false;
436
+ }
437
+ throw error;
438
+ }
439
+ }
440
+ /**
441
+ * Re-wraps the vault key after rotation. Updates persisted `encryptedVaultKey` on success.
442
+ *
443
+ * Does not verify WebAuthn or ceremony state—call only after your layer has authenticated
444
+ * the user (passkey `get()` + verified assertion, or verified password). On passkey paths,
445
+ * pass the same `authenticationResponse` you just verified (e.g. from
446
+ * {@link retrieveVaultKeyWithPasskey} / {@link verifyPasskeyAuthentication}).
447
+ *
448
+ * For password change with passkey step-up, prefer
449
+ * {@link changePasswordWithPasskeyVerification}, which orchestrates keyring export,
450
+ * `changePassword`, and re-wrap in one call.
451
+ *
452
+ * @param params - Re-wrap inputs.
453
+ * @param params.authenticationResponse - Used to derive the wrapping key.
454
+ * @param params.oldVaultKey - Expected current vault key.
455
+ * @param params.newVaultKey - New vault key to encrypt under the passkey.
456
+ * @returns Resolves when the passkey record is updated.
457
+ */
458
+ async renewVaultKeyProtection(params) {
459
+ return this.#withOperationLock(() => this.#renewVaultKeyProtection(params));
460
+ }
461
+ async #renewVaultKeyProtection(params) {
462
+ const { authenticationResponse } = params;
463
+ const passkeyRecord = this.#requireEnrolled();
464
+ // derive key
465
+ const encKey = deriveKeyFromAuthenticationResponse(authenticationResponse, passkeyRecord);
466
+ // decrypt vault key
467
+ let decryptedVaultKey;
468
+ try {
469
+ decryptedVaultKey = decryptWithKey(passkeyRecord.encryptedVaultKey.ciphertext, passkeyRecord.encryptedVaultKey.iv, encKey);
470
+ }
471
+ catch (error) {
472
+ log('Error decrypting vault key during passkey vault key renewal', error instanceof Error ? error : new Error(String(error)));
473
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.VaultKeyDecryptionFailed, {
474
+ code: PasskeyControllerErrorCode.VaultKeyDecryptionFailed,
475
+ cause: error instanceof Error ? error : new Error(String(error)),
476
+ });
477
+ }
478
+ // check if vault key matches
479
+ const { oldVaultKey, newVaultKey } = params;
480
+ if (!areUint8ArraysEqual(stringToBytes(decryptedVaultKey), stringToBytes(oldVaultKey))) {
481
+ log('Passkey renewal rejected: decrypted vault key does not match oldVaultKey');
482
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.VaultKeyMismatch, { code: PasskeyControllerErrorCode.VaultKeyMismatch });
483
+ }
484
+ // encrypt new vault key
485
+ const { ciphertext, iv } = encryptWithKey(newVaultKey, encKey);
486
+ // persist passkey record (mutate current state only for vault key material)
487
+ this.update((state) => {
488
+ if (!state.passkeyRecord) {
489
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.NotEnrolled, {
490
+ code: PasskeyControllerErrorCode.NotEnrolled,
491
+ });
492
+ }
493
+ state.passkeyRecord.encryptedVaultKey = { ciphertext, iv };
494
+ });
495
+ }
496
+ /**
497
+ * Changes the wallet password after passkey step-up authentication.
498
+ *
499
+ * When `renewVaultKeyProtection` is `true` (default), re-wraps the vault key under the
500
+ * passkey after rotation. When `false`, removes the passkey instead.
501
+ *
502
+ * @param params - Change-password inputs.
503
+ * @param params.newPassword - New wallet password.
504
+ * @param params.authenticationResponse - Result of `navigator.credentials.get()`.
505
+ * @param params.options - Optional flow controls.
506
+ * @param params.options.renewVaultKeyProtection - Re-wrap vault key after password change.
507
+ * @returns Resolves when the password change completes.
508
+ */
509
+ async changePasswordWithPasskeyVerification(params) {
510
+ return this.#withOperationLock(() => this.#changePasswordWithPasskeyVerification(params));
511
+ }
512
+ async #changePasswordWithPasskeyVerification(params) {
513
+ this.#requireEnrolled();
514
+ const verified = await this.#verifyPasskeyAuthentication(params.authenticationResponse);
515
+ if (!verified) {
516
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.AuthenticationVerificationFailed, { code: PasskeyControllerErrorCode.AuthenticationVerificationFailed });
517
+ }
518
+ const renewVaultKeyProtection = params.options?.renewVaultKeyProtection ?? true;
519
+ if (!renewVaultKeyProtection) {
520
+ await this.messenger.call('KeyringController:changePassword', params.newPassword);
521
+ this.#removePasskey();
522
+ return;
523
+ }
524
+ const vaultKeyBefore = await this.messenger.call('KeyringController:exportEncryptionKey');
525
+ await this.messenger.call('KeyringController:changePassword', params.newPassword);
526
+ try {
527
+ const vaultKeyAfter = await this.messenger.call('KeyringController:exportEncryptionKey');
528
+ await this.#renewVaultKeyProtection({
529
+ authenticationResponse: params.authenticationResponse,
530
+ oldVaultKey: vaultKeyBefore,
531
+ newVaultKey: vaultKeyAfter,
532
+ });
533
+ }
534
+ catch (error) {
535
+ this.#removePasskey();
536
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.VaultKeyRenewalFailed, {
537
+ code: PasskeyControllerErrorCode.VaultKeyRenewalFailed,
538
+ cause: error instanceof Error ? error : new Error(String(error)),
539
+ });
540
+ }
541
+ }
542
+ /**
543
+ * Removes the enrolled passkey after verifying a passkey authentication assertion.
544
+ *
545
+ * @param authenticationResponse - Result of `navigator.credentials.get()`.
546
+ * @returns Resolves when the passkey is removed.
547
+ */
548
+ async removePasskeyWithPasskeyVerification(authenticationResponse) {
549
+ return this.#withOperationLock(() => this.#removePasskeyWithPasskeyVerification(authenticationResponse));
550
+ }
551
+ async #removePasskeyWithPasskeyVerification(authenticationResponse) {
552
+ this.#requireEnrolled();
553
+ const verified = await this.#verifyPasskeyAuthentication(authenticationResponse);
554
+ if (!verified) {
555
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.AuthenticationVerificationFailed, { code: PasskeyControllerErrorCode.AuthenticationVerificationFailed });
556
+ }
557
+ this.#removePasskey();
558
+ }
559
+ /**
560
+ * Removes the enrolled passkey after verifying the wallet password.
561
+ *
562
+ * @param password - Wallet password for step-up verification.
563
+ * @returns Resolves when the passkey is removed.
564
+ */
565
+ async removePasskeyWithPasswordVerification(password) {
566
+ return this.#withOperationLock(() => this.#removePasskeyWithPasswordVerification(password));
567
+ }
568
+ async #removePasskeyWithPasswordVerification(password) {
569
+ this.#requireEnrolled();
570
+ await this.messenger.call('KeyringController:verifyPassword', password);
571
+ this.#removePasskey();
572
+ }
573
+ /**
574
+ * Resets state and clears in-flight registration/authentication ceremonies.
575
+ *
576
+ * For user-facing passkey removal with step-up, use
577
+ * {@link removePasskeyWithPasskeyVerification} or
578
+ * {@link removePasskeyWithPasswordVerification}.
579
+ */
580
+ clearState() {
581
+ this.#removePasskey();
582
+ }
583
+ /**
584
+ * Releases all in-flight ceremony state and tears down the messenger.
585
+ */
586
+ destroy() {
587
+ this.#ceremonyManager.clear();
588
+ super.destroy();
589
+ }
590
+ /**
591
+ * Validates a WebAuthn authentication response against stored credential data.
592
+ *
593
+ * @param authenticationResponse - Parsed authentication response from the client.
594
+ * @param credential - Credential identifiers and public key material for verification.
595
+ * @returns Updated authenticator signature counter.
596
+ */
597
+ async #verifyAuthenticationResponse(authenticationResponse, credential) {
598
+ // get challenge
599
+ const challenge = this.#getChallengeFromClientData(authenticationResponse.response.clientDataJSON);
600
+ // get authentication ceremony
601
+ const authenticationCeremony = this.#ceremonyManager.getAuthenticationCeremony(challenge);
602
+ if (!authenticationCeremony) {
603
+ log('No active passkey authentication ceremony for challenge');
604
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.NoAuthenticationCeremony, { code: PasskeyControllerErrorCode.NoAuthenticationCeremony });
605
+ }
606
+ try {
607
+ // verify authentication response
608
+ const result = await verifyAuthenticationResponse({
609
+ response: authenticationResponse,
610
+ expectedChallenge: authenticationCeremony.challenge,
611
+ expectedOrigin: this.#expectedOrigin,
612
+ expectedRPIDs: this.#expectedRPIDs,
613
+ credential: {
614
+ id: credential.id,
615
+ publicKey: base64URLToBytes(credential.publicKey),
616
+ counter: credential.counter,
617
+ transports: credential.transports,
618
+ },
619
+ requireUserVerification: true,
620
+ }).catch((error) => {
621
+ log('Error verifying passkey authentication response', error instanceof Error ? error : new Error(String(error)));
622
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.AuthenticationVerificationFailed, {
623
+ code: PasskeyControllerErrorCode.AuthenticationVerificationFailed,
624
+ cause: error instanceof Error ? error : new Error(String(error)),
625
+ });
626
+ });
627
+ if (!result.verified) {
628
+ log('Passkey authentication verification returned unverified');
629
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.AuthenticationVerificationFailed, {
630
+ code: PasskeyControllerErrorCode.AuthenticationVerificationFailed,
631
+ });
632
+ }
633
+ return { newCounter: result.authenticationInfo.newCounter };
634
+ }
635
+ finally {
636
+ // delete authentication ceremony
637
+ this.#ceremonyManager.deleteAuthenticationCeremony(challenge);
638
+ }
639
+ }
640
+ /**
641
+ * Serializes orchestrated passkey operations that mutate state or call KeyringController.
642
+ *
643
+ * @param callback - Operation to run while the mutex is held.
644
+ * @returns The result of the callback.
645
+ */
646
+ async #withOperationLock(callback) {
647
+ return this.#operationMutex.runExclusive(callback);
648
+ }
649
+ async #assertEnrollmentAllowed(password) {
650
+ if (!this.#getIsOnboardingCompleted()) {
651
+ return;
652
+ }
653
+ if (!password) {
654
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.EnrollmentPasswordRequired, {
655
+ code: PasskeyControllerErrorCode.EnrollmentPasswordRequired,
656
+ });
657
+ }
658
+ await this.messenger.call('KeyringController:verifyPassword', password);
659
+ }
660
+ #requireEnrolled() {
661
+ const record = this.state.passkeyRecord;
662
+ if (!record) {
663
+ throw new PasskeyControllerError(PasskeyControllerErrorMessage.NotEnrolled, {
664
+ code: PasskeyControllerErrorCode.NotEnrolled,
665
+ });
666
+ }
667
+ return record;
668
+ }
669
+ #getChallengeFromClientData(clientDataJSON) {
670
+ return decodeClientDataJSON(clientDataJSON).challenge;
671
+ }
672
+ /**
673
+ * Clears enrolled passkey state and in-flight ceremonies.
674
+ */
675
+ #removePasskey() {
676
+ this.update(() => getDefaultPasskeyControllerState());
677
+ this.#ceremonyManager.clear();
678
+ }
679
+ }
680
+ //# sourceMappingURL=PasskeyController.js.map