fastauth-plugin-passkey 0.4.0

Passkeys (WebAuthn) for fastauth, built on webauthn-rs and wire-compatible with Better Auth's passkey plugin.
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
//! The `/passkey/*` endpoints.

use fastauth_core::crypto::base64url;
use fastauth_core::plugin_prelude::*;
use fastauth_core::routes::Status;
use serde_json::{Map, Value as Json};
use webauthn_rs::prelude::{
    Credential, PublicKeyCredential, RegisterPublicKeyCredential, Uuid, WebauthnError,
};
use webauthn_rs_proto::{
    AllowCredentials, AuthenticatorAttachment, PublicKeyCredentialCreationOptions,
    PublicKeyCredentialDescriptor, PublicKeyCredentialRequestOptions, ResidentKeyRequirement,
};

use crate::ceremony::{
    self, CHALLENGE_COOKIE, CHALLENGE_TTL, Challenge, IDENTIFIER, MULTI_DEVICE, SINGLE_DEVICE,
};
use crate::model::PasskeyRow;
use crate::{Passkey, PasskeyAdded, PasskeyDeleted, PasskeyError};

/// A passkey as clients see it: Better Auth's row, camelCase, `credentialID` included.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PasskeyView {
    pub id: Id,
    pub name: Option<String>,
    pub public_key: String,
    pub user_id: Id,
    #[serde(rename = "credentialID")]
    pub credential_id: String,
    pub counter: i64,
    pub device_type: String,
    pub backed_up: bool,
    pub transports: Option<String>,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    pub aaguid: Option<String>,
}

impl From<PasskeyRow> for PasskeyView {
    fn from(row: PasskeyRow) -> Self {
        Self {
            id: row.id,
            name: row.name,
            public_key: row.public_key,
            user_id: row.user_id,
            credential_id: row.credential_id,
            counter: row.counter,
            device_type: row.device_type,
            backed_up: row.backed_up,
            transports: row.transports,
            created_at: row.created_at,
            aaguid: row.aaguid,
        }
    }
}

/// Starts a ceremony: stores its state for `CHALLENGE_TTL` and names it in the signed cookie.
async fn store_challenge<D: Adapter, A>(
    ctx: &Ctx<D, A>,
    challenge: &Challenge,
) -> Result<(), AuthError> {
    let data = serde_json::to_string(challenge).map_err(AuthError::internal)?;
    let token = ctx
        .internal()
        .create_verification(IDENTIFIER, CHALLENGE_TTL, Some(data))
        .await?;
    ctx.set_signed_cookie(CHALLENGE_COOKIE, &token, Some(CHALLENGE_TTL));
    Ok(())
}

/// Consumes the challenge the cookie names. Each one works once, whatever the outcome.
async fn take_challenge<D: Adapter, A>(ctx: &Ctx<D, A>) -> Result<Challenge, AuthError> {
    let token = ctx
        .signed_cookie(CHALLENGE_COOKIE)
        .ok_or(PasskeyError::ChallengeNotFound)?;
    ctx.delete_cookie(CHALLENGE_COOKIE);
    ctx.internal()
        .consume_verification(&token)
        .await?
        .filter(|v| v.identifier == IDENTIFIER)
        .and_then(|v| serde_json::from_str(v.data.as_deref()?).ok())
        .ok_or_else(|| PasskeyError::ChallengeNotFound.into())
}

async fn user_passkeys<D: Adapter, A>(
    ctx: &Ctx<D, A>,
    user_id: &Id,
) -> Result<Vec<PasskeyRow>, AuthError> {
    Ok(ctx
        .db()
        .find::<PasskeyRow>(PasskeyRow::USER_ID.eq(user_id))
        .all()
        .await?)
}

