Skip to content

API reference

Auto-generated from the source docstrings. Everything below is part of the public, supported API and is importable from the top-level fastapi_passkeys package.

Facade (Layer A)

fastapi_passkeys.Passkeys

High-level entry point wiring config, storage, engine, and HTTP routes.

Source code in src/fastapi_passkeys/api/router.py
 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
class Passkeys:
    """High-level entry point wiring config, storage, engine, and HTTP routes."""

    def __init__(
        self,
        *,
        config: PasskeyConfig,
        credential_repository: CredentialRepository,
        challenge_store: ChallengeStore | None = None,
        get_user: GetUser | None = None,
        on_authenticated: OnAuthenticated | None = None,
        engine: WebAuthnEngine | None = None,
        audit: AuditSink | None = None,
        clock: Clock | None = None,
    ) -> None:
        self.config = config
        self._clock = clock or SystemClock()
        self._audit = audit or NullAuditSink()
        self._engine = engine or PyWebAuthnEngine()
        self._credentials = credential_repository
        self._challenges = challenge_store or self._default_store(config, self._clock)
        self._get_user = get_user
        self._on_authenticated = on_authenticated

        self.registration = RegistrationService(
            config=config,
            credentials=self._credentials,
            challenges=self._challenges,
            engine=self._engine,
            clock=self._clock,
            audit=self._audit,
        )
        self.authentication = AuthenticationService(
            config=config,
            credentials=self._credentials,
            challenges=self._challenges,
            engine=self._engine,
            clock=self._clock,
            audit=self._audit,
        )
        self.router = self._build_router()

    @staticmethod
    def _default_store(config: PasskeyConfig, clock: Clock) -> ChallengeStore:
        if config.signing_secret is not None:
            return StatelessChallengeStore(config.signing_secret.get_secret_value(), clock=clock)
        return InMemoryChallengeStore(clock=clock)

    def install_exception_handlers(self, app: FastAPI) -> None:
        """Register JSON error responses for the library's exceptions."""
        install_exception_handlers(app)

    @property
    def well_known_router(self) -> APIRouter:
        """Serves ``/.well-known/webauthn`` for WebAuthn Related Origin Requests.

        Mount it **without a prefix** on the app served at ``rp_id``::

            app.include_router(passkeys.well_known_router)

        Responds 404 unless ``config.related_origins`` is set.
        """
        router = APIRouter()

        @router.get("/.well-known/webauthn", include_in_schema=False)
        async def related_origins() -> dict[str, list[str]]:
            if not self.config.related_origins:
                raise HTTPException(status_code=404)
            origins = [o for o in self.config.allowed_origins if o.startswith("http")]
            return {"origins": origins}

        return router

    def _build_router(self) -> APIRouter:
        router = APIRouter(tags=["passkeys"])

        @router.post("/register/begin", response_model=BeginResponse)
        async def register_begin(request: Request) -> BeginResponse:
            user = await resolve_user(self._get_user, request)
            options, handle = await self.registration.begin(user)
            return BeginResponse(publicKey=options, state=handle)

        @router.post("/register/finish", response_model=RegisterFinishResponse)
        async def register_finish(
            body: RegisterFinishRequest, request: Request
        ) -> RegisterFinishResponse:
            # Bind the ceremony to the caller: a handle issued to another user is
            # rejected, so a leaked handle cannot attach an attacker's key.
            user = await resolve_user(self._get_user, request)
            credential = await self.registration.finish(
                response=body.credential,
                handle=body.state,
                device_name=body.device_name,
                user=user,
            )
            return RegisterFinishResponse(credentialId=bytes_to_b64url(credential.credential_id))

        @router.post("/authenticate/begin", response_model=BeginResponse)
        async def authenticate_begin(body: AuthBeginRequest | None = None) -> BeginResponse:
            options, handle = await self.authentication.begin(
                user_id=body.user_id if body else None
            )
            return BeginResponse(publicKey=options, state=handle)

        @router.post("/authenticate/finish")
        async def authenticate_finish(body: AuthFinishRequest, request: Request) -> Any:
            result = await self.authentication.finish(response=body.credential, handle=body.state)
            if self._on_authenticated is not None:
                return await maybe_await(self._on_authenticated(request, result))
            return {"status": "ok", "userId": result.user_id}

        @router.get("/credentials", response_model=list[CredentialView])
        async def list_credentials(request: Request) -> list[CredentialView]:
            user = await resolve_user(self._get_user, request)
            credentials = await self._credentials.list_by_user(user.id)
            return [CredentialView.from_domain(c) for c in credentials]

        @router.get("/credentials/signals", response_model=SignalsResponse)
        async def credential_signals(request: Request) -> SignalsResponse:
            user = await resolve_user(self._get_user, request)
            credentials = await self._credentials.list_by_user(user.id)
            user_id = bytes_to_b64url(user_handle(user.id))
            return SignalsResponse(
                allAcceptedCredentials={
                    "rpId": self.config.rp_id,
                    "userId": user_id,
                    "allAcceptedCredentialIds": [
                        bytes_to_b64url(c.credential_id) for c in credentials
                    ],
                },
                currentUserDetails={
                    "rpId": self.config.rp_id,
                    "userId": user_id,
                    "name": user.name,
                    "displayName": user.display_name or user.name,
                },
            )

        @router.patch("/credentials/{credential_id}", status_code=204)
        async def rename_credential(
            credential_id: str, body: RenameRequest, request: Request
        ) -> Response:
            user = await resolve_user(self._get_user, request)
            credential = await self._owned_credential(credential_id, user.id)
            await self._credentials.rename(credential.credential_id, user.id, body.device_name)
            await self._emit(AuditEventType.CREDENTIAL_RENAMED, user.id, credential)
            return Response(status_code=204)

        @router.delete("/credentials/{credential_id}", status_code=204)
        async def delete_credential(credential_id: str, request: Request) -> Response:
            user = await resolve_user(self._get_user, request)
            credential = await self._owned_credential(credential_id, user.id)
            await self._credentials.delete(credential.credential_id, user.id)
            await self._emit(AuditEventType.CREDENTIAL_REVOKED, user.id, credential)
            return Response(status_code=204)

        return router

    async def _owned_credential(self, credential_id: str, user_id: str) -> Credential:
        """Resolve a credential the caller owns, or 404 — identically for "absent"
        and "someone else's", so ids cannot be probed across accounts."""
        try:
            raw = b64url_to_bytes(credential_id)
        except ValueError:
            raise ManagedCredentialNotFound() from None
        credential = await self._credentials.get_by_credential_id(raw)
        if credential is None or credential.user_id != user_id:
            raise ManagedCredentialNotFound()
        return credential

    async def _emit(self, kind: AuditEventType, user_id: str, credential: Credential) -> None:
        await emit_safely(
            self._audit,
            AuditEvent(
                type=kind,
                timestamp=self._clock.now(),
                user_id=user_id,
                credential_id=bytes_to_b64url(credential.credential_id),
            ),
        )

