better-auth-api 0.10.0

Plugin implementations for better-auth
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
154
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
use super::*;
use crate::plugins::test_helpers;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use better_auth_core::adapters::{PasskeyOps, UserOps, VerificationOps};
use better_auth_core::entity::AuthPasskey;
use better_auth_core::{CreatePasskey, CreateUser, CreateVerification, HttpMethod};
use chrono::{Duration, Utc};

fn encoded_client_data(challenge: &str, client_type: &str, origin: &str) -> String {
    let client_data = serde_json::json!({
        "type": client_type,
        "challenge": challenge,
        "origin": origin,
    });
    URL_SAFE_NO_PAD.encode(serde_json::to_vec(&client_data).unwrap())
}

#[tokio::test]
async fn test_verify_registration_requires_insecure_opt_in() {
    let plugin = PasskeyPlugin::new();
    let (ctx, _user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let body = serde_json::json!({
        "response": {
            "id": "cred-1",
            "response": {
                "clientDataJSON": encoded_client_data("challenge-1", "webauthn.create", "http://localhost:3000"),
            }
        }
    });

    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/verify-registration",
        Some(&session.token),
        Some(body),
    );

    let err = plugin
        .handle_verify_registration(&req, &ctx)
        .await
        .unwrap_err();
    assert_eq!(err.status_code(), 501);
}

#[tokio::test]
async fn test_verify_registration_consumes_exact_challenge_once() {
    let plugin = PasskeyPlugin::new().allow_insecure_unverified_assertion(true);
    let (ctx, user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let challenge = "register-challenge";
    let identifier = format!("passkey_reg:{}", user.id);

    ctx.database
        .create_verification(CreateVerification {
            identifier: identifier.clone(),
            value: challenge.to_string(),
            expires_at: Utc::now() + Duration::minutes(5),
        })
        .await
        .unwrap();

    let wrong_body = serde_json::json!({
        "response": {
            "id": "cred-reg-1",
            "response": {
                "clientDataJSON": encoded_client_data("wrong-challenge", "webauthn.create", "http://localhost:3000"),
                "attestationObject": "fake-attestation",
            }
        }
    });
    let wrong_req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/verify-registration",
        Some(&session.token),
        Some(wrong_body),
    );
    let err = plugin
        .handle_verify_registration(&wrong_req, &ctx)
        .await
        .unwrap_err();
    assert_eq!(err.status_code(), 400);

    assert!(
        ctx.database
            .get_verification(&identifier, challenge)
            .await
            .unwrap()
            .is_some()
    );

    let ok_body = serde_json::json!({
        "response": {
            "id": "cred-reg-1",
            "response": {
                "clientDataJSON": encoded_client_data(challenge, "webauthn.create", "http://localhost:3000"),
                "attestationObject": "fake-attestation",
            }
        }
    });
    let ok_req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/verify-registration",
        Some(&session.token),
        Some(ok_body),
    );
    let response = plugin
        .handle_verify_registration(&ok_req, &ctx)
        .await
        .unwrap();
    assert_eq!(response.status, 200);

    assert!(
        ctx.database
            .get_verification(&identifier, challenge)
            .await
            .unwrap()
            .is_none()
    );

    let passkeys = ctx.database.list_passkeys_by_user(&user.id).await.unwrap();
    assert_eq!(passkeys.len(), 1);
}