/// Query of `/passkey/generate-register-options`.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GenerateRegisterOptionsInput {
    /// `platform` for this device's authenticator, `cross-platform` for a security key or
    /// phone.
    #[serde(default)]
    pub authenticator_attachment: Option<AuthenticatorAttachment>,
    /// The account name the authenticator shows. Default: the user's email.
    #[serde(default)]
    pub name: Option<String>,
    /// Better Auth's passkey-first registration context. Accepted and ignored: fastauth
    /// registers passkeys for signed-in users only.
    #[serde(default)]
    pub context: Option<String>,
}

/// `GET /passkey/generate-register-options`: the `PublicKeyCredentialCreationOptions` to
/// pass to `navigator.credentials.create()`. Needs a fresh session, read again from the
/// database (`Ctx::sensitive_session`), so API-key and impersonation sessions can't
/// register passkeys. The user's passkeys are excluded, so an authenticator can't register
/// twice.
pub struct GenerateRegisterOptions(pub(crate) Arc<Passkey>);

impl<D: Adapter> Endpoint<D> for GenerateRegisterOptions {
    const METHOD: Method = Method::GET;
    const PATH: &'static str = "/passkey/generate-register-options";
    type Access = Fresh;
    type Input = GenerateRegisterOptionsInput;
    type Output = PublicKeyCredentialCreationOptions;

    async fn call(
        &self,
        ctx: Ctx<D, Fresh>,
        input: GenerateRegisterOptionsInput,
    ) -> Result<PublicKeyCredentialCreationOptions, AuthError> {
        let session = ctx.sensitive_session().await?;
        let user = &session.user;
        let rp = self.0.relying_party(ctx.config())?;
        let existing = user_passkeys(&ctx, &user.id).await?;
        let exclude = existing
            .iter()
            .map(|row| {
                Ok(PublicKeyCredentialDescriptor {
                    type_: "public-key".into(),
                    id: ceremony::credential_id(row)?,
                    transports: ceremony::transports(row.transports.as_deref()),
                })
            })
            .collect::<Result<Vec<_>, AuthError>>()?;
        let account = if user.email.is_empty() {
            user.id.as_str()
        } else {
            &user.email
        };
        let user_name = input.name.as_deref().filter(|n| !n.is_empty());
        let (mut options, state) = rp
            .start_passkey_registration(
                Uuid::new_v4(),
                user_name.unwrap_or(account),
                account,
                Some(exclude.iter().map(|d| d.id.clone()).collect()),
            )
            .map_err(AuthError::internal)?;
        let options = &mut options.public_key;
        options.exclude_credentials = Some(exclude);
        if let Some(selection) = &mut options.authenticator_selection {
            selection.resident_key = Some(ResidentKeyRequirement::Preferred);
            selection.require_resident_key = false;
            selection.authenticator_attachment = input.authenticator_attachment;
        }
        store_challenge(
            &ctx,
            &Challenge::Registration {
                user_id: user.id.to_string(),
                state,
            },
        )
        .await?;
        Ok(options.clone())
    }
}

/// Body of `/passkey/verify-registration`.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VerifyRegistrationInput {
    /// The `navigator.credentials.create()` result as JSON (`RegistrationResponseJSON`).
    pub response: Json,
    /// A name for the passkey.
    #[serde(default)]
    pub name: Option<String>,
    /// Also start a new session, as Better Auth does.
    #[serde(default)]
    pub create_session: Option<bool>,
}

/// The new passkey; with `createSession`, also the new session and the user.
#[derive(Debug, Serialize)]
pub struct RegisterOutput {
    #[serde(flatten)]
    pub passkey: PasskeyView,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session: Option<Map<String, Json>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<Map<String, Json>>,
}

/// `POST /passkey/verify-registration`: verifies the authenticator's attestation against the
/// challenge from `generate-register-options` and stores the passkey. Needs a fresh session,
/// the same user's, read again from the database like `generate-register-options`.
pub struct VerifyRegistration(pub(crate) Arc<Passkey>);

impl<D: Adapter> Endpoint<D> for VerifyRegistration {
    const METHOD: Method = Method::POST;
    const PATH: &'static str = "/passkey/verify-registration";
    type Access = Fresh;
    type Input = VerifyRegistrationInput;
    type Output = RegisterOutput;