well_known_router property

Serves /.well-known/webauthn for WebAuthn Related Origin Requests.

Mount it without a prefix on the app served at rp_id::

app.include_router(passkeys.well_known_router)

Responds 404 unless config.related_origins is set.

install_exception_handlers(app)

Register JSON error responses for the library's exceptions.

Source code in src/fastapi_passkeys/api/router.py
101
102
103
def install_exception_handlers(self, app: FastAPI) -> None:
    """Register JSON error responses for the library's exceptions."""
    install_exception_handlers(app)

fastapi_passkeys.PasskeyConfig

Bases: BaseSettings

Relying-party policy for passkey ceremonies.

Source code in src/fastapi_passkeys/config.py
 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
class PasskeyConfig(BaseSettings):
    """Relying-party policy for passkey ceremonies."""

    model_config = SettingsConfigDict(env_prefix="PASSKEYS_", extra="ignore")

    rp_id: str = Field(
        description="Relying Party ID — a bare registrable domain such as 'example.com' "
        "(no scheme, port or path). Every web origin must be this domain or a subdomain.",
    )
    rp_name: str = Field(description="Human-readable RP name shown by authenticators.")
    expected_origins: list[str] = Field(
        description="Allowed origins, e.g. ['https://example.com']. Normalized to the "
        "browser's serialization. Android app origins ('android:apk-key-hash:...') are "
        "accepted verbatim.",
    )

    challenge_ttl: timedelta = Field(
        default=timedelta(seconds=300),
        description="Server-enforced challenge lifetime, independent of the client timeout.",
    )
    timeout_ms: int = Field(
        default=60_000,
        ge=1_000,
        description="Client-side ceremony timeout hint passed to the authenticator.",
    )

    user_verification: UserVerification = UserVerification.PREFERRED
    attestation: AttestationPreference = AttestationPreference.NONE
    authenticator_attachment: AuthenticatorAttachment | None = None
    resident_key: ResidentKeyRequirement = ResidentKeyRequirement.PREFERRED
    sign_count_policy: SignCountPolicy = SignCountPolicy.STRICT_REJECT

    hints: list[Hint] = Field(
        default_factory=list,
        description="WebAuthn L3 hints sent with both ceremonies, most preferred first.",
    )
    max_credentials_per_user: int | None = Field(
        default=None,
        ge=1,
        description="Refuse to register more passkeys than this per user. None = no limit.",
    )
    verify_user_handle: bool = Field(
        default=True,
        description="Require the assertion's userHandle to identify the credential's owner "
        "(WebAuthn §7.2 step 6). Disable only for credentials imported from a library that "
        "used a different user-handle scheme.",
    )
    enforce_backup_eligibility: bool = Field(
        default=True,
        description="Reject an assertion whose backup-eligible (BE) flag differs from the one "
        "recorded at registration; BE is fixed for a credential's lifetime.",
    )
    related_origins: list[str] = Field(
        default_factory=list,
        description="WebAuthn Related Origin Requests: extra web origins (on other domains) "
        "allowed to use this rp_id. Served from /.well-known/webauthn and accepted at verify.",
    )

    signing_secret: SecretStr | None = Field(
        default=None,
        description="HMAC secret for the stateless challenge store. Required only when used.",
    )

    @field_validator("rp_id")
    @classmethod
    def _validate_rp_id(cls, value: str) -> str:
        rp_id = value.strip().lower().rstrip(".")
        if not rp_id or any(c in rp_id for c in ":/?#@ \t") or rp_id.startswith("."):
            raise ValueError(
                f"rp_id must be a bare domain such as 'example.com' (no scheme, port or "
                f"path), got {value!r}"
            )
        return rp_id

    @field_validator("expected_origins")
    @classmethod
    def _validate_origins(cls, value: list[str]) -> list[str]:
        if not value:
            raise ValueError("expected_origins must contain at least one origin")
        normalized: list[str] = []
        for origin in value:
            item = _normalize_origin(origin)
            if item not in normalized:
                normalized.append(item)
        return normalized

    @field_validator("related_origins")
    @classmethod
    def _validate_related_origins(cls, value: list[str]) -> list[str]:
        normalized: list[str] = []
        for origin in value:
            item = _normalize_origin(origin)
            if item.startswith(_ANDROID_ORIGIN_PREFIX):
                raise ValueError("related_origins must be web origins (http/https)")
            if item not in normalized:
                normalized.append(item)
        return normalized

    @field_validator("challenge_ttl")
    @classmethod
    def _validate_ttl(cls, value: timedelta) -> timedelta:
        if value <= timedelta(0):
            raise ValueError("challenge_ttl must be positive")
        return value

    @model_validator(mode="after")
    def _check_origins_match_rp_id(self) -> PasskeyConfig:
        for origin in self.expected_origins:
            if origin.startswith(_ANDROID_ORIGIN_PREFIX):
                continue
            host = urlsplit(origin).hostname or ""
            if host != self.rp_id and not host.endswith("." + self.rp_id):
                # Browsers refuse such a pairing ("The RP ID is not a registrable
                # domain suffix of the origin"), so fail at startup, not at runtime.
                raise ValueError(
                    f"origin {origin!r} is not on rp_id {self.rp_id!r} or one of its subdomains"
                )
        if self.challenge_ttl < timedelta(milliseconds=self.timeout_ms):
            warnings.warn(
                "challenge_ttl is shorter than timeout_ms: a user who takes the full "
                "client timeout will find the challenge already expired.",
                stacklevel=2,
            )
        return self

    @property
    def allowed_origins(self) -> list[str]:
        """Every origin accepted at verification: ``expected_origins`` + ``related_origins``."""
        return self.expected_origins + [
            o for o in self.related_origins if o not in self.expected_origins
        ]

    @property
    def require_user_verification(self) -> bool:
        """Whether assertions/attestations must prove user verification."""
        return self.user_verification is UserVerification.REQUIRED

