feat(kiosk): PC-Terminal-Frontend für NFC-Login + Stempeln
Security Audit / Python Dependency Audit (push) Canceled after 0s
Security Audit / Node.js Dependency Audit (push) Canceled after 0s

Bisher zeigte KioskStampPage nur einen Status ("Kiosk-Modus aktiv"), es gab
keine Möglichkeit sich einzuloggen oder tatsächlich zu stempeln. Jetzt:

- NFC-Erfassung ohne Fokus-Anforderung: globaler keydown-Listener erkennt den
  Tastatur-Emulations-Output günstiger USB-HID-RFID-Reader (Zeichen-Burst
  <300ms + Enter) und unterscheidet ihn von echter Tastatureingabe
- PIN-Pad nach Kartenerkennung (Pflicht-Zweitfaktor, siehe 3650da8/K-3-Fix)
- Nach Login: Stempel-Aktionen je nach aktuellem Status (Ein/Aus/Pause
  starten/beenden) über die neuen /kiosk/stamp/*-Endpunkte (2ce363c)
- Automatischer Reset zur Kartenauflege-Ansicht nach jeder Aktion

Alle Requests laufen weiter transparent durch den bestehenden Ed25519-
signierenden ServiceWorker (kiosk-sw.js, kein Adapter nötig).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gis16MnuwkYcivLrSxK1pD
This commit is contained in:
2026-08-27 13:37:06 +02:00
co-authored by Claude Sonnet 5
parent 21c7c0bd14
commit 81d58f720e
+262 -17
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
interface HeartbeatResponse {
@@ -12,6 +12,19 @@ const HEARTBEAT_CHANNEL = 'kiosk-heartbeat'
const HEARTBEAT_INTERVAL_MS = 30_000
const CLIENT_VERSION = '1.0.0'
// NFC keyboard-wedge readers "type" the card UID very fast, ending with Enter.
// A human never types 10 digits in under this window, so a burst of digit
// keys arriving within NFC_BURST_MS is treated as a card tap, not typing.
const NFC_BURST_MS = 300
const NFC_MIN_LENGTH = 4
type Step = 'idle' | 'pin' | 'action' | 'done'
interface StampStatus {
stamped_in: boolean
on_break: boolean
}
function formatTime(date: Date): string {
return date.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit', second: '2-digit' })
}
@@ -39,6 +52,19 @@ async function sendMessageToSW(
})
}
async function kioskFetch<T>(path: string, body: object): Promise<T> {
const res = await fetch(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
throw new Error(typeof data.detail === 'string' ? data.detail : `Fehler ${res.status}`)
}
return data as T
}
export function KioskStampPage() {
const [displayTime, setDisplayTime] = useState(new Date())
const [serverTimeOffset, setServerTimeOffset] = useState(0) // ms offset from server
@@ -49,11 +75,44 @@ export function KioskStampPage() {
const [deviceId, setDeviceId] = useState<string | null>(null)
const [isLeaderTab, setIsLeaderTab] = useState(false)
// ── Login/Stamp-Flow ────────────────────────────────────────────────────
const [step, setStep] = useState<Step>('idle')
const [nfcUid, setNfcUid] = useState<string | null>(null)
const [pin, setPin] = useState('')
const [sessionToken, setSessionToken] = useState<string | null>(null)
const [userName, setUserName] = useState<string | null>(null)
const [stampStatus, setStampStatus] = useState<StampStatus | null>(null)
const [flowError, setFlowError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [doneMessage, setDoneMessage] = useState<string | null>(null)
const heartbeatIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
const clockIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
const broadcastRef = useRef<BroadcastChannel | null>(null)
const swRegRef = useRef<ServiceWorkerRegistration | null>(null)
const startTimeRef = useRef<number>(Date.now())
const resetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
// NFC keyboard-wedge capture buffer
const nfcBufferRef = useRef('')
const nfcLastKeyAtRef = useRef(0)
const resetFlow = useCallback(() => {
setStep('idle')
setNfcUid(null)
setPin('')
setSessionToken(null)
setUserName(null)
setStampStatus(null)
setFlowError(null)
setDoneMessage(null)
nfcBufferRef.current = ''
}, [])
function scheduleAutoReset(ms = 4000) {
if (resetTimeoutRef.current) clearTimeout(resetTimeoutRef.current)
resetTimeoutRef.current = setTimeout(resetFlow, ms)
}
// Live clock uses server time offset
useEffect(() => {
@@ -156,6 +215,39 @@ export function KioskStampPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
// NFC keyboard-wedge listener: only active on the idle screen. Cheap USB-HID
// RFID readers "type" the UID as fast keystrokes ending with Enter - a human
// typing on a real keyboard can't hit 4+ digits within NFC_BURST_MS.
useEffect(() => {
if (step !== 'idle' || hasCredentials !== true) return
function onKeyDown(e: KeyboardEvent) {
const now = Date.now()
if (now - nfcLastKeyAtRef.current > NFC_BURST_MS) {
nfcBufferRef.current = ''
}
nfcLastKeyAtRef.current = now
if (e.key === 'Enter') {
const uid = nfcBufferRef.current
nfcBufferRef.current = ''
if (uid.length >= NFC_MIN_LENGTH) {
setNfcUid(uid)
setStep('pin')
setPin('')
setFlowError(null)
}
return
}
if (/^[0-9A-Za-z]$/.test(e.key)) {
nfcBufferRef.current += e.key
}
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, [step, hasCredentials])
function startHeartbeatLoop() {
// Send immediately, then on interval
sendHeartbeat()
@@ -215,6 +307,56 @@ export function KioskStampPage() {
}
}
async function submitPin() {
if (!nfcUid || pin.length < 4) return
setBusy(true)
setFlowError(null)
try {
const login = await kioskFetch<{ session_token: string; user_name: string }>(
'/api/v1/kiosk/auth/nfc', { nfc_uid: nfcUid, pin }
)
setSessionToken(login.session_token)
setUserName(login.user_name)
const status = await kioskFetch<StampStatus>(
'/api/v1/kiosk/stamp/status', { session_token: login.session_token }
)
setStampStatus(status)
setStep('action')
} catch (e: unknown) {
setFlowError(e instanceof Error ? e.message : 'Anmeldung fehlgeschlagen')
setPin('')
} finally {
setBusy(false)
}
}
async function performAction(action: 'in' | 'out' | 'break-start' | 'break-end') {
if (!sessionToken) return
setBusy(true)
setFlowError(null)
try {
const result = await kioskFetch<{ status: string; warnings?: string[] }>(
`/api/v1/kiosk/stamp/${action}`, { session_token: sessionToken }
)
const labels: Record<string, string> = {
stamped_in: 'Eingestempelt ✓',
stamped_out: 'Ausgestempelt ✓',
break_started: 'Pause gestartet ✓',
break_ended: 'Pause beendet ✓',
}
setDoneMessage(labels[result.status] ?? 'Erledigt ✓')
if (result.warnings?.length) {
setFlowError(result.warnings.join(' · '))
}
setStep('done')
scheduleAutoReset()
} catch (e: unknown) {
setFlowError(e instanceof Error ? e.message : 'Aktion fehlgeschlagen')
} finally {
setBusy(false)
}
}
return (
<div className='min-h-screen bg-gray-950 text-white flex flex-col'>
@@ -278,11 +420,6 @@ export function KioskStampPage() {
<div className='text-xl text-gray-400 mt-2'>
{formatDate(displayTime)}
</div>
{Math.abs(serverTimeOffset) > 1000 && (
<div className='text-xs text-yellow-600 mt-1'>
Server-Zeit-Offset: {serverTimeOffset > 0 ? '+' : ''}{Math.round(serverTimeOffset / 1000)}s
</div>
)}
</div>
{/* Credentials missing warning */}
@@ -304,27 +441,135 @@ export function KioskStampPage() {
</div>
)}
{/* Kiosk active state */}
{hasCredentials === true && (
<div className='max-w-md w-full bg-gray-800 rounded-2xl p-6 text-center space-y-4'>
<div className='text-4xl'></div>
<p className='text-green-400 font-semibold text-lg'>Kiosk-Modus aktiv</p>
<p className='text-gray-400 text-sm'>
Alle Stempel-Anfragen werden automatisch per Ed25519 signiert.
{/* ── Login/Stempel-Flow ─────────────────────────────────────────── */}
{hasCredentials === true && step === 'idle' && (
<div className='max-w-md w-full bg-gray-800 rounded-2xl p-8 text-center space-y-3'>
<div className='text-5xl'>💳</div>
<p className='text-gray-200 font-semibold text-lg'>Bitte Karte auflegen</p>
<p className='text-gray-500 text-sm'>
Kein Kartenleser-Fokus nötig Eingabe wird automatisch erkannt.
</p>
{heartbeatStatus === 'error' && heartbeatError && (
<div className='bg-red-900/40 border border-red-700 rounded-lg px-3 py-2 text-sm text-red-300'>
Verbindungsfehler: {heartbeatError}
</div>
)}
</div>
)}
{hasCredentials === true && step === 'pin' && (
<div className='max-w-xs w-full bg-gray-800 rounded-2xl p-6 text-center space-y-4'>
<div className='text-4xl'>🔑</div>
<p className='text-gray-200 font-semibold'>PIN eingeben</p>
<div className='text-2xl font-mono tracking-[0.5em] h-8'>
{'•'.repeat(pin.length)}
</div>
{flowError && (
<div className='bg-red-900/40 border border-red-700 rounded-lg px-3 py-2 text-sm text-red-300'>
{flowError}
</div>
)}
<div className='grid grid-cols-3 gap-2'>
{['1','2','3','4','5','6','7','8','9','','0','⌫'].map((k, i) => (
k === '' ? <div key={i} /> : (
<button
onClick={sendHeartbeat}
className='text-xs text-gray-500 hover:text-gray-300 underline transition-colors'
key={i}
disabled={busy}
onClick={() => {
if (k === '⌫') { setPin(p => p.slice(0, -1)); return }
setPin(p => (p.length < 6 ? p + k : p))
}}
className='py-3 rounded-xl bg-gray-700 hover:bg-gray-600 text-lg font-semibold
disabled:opacity-50 transition-colors'
>
Heartbeat manuell senden
{k}
</button>
)
))}
</div>
<div className='flex gap-2 pt-2'>
<button
onClick={resetFlow}
className='flex-1 py-2 rounded-xl bg-gray-700 hover:bg-gray-600 text-sm'
>
Abbrechen
</button>
<button
onClick={submitPin}
disabled={pin.length < 4 || busy}
className='flex-1 py-2 rounded-xl bg-blue-600 hover:bg-blue-500 text-sm font-semibold
disabled:opacity-50'
>
{busy ? '…' : 'Bestätigen'}
</button>
</div>
</div>
)}
{hasCredentials === true && step === 'action' && stampStatus && (
<div className='max-w-sm w-full bg-gray-800 rounded-2xl p-6 text-center space-y-4'>
<p className='text-gray-400 text-sm'>Angemeldet als</p>
<p className='text-gray-100 font-semibold text-xl'>{userName}</p>
{flowError && (
<div className='bg-red-900/40 border border-red-700 rounded-lg px-3 py-2 text-sm text-red-300'>
{flowError}
</div>
)}
<div className='space-y-2 pt-2'>
{!stampStatus.stamped_in && (
<button
onClick={() => performAction('in')}
disabled={busy}
className='w-full py-4 rounded-xl bg-green-600 hover:bg-green-500 font-semibold text-lg disabled:opacity-50'
>
Einstempeln
</button>
)}
{stampStatus.stamped_in && !stampStatus.on_break && (
<>
<button
onClick={() => performAction('out')}
disabled={busy}
className='w-full py-4 rounded-xl bg-red-600 hover:bg-red-500 font-semibold text-lg disabled:opacity-50'
>
Ausstempeln
</button>
<button
onClick={() => performAction('break-start')}
disabled={busy}
className='w-full py-3 rounded-xl bg-gray-700 hover:bg-gray-600 font-medium disabled:opacity-50'
>
Pause starten
</button>
</>
)}
{stampStatus.stamped_in && stampStatus.on_break && (
<button
onClick={() => performAction('break-end')}
disabled={busy}
className='w-full py-4 rounded-xl bg-blue-600 hover:bg-blue-500 font-semibold text-lg disabled:opacity-50'
>
Pause beenden
</button>
)}
</div>
<button
onClick={resetFlow}
className='text-xs text-gray-500 hover:text-gray-300 underline pt-2'
>
Abbrechen
</button>
</div>
)}
{hasCredentials === true && step === 'done' && (
<div className='max-w-sm w-full bg-gray-800 rounded-2xl p-8 text-center space-y-3'>
<div className='text-5xl'></div>
<p className='text-green-400 font-semibold text-xl'>{doneMessage}</p>
{flowError && (
<p className='text-yellow-400 text-sm'>{flowError}</p>
)}
<p className='text-gray-600 text-xs'>Zurück zur Startseite in wenigen Sekunden</p>
</div>
)}