    async fn call(
        &self,
        ctx: Ctx<D, Fresh>,
        input: VerifyRegistrationInput,
    ) -> Result<RegisterOutput, AuthError> {
        let session = ctx.sensitive_session().await?;
        let rp = self.0.relying_party(ctx.config())?;
        let Challenge::Registration { user_id, state } = take_challenge(&ctx).await? else {
            return Err(PasskeyError::ChallengeNotFound.into());
        };
        let user_id = Id::from(user_id);
        if user_id != session.user.id {
            return Err(PasskeyError::NotAllowed.into());
        }
        let failed = PasskeyError::FailedToVerifyRegistration;
        let transports = input.response["response"]["transports"]
            .as_array()
            .map(|t| {
                t.iter()
                    .filter_map(Json::as_str)
                    .collect::<Vec<_>>()
                    .join(",")
            })
            .unwrap_or_default();
        let response: RegisterPublicKeyCredential =
            serde_json::from_value(input.response).map_err(|_| failed)?;
        let passkey = rp
            .finish_passkey_registration(&response, &state)
            .map_err(|_| failed)?;
        let attested = ceremony::attested(&response.response.attestation_object).ok_or(failed)?;
        let credential = Credential::from(passkey);
        let credential_id = base64url(&credential.cred_id);
        if ctx
            .db()
            .find::<PasskeyRow>(PasskeyRow::CREDENTIAL_ID.eq(&credential_id))
            .one()
            .await?
            .is_some()
        {
            return Err(failed.into());
        }
        let row = PasskeyRow {
            id: ctx.new_id()?,
            name: input
                .name
                .map(|n| n.trim().to_owned())
                .filter(|n| !n.is_empty()),
            public_key: attested.public_key,
            user_id: user_id.clone(),
            credential_id,
            counter: i64::from(credential.counter),
            device_type: if credential.backup_eligible {
                MULTI_DEVICE
            } else {
                SINGLE_DEVICE
            }
            .into(),
            backed_up: credential.backup_state,
            transports: Some(transports),
            created_at: ctx.now(),
            aaguid: Some(attested.aaguid),
        };
        ctx.db().insert(&row).await?;
        ctx.emit(PasskeyAdded {
            user_id: user_id.clone(),
            passkey_id: row.id.clone(),
        });
        let (session, user) = if input.create_session == Some(true) {
            let session = ctx.internal().create_session(&user_id, true).await?;
            (Some(session.to_json()), Some(session.user.to_json()))
        } else {
            (None, None)
        };
        Ok(RegisterOutput {
            passkey: row.into(),
            session,
            user,
        })
    }
}

/// `GET /passkey/generate-authenticate-options`: the `PublicKeyCredentialRequestOptions` to
/// pass to `navigator.credentials.get()`. Signed out, any discoverable passkey for this site
/// may answer; signed in, the options list the user's passkeys.
pub struct GenerateAuthenticateOptions(pub(crate) Arc<Passkey>);

impl<D: Adapter> Endpoint<D> for GenerateAuthenticateOptions {
    const METHOD: Method = Method::GET;
    const PATH: &'static str = "/passkey/generate-authenticate-options";
    type Access = MaybeAuthenticated;
    type Input = Empty;
    type Output = PublicKeyCredentialRequestOptions;

    async fn call(
        &self,
        ctx: Ctx<D, MaybeAuthenticated>,
        _: Empty,
    ) -> Result<PublicKeyCredentialRequestOptions, AuthError> {
        let rp = self.0.relying_party(ctx.config())?;
        let (options, state) = rp
            .start_discoverable_authentication()
            .map_err(AuthError::internal)?;
        let mut options = options.public_key;
        if let Some(session) = ctx.session() {
            options.allow_credentials = user_passkeys(&ctx, &session.user.id)
                .await?
                .iter()
                .map(|row| {
                    Ok(AllowCredentials {
                        type_: "public-key".into(),
                        id: ceremony::credential_id(row)?,
                        transports: ceremony::transports(row.transports.as_deref()),
                    })
                })
                .collect::<Result<_, AuthError>>()?;
        }
        store_challenge(&ctx, &Challenge::Authentication { state }).await?;
        Ok(options)
    }
}