#[tokio::test]
async fn test_verify_authentication_checks_type_origin_and_prevents_replay() {
    let plugin = PasskeyPlugin::new().allow_insecure_unverified_assertion(true);
    let (ctx, user, _session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let credential_id = "cred-auth-1";
    ctx.database
        .create_passkey(CreatePasskey {
            user_id: user.id.clone(),
            name: "Authenticator".to_string(),
            credential_id: credential_id.to_string(),
            public_key: "fake-public-key".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: None,
        })
        .await
        .unwrap();

    let challenge = "auth-challenge-1";
    let identifier = format!("passkey_auth:{}", challenge);

    ctx.database
        .create_verification(CreateVerification {
            identifier: identifier.clone(),
            value: challenge.to_string(),
            expires_at: Utc::now() + Duration::minutes(5),
        })
        .await
        .unwrap();

    let wrong_type_body = serde_json::json!({
        "response": {
            "id": credential_id,
            "response": {
                "clientDataJSON": encoded_client_data(challenge, "webauthn.create", "http://localhost:3000"),
            }
        }
    });
    let wrong_type_req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/verify-authentication",
        None,
        Some(wrong_type_body),
    );
    let err = plugin
        .handle_verify_authentication(&wrong_type_req, &ctx)
        .await
        .unwrap_err();
    assert_eq!(err.status_code(), 400);

    let wrong_origin_body = serde_json::json!({
        "response": {
            "id": credential_id,
            "response": {
                "clientDataJSON": encoded_client_data(challenge, "webauthn.get", "http://evil.example"),
            }
        }
    });
    let wrong_origin_req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/verify-authentication",
        None,
        Some(wrong_origin_body),
    );
    let err = plugin
        .handle_verify_authentication(&wrong_origin_req, &ctx)
        .await
        .unwrap_err();
    assert_eq!(err.status_code(), 400);

    assert!(
        ctx.database
            .get_verification(&identifier, challenge)
            .await
            .unwrap()
            .is_some()
    );

    let ok_body = serde_json::json!({
        "response": {
            "id": credential_id,
            "response": {
                "clientDataJSON": encoded_client_data(challenge, "webauthn.get", "http://localhost:3000"),
            }
        }
    });
    let ok_req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/verify-authentication",
        None,
        Some(ok_body.clone()),
    );
    let response = plugin
        .handle_verify_authentication(&ok_req, &ctx)
        .await
        .unwrap();
    assert_eq!(response.status, 200);

    assert!(
        ctx.database
            .get_verification(&identifier, challenge)
            .await
            .unwrap()
            .is_none()
    );

    let replay_req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/verify-authentication",
        None,
        Some(ok_body),
    );
    let err = plugin
        .handle_verify_authentication(&replay_req, &ctx)
        .await
        .unwrap_err();
    assert_eq!(err.status_code(), 400);

    let passkey = ctx
        .database
        .get_passkey_by_credential_id(credential_id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(passkey.counter(), 1);
}

#[tokio::test]
async fn test_generate_register_options_returns_challenge_and_stores_verification() {
    let plugin = PasskeyPlugin::new();
    let (ctx, user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Get,
        "/passkey/generate-register-options",
        Some(&session.token),
        None,
    );

    let response = plugin
        .handle_generate_register_options(&req, &ctx)
        .await
        .unwrap();
    assert_eq!(response.status, 200);

    let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
    assert!(body["challenge"].is_string());
    assert_eq!(body["rp"]["id"], "localhost");
    assert_eq!(body["rp"]["name"], "Better Auth");
    assert!(body["user"]["id"].is_string());
    assert!(body["pubKeyCredParams"].is_array());
    assert!(body["excludeCredentials"].is_array());

    // Verify challenge was stored
    let challenge = body["challenge"].as_str().unwrap();
    let identifier = format!("passkey_reg:{}", user.id);
    let verification = ctx
        .database
        .get_verification(&identifier, challenge)
        .await
        .unwrap();
    assert!(verification.is_some());
}

#[tokio::test]
async fn test_generate_register_options_unauthenticated() {
    let plugin = PasskeyPlugin::new();
    let (ctx, _user, _session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Get,
        "/passkey/generate-register-options",
        None,
        None,
    );

    let err = plugin
        .handle_generate_register_options(&req, &ctx)
        .await
        .unwrap_err();
    assert_eq!(err.status_code(), 401);
}

#[tokio::test]
async fn test_generate_authenticate_options_returns_challenge() {
    let plugin = PasskeyPlugin::new();
    let (ctx, _user, _session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    // No auth required for this endpoint
    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/generate-authenticate-options",
        None,
        None,
    );

    let response = plugin
        .handle_generate_authenticate_options(&req, &ctx)
        .await
        .unwrap();
    assert_eq!(response.status, 200);

    let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
    assert!(body["challenge"].is_string());
    assert_eq!(body["rpId"], "localhost");
    assert!(body["allowCredentials"].is_array());
    assert_eq!(body["allowCredentials"].as_array().unwrap().len(), 0);
}

