rustauth-passkey 0.3.0

Server-side passkey plugin for RustAuth.
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
use std::future::{ready, Future};
use std::pin::Pin;
use std::sync::Arc;

use indexmap::IndexMap;
use rustauth_core::options::RateLimitRule;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use time::Duration;

use crate::webauthn::{PasskeyWebAuthnBackend, RealPasskeyWebAuthnBackend};

/// Rate limit settings for passkey ceremony endpoints (challenge generation and verification).
///
/// Defaults match RustAuth core's strict sign-in policy (`3` requests per `10` seconds).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasskeyRateLimit {
    pub window: Duration,
    pub max: u64,
}

impl Default for PasskeyRateLimit {
    fn default() -> Self {
        Self {
            window: Duration::seconds(10),
            max: 3,
        }
    }
}

impl PasskeyRateLimit {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn window(mut self, window: Duration) -> Self {
        self.window = window;
        self
    }

    #[must_use]
    pub fn max(mut self, max: u64) -> Self {
        self.max = max;
        self
    }
}

/// Per signed challenge cookie rate limits for passkey verify endpoints.
///
/// Limits verification attempts per challenge independently of the ceremony
/// IP+path bucket. Storage keys use `HMAC-SHA256(secret, challenge_token)` via
/// RustAuth core; raw tokens are never persisted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasskeyChallengeRateLimit {
    pub window: Duration,
    pub max: u64,
}

impl Default for PasskeyChallengeRateLimit {
    fn default() -> Self {
        Self {
            window: Duration::minutes(5),
            max: 5,
        }
    }
}

impl PasskeyChallengeRateLimit {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn window(mut self, window: Duration) -> Self {
        self.window = window;
        self
    }

    #[must_use]
    pub fn max(mut self, max: u64) -> Self {
        self.max = max;
        self
    }

    /// Disable per-challenge verification rate limiting.
    #[must_use]
    pub fn disabled(mut self) -> Self {
        self.max = 0;
        self
    }

    pub(crate) fn rule(&self) -> Option<RateLimitRule> {
        if self.max == 0 || self.window.is_zero() {
            return None;
        }
        Some(RateLimitRule {
            window: self.window,
            max: self.max,
        })
    }
}

/// Advanced passkey plugin settings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PasskeyAdvancedOptions {
    pub webauthn_challenge_cookie: String,
}

impl Default for PasskeyAdvancedOptions {
    fn default() -> Self {
        Self {
            webauthn_challenge_cookie: "better-auth-passkey".to_owned(),
        }
    }
}

/// Passkey management mutation settings (delete, rename).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasskeyManagementOptions {
    /// Require a fresh session before passkey management mutations.
    pub require_fresh_session: bool,
}

impl Default for PasskeyManagementOptions {
    fn default() -> Self {
        Self {
            require_fresh_session: true,
        }
    }
}

impl PasskeyManagementOptions {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn require_fresh_session(mut self, require_fresh_session: bool) -> Self {
        self.require_fresh_session = require_fresh_session;
        self
    }
}

/// Database schema naming overrides for the passkey model.
///
/// The Rust API continues to use RustAuth's logical snake_case names; these
/// overrides only affect the physical table and column names used by adapters.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PasskeySchemaOptions {
    pub table_name: Option<String>,
    pub field_names: IndexMap<String, String>,
}

impl PasskeySchemaOptions {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn table_name(mut self, table_name: impl Into<String>) -> Self {
        self.table_name = Some(table_name.into());
        self
    }

    #[must_use]
    pub fn field_name(
        mut self,
        logical_name: impl Into<String>,
        database_name: impl Into<String>,
    ) -> Self {
        self.field_names
            .insert(logical_name.into(), database_name.into());
        self
    }

    pub(crate) fn table_name_or<'a>(&'a self, default_name: &'a str) -> &'a str {
        self.table_name.as_deref().unwrap_or(default_name)
    }

    pub(crate) fn field_name_or<'a>(
        &'a self,
        logical_name: &str,
        default_name: &'a str,
    ) -> &'a str {
        self.field_names
            .get(logical_name)
            .map(String::as_str)
            .unwrap_or(default_name)
    }
}