allowed_origins property

Every origin accepted at verification: expected_origins + related_origins.

require_user_verification property

Whether assertions/attestations must prove user verification.

Services (Layer B)

fastapi_passkeys.RegistrationService

Begins and finishes passkey registration (attestation) ceremonies.

Source code in src/fastapi_passkeys/services/registration.py
 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
class RegistrationService:
    """Begins and finishes passkey registration (attestation) ceremonies."""

    def __init__(
        self,
        *,
        config: PasskeyConfig,
        credentials: CredentialRepository,
        challenges: ChallengeStore,
        engine: WebAuthnEngine,
        clock: Clock | None = None,
        audit: AuditSink | None = None,
    ) -> None:
        self._config = config
        self._credentials = credentials
        self._challenges = challenges
        self._engine = engine
        self._clock = clock or SystemClock()
        self._audit = audit or NullAuditSink()

    async def begin(self, user: PasskeyUser) -> tuple[dict[str, Any], str]:
        """Issue creation options and a challenge handle the client echoes back."""
        user = _validated(user)
        existing = await self._credentials.list_by_user(user.id)
        self._check_limit(existing)
        challenge = secrets.token_bytes(_CHALLENGE_BYTES)
        now = self._clock.now()
        options = self._engine.registration_options(
            config=self._config, user=user, challenge=challenge, exclude=existing
        )
        handle = await self._challenges.put(
            RegistrationChallenge(
                challenge=challenge,
                user=user,
                created_at=now,
                expires_at=now + self._config.challenge_ttl,
            )
        )
        await emit_safely(
            self._audit,
            AuditEvent(type=AuditEventType.REGISTRATION_BEGAN, timestamp=now, user_id=user.id),
        )
        return options, handle

    async def finish(
        self,
        *,
        response: dict[str, Any] | str,
        handle: str,
        device_name: str = "",
        user: PasskeyUser | None = None,
    ) -> Credential:
        """Verify the attestation response and persist the new credential.

        Pass ``user`` — the user authenticated on *this* request — to bind the
        ceremony to them: a handle issued to someone else is rejected. The
        bundled router always does this. Without it, anyone holding a valid
        handle can attach their own authenticator to the account it was issued
        for.
        """
        stored = await self._challenges.consume(handle)
        if not isinstance(stored, RegistrationChallenge):
            await self._fail(AuditEventType.CHALLENGE_EXPIRED, user_id=None)
            raise ChallengeNotFound()

        try:
            if user is not None and user.id != stored.user.id:
                raise RegistrationUserMismatch()
            verified = self._engine.verify_registration(
                config=self._config, response=response, expected_challenge=stored.challenge
            )
            if await self._credentials.get_by_credential_id(verified.credential_id) is not None:
                raise CredentialAlreadyExists()
            self._check_limit(await self._credentials.list_by_user(stored.user.id))

            now = self._clock.now()
            discoverable = verified.is_discoverable
            if discoverable is None:  # client did not report credProps
                discoverable = self._config.resident_key is ResidentKeyRequirement.REQUIRED
            credential = Credential(
                credential_id=verified.credential_id,
                user_id=stored.user.id,
                public_key=verified.public_key,
                sign_count=verified.sign_count,
                transports=verified.transports,
                aaguid=verified.aaguid,
                backup_eligible=verified.backup_eligible,
                backup_state=verified.backup_state,
                device_name=device_name,
                is_discoverable=discoverable,
                attestation_fmt=verified.attestation_fmt,
                created_at=now,
                last_used_at=None,
            )
            # Repositories raise CredentialAlreadyExists on a concurrent duplicate.
            await self._credentials.add(credential)
        except PasskeyError as exc:
            await self._fail(
                AuditEventType.REGISTRATION_FAILED, user_id=stored.user.id, reason=exc.code
            )
            raise

        await emit_safely(
            self._audit,
            AuditEvent(
                type=AuditEventType.REGISTRATION_SUCCEEDED,
                timestamp=now,
                user_id=stored.user.id,
                credential_id=bytes_to_b64url(verified.credential_id),
            ),
        )
        return credential

    def _check_limit(self, existing: list[Credential]) -> None:
        limit = self._config.max_credentials_per_user
        if limit is not None and len(existing) >= limit:
            raise CredentialLimitReached()

    async def _fail(
        self, event_type: AuditEventType, *, user_id: str | None, reason: str | None = None
    ) -> None:
        await emit_safely(
            self._audit,
            AuditEvent(
                type=event_type,
                timestamp=self._clock.now(),
                user_id=user_id,
                detail={"reason": reason} if reason else {},
            ),
        )