#[tokio::test]
async fn test_generate_authenticate_options_with_auth_includes_credentials() {
    let plugin = PasskeyPlugin::new();
    let (ctx, user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    // Create a passkey for the user
    ctx.database
        .create_passkey(CreatePasskey {
            user_id: user.id.clone(),
            name: "Test Key".to_string(),
            credential_id: "cred-gen-auth-1".to_string(),
            public_key: "pk".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: Some("[\"usb\"]".to_string()),
        })
        .await
        .unwrap();

    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/generate-authenticate-options",
        Some(&session.token),
        None,
    );

    let response = plugin
        .handle_generate_authenticate_options(&req, &ctx)
        .await
        .unwrap();
    assert_eq!(response.status, 200);

    let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
    let allow = body["allowCredentials"].as_array().unwrap();
    assert_eq!(allow.len(), 1);
    assert_eq!(allow[0]["id"], "cred-gen-auth-1");
}

#[tokio::test]
async fn test_list_user_passkeys() {
    let plugin = PasskeyPlugin::new();
    let (ctx, user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    // No passkeys yet
    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Get,
        "/passkey/list-user-passkeys",
        Some(&session.token),
        None,
    );
    let response = plugin.handle_list_user_passkeys(&req, &ctx).await.unwrap();
    assert_eq!(response.status, 200);
    let body: Vec<serde_json::Value> = serde_json::from_slice(&response.body).unwrap();
    assert_eq!(body.len(), 0);

    // Create a passkey
    ctx.database
        .create_passkey(CreatePasskey {
            user_id: user.id.clone(),
            name: "My Key".to_string(),
            credential_id: "cred-list-1".to_string(),
            public_key: "pk".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: None,
        })
        .await
        .unwrap();

    let response = plugin.handle_list_user_passkeys(&req, &ctx).await.unwrap();
    assert_eq!(response.status, 200);
    let body: Vec<serde_json::Value> = serde_json::from_slice(&response.body).unwrap();
    assert_eq!(body.len(), 1);
    assert_eq!(body[0]["name"], "My Key");
    assert_eq!(body[0]["credentialID"], "cred-list-1");
}

#[tokio::test]
async fn test_list_user_passkeys_unauthenticated() {
    let plugin = PasskeyPlugin::new();
    let (ctx, _user, _session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Get,
        "/passkey/list-user-passkeys",
        None,
        None,
    );
    let err = plugin
        .handle_list_user_passkeys(&req, &ctx)
        .await
        .unwrap_err();
    assert_eq!(err.status_code(), 401);
}

#[tokio::test]
async fn test_delete_passkey_success() {
    let plugin = PasskeyPlugin::new();
    let (ctx, user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let passkey = ctx
        .database
        .create_passkey(CreatePasskey {
            user_id: user.id.clone(),
            name: "To Delete".to_string(),
            credential_id: "cred-del-1".to_string(),
            public_key: "pk".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: None,
        })
        .await
        .unwrap();

    let body = serde_json::json!({ "id": passkey.id });
    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/delete-passkey",
        Some(&session.token),
        Some(body),
    );

    let response = plugin.handle_delete_passkey(&req, &ctx).await.unwrap();
    assert_eq!(response.status, 200);

    // Verify deleted
    let result = ctx.database.get_passkey_by_id(&passkey.id).await.unwrap();
    assert!(result.is_none());
}

#[tokio::test]
async fn test_delete_passkey_non_owner_rejected() {
    let plugin = PasskeyPlugin::new();
    let (ctx, _user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    // Create another user's passkey
    let other_user = ctx
        .database
        .create_user(
            CreateUser::new()
                .with_email("other@example.com")
                .with_name("Other User"),
        )
        .await
        .unwrap();

    let passkey = ctx
        .database
        .create_passkey(CreatePasskey {
            user_id: other_user.id.clone(),
            name: "Other's Key".to_string(),
            credential_id: "cred-other-del".to_string(),
            public_key: "pk".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: None,
        })
        .await
        .unwrap();

    let body = serde_json::json!({ "id": passkey.id });
    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/delete-passkey",
        Some(&session.token),
        Some(body),
    );

    let err = plugin.handle_delete_passkey(&req, &ctx).await.unwrap_err();
    assert_eq!(err.status_code(), 404);

    // Verify NOT deleted
    let result = ctx.database.get_passkey_by_id(&passkey.id).await.unwrap();
    assert!(result.is_some());
}

