Module: BetterAuth::Plugins

Defined in:
lib/better_auth/plugins/passkey.rb

Constant Summary collapse

PASSKEY_ERROR_CODES =
{
  "CHALLENGE_NOT_FOUND" => "Challenge not found",
  "YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY" => "You are not allowed to register this passkey",
  "FAILED_TO_VERIFY_REGISTRATION" => "Failed to verify registration",
  "PASSKEY_NOT_FOUND" => "Passkey not found",
  "AUTHENTICATION_FAILED" => "Authentication failed",
  "UNABLE_TO_CREATE_SESSION" => "Unable to create session",
  "FAILED_TO_UPDATE_PASSKEY" => "Failed to update passkey",
  "PREVIOUSLY_REGISTERED" => "Previously registered",
  "REGISTRATION_CANCELLED" => "Registration cancelled",
  "AUTH_CANCELLED" => "Auth cancelled",
  "UNKNOWN_ERROR" => "Unknown error",
  "SESSION_REQUIRED" => "Passkey registration requires an authenticated session",
  "RESOLVE_USER_REQUIRED" => "Passkey registration requires either an authenticated session or a resolveUser callback when requireSession is false",
  "RESOLVED_USER_INVALID" => "Resolved user is invalid"
}.freeze
PASSKEY_CHALLENGE_MAX_AGE =
60 * 5

Class Method Summary collapse

Class Method Details

.delete_passkey_endpointObject



212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/better_auth/plugins/passkey.rb', line 212

def delete_passkey_endpoint
  Endpoint.new(path: "/passkey/delete-passkey", method: "POST") do |ctx|
    session = Routes.current_session(ctx)
    body = normalize_hash(ctx.body)
    passkey = ctx.context.adapter.find_one(model: "passkey", where: [{field: "id", value: body[:id]}])
    raise APIError.new("NOT_FOUND", message: PASSKEY_ERROR_CODES.fetch("PASSKEY_NOT_FOUND")) unless passkey
    raise APIError.new("UNAUTHORIZED") unless passkey.fetch("userId") == session.fetch(:user).fetch("id")

    ctx.context.adapter.delete(model: "passkey", where: [{field: "id", value: passkey.fetch("id")}])
    ctx.json({status: true})
  end
end

.generate_passkey_authentication_options_endpoint(config) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/better_auth/plugins/passkey.rb', line 87

def generate_passkey_authentication_options_endpoint(config)
  Endpoint.new(path: "/passkey/generate-authenticate-options", method: "GET") do |ctx|
    session = Routes.current_session(ctx, allow_nil: true)
    passkey_configure_webauthn(config, ctx)
    passkeys = if session
      ctx.context.adapter.find_many(model: "passkey", where: [{field: "userId", value: session.fetch(:user).fetch("id")}])
    else
      []
    end
    options = WebAuthn::Credential.options_for_get(
      allow: passkeys.map { |passkey| passkey_credential_id(passkey) },
      extensions: passkey_resolve_extensions(config.dig(:authentication, :extensions), ctx)
    )
    passkey_store_challenge(ctx, config, options.challenge, session ? session.fetch(:user).fetch("id") : "")
    payload = options.as_json.merge(userVerification: "preferred")
    payload[:allowCredentials] = passkeys.map { |passkey| passkey_credential_descriptor(passkey) } if passkeys.any?
    ctx.json(payload)
  end
end

.generate_passkey_registration_options_endpoint(config) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/better_auth/plugins/passkey.rb', line 62