/// Body of `/passkey/verify-authentication`.
#[derive(Debug, Deserialize)]
pub struct VerifyAuthenticationInput {
    /// The `navigator.credentials.get()` result as JSON (`AuthenticationResponseJSON`).
    pub response: Json,
}

/// What a passkey sign-in answers.
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum SignInOutput {
    /// Signed in: Better Auth's `{ session, user }`.
    SignedIn {
        session: Map<String, Json>,
        user: Map<String, Json>,
    },
    /// A sign-in gate's answer, e.g. `{"twoFactorRedirect": true}`. No session exists yet.
    Challenge(Json),
}

/// `POST /passkey/verify-authentication`: verifies the assertion against the challenge from
/// `generate-authenticate-options` and the stored public key, checks and advances the
/// signature counter, then signs the passkey's user in through the sign-in gates (method
/// `"passkey"`).
pub struct VerifyAuthentication(pub(crate) Arc<Passkey>);

impl<D: Adapter> Endpoint<D> for VerifyAuthentication {
    const METHOD: Method = Method::POST;
    const PATH: &'static str = "/passkey/verify-authentication";
    type Access = Public;
    type Input = VerifyAuthenticationInput;
    type Output = SignInOutput;

    async fn call(
        &self,
        ctx: Ctx<D, Public>,
        input: VerifyAuthenticationInput,
    ) -> Result<SignInOutput, AuthError> {
        let rp = self.0.relying_party(ctx.config())?;
        let Challenge::Authentication { state } = take_challenge(&ctx).await? else {
            return Err(PasskeyError::ChallengeNotFound.into());
        };
        let response: PublicKeyCredential =
            serde_json::from_value(input.response).map_err(|_| PasskeyError::InvalidAssertion)?;
        let row = ctx
            .db()
            .find::<PasskeyRow>(PasskeyRow::CREDENTIAL_ID.eq(base64url(&response.raw_id)))
            .one()
            .await?
            .ok_or(PasskeyError::UnknownCredential)?;
        let credential = ceremony::credential(&row)?;
        let result = rp
            .finish_discoverable_authentication_v2(&response, state, &credential)
            .map_err(|err| match err {
                WebauthnError::AuthenticationFailure => PasskeyError::AuthenticationFailed,
                _ => PasskeyError::InvalidAssertion,
            })?;
        let counter = i64::from(result.counter().max(credential.counter));
        let advanced = ctx
            .db()
            .update::<PasskeyRow>(
                PasskeyRow::ID
                    .eq(&row.id)
                    .and(PasskeyRow::COUNTER.eq(row.counter)),
            )
            .set(PasskeyRow::COUNTER, counter)
            .set(PasskeyRow::BACKED_UP, result.backup_state())
            .exec()
            .await?;
        if advanced == 0 {
            return Err(PasskeyError::InvalidAssertion.into());
        }
        let user = ctx
            .internal()
            .find_user_by_id(&row.user_id)
            .await?
            .ok_or_else(|| AuthError::internal("a passkey's user is gone"))?;
        Ok(
            match ctx.internal().sign_in(user, Passkey::ID, true).await? {
                SignInResult::SignedIn(session) => SignInOutput::SignedIn {
                    session: session.to_json(),
                    user: session.user.to_json(),
                },
                SignInResult::Challenge(body) => SignInOutput::Challenge(body),
            },
        )
    }
}

/// `GET /passkey/list-user-passkeys`: the signed-in user's passkeys.
pub struct ListUserPasskeys;

impl<D: Adapter> Endpoint<D> for ListUserPasskeys {
    const METHOD: Method = Method::GET;
    const PATH: &'static str = "/passkey/list-user-passkeys";
    type Access = Authenticated;
    type Input = Empty;
    type Output = Vec<PasskeyView>;