/// Passkey plugin settings.
#[derive(Clone)]
pub struct PasskeyOptions {
    pub rp_id: Option<String>,
    pub rp_name: Option<String>,
    pub origin: Vec<String>,
    pub passkey_table: String,
    pub schema: PasskeySchemaOptions,
    pub authenticator_selection: AuthenticatorSelection,
    pub registration: PasskeyRegistrationOptions,
    pub authentication: PasskeyAuthenticationOptions,
    pub management: PasskeyManagementOptions,
    pub advanced: PasskeyAdvancedOptions,
    pub rate_limit: PasskeyRateLimit,
    pub challenge_rate_limit: PasskeyChallengeRateLimit,
    pub(crate) backend: Arc<dyn PasskeyWebAuthnBackend>,
}

impl Default for PasskeyOptions {
    fn default() -> Self {
        Self {
            rp_id: None,
            rp_name: None,
            origin: Vec::new(),
            passkey_table: "passkeys".to_owned(),
            schema: PasskeySchemaOptions::default(),
            authenticator_selection: AuthenticatorSelection::default(),
            registration: PasskeyRegistrationOptions::default(),
            authentication: PasskeyAuthenticationOptions::default(),
            management: PasskeyManagementOptions::default(),
            advanced: PasskeyAdvancedOptions::default(),
            rate_limit: PasskeyRateLimit::default(),
            challenge_rate_limit: PasskeyChallengeRateLimit::default(),
            backend: Arc::new(RealPasskeyWebAuthnBackend),
        }
    }
}

impl PasskeyOptions {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn rp_id(mut self, rp_id: impl Into<String>) -> Self {
        self.rp_id = Some(rp_id.into());
        self
    }

    #[must_use]
    pub fn rp_name(mut self, rp_name: impl Into<String>) -> Self {
        self.rp_name = Some(rp_name.into());
        self
    }

    #[must_use]
    pub fn origin(mut self, origin: impl Into<String>) -> Self {
        self.origin.push(origin.into());
        self
    }

    #[must_use]
    pub fn passkey_table(mut self, table: impl Into<String>) -> Self {
        self.passkey_table = table.into();
        self
    }

    #[must_use]
    pub fn schema(mut self, schema: PasskeySchemaOptions) -> Self {
        self.schema = schema;
        self
    }

    #[must_use]
    pub fn authenticator_selection(mut self, selection: AuthenticatorSelection) -> Self {
        self.authenticator_selection = selection;
        self
    }

    #[must_use]
    pub fn registration(mut self, registration: PasskeyRegistrationOptions) -> Self {
        self.registration = registration;
        self
    }

    #[must_use]
    pub fn authentication(mut self, authentication: PasskeyAuthenticationOptions) -> Self {
        self.authentication = authentication;
        self
    }

    #[must_use]
    pub fn management(mut self, management: PasskeyManagementOptions) -> Self {
        self.management = management;
        self
    }

    #[must_use]
    pub fn advanced(mut self, advanced: PasskeyAdvancedOptions) -> Self {
        self.advanced = advanced;
        self
    }

    #[must_use]
    pub fn rate_limit(mut self, rate_limit: PasskeyRateLimit) -> Self {
        self.rate_limit = rate_limit;
        self
    }

    #[must_use]
    pub fn challenge_rate_limit(mut self, challenge_rate_limit: PasskeyChallengeRateLimit) -> Self {
        self.challenge_rate_limit = challenge_rate_limit;
        self
    }

    #[cfg(feature = "test-util")]
    /// Inject a custom WebAuthn backend (test builds only).
    #[must_use]
    pub fn backend(mut self, backend: Arc<dyn PasskeyWebAuthnBackend>) -> Self {
        self.backend = backend;
        self
    }

    pub(crate) fn rate_limit_rule(&self) -> RateLimitRule {
        RateLimitRule {
            window: self.rate_limit.window,
            max: self.rate_limit.max,
        }
    }
}

/// Browser authenticator attachment hint.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuthenticatorAttachment {
    Platform,
    CrossPlatform,
}

impl AuthenticatorAttachment {
    pub(crate) fn from_query(value: &str) -> Option<Self> {
        match value {
            "platform" => Some(Self::Platform),
            "cross-platform" => Some(Self::CrossPlatform),
            _ => None,
        }
    }

    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Platform => "platform",
            Self::CrossPlatform => "cross-platform",
        }
    }
}