def generate_passkey_registration_options_endpoint(config)
  Endpoint.new(path: "/passkey/generate-register-options", method: "GET") do |ctx|
    query = normalize_hash(ctx.query)
    user = passkey_resolve_registration_user(config, ctx, query)
    passkey_configure_webauthn(config, ctx)
    existing = ctx.context.adapter.find_many(model: "passkey", where: [{field: "userId", value: user.fetch("id")}])
    options = WebAuthn::Credential.options_for_create(
      user: {
        id: Crypto.random_string(32).downcase,
        name: query[:name].to_s.empty? ? (user["email"] || user["name"] || user["id"]) : query[:name].to_s,
        display_name: user["displayName"] || user["display_name"] || user["email"] || user["name"] || user["id"]
      },
      exclude: existing.map { |passkey| passkey_credential_id(passkey) },
      authenticator_selection: passkey_authenticator_selection(config, query),
      extensions: passkey_resolve_extensions(config.dig(:registration, :extensions), ctx)
    )
    passkey_store_challenge(ctx, config, options.challenge, {
      id: user.fetch("id"),
      name: user["name"] || user["email"] || user["id"],
      displayName: user["displayName"] || user["display_name"]
    }.compact)
    ctx.json(options.as_json.merge(excludeCredentials: existing.map { |passkey| passkey_credential_descriptor(passkey) }))
  end
end

.list_passkeys_endpointObject



204
205
206
207
208
209
210
# File 'lib/better_auth/plugins/passkey.rb', line 204

def list_passkeys_endpoint
  Endpoint.new(path: "/passkey/list-user-passkeys", method: "GET") do |ctx|
    session = Routes.current_session(ctx)
    passkeys = ctx.context.adapter.find_many(model: "passkey", where: [{field: "userId", value: session.fetch(:user).fetch("id")}])
    ctx.json(passkeys.map { |passkey| passkey_wire(passkey) })
  end
end