    async fn call(
        &self,
        ctx: Ctx<D, Authenticated>,
        _: Empty,
    ) -> Result<Vec<PasskeyView>, AuthError> {
        let rows = user_passkeys(&ctx, &ctx.session().user.id).await?;
        Ok(rows.into_iter().map(PasskeyView::from).collect())
    }
}

/// The caller's passkey `id`: 404 `PASSKEY_NOT_FOUND` when there's none, 401 `not_yours`
/// when it's someone else's, as Better Auth's ownership check answers.
async fn own_passkey<D: Adapter>(
    ctx: &Ctx<D, Authenticated>,
    id: &str,
    not_yours: AuthError,
) -> Result<PasskeyRow, AuthError> {
    let row = ctx
        .db()
        .find::<PasskeyRow>(PasskeyRow::ID.eq(Id::from(id)))
        .one()
        .await?
        .ok_or(PasskeyError::PasskeyNotFound)?;
    if row.user_id != ctx.session().user.id {
        return Err(not_yours);
    }
    Ok(row)
}

/// Body of `/passkey/delete-passkey`.
#[derive(Debug, Deserialize)]
pub struct DeletePasskeyInput {
    pub id: String,
}

/// `POST /passkey/delete-passkey`: deletes one of the signed-in user's passkeys.
pub struct DeletePasskey;

impl<D: Adapter> Endpoint<D> for DeletePasskey {
    const METHOD: Method = Method::POST;
    const PATH: &'static str = "/passkey/delete-passkey";
    type Access = Authenticated;
    type Input = DeletePasskeyInput;
    type Output = Status;

    async fn call(
        &self,
        ctx: Ctx<D, Authenticated>,
        input: DeletePasskeyInput,
    ) -> Result<Status, AuthError> {
        let not_yours = AuthError::new(
            StatusCode::UNAUTHORIZED,
            codes::UNAUTHORIZED,
            "Unauthorized",
        );
        let row = own_passkey(&ctx, &input.id, not_yours).await?;
        ctx.db()
            .delete::<PasskeyRow>(PasskeyRow::ID.eq(&row.id))
            .await?;
        ctx.emit(PasskeyDeleted {
            user_id: row.user_id,
            passkey_id: row.id,
        });
        Ok(Status { status: true })
    }
}

/// Body of `/passkey/update-passkey`.
#[derive(Debug, Deserialize)]
pub struct UpdatePasskeyInput {
    pub id: String,
    /// The new name; trimmed, and not empty.
    pub name: String,
}

#[derive(Debug, Serialize)]
pub struct UpdatePasskeyOutput {
    pub passkey: PasskeyView,
}

/// `POST /passkey/update-passkey`: renames one of the signed-in user's passkeys.
pub struct UpdatePasskey;

impl<D: Adapter> Endpoint<D> for UpdatePasskey {
    const METHOD: Method = Method::POST;
    const PATH: &'static str = "/passkey/update-passkey";
    type Access = Authenticated;
    type Input = UpdatePasskeyInput;
    type Output = UpdatePasskeyOutput;

    async fn call(
        &self,
        ctx: Ctx<D, Authenticated>,
        input: UpdatePasskeyInput,
    ) -> Result<UpdatePasskeyOutput, AuthError> {
        let name = input.name.trim();
        if name.is_empty() {
            return Err(AuthError::bad_request(
                codes::INVALID_BODY,
                "name must not be empty",
            ));
        }
        let mut row = own_passkey(&ctx, &input.id, PasskeyError::NotAllowed.into()).await?;
        ctx.db()
            .update::<PasskeyRow>(PasskeyRow::ID.eq(&row.id))
            .set(PasskeyRow::NAME, Some(name.to_owned()))
            .exec()
            .await?;
        row.name = Some(name.to_owned());
        Ok(UpdatePasskeyOutput {
            passkey: row.into(),
        })
    }
}