Passkey-Anmeldung (WebAuthn) zusätzlich zum Passwort

- Tabelle passkeys + lib/passkeys.ts (CRUD, Counter-Replay-Schutz)
- lib/webauthn.ts: RP-Config via RP_ID/RP_ORIGIN/RP_NAME, Challenge im
  httpOnly-Cookie, Wrapper um @simplewebauthn/server
- API: app/api/passkey/{register,authenticate,route}; authenticate ist
  öffentlich (proxy.ts ausgenommen) und setzt bei Erfolg die Session
- Login-Button "Mit Passkey anmelden", Verwaltung im Einstellungen-Tab
- Passwort bleibt als Fallback; Version 0.1.1

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-22 13:30:12 +02:00
parent 4dc64bfb5c
commit 4a3dfa5821
13 changed files with 856 additions and 26 deletions
+2
View File
@@ -5,6 +5,7 @@ import type { ArbeitszeitEintrag } from '@/types/arbeitszeit';
import ArbeitszeitForm from '@/components/ArbeitszeitForm';
import ArbeitszeitList from '@/components/ArbeitszeitList';
import Einstellungen from '@/components/Einstellungen';
import Passkeys from '@/components/Passkeys';
import packageJson from '@/package.json';
interface Props {
@@ -143,6 +144,7 @@ export default function MainClient({ username }: Props) {
<div className="border-2 border-gray-400 rounded-xl bg-white p-3">
<h2 className="text-sm font-semibold text-gray-900 mb-3">Einstellungen</h2>
<Einstellungen pause={pause} onPauseChange={setPause} />
<Passkeys />
</div>
)}
+29
View File
@@ -0,0 +1,29 @@
import { NextRequest, NextResponse } from 'next/server';
import { buildAuthenticationOptions, finishAuthentication } from '@/lib/webauthn';
import { createSession } from '@/lib/session';
import { getConfiguredUsername } from '@/lib/auth';
// Öffentlich (kein Login): Optionen für die Anmeldung per Passkey.
export async function GET() {
try {
return NextResponse.json(await buildAuthenticationOptions());
} catch (error) {
console.error('GET /api/passkey/authenticate:', error);
return NextResponse.json({ error: 'Serverfehler' }, { status: 500 });
}
}
// Öffentlich: Verifiziert die Anmelde-Antwort und erstellt bei Erfolg die Session.
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const result = await finishAuthentication(body?.response);
if (!result.ok) return NextResponse.json({ error: result.error }, { status: 401 });
await createSession({ username: getConfiguredUsername(), isAuthenticated: true });
return NextResponse.json({ ok: true });
} catch (error) {
console.error('POST /api/passkey/authenticate:', error);
return NextResponse.json({ error: 'Serverfehler' }, { status: 500 });
}
}
+32
View File
@@ -0,0 +1,32 @@
import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import { buildRegistrationOptions, finishRegistration } from '@/lib/webauthn';
// Optionen für die Registrierung eines neuen Passkeys (Session erforderlich).
export async function GET() {
const session = await getSession();
if (!session) return NextResponse.json({ error: 'Nicht angemeldet' }, { status: 401 });
try {
return NextResponse.json(await buildRegistrationOptions());
} catch (error) {
console.error('GET /api/passkey/register:', error);
return NextResponse.json({ error: 'Serverfehler' }, { status: 500 });
}
}
// Verifiziert die Registrierungs-Antwort und speichert den Passkey.
export async function POST(request: NextRequest) {
const session = await getSession();
if (!session) return NextResponse.json({ error: 'Nicht angemeldet' }, { status: 401 });
try {
const body = await request.json();
const result = await finishRegistration(body?.response, String(body?.label ?? ''));
if (!result.ok) return NextResponse.json({ error: result.error }, { status: 400 });
return NextResponse.json({ ok: true });
} catch (error) {
console.error('POST /api/passkey/register:', error);
return NextResponse.json({ error: 'Serverfehler' }, { status: 500 });
}
}
+30
View File
@@ -0,0 +1,30 @@
import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import { listPasskeys, deletePasskey } from '@/lib/passkeys';
// Liste der registrierten Passkeys (ohne öffentlichen Schlüssel).
export async function GET() {
const session = await getSession();
if (!session) return NextResponse.json({ error: 'Nicht angemeldet' }, { status: 401 });
const passkeys = listPasskeys().map((pk) => ({
credentialId: pk.credentialId,
label: pk.label,
createdAt: pk.createdAt,
lastUsedAt: pk.lastUsedAt,
}));
return NextResponse.json({ passkeys });
}
// Löscht einen Passkey anhand seiner credentialId (?id=...).
export async function DELETE(request: NextRequest) {
const session = await getSession();
if (!session) return NextResponse.json({ error: 'Nicht angemeldet' }, { status: 401 });
const id = request.nextUrl.searchParams.get('id');
if (!id) return NextResponse.json({ error: 'Keine ID angegeben.' }, { status: 400 });
const removed = deletePasskey(id);
if (!removed) return NextResponse.json({ error: 'Passkey nicht gefunden.' }, { status: 404 });
return NextResponse.json({ ok: true });
}
+59
View File
@@ -1,12 +1,47 @@
'use client';
import { useActionState, useState } from 'react';
import { startAuthentication } from '@simplewebauthn/browser';
import { login } from './actions';
import packageJson from '@/package.json';
export default function LoginPage() {
const [state, loginAction, isPending] = useActionState(login, undefined);
const [showPassword, setShowPassword] = useState(false);
const [passkeyBusy, setPasskeyBusy] = useState(false);
const [passkeyError, setPasskeyError] = useState<string | null>(null);
async function handlePasskeyLogin() {
setPasskeyError(null);
setPasskeyBusy(true);
try {
const optRes = await fetch('/api/passkey/authenticate');
if (!optRes.ok) throw new Error('Optionen konnten nicht geladen werden.');
const optionsJSON = await optRes.json();
const response = await startAuthentication({ optionsJSON });
const verifyRes = await fetch('/api/passkey/authenticate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ response }),
});
if (!verifyRes.ok) {
const data = await verifyRes.json().catch(() => null);
throw new Error(data?.error ?? 'Anmeldung mit Passkey fehlgeschlagen.');
}
window.location.href = '/';
} catch (err) {
// Abbruch durch Nutzer (NotAllowedError) nicht als Fehler anzeigen.
if (err instanceof Error && err.name === 'NotAllowedError') {
setPasskeyError(null);
} else {
setPasskeyError(err instanceof Error ? err.message : 'Anmeldung mit Passkey fehlgeschlagen.');
}
} finally {
setPasskeyBusy(false);
}
}
const version = packageJson.version;
const buildDate =
@@ -92,6 +127,30 @@ export default function LoginPage() {
{isPending ? 'Anmeldung läuft...' : 'Anmelden'}
</button>
</form>
<div className="flex items-center gap-3 my-5">
<div className="h-px flex-1 bg-gray-200" />
<span className="text-xs text-gray-400">oder</span>
<div className="h-px flex-1 bg-gray-200" />
</div>
<button
type="button"
onClick={handlePasskeyLogin}
disabled={passkeyBusy}
className="w-full py-2 px-4 flex items-center justify-center gap-2 border-2 border-gray-400 hover:border-green-600 text-gray-900 font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed text-sm"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
</svg>
{passkeyBusy ? 'Anmeldung läuft...' : 'Mit Passkey anmelden'}
</button>
{passkeyError && (
<div className="mt-4 bg-red-50 border border-red-300 text-red-700 px-3 py-2 rounded-lg text-sm">
{passkeyError}
</div>
)}
</div>
</div>