/// Resident key preference used in registration options.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ResidentKeyRequirement {
    Discouraged,
    Preferred,
    Required,
}

impl ResidentKeyRequirement {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Discouraged => "discouraged",
            Self::Preferred => "preferred",
            Self::Required => "required",
        }
    }
}

/// User verification preference used in WebAuthn options.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum UserVerificationRequirement {
    Discouraged,
    Preferred,
    Required,
}

impl UserVerificationRequirement {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Discouraged => "discouraged",
            Self::Preferred => "preferred",
            Self::Required => "required",
        }
    }
}

/// Authenticator selection hints for generated registration options.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthenticatorSelection {
    pub resident_key: ResidentKeyRequirement,
    pub user_verification: UserVerificationRequirement,
    pub authenticator_attachment: Option<AuthenticatorAttachment>,
}

impl Default for AuthenticatorSelection {
    fn default() -> Self {
        Self {
            resident_key: ResidentKeyRequirement::Preferred,
            user_verification: UserVerificationRequirement::Preferred,
            authenticator_attachment: None,
        }
    }
}

impl AuthenticatorSelection {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn resident_key(mut self, resident_key: ResidentKeyRequirement) -> Self {
        self.resident_key = resident_key;
        self
    }

    #[must_use]
    pub fn user_verification(mut self, user_verification: UserVerificationRequirement) -> Self {
        self.user_verification = user_verification;
        self
    }

    #[must_use]
    pub fn authenticator_attachment(mut self, attachment: AuthenticatorAttachment) -> Self {
        self.authenticator_attachment = Some(attachment);
        self
    }

    pub(crate) fn with_attachment_override(
        &self,
        attachment: Option<AuthenticatorAttachment>,
    ) -> Self {
        let mut selection = self.clone();
        if attachment.is_some() {
            selection.authenticator_attachment = attachment;
        }
        selection
    }

    pub fn to_json(&self) -> Value {
        let mut value = json!({
            "residentKey": self.resident_key.as_str(),
            "userVerification": self.user_verification.as_str(),
        });
        if let Some(attachment) = self.authenticator_attachment {
            value["authenticatorAttachment"] = json!(attachment.as_str());
        }
        value
    }
}

/// WebAuthn option customizations resolved for one registration request.
#[derive(Debug, Clone, PartialEq)]
pub struct RegistrationWebAuthnOptions {
    pub authenticator_selection: AuthenticatorSelection,
    pub extensions: Option<Value>,
}

impl RegistrationWebAuthnOptions {
    pub(crate) fn new(
        authenticator_selection: AuthenticatorSelection,
        extensions: Option<Value>,
    ) -> Self {
        Self {
            authenticator_selection,
            extensions,
        }
    }
}

/// User identity used for passkey registration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PasskeyRegistrationUser {
    pub id: String,
    pub name: String,
    pub display_name: Option<String>,
}

impl PasskeyRegistrationUser {
    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            display_name: None,
        }
    }

    #[must_use]
    pub fn display_name(mut self, display_name: impl Into<String>) -> Self {
        self.display_name = Some(display_name.into());
        self
    }
}

pub type PasskeyBoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;

pub type ResolveRegistrationUser = Arc<
    dyn Fn(ResolveRegistrationUserInput) -> PasskeyBoxFuture<Option<PasskeyRegistrationUser>>
        + Send
        + Sync,
>;

pub type AfterRegistrationVerification = Arc<
    dyn Fn(AfterRegistrationVerificationInput) -> PasskeyBoxFuture<Option<String>> + Send + Sync,
>;

/// Rejection returned by authentication `after_verification` hooks to abort login
/// after WebAuthn proof verification without updating the passkey counter or
/// minting a session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasskeyAuthenticationRejected;

pub type AfterAuthenticationVerification = Arc<
    dyn Fn(
            AfterAuthenticationVerificationInput,
        ) -> PasskeyBoxFuture<Result<(), PasskeyAuthenticationRejected>>
        + Send
        + Sync,
>;

pub type PasskeyExtensionsResolver =
    Arc<dyn Fn(PasskeyExtensionsInput) -> PasskeyBoxFuture<Option<Value>> + Send + Sync>;