begin(user) async

Issue creation options and a challenge handle the client echoes back.

Source code in src/fastapi_passkeys/services/registration.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
async def begin(self, user: PasskeyUser) -> tuple[dict[str, Any], str]:
    """Issue creation options and a challenge handle the client echoes back."""
    user = _validated(user)
    existing = await self._credentials.list_by_user(user.id)
    self._check_limit(existing)
    challenge = secrets.token_bytes(_CHALLENGE_BYTES)
    now = self._clock.now()
    options = self._engine.registration_options(
        config=self._config, user=user, challenge=challenge, exclude=existing
    )
    handle = await self._challenges.put(
        RegistrationChallenge(
            challenge=challenge,
            user=user,
            created_at=now,
            expires_at=now + self._config.challenge_ttl,
        )
    )
    await emit_safely(
        self._audit,
        AuditEvent(type=AuditEventType.REGISTRATION_BEGAN, timestamp=now, user_id=user.id),
    )
    return options, handle

finish(*, response, handle, device_name='', user=None) async

Verify the attestation response and persist the new credential.

Pass user — the user authenticated on this request — to bind the ceremony to them: a handle issued to someone else is rejected. The bundled router always does this. Without it, anyone holding a valid handle can attach their own authenticator to the account it was issued for.

Source code in src/fastapi_passkeys/services/registration.py
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
async def finish(
    self,
    *,
    response: dict[str, Any] | str,
    handle: str,
    device_name: str = "",
    user: PasskeyUser | None = None,
) -> Credential:
    """Verify the attestation response and persist the new credential.

    Pass ``user`` — the user authenticated on *this* request — to bind the
    ceremony to them: a handle issued to someone else is rejected. The
    bundled router always does this. Without it, anyone holding a valid
    handle can attach their own authenticator to the account it was issued
    for.
    """
    stored = await self._challenges.consume(handle)
    if not isinstance(stored, RegistrationChallenge):
        await self._fail(AuditEventType.CHALLENGE_EXPIRED, user_id=None)
        raise ChallengeNotFound()

    try:
        if user is not None and user.id != stored.user.id:
            raise RegistrationUserMismatch()
        verified = self._engine.verify_registration(
            config=self._config, response=response, expected_challenge=stored.challenge
        )
        if await self._credentials.get_by_credential_id(verified.credential_id) is not None:
            raise CredentialAlreadyExists()
        self._check_limit(await self._credentials.list_by_user(stored.user.id))

        now = self._clock.now()
        discoverable = verified.is_discoverable
        if discoverable is None:  # client did not report credProps
            discoverable = self._config.resident_key is ResidentKeyRequirement.REQUIRED
        credential = Credential(
            credential_id=verified.credential_id,
            user_id=stored.user.id,
            public_key=verified.public_key,
            sign_count=verified.sign_count,
            transports=verified.transports,
            aaguid=verified.aaguid,
            backup_eligible=verified.backup_eligible,
            backup_state=verified.backup_state,
            device_name=device_name,
            is_discoverable=discoverable,
            attestation_fmt=verified.attestation_fmt,
            created_at=now,
            last_used_at=None,
        )
        # Repositories raise CredentialAlreadyExists on a concurrent duplicate.
        await self._credentials.add(credential)
    except PasskeyError as exc:
        await self._fail(
            AuditEventType.REGISTRATION_FAILED, user_id=stored.user.id, reason=exc.code
        )
        raise

    await emit_safely(
        self._audit,
        AuditEvent(
            type=AuditEventType.REGISTRATION_SUCCEEDED,
            timestamp=now,
            user_id=stored.user.id,
            credential_id=bytes_to_b64url(verified.credential_id),
        ),
    )
    return credential

fastapi_passkeys.AuthenticationService

Begins and finishes passkey authentication (assertion) ceremonies.

Source code in src/fastapi_passkeys/services/authentication.py
 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