.passkey(options = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/better_auth/plugins/passkey.rb', line 34

def passkey(options = {})
  config = {
    origin: nil,
    advanced: {
      web_authn_challenge_cookie: "better-auth-passkey"
    }
  }.merge(normalize_hash(options))
  config[:advanced] = {
    web_authn_challenge_cookie: "better-auth-passkey"
  }.merge(config[:advanced] || {})

  Plugin.new(
    id: "passkey",
    schema: passkey_schema(config[:schema]),
    endpoints: {
      generate_passkey_registration_options: generate_passkey_registration_options_endpoint(config),
      generate_passkey_authentication_options: generate_passkey_authentication_options_endpoint(config),
      verify_passkey_registration: verify_passkey_registration_endpoint(config),
      verify_passkey_authentication: verify_passkey_authentication_endpoint(config),
      list_passkeys: list_passkeys_endpoint,
      delete_passkey: delete_passkey_endpoint,
      update_passkey: update_passkey_endpoint
    },
    error_codes: PASSKEY_ERROR_CODES,
    options: config
  )
end

.passkey_after_registration_verification_user_id(config, ctx, credential, challenge, response, session) ⇒ Object



394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/better_auth/plugins/passkey.rb', line 394

def passkey_after_registration_verification_user_id(config, ctx, credential, challenge, response, session)
  user_data = challenge.fetch("userData")
  target_user_id = user_data.fetch("id")
  callback = config.dig(:registration, :after_verification)
  return target_user_id unless callback.respond_to?(:call)

  result = normalize_hash(passkey_call_callback(callback, {
    ctx: ctx,
    verification: credential,
    user: {
      id: user_data.fetch("id"),
      name: user_data["name"] || user_data.fetch("id"),
      display_name: user_data["displayName"] || user_data["display_name"]
    },
    client_data: response,
    context: challenge["context"]
  }) || {})
  returned_user_id = result[:user_id]
  return target_user_id if returned_user_id.to_s.empty?

  unless returned_user_id.is_a?(String)
    raise APIError.new("BAD_REQUEST", message: PASSKEY_ERROR_CODES.fetch("RESOLVED_USER_INVALID"))
  end

  if session && returned_user_id != session.fetch(:user).fetch("id")
    raise APIError.new("UNAUTHORIZED", message: PASSKEY_ERROR_CODES.fetch("YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY"))
  end

  returned_user_id
end

.passkey_allowed_origins(config, ctx, origin: nil) ⇒ Object



314
315
316
# File 'lib/better_auth/plugins/passkey.rb', line 314

def passkey_allowed_origins(config, ctx, origin: nil)
  Array(origin || config[:origin] || ctx.context.options.base_url).compact
end

.passkey_attestation_response(credential) ⇒ Object



457
458
459
# File 'lib/better_auth/plugins/passkey.rb', line 457

def passkey_attestation_response(credential)
  credential.instance_variable_get(:@response)
end

.passkey_authenticator_data(credential) ⇒ Object



461
462
463
# File 'lib/better_auth/plugins/passkey.rb', line 461

def passkey_authenticator_data(credential)
  passkey_attestation_response(credential)&.authenticator_data
end

.passkey_authenticator_selection(config, query) ⇒ Object



326
327
328
329
330
331
332
333
334
335
# File 'lib/better_auth/plugins/passkey.rb', line 326

def passkey_authenticator_selection(config, query)
  selection = normalize_hash(config[:authenticator_selection] || {})
  attachment = query[:authenticator_attachment]
  selection[:authenticator_attachment] = attachment if attachment
  {
    resident_key: selection[:resident_key] || "preferred",
    user_verification: selection[:user_verification] || "preferred",
    authenticator_attachment: selection[:authenticator_attachment]
  }.compact
end

.passkey_call_callback(callback, data) ⇒ Object



425
426
427
428
429
430
431
432
433
# File 'lib/better_auth/plugins/passkey.rb', line 425

def passkey_call_callback(callback, data)
  return nil unless callback.respond_to?(:call)

  if callback.parameters.any? { |kind, _name| [:key, :keyreq, :keyrest].include?(kind) }
    callback.call(**data)
  else
    callback.call(data)
  end
end


300
301
302
# File 'lib/better_auth/plugins/passkey.rb', line 300

def passkey_challenge_cookie(ctx, config)
  ctx.context.create_auth_cookie(config.dig(:advanced, :web_authn_challenge_cookie), max_age: PASSKEY_CHALLENGE_MAX_AGE)
end

.passkey_challenge_token(ctx, config) ⇒ Object



296
297
298
# File 'lib/better_auth/plugins/passkey.rb', line 296

def passkey_challenge_token(ctx, config)
  ctx.get_signed_cookie(passkey_challenge_cookie(ctx, config).name, ctx.context.secret)
end

.passkey_configure_webauthn(config, ctx, origin: nil) ⇒ Object



304
305
306
307
308
# File 'lib/better_auth/plugins/passkey.rb', line 304

def passkey_configure_webauthn(config, ctx, origin: nil)
  WebAuthn.configuration.rp_id = passkey_rp_id(config, ctx)
  WebAuthn.configuration.rp_name = config[:rp_name] || ctx.context.app_name
  WebAuthn.configuration.allowed_origins = passkey_allowed_origins(config, ctx, origin: origin)
end

.passkey_credential_descriptor(record) ⇒ Object



477
478
479
480
481
482
483
484
485
# File 'lib/better_auth/plugins/passkey.rb', line 477

def passkey_credential_descriptor(record)
  descriptor = {
    id: passkey_credential_id(record),
    type: "public-key"
  }
  transports = (record["transports"] || record[:transports]).to_s.split(",").map(&:strip).reject(&:empty?)
  descriptor[:transports] = transports if transports.any?
  descriptor
end

.passkey_credential_id(record) ⇒ Object



473
474
475
# File 'lib/better_auth/plugins/passkey.rb', line 473

def passkey_credential_id(record)
  record["credentialID"] || record["credentialId"] || record[:credentialID] || record[:credential_id]
end

.passkey_find_challenge(ctx, verification_token) ⇒ Object



287
288
289
290
291
292
293
294
# File 'lib/better_auth/plugins/passkey.rb', line 287

def passkey_find_challenge(ctx, verification_token)
  verification = ctx.context.internal_adapter.find_verification_value(verification_token)
  return nil unless verification && !Routes.expired_time?(verification["expiresAt"])

  JSON.parse(verification.fetch("value"))
rescue JSON::ParserError
  nil
end

.passkey_origin(config, ctx) ⇒ Object



310
311
312
# File 'lib/better_auth/plugins/passkey.rb', line 310

def passkey_origin(config, ctx)
  config[:origin] || ctx.headers["origin"]
end

.passkey_registration_user_data(id:, name:, display_name: nil, email: nil) ⇒ Object



379
380
381
382
383
384
385
386
# File 'lib/better_auth/plugins/passkey.rb', line 379

def passkey_registration_user_data(id:, name:, display_name: nil, email: nil)
  {
    "id" => id,
    "name" => name,
    "displayName" => display_name,
    "email" => email
  }.compact
end

.passkey_resolve_extensions(extensions, ctx) ⇒ Object



388
389
390
391
392
# File 'lib/better_auth/plugins/passkey.rb', line 388

def passkey_resolve_extensions(extensions, ctx)
  return nil unless extensions

  normalize_hash(extensions.respond_to?(:call) ? passkey_call_callback(extensions, {ctx: ctx}) : extensions)
end

.passkey_resolve_registration_user(config, ctx, query) ⇒ Object



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/better_auth/plugins/passkey.rb', line 337

def passkey_resolve_registration_user(config, ctx, query)
  require_session = config.dig(:registration, :require_session) != false
  if require_session
    session = Routes.current_session(ctx, sensitive: true)
    user = session.fetch(:user)
    return passkey_registration_user_data(
      id: user.fetch("id"),
      name: user["email"] || user["id"],
      display_name: user["email"] || user["id"],
      email: user["email"]
    )
  end

  session = Routes.current_session(ctx, allow_nil: true)
  if session
    user = session.fetch(:user)
    return passkey_registration_user_data(
      id: user.fetch("id"),
      name: user["email"] || user["id"],
      display_name: user["email"] || user["id"],
      email: user["email"]
    )
  end

  resolver = config.dig(:registration, :resolve_user)
  unless resolver.respond_to?(:call)
    raise APIError.new("BAD_REQUEST", message: PASSKEY_ERROR_CODES.fetch("RESOLVE_USER_REQUIRED"))
  end

  resolved = normalize_hash(passkey_call_callback(resolver, {ctx: ctx, context: query[:context]}) || {})
  unless resolved[:id].to_s != "" && resolved[:name].to_s != ""
    raise APIError.new("BAD_REQUEST", message: PASSKEY_ERROR_CODES.fetch("RESOLVED_USER_INVALID"))
  end

  passkey_registration_user_data(
    id: resolved[:id],
    name: resolved[:name],
    display_name: resolved[:display_name],
    email: resolved[:email]
  )
end

.passkey_rp_id(config, ctx) ⇒ Object



318
319
320
321
322
323
324
# File 'lib/better_auth/plugins/passkey.rb', line 318

def passkey_rp_id(config, ctx)
  return config[:rp_id] if config[:rp_id]

  URI.parse(ctx.context.options.base_url.to_s).host || "localhost"
rescue URI::InvalidURIError
  "localhost"
end

.passkey_schema(custom_schema = nil) ⇒ Object



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/better_auth/plugins/passkey.rb', line 246

def passkey_schema(custom_schema = nil)
  base = {
    passkey: {
      model_name: "passkeys",
      fields: {
        name: {type: "string", required: false},
        publicKey: {type: "string", required: true},
        userId: {type: "string", references: {model: "user", field: "id"}, required: true, index: true},
        credentialID: {type: "string", required: true, index: true},
        counter: {type: "number", required: true},
        deviceType: {type: "string", required: true},
        backedUp: {type: "boolean", required: true},
        transports: {type: "string", required: false},
        createdAt: {type: "date", required: false},
        aaguid: {type: "string", required: false}
      }
    }
  }
  return base unless custom_schema.is_a?(Hash)

  base.merge(custom_schema) do |_key, old_value, new_value|
    (old_value.is_a?(Hash) && new_value.is_a?(Hash)) ? old_value.merge(new_value) : new_value
  end
end

.passkey_store_challenge(ctx, config, challenge, user_id) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/better_auth/plugins/passkey.rb', line 271

def passkey_store_challenge(ctx, config, challenge, user_id)
  user_data = user_id.is_a?(Hash) ? user_id : {id: user_id}
  verification_token = Crypto.random_string(32)
  cookie = passkey_challenge_cookie(ctx, config)
  ctx.set_signed_cookie(cookie.name, verification_token, ctx.context.secret, cookie.attributes.merge(max_age: PASSKEY_CHALLENGE_MAX_AGE))
  ctx.context.internal_adapter.create_verification_value(
    identifier: verification_token,
    value: JSON.generate({
      expectedChallenge: challenge,
      userData: user_data,
      context: normalize_hash(ctx.query)[:context]
    }),
    expiresAt: Time.now + PASSKEY_CHALLENGE_MAX_AGE
  )
end

.passkey_webauthn_response(value) ⇒ Object



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/better_auth/plugins/passkey.rb', line 435

def passkey_webauthn_response(value)
  data = normalize_hash(value || {})
  response = normalize_hash(data[:response] || {})
  webauthn = {
    "type" => data[:type],
    "id" => data[:id],
    "rawId" => data[:raw_id],
    "authenticatorAttachment" => data[:authenticator_attachment],
    "clientExtensionResults" => data[:client_extension_results] || {},
    "response" => {
      "attestationObject" => response[:attestation_object],
      "clientDataJSON" => response[:client_data_json],
      "transports" => response[:transports],
      "authenticatorData" => response[:authenticator_data],
      "signature" => response[:signature],
      "userHandle" => response[:user_handle]
    }.compact
  }.compact
  webauthn["rawId"] ||= webauthn["id"]
  webauthn
end

.passkey_wire(record) ⇒ Object



465
466
467
468
469
470
471
# File 'lib/better_auth/plugins/passkey.rb', line 465

def passkey_wire(record)
  return record unless record.is_a?(Hash)

  output = record.dup
  output["credentialID"] = output.delete("credentialId") if output.key?("credentialId")
  output
end

.update_passkey_endpointObject



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/better_auth/plugins/passkey.rb', line 225

def update_passkey_endpoint
  Endpoint.new(path: "/passkey/update-passkey", method: "POST") do |ctx|
    session = Routes.current_session(ctx)
    body = normalize_hash(ctx.body)
    passkey = ctx.context.adapter.find_one(model: "passkey", where: [{field: "id", value: body[:id]}])
    raise APIError.new("NOT_FOUND", message: PASSKEY_ERROR_CODES.fetch("PASSKEY_NOT_FOUND")) unless passkey
    if passkey.fetch("userId") != session.fetch(:user).fetch("id")
      raise APIError.new("UNAUTHORIZED", message: PASSKEY_ERROR_CODES.fetch("YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY"))
    end

    updated = ctx.context.adapter.update(
      model: "passkey",
      where: [{field: "id", value: body[:id]}],
      update: {name: body[:name].to_s}
    )
    raise APIError.new("INTERNAL_SERVER_ERROR", message: PASSKEY_ERROR_CODES.fetch("FAILED_TO_UPDATE_PASSKEY")) unless updated

    ctx.json({passkey: passkey_wire(updated)})
  end
end

.verify_passkey_authentication_endpoint(config) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/better_auth/plugins/passkey.rb', line 155

def verify_passkey_authentication_endpoint(config)
  Endpoint.new(path: "/passkey/verify-authentication", method: "POST") do |ctx|
    origin = passkey_origin(config, ctx)
    raise APIError.new("BAD_REQUEST", message: "origin missing") if origin.to_s.empty?

    verification_token = passkey_challenge_token(ctx, config)
    raise APIError.new("BAD_REQUEST", message: PASSKEY_ERROR_CODES.fetch("CHALLENGE_NOT_FOUND")) unless verification_token

    challenge = passkey_find_challenge(ctx, verification_token)
    raise APIError.new("BAD_REQUEST", message: PASSKEY_ERROR_CODES.fetch("CHALLENGE_NOT_FOUND")) unless challenge

    response = passkey_webauthn_response(normalize_hash(ctx.body)[:response])
    credential_id = response.fetch("id")
    passkey = ctx.context.adapter.find_one(model: "passkey", where: [{field: "credentialID", value: credential_id}])
    raise APIError.new("UNAUTHORIZED", message: PASSKEY_ERROR_CODES.fetch("PASSKEY_NOT_FOUND")) unless passkey

    passkey_configure_webauthn(config, ctx, origin: origin)
    credential = WebAuthn::Credential.from_get(response)
    credential.verify(
      challenge.fetch("expectedChallenge"),
      public_key: Base64.strict_decode64(passkey.fetch("publicKey")),
      sign_count: passkey.fetch("counter").to_i,
      user_verification: false
    )
    passkey_call_callback(config.dig(:authentication, :after_verification), {
      ctx: ctx,
      verification: credential,
      client_data: response
    })
    ctx.context.adapter.update(
      model: "passkey",
      where: [{field: "id", value: passkey.fetch("id")}],
      update: {counter: credential.sign_count}
    )
    session = ctx.context.internal_adapter.create_session(passkey.fetch("userId"))
    raise APIError.new("INTERNAL_SERVER_ERROR", message: PASSKEY_ERROR_CODES.fetch("UNABLE_TO_CREATE_SESSION")) unless session

    user = ctx.context.internal_adapter.find_user_by_id(passkey.fetch("userId"))
    raise APIError.new("INTERNAL_SERVER_ERROR", message: "User not found") unless user

    Cookies.set_session_cookie(ctx, {session: session, user: user})
    ctx.context.internal_adapter.delete_verification_by_identifier(verification_token)
    ctx.json({session: session, user: user})
  rescue WebAuthn::Error, ArgumentError => error
    ctx.context.logger&.error("Failed to verify authentication", error)
    raise APIError.new("BAD_REQUEST", message: PASSKEY_ERROR_CODES.fetch("AUTHENTICATION_FAILED"))
  end
end

.verify_passkey_registration_endpoint(config) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/better_auth/plugins/passkey.rb', line 107

def verify_passkey_registration_endpoint(config)
  Endpoint.new(path: "/passkey/verify-registration", method: "POST") do |ctx|
    require_session = config.dig(:registration, :require_session) != false
    session = require_session ? Routes.current_session(ctx, sensitive: true) : Routes.current_session(ctx, allow_nil: true, sensitive: true)
    origin = passkey_origin(config, ctx)
    raise APIError.new("BAD_REQUEST", message: "origin missing") if origin.to_s.empty?

    verification_token = passkey_challenge_token(ctx, config)
    raise APIError.new("BAD_REQUEST", message: PASSKEY_ERROR_CODES.fetch("CHALLENGE_NOT_FOUND")) unless verification_token

    challenge = passkey_find_challenge(ctx, verification_token)
    unless challenge
      raise APIError.new("BAD_REQUEST", message: PASSKEY_ERROR_CODES.fetch("CHALLENGE_NOT_FOUND"))
    end
    if session && challenge.fetch("userData").fetch("id") != session.fetch(:user).fetch("id")
      raise APIError.new("UNAUTHORIZED", message: PASSKEY_ERROR_CODES.fetch("YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY"))
    end

    response = passkey_webauthn_response(normalize_hash(ctx.body)[:response])
    passkey_configure_webauthn(config, ctx, origin: origin)
    credential = WebAuthn::Credential.from_create(response)
    credential.verify(challenge.fetch("expectedChallenge"), user_verification: false)
    authenticator_data = passkey_authenticator_data(credential)
    body = normalize_hash(ctx.body)
    target_user_id = passkey_after_registration_verification_user_id(config, ctx, credential, challenge, response, session)
    data = ctx.context.adapter.create(
      model: "passkey",
      data: {
        name: body[:name],
        userId: target_user_id,
        credentialID: credential.id,
        publicKey: Base64.strict_encode64(credential.public_key),
        counter: credential.sign_count,
        deviceType: authenticator_data&.credential_backup_eligible? ? "multiDevice" : "singleDevice",
        backedUp: authenticator_data&.credential_backed_up? || false,
        transports: Array(passkey_attestation_response(credential)&.transports).join(","),
        createdAt: Time.now,
        aaguid: passkey_attestation_response(credential)&.aaguid
      }
    )
    ctx.context.internal_adapter.delete_verification_by_identifier(verification_token)
    ctx.json(passkey_wire(data))
  rescue WebAuthn::Error => error
    ctx.context.logger&.error("Failed to verify registration", error)
    raise APIError.new("INTERNAL_SERVER_ERROR", message: PASSKEY_ERROR_CODES.fetch("FAILED_TO_VERIFY_REGISTRATION"))
  end
end