#[derive(Clone)]
pub struct PasskeyRegistrationOptions {
    pub require_session: bool,
    pub resolve_user: Option<ResolveRegistrationUser>,
    pub after_verification: Option<AfterRegistrationVerification>,
    pub extensions: Option<PasskeyExtensionsResolver>,
}

impl Default for PasskeyRegistrationOptions {
    fn default() -> Self {
        Self {
            require_session: true,
            resolve_user: None,
            after_verification: None,
            extensions: None,
        }
    }
}

impl PasskeyRegistrationOptions {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn require_session(mut self, require_session: bool) -> Self {
        self.require_session = require_session;
        self
    }

    #[must_use]
    pub fn resolve_user<F>(mut self, resolver: F) -> Self
    where
        F: Fn(ResolveRegistrationUserInput) -> Option<PasskeyRegistrationUser>
            + Send
            + Sync
            + 'static,
    {
        self.resolve_user = Some(Arc::new(move |input| Box::pin(ready(resolver(input)))));
        self
    }

    #[must_use]
    pub fn resolve_user_async<F, Fut>(mut self, resolver: F) -> Self
    where
        F: Fn(ResolveRegistrationUserInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Option<PasskeyRegistrationUser>> + Send + 'static,
    {
        self.resolve_user = Some(Arc::new(move |input| Box::pin(resolver(input))));
        self
    }

    #[must_use]
    pub fn after_verification<F>(mut self, callback: F) -> Self
    where
        F: Fn(AfterRegistrationVerificationInput) -> Option<String> + Send + Sync + 'static,
    {
        self.after_verification = Some(Arc::new(move |input| Box::pin(ready(callback(input)))));
        self
    }

    #[must_use]
    pub fn after_verification_async<F, Fut>(mut self, callback: F) -> Self
    where
        F: Fn(AfterRegistrationVerificationInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Option<String>> + Send + 'static,
    {
        self.after_verification = Some(Arc::new(move |input| Box::pin(callback(input))));
        self
    }

    #[must_use]
    pub fn extensions(mut self, extensions: Value) -> Self {
        self.extensions = Some(Arc::new(move |_| Box::pin(ready(Some(extensions.clone())))));
        self
    }

    #[must_use]
    pub fn extensions_resolver<F, Fut>(mut self, resolver: F) -> Self
    where
        F: Fn(PasskeyExtensionsInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Option<Value>> + Send + 'static,
    {
        self.extensions = Some(Arc::new(move |input| Box::pin(resolver(input))));
        self
    }
}

#[derive(Clone, Default)]
pub struct PasskeyAuthenticationOptions {
    pub after_verification: Option<AfterAuthenticationVerification>,
    pub extensions: Option<PasskeyExtensionsResolver>,
}

impl PasskeyAuthenticationOptions {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn after_verification<F>(mut self, callback: F) -> Self
    where
        F: Fn(AfterAuthenticationVerificationInput) + Send + Sync + 'static,
    {
        self.after_verification = Some(Arc::new(move |input| {
            callback(input);
            Box::pin(ready(Ok(())))
        }));
        self
    }

    #[must_use]
    pub fn after_verification_async<F, Fut>(mut self, callback: F) -> Self
    where
        F: Fn(AfterAuthenticationVerificationInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), PasskeyAuthenticationRejected>> + Send + 'static,
    {
        self.after_verification = Some(Arc::new(move |input| Box::pin(callback(input))));
        self
    }

    #[must_use]
    pub fn extensions(mut self, extensions: Value) -> Self {
        self.extensions = Some(Arc::new(move |_| Box::pin(ready(Some(extensions.clone())))));
        self
    }

    #[must_use]
    pub fn extensions_resolver<F, Fut>(mut self, resolver: F) -> Self
    where
        F: Fn(PasskeyExtensionsInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Option<Value>> + Send + 'static,
    {
        self.extensions = Some(Arc::new(move |input| Box::pin(resolver(input))));
        self
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolveRegistrationUserInput {
    pub context: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PasskeyExtensionsInput {
    pub context: Option<String>,
    /// Authenticated user id when generating session-scoped authentication options.
    pub user_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct AfterRegistrationVerificationInput {
    pub user: PasskeyRegistrationUser,
    pub client_data: Value,
    pub context: Option<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct AfterAuthenticationVerificationInput {
    pub credential_id: String,
    pub client_data: Value,
}