class AuthenticationService:
    """Begins and finishes passkey authentication (assertion) ceremonies."""

    def __init__(
        self,
        *,
        config: PasskeyConfig,
        credentials: CredentialRepository,
        challenges: ChallengeStore,
        engine: WebAuthnEngine,
        clock: Clock | None = None,
        audit: AuditSink | None = None,
    ) -> None:
        self._config = config
        self._credentials = credentials
        self._challenges = challenges
        self._engine = engine
        self._clock = clock or SystemClock()
        self._audit = audit or NullAuditSink()
        # Repositories written against 0.1 have no ``backup_state`` parameter.
        self._persist_backup_state = _accepts_kwarg(credentials.update_usage, "backup_state")

    async def begin(self, *, user_id: str | None = None) -> tuple[dict[str, Any], str]:
        """Issue request options and a challenge handle.

        Pass ``user_id`` for a username-first flow (restricts allowed credentials)
        or omit it for a usernameless / discoverable-credential flow.
        """
        user_id = user_id or None
        allow = await self._credentials.list_by_user(user_id) if user_id else []
        challenge = secrets.token_bytes(_CHALLENGE_BYTES)
        now = self._clock.now()
        options = self._engine.authentication_options(
            config=self._config, challenge=challenge, allow=allow
        )
        handle = await self._challenges.put(
            AuthenticationChallenge(
                challenge=challenge,
                user_id=user_id,
                created_at=now,
                expires_at=now + self._config.challenge_ttl,
            )
        )
        await self._emit(AuditEventType.AUTHENTICATION_BEGAN, user_id=user_id)
        return options, handle

    async def finish(self, *, response: dict[str, Any] | str, handle: str) -> AuthenticationResult:
        """Verify the assertion, enforce the signature counter, and record usage."""
        stored = await self._challenges.consume(handle)
        if not isinstance(stored, AuthenticationChallenge):
            await self._emit(AuditEventType.CHALLENGE_EXPIRED)
            raise ChallengeNotFound()

        data = _as_dict(response)
        credential = await self._resolve_credential(data, stored)
        cred_b64 = bytes_to_b64url(credential.credential_id)

        try:
            verified = self._engine.verify_authentication(
                config=self._config,
                response=response,
                expected_challenge=stored.challenge,
                credential=credential,
            )
            if verified.credential_id != credential.credential_id:
                raise AssertionVerificationError()
            self._check_backup_eligibility(credential, verified)
        except PasskeyError as exc:
            await self._emit(
                AuditEventType.AUTHENTICATION_FAILED,
                user_id=credential.user_id,
                credential_id=cred_b64,
                reason=exc.code,
            )
            raise

        await self._enforce_sign_count(credential, verified)

        now = self._clock.now()
        backup_state = (
            verified.backup_state if verified.backup_state is not None else credential.backup_state
        )
        if self._persist_backup_state:
            await self._credentials.update_usage(
                credential.credential_id,
                sign_count=verified.new_sign_count,
                last_used_at=now,
                backup_state=backup_state,
            )
        else:
            await self._credentials.update_usage(
                credential.credential_id, sign_count=verified.new_sign_count, last_used_at=now
            )
        await self._emit(
            AuditEventType.AUTHENTICATION_SUCCEEDED,
            user_id=credential.user_id,
            credential_id=cred_b64,
        )
        updated = dataclasses.replace(
            credential,
            sign_count=verified.new_sign_count,
            last_used_at=now,
            backup_state=backup_state,
        )
        attachment = data.get("authenticatorAttachment")
        return AuthenticationResult(
            user_id=credential.user_id,
            credential=updated,
            detail={
                "user_verified": verified.user_verified,
                # Flags as presented by *this* assertion.
                "backup_eligible": (
                    verified.backup_eligible
                    if verified.backup_eligible is not None
                    else credential.backup_eligible
                ),
                "backup_state": backup_state,
                "authenticator_attachment": attachment if attachment in _ATTACHMENTS else None,
            },
        )

    async def _resolve_credential(
        self, data: dict[str, Any], stored: AuthenticationChallenge
    ) -> Credential:
        credential_id = _b64_field(data.get("rawId") or data.get("id"))
        credential = (
            await self._credentials.get_by_credential_id(credential_id) if credential_id else None
        )
        if credential is None:
            await self._emit(AuditEventType.AUTHENTICATION_FAILED, user_id=stored.user_id)
            error = CredentialNotFound()
            if credential_id:
                # Lets the browser prune a passkey we no longer know about
                # (PublicKeyCredential.signalUnknownCredential).
                error.extra["signal"] = {
                    "unknownCredential": {
                        "rpId": self._config.rp_id,
                        "credentialId": bytes_to_b64url(credential_id),
                    }
                }
            raise error

        if not self._owner_matches(credential, data, stored):
            # Same generic error as "unknown" so we do not leak which check failed.
            await self._emit(
                AuditEventType.AUTHENTICATION_FAILED,
                user_id=stored.user_id,
                credential_id=bytes_to_b64url(credential.credential_id),
                reason="owner_mismatch",
            )
            raise CredentialNotFound()
        return credential

    def _owner_matches(
        self, credential: Credential, data: dict[str, Any], stored: AuthenticationChallenge
    ) -> bool:
        """WebAuthn §7.2 step 6: the credential must belong to the identified user."""
        if stored.user_id is not None and credential.user_id != stored.user_id:
            return False
        if not self._config.verify_user_handle:
            return True
        inner = data.get("response")
        raw_handle = inner.get("userHandle") if isinstance(inner, dict) else None
        if raw_handle is None:
            # Optional only when the user was identified before the ceremony.
            return stored.user_id is not None
        return _b64_field(raw_handle) == user_handle(credential.user_id)

    def _check_backup_eligibility(
        self, credential: Credential, verified: VerifiedAuthentication
    ) -> None:
        if (
            self._config.enforce_backup_eligibility
            and verified.backup_eligible is not None
            and verified.backup_eligible != credential.backup_eligible
        ):
            # BE is fixed for a credential's lifetime (WebAuthn §6.1.3); a change
            # means a different or misbehaving authenticator.
            raise AssertionVerificationError()

    async def _enforce_sign_count(
        self, credential: Credential, verified: VerifiedAuthentication
    ) -> None:
        old, new = credential.sign_count, verified.new_sign_count
        # Counter of 0 on both sides means the authenticator does not implement one.
        if new == 0 and old == 0:
            return
        if new > old:
            return
        cred_b64 = bytes_to_b64url(credential.credential_id)
        await emit_safely(
            self._audit,
            AuditEvent(
                type=AuditEventType.CLONE_SUSPECTED,
                timestamp=self._clock.now(),
                user_id=credential.user_id,
                credential_id=cred_b64,
                detail={
                    "stored_sign_count": old,
                    "presented_sign_count": new,
                    "policy": self._config.sign_count_policy.value,
                },
            ),
        )
        policy = self._config.sign_count_policy
        if policy is SignCountPolicy.AUDIT_ONLY:
            return
        if policy is SignCountPolicy.FLAG_DISABLE:
            await self._credentials.delete(credential.credential_id, credential.user_id)
            await self._emit(
                AuditEventType.CREDENTIAL_REVOKED,
                user_id=credential.user_id,
                credential_id=cred_b64,
                reason="clone_suspected",
            )
        raise CloneDetectedError()

    async def _emit(
        self,
        event_type: AuditEventType,
        *,
        user_id: str | None = None,
        credential_id: str | None = None,
        reason: str | None = None,
    ) -> None:
        await emit_safely(
            self._audit,
            AuditEvent(
                type=event_type,
                timestamp=self._clock.now(),
                user_id=user_id,
                credential_id=credential_id,
                detail={"reason": reason} if reason else {},
            ),
        )

