Files
mizan/react/src/allauth/components/settings/PasskeysSection.tsx
Ryth Azhur 4451ec24a1 Full test infrastructure, code audit fixes, and real E2E integration tests
Test infrastructure:
- Django standalone test runner (pytest-django, test settings, EmailUser model)
- React unit tests via Vitest with jsdom, jest compat layer, path aliases
- Playwright E2E tests using generated hooks in a real Chromium browser
- Docker Compose test backend (Django + Redis) for integration testing
- Desktop integration test app (PyWebView + Django + uvicorn)
- Makefile with test/test-django/test-react/test-integration targets

Library bugs found and fixed:
- hasJWT truthiness: undefined !== null was true, skipping session init
- process.env crash: CSR client referenced process.env in non-Node browsers
- baseUrl not forwarded: DjareaProvider didn't pass baseUrl to CSR client
- Relative URL handling: new URL() failed with relative base paths
- call() race condition: HTTP requests fired before CSRF cookie was set
- Session init await: added sessionRef promise so call() waits for session
- path_prefix on schema export: both export commands failed with URL reverse
- NullBooleanField removed: referenced field doesn't exist in Django 5.0+
- lru_cache on JWT settings: get_settings() now cached as intended
- Channel message routing: broadcasts now include channel name and params
- httpFunctionCall: fixed URL and request body format

Generator fixes:
- Removed 1,100 lines of REST/OpenAPI client generation (not part of Djarea)
- Generator now works for djarea-only projects without django-ninja REST APIs
- Generated DjangoContext now includes ChannelProvider when channels exist
- Fixed env var passthrough for schema export commands
- Deduplicated fetch logic into single runDjangoCommand helper

Test quality:
- Fixed 33 tautological Django tests with real assertions
- Found hidden bug: benchmark functions were never registered
- Found hidden bug: unicode lookalike test used plain ASCII
- Deleted worthless React unit tests (duplicates, shape checks, Zod-tests-Zod)
- Replaced jsdom integration tests with Playwright browser tests

Example apps:
- example/: Integration test backend with 33 server functions, 5 forms,
  4 channels covering auth variations, contexts, class-based ServerFunction,
  error codes, DjareaFormMixin, formsets, and JWT
- desktop/: PyWebView desktop app with file system access, SQLite CRUD,
  system introspection, and 39 real HTTP integration tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 01:17:48 -04:00

104 lines
3.8 KiB
TypeScript

'use client'
import { useState, useEffect } from 'react'
import { useAllauthAPI } from '../../contexts/APIContext'
import { useConfig } from '../../contexts/AuthContext'
import { useStyles } from '../../contexts/StylesContext'
import { SettingsSection, SettingsItem, SettingsList, Button } from './SettingsComponents'
import type { Authenticator, WebAuthnAuthenticator } from '../../types'
export function PasskeysSection() {
const api = useAllauthAPI()
const config = useConfig()
const styles = useStyles()
const [passkeys, setPasskeys] = useState<WebAuthnAuthenticator[]>([])
const [loading, setLoading] = useState(true)
// Check if passkey login is enabled
const passkeyLoginEnabled = config?.data?.mfa?.passkey_login_enabled
const fetchPasskeys = async () => {
try {
const res = await api.mfa.list()
if (res.status === 200 && res.data) {
const authenticators = res.data as Authenticator[]
setPasskeys(authenticators.filter((a): a is WebAuthnAuthenticator => a.type === 'webauthn'))
}
} catch {
// Silently fail - passkeys just won't show
}
setLoading(false)
}
useEffect(() => { fetchPasskeys() }, [])
// Don't render if passkey login isn't enabled
if (!passkeyLoginEnabled) return null
if (loading) return null
const handleAdd = async () => {
try {
const { startRegistration } = await import('@simplewebauthn/browser')
// Request creation options - use passwordless=true for login passkeys
const optionsRes = await api.webauthn.requestOptions.creation(true)
if (optionsRes.status !== 200) {
return
}
const publicKeyOptions = optionsRes.data?.creation_options?.publicKey
if (!publicKeyOptions) throw new Error('Invalid options response')
// @simplewebauthn/browser v13+ expects { optionsJSON: ... }
const credential = await startRegistration({ optionsJSON: publicKeyOptions as any })
const name = prompt('Name this passkey:') || 'Passkey'
const res = await api.webauthn.add(name, credential)
if (res.status === 200) {
fetchPasskeys()
}
} catch (e: any) {
if (e.name !== 'AbortError') {
alert(e.message || 'Failed to add passkey')
}
}
}
const handleRemove = async (id: number) => {
if (!confirm('Remove this passkey? You won\'t be able to use it to sign in anymore.')) return
await api.webauthn.delete([id])
fetchPasskeys()
}
return (
<SettingsSection title="Passkeys">
<p className={styles.settingsItemMeta} style={{ marginBottom: '1rem' }}>
Passkeys let you sign in quickly using your device's biometrics or security key.
No password needed.
</p>
{passkeys.length > 0 && (
<SettingsList>
{passkeys.map(passkey => (
<SettingsItem
key={passkey.id}
label={passkey.name}
meta={`Added ${new Date(passkey.created_at * 1000).toLocaleDateString()}`}
actions={
<Button variant="danger" onClick={() => handleRemove(passkey.id)}>
Remove
</Button>
}
/>
))}
</SettingsList>
)}
<Button onClick={handleAdd}>
{passkeys.length > 0 ? 'Add Another Passkey' : 'Set Up Passkey'}
</Button>
</SettingsSection>
)
}