#[tokio::test]
async fn test_update_passkey_success() {
    let plugin = PasskeyPlugin::new();
    let (ctx, user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let passkey = ctx
        .database
        .create_passkey(CreatePasskey {
            user_id: user.id.clone(),
            name: "Old Name".to_string(),
            credential_id: "cred-upd-1".to_string(),
            public_key: "pk".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: None,
        })
        .await
        .unwrap();

    let body = serde_json::json!({ "id": passkey.id, "name": "New Name" });
    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/update-passkey",
        Some(&session.token),
        Some(body),
    );

    let response = plugin.handle_update_passkey(&req, &ctx).await.unwrap();
    assert_eq!(response.status, 200);

    let resp_body: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
    assert_eq!(resp_body["passkey"]["name"], "New Name");

    // Verify persisted
    let updated = ctx
        .database
        .get_passkey_by_id(&passkey.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(updated.name(), "New Name");
}

#[tokio::test]
async fn test_update_passkey_non_owner_rejected() {
    let plugin = PasskeyPlugin::new();
    let (ctx, _user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let other_user = ctx
        .database
        .create_user(
            CreateUser::new()
                .with_email("other-upd@example.com")
                .with_name("Other"),
        )
        .await
        .unwrap();

    let passkey = ctx
        .database
        .create_passkey(CreatePasskey {
            user_id: other_user.id.clone(),
            name: "Other's Key".to_string(),
            credential_id: "cred-other-upd".to_string(),
            public_key: "pk".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: None,
        })
        .await
        .unwrap();

    let body = serde_json::json!({ "id": passkey.id, "name": "Hijacked" });
    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/update-passkey",
        Some(&session.token),
        Some(body),
    );

    let err = plugin.handle_update_passkey(&req, &ctx).await.unwrap_err();
    assert_eq!(err.status_code(), 404);

    // Verify unchanged
    let unchanged = ctx
        .database
        .get_passkey_by_id(&passkey.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(unchanged.name(), "Other's Key");
}

#[tokio::test]
async fn test_expired_challenge_rejected() {
    let plugin = PasskeyPlugin::new().allow_insecure_unverified_assertion(true);
    let (ctx, user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let challenge = "expired-challenge";
    let identifier = format!("passkey_reg:{}", user.id);

    // Create an already-expired verification
    ctx.database
        .create_verification(CreateVerification {
            identifier: identifier.clone(),
            value: challenge.to_string(),
            expires_at: Utc::now() - Duration::seconds(1),
        })
        .await
        .unwrap();

    let body = serde_json::json!({
        "response": {
            "id": "cred-exp-1",
            "response": {
                "clientDataJSON": encoded_client_data(challenge, "webauthn.create", "http://localhost:3000"),
                "attestationObject": "fake",
            }
        }
    });
    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/verify-registration",
        Some(&session.token),
        Some(body),
    );

    let err = plugin
        .handle_verify_registration(&req, &ctx)
        .await
        .unwrap_err();
    assert_eq!(err.status_code(), 400);
}

#[tokio::test]
async fn test_verify_authentication_requires_insecure_opt_in() {
    let plugin = PasskeyPlugin::new(); // default: insecure=false
    let (ctx, _user, _session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let body = serde_json::json!({
        "response": {
            "id": "cred-1",
            "response": {
                "clientDataJSON": encoded_client_data("c", "webauthn.get", "http://localhost:3000"),
            }
        }
    });

    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/verify-authentication",
        None,
        Some(body),
    );

    let err = plugin
        .handle_verify_authentication(&req, &ctx)
        .await
        .unwrap_err();
    assert_eq!(err.status_code(), 501);
}

#[tokio::test]
async fn test_memory_passkey_list_is_sorted_by_created_at_desc() {
    let (ctx, user, _session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let first = ctx
        .database
        .create_passkey(CreatePasskey {
            user_id: user.id.clone(),
            name: "first".to_string(),
            credential_id: "cred-sort-1".to_string(),
            public_key: "pk-1".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: None,
        })
        .await
        .unwrap();

    tokio::time::sleep(std::time::Duration::from_millis(2)).await;

    let second = ctx
        .database
        .create_passkey(CreatePasskey {
            user_id: user.id.clone(),
            name: "second".to_string(),
            credential_id: "cred-sort-2".to_string(),
            public_key: "pk-2".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: None,
        })
        .await
        .unwrap();

    let listed = ctx.database.list_passkeys_by_user(&user.id).await.unwrap();
    assert_eq!(listed.len(), 2);
    assert_eq!(listed[0].id(), second.id());
    assert_eq!(listed[1].id(), first.id());
}