begin(*, user_id=None) async

Issue request options and a challenge handle.

Pass user_id for a username-first flow (restricts allowed credentials) or omit it for a usernameless / discoverable-credential flow.

Source code in src/fastapi_passkeys/services/authentication.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
async def begin(self, *, user_id: str | None = None) -> tuple[dict[str, Any], str]:
    """Issue request options and a challenge handle.

    Pass ``user_id`` for a username-first flow (restricts allowed credentials)
    or omit it for a usernameless / discoverable-credential flow.
    """
    user_id = user_id or None
    allow = await self._credentials.list_by_user(user_id) if user_id else []
    challenge = secrets.token_bytes(_CHALLENGE_BYTES)
    now = self._clock.now()
    options = self._engine.authentication_options(
        config=self._config, challenge=challenge, allow=allow
    )
    handle = await self._challenges.put(
        AuthenticationChallenge(
            challenge=challenge,
            user_id=user_id,
            created_at=now,
            expires_at=now + self._config.challenge_ttl,
        )
    )
    await self._emit(AuditEventType.AUTHENTICATION_BEGAN, user_id=user_id)
    return options, handle

finish(*, response, handle) async

Verify the assertion, enforce the signature counter, and record usage.

Source code in src/fastapi_passkeys/services/authentication.py
 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
async def finish(self, *, response: dict[str, Any] | str, handle: str) -> AuthenticationResult:
    """Verify the assertion, enforce the signature counter, and record usage."""
    stored = await self._challenges.consume(handle)
    if not isinstance(stored, AuthenticationChallenge):
        await self._emit(AuditEventType.CHALLENGE_EXPIRED)
        raise ChallengeNotFound()

    data = _as_dict(response)
    credential = await self._resolve_credential(data, stored)
    cred_b64 = bytes_to_b64url(credential.credential_id)

    try:
        verified = self._engine.verify_authentication(
            config=self._config,
            response=response,
            expected_challenge=stored.challenge,
            credential=credential,
        )
        if verified.credential_id != credential.credential_id:
            raise AssertionVerificationError()
        self._check_backup_eligibility(credential, verified)
    except PasskeyError as exc:
        await self._emit(
            AuditEventType.AUTHENTICATION_FAILED,
            user_id=credential.user_id,
            credential_id=cred_b64,
            reason=exc.code,
        )
        raise

    await self._enforce_sign_count(credential, verified)

    now = self._clock.now()
    backup_state = (
        verified.backup_state if verified.backup_state is not None else credential.backup_state
    )
    if self._persist_backup_state:
        await self._credentials.update_usage(
            credential.credential_id,
            sign_count=verified.new_sign_count,
            last_used_at=now,
            backup_state=backup_state,
        )
    else:
        await self._credentials.update_usage(
            credential.credential_id, sign_count=verified.new_sign_count, last_used_at=now
        )
    await self._emit(
        AuditEventType.AUTHENTICATION_SUCCEEDED,
        user_id=credential.user_id,
        credential_id=cred_b64,
    )
    updated = dataclasses.replace(
        credential,
        sign_count=verified.new_sign_count,
        last_used_at=now,
        backup_state=backup_state,
    )
    attachment = data.get("authenticatorAttachment")
    return AuthenticationResult(
        user_id=credential.user_id,
        credential=updated,
        detail={
            "user_verified": verified.user_verified,
            # Flags as presented by *this* assertion.
            "backup_eligible": (
                verified.backup_eligible
                if verified.backup_eligible is not None
                else credential.backup_eligible
            ),
            "backup_state": backup_state,
            "authenticator_attachment": attachment if attachment in _ATTACHMENTS else None,
        },
    )

Domain models

fastapi_passkeys.PasskeyUser dataclass

The subject of a ceremony.

id is your stable internal identifier (it becomes the WebAuthn user handle). name and display_name are shown by the authenticator UI.

Source code in src/fastapi_passkeys/domain/models.py
16
17
18
19
20
21
22
23
24
25
26
@dataclass(frozen=True, slots=True)
class PasskeyUser:
    """The subject of a ceremony.

    ``id`` is your stable internal identifier (it becomes the WebAuthn user
    handle). ``name`` and ``display_name`` are shown by the authenticator UI.
    """

    id: str
    name: str
    display_name: str

fastapi_passkeys.Credential dataclass

A registered passkey, as persisted by a :class:CredentialRepository.

Source code in src/fastapi_passkeys/domain/models.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@dataclass(frozen=True, slots=True)
class Credential:
    """A registered passkey, as persisted by a :class:`CredentialRepository`."""

    credential_id: bytes
    user_id: str
    public_key: bytes
    sign_count: int
    transports: tuple[Transport, ...] = ()
    aaguid: bytes | None = None
    backup_eligible: bool = False
    backup_state: bool = False
    device_name: str = ""
    is_discoverable: bool = False
    attestation_fmt: str | None = None
    created_at: datetime | None = None
    last_used_at: datetime | None = None

fastapi_passkeys.AuthenticationResult dataclass

Returned to the application once a passkey assertion is verified.

Source code in src/fastapi_passkeys/domain/models.py
104
105
106
107
108
109
110
@dataclass(frozen=True, slots=True)
class AuthenticationResult:
    """Returned to the application once a passkey assertion is verified."""

    user_id: str
    credential: Credential
    detail: dict[str, object] = field(default_factory=dict)

Storage protocols

fastapi_passkeys.CredentialRepository

Bases: Protocol

Persistence for registered passkeys. All methods are coroutines.

Source code in src/fastapi_passkeys/repositories/credentials.py
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
@runtime_checkable
class CredentialRepository(Protocol):
    """Persistence for registered passkeys. All methods are coroutines."""

    async def add(self, credential: Credential) -> None:
        """Persist a newly registered credential.

        Must raise :class:`~fastapi_passkeys.exceptions.CredentialAlreadyExists`
        — never overwrite — if the credential id is already stored. Credential
        ids are chosen by the authenticator, so an overwrite would let one user
        replace another's passkey.
        """
        ...

    async def get_by_credential_id(self, credential_id: bytes) -> Credential | None:
        """Return the credential with this id, or ``None`` if unknown."""
        ...

    async def list_by_user(self, user_id: str) -> list[Credential]:
        """Return all credentials registered to a user (may be empty)."""
        ...

    async def update_usage(
        self,
        credential_id: bytes,
        *,
        sign_count: int,
        last_used_at: datetime,
        backup_state: bool | None = None,
    ) -> None:
        """Record a successful authentication: advance counter and last-used.

        ``backup_state`` (added in 0.2) is the credential's current BS flag;
        ``None`` means leave it unchanged. Implementations written against 0.1
        that do not accept it keep working — the service detects that.
        """
        ...

    async def rename(self, credential_id: bytes, user_id: str, name: str) -> None:
        """Set a user-facing device name. Scoped to ``user_id`` for safety."""
        ...

    async def delete(self, credential_id: bytes, user_id: str) -> None:
        """Revoke a credential. Scoped to ``user_id`` so users cannot delete others'."""
        ...

add(credential) async

Persist a newly registered credential.

Must raise :class:~fastapi_passkeys.exceptions.CredentialAlreadyExists — never overwrite — if the credential id is already stored. Credential ids are chosen by the authenticator, so an overwrite would let one user replace another's passkey.

Source code in src/fastapi_passkeys/repositories/credentials.py
21
22
23
24
25
26
27
28
29
async def add(self, credential: Credential) -> None:
    """Persist a newly registered credential.

    Must raise :class:`~fastapi_passkeys.exceptions.CredentialAlreadyExists`
    — never overwrite — if the credential id is already stored. Credential
    ids are chosen by the authenticator, so an overwrite would let one user
    replace another's passkey.
    """
    ...

delete(credential_id, user_id) async

Revoke a credential. Scoped to user_id so users cannot delete others'.

Source code in src/fastapi_passkeys/repositories/credentials.py
59
60
61
async def delete(self, credential_id: bytes, user_id: str) -> None:
    """Revoke a credential. Scoped to ``user_id`` so users cannot delete others'."""
    ...

get_by_credential_id(credential_id) async

Return the credential with this id, or None if unknown.

Source code in src/fastapi_passkeys/repositories/credentials.py
31
32
33
async def get_by_credential_id(self, credential_id: bytes) -> Credential | None:
    """Return the credential with this id, or ``None`` if unknown."""
    ...

list_by_user(user_id) async

Return all credentials registered to a user (may be empty).

Source code in src/fastapi_passkeys/repositories/credentials.py
35
36
37
async def list_by_user(self, user_id: str) -> list[Credential]:
    """Return all credentials registered to a user (may be empty)."""
    ...

rename(credential_id, user_id, name) async

Set a user-facing device name. Scoped to user_id for safety.

Source code in src/fastapi_passkeys/repositories/credentials.py
55
56
57
async def rename(self, credential_id: bytes, user_id: str, name: str) -> None:
    """Set a user-facing device name. Scoped to ``user_id`` for safety."""
    ...

update_usage(credential_id, *, sign_count, last_used_at, backup_state=None) async

Record a successful authentication: advance counter and last-used.

backup_state (added in 0.2) is the credential's current BS flag; None means leave it unchanged. Implementations written against 0.1 that do not accept it keep working — the service detects that.

Source code in src/fastapi_passkeys/repositories/credentials.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
async def update_usage(
    self,
    credential_id: bytes,
    *,
    sign_count: int,
    last_used_at: datetime,
    backup_state: bool | None = None,
) -> None:
    """Record a successful authentication: advance counter and last-used.

    ``backup_state`` (added in 0.2) is the credential's current BS flag;
    ``None`` means leave it unchanged. Implementations written against 0.1
    that do not accept it keep working — the service detects that.
    """
    ...

fastapi_passkeys.ChallengeStore

Bases: Protocol

Single-use storage for in-flight ceremony challenges.

Source code in src/fastapi_passkeys/repositories/challenges.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@runtime_checkable
class ChallengeStore(Protocol):
    """Single-use storage for in-flight ceremony challenges."""

    async def put(self, challenge: RegistrationChallenge | AuthenticationChallenge) -> str:
        """Store a challenge and return an opaque handle the client echoes back."""
        ...

    async def consume(self, handle: str) -> RegistrationChallenge | AuthenticationChallenge | None:
        """Atomically fetch and invalidate the challenge.

        Returns ``None`` if the handle is unknown, already consumed, expired, or
        tampered with. Never returns an expired challenge.
        """
        ...

consume(handle) async

Atomically fetch and invalidate the challenge.

Returns None if the handle is unknown, already consumed, expired, or tampered with. Never returns an expired challenge.

Source code in src/fastapi_passkeys/repositories/challenges.py
24
25
26
27
28
29
30
async def consume(self, handle: str) -> RegistrationChallenge | AuthenticationChallenge | None:
    """Atomically fetch and invalidate the challenge.

    Returns ``None`` if the handle is unknown, already consumed, expired, or
    tampered with. Never returns an expired challenge.
    """
    ...

put(challenge) async

Store a challenge and return an opaque handle the client echoes back.

Source code in src/fastapi_passkeys/repositories/challenges.py
20
21
22
async def put(self, challenge: RegistrationChallenge | AuthenticationChallenge) -> str:
    """Store a challenge and return an opaque handle the client echoes back."""
    ...

Audit

fastapi_passkeys.AuditEvent dataclass

Source code in src/fastapi_passkeys/audit.py
30
31
32
33
34
35
36
@dataclass(frozen=True, slots=True)
class AuditEvent:
    type: AuditEventType
    timestamp: datetime
    user_id: str | None = None
    credential_id: str | None = None  # base64url, never raw bytes
    detail: dict[str, Any] = field(default_factory=dict)

fastapi_passkeys.AuditSink

Bases: Protocol

Receives audit events. Implementations must not raise on the hot path.

Source code in src/fastapi_passkeys/audit.py
39
40
41
42
43
@runtime_checkable
class AuditSink(Protocol):
    """Receives audit events. Implementations must not raise on the hot path."""

    async def emit(self, event: AuditEvent) -> None: ...

Exceptions

Typed exception hierarchy.

Every error the library raises carries a machine-readable code and a default status_code. install_exception_handlers (see :mod:fastapi_passkeys.api) turns these into JSON responses without leaking internal detail. The messages are intentionally generic for verification failures to avoid handing attackers an oracle (e.g. we do not say why an assertion failed).

PasskeyError

Bases: Exception

Base class for every error raised by fastapi-passkeys.

Source code in src/fastapi_passkeys/exceptions.py
15
16
17
18
19
20
21
22
23
24
25
26
class PasskeyError(Exception):
    """Base class for every error raised by fastapi-passkeys."""

    code = "passkey_error"
    status_code = 400

    def __init__(self, message: str | None = None) -> None:
        super().__init__(message or self.__doc__ or self.code)
        self.message = message or (self.__doc__ or self.code)
        # Optional, client-safe payload merged into the JSON error body (e.g. a
        # WebAuthn Signal API hint). Never put secrets or internal detail here.
        self.extra: dict[str, Any] = {}

ConfigurationError

Bases: PasskeyError

The library was configured incorrectly.

Source code in src/fastapi_passkeys/exceptions.py
29
30
31
32
33
class ConfigurationError(PasskeyError):
    """The library was configured incorrectly."""

    code = "configuration_error"
    status_code = 500

ChallengeError

Bases: PasskeyError

A challenge could not be validated.

Source code in src/fastapi_passkeys/exceptions.py
39
40
41
42
43
class ChallengeError(PasskeyError):
    """A challenge could not be validated."""

    code = "challenge_error"
    status_code = 400

ChallengeNotFound

Bases: ChallengeError

The challenge is unknown, already used, or has expired.

Source code in src/fastapi_passkeys/exceptions.py
46
47
48
49
50
class ChallengeNotFound(ChallengeError):
    """The challenge is unknown, already used, or has expired."""

    code = "challenge_not_found"
    status_code = 400

ChallengeExpired

Bases: ChallengeError

The challenge is no longer valid.

Source code in src/fastapi_passkeys/exceptions.py
53
54
55
56
57
class ChallengeExpired(ChallengeError):
    """The challenge is no longer valid."""

    code = "challenge_expired"
    status_code = 400

RegistrationError

Bases: PasskeyError

Registration could not be completed.

Source code in src/fastapi_passkeys/exceptions.py
63
64
65
66
67
class RegistrationError(PasskeyError):
    """Registration could not be completed."""

    code = "registration_error"
    status_code = 400

CredentialAlreadyExists

Bases: RegistrationError

This credential is already registered.

Source code in src/fastapi_passkeys/exceptions.py
70
71
72
73
74
class CredentialAlreadyExists(RegistrationError):
    """This credential is already registered."""

    code = "credential_already_exists"
    status_code = 409

RegistrationUserMismatch

Bases: RegistrationError

This registration was started by a different user.

Source code in src/fastapi_passkeys/exceptions.py
77
78
79
80
81
class RegistrationUserMismatch(RegistrationError):
    """This registration was started by a different user."""

    code = "registration_user_mismatch"
    status_code = 400

CredentialLimitReached

Bases: RegistrationError

This account already has the maximum number of passkeys.

Source code in src/fastapi_passkeys/exceptions.py
84
85
86
87
88
class CredentialLimitReached(RegistrationError):
    """This account already has the maximum number of passkeys."""

    code = "credential_limit_reached"
    status_code = 409

AttestationVerificationError

Bases: RegistrationError

The registration response failed verification.

Source code in src/fastapi_passkeys/exceptions.py
91
92
93
94
95
class AttestationVerificationError(RegistrationError):
    """The registration response failed verification."""

    code = "attestation_verification_failed"
    status_code = 400

AuthenticationError

Bases: PasskeyError

Authentication could not be completed.

Source code in src/fastapi_passkeys/exceptions.py
101
102
103
104
105
class AuthenticationError(PasskeyError):
    """Authentication could not be completed."""

    code = "authentication_error"
    status_code = 401

CredentialNotFound

Bases: AuthenticationError

No matching registered credential was found.

Source code in src/fastapi_passkeys/exceptions.py
108
109
110
111
112
class CredentialNotFound(AuthenticationError):
    """No matching registered credential was found."""

    code = "credential_not_found"
    status_code = 401

ManagedCredentialNotFound

Bases: PasskeyError

No such passkey on this account.

Source code in src/fastapi_passkeys/exceptions.py
115
116
117
118
119
class ManagedCredentialNotFound(PasskeyError):
    """No such passkey on this account."""

    code = "credential_not_found"
    status_code = 404

AssertionVerificationError

Bases: AuthenticationError

The authentication response failed verification.

Source code in src/fastapi_passkeys/exceptions.py
122
123
124
125
126
class AssertionVerificationError(AuthenticationError):
    """The authentication response failed verification."""

    code = "assertion_verification_failed"
    status_code = 401

CloneDetectedError

Bases: AuthenticationError

The signature counter did not advance; the authenticator may be cloned.

Source code in src/fastapi_passkeys/exceptions.py
129
130
131
132
133
class CloneDetectedError(AuthenticationError):
    """The signature counter did not advance; the authenticator may be cloned."""

    code = "clone_detected"
    status_code = 401