diff --git a/README.md b/README.md index 52f60ae..0d68526 100644 --- a/README.md +++ b/README.md @@ -253,7 +253,7 @@ Beispiel für die crontab, täglich um 18:00 Uhr: - Es wird die erste tippbare Runde der aktiven Saison ermittelt, also die erste Runde ohne gesperrtes Spiel. - Sperrt diese Runde erst in mehr als 48 Stunden, passiert nichts. -- Andernfalls bekommen alle bezahlten Spieler mit fehlenden Tipps oder fehlendem Joker eine Mail, sofern sie Erinnerungen nicht in ihrem Profil abgeschaltet haben (`users.gets_reminders`). +- Andernfalls bekommen alle bezahlten Spieler mit fehlenden Tipps oder fehlendem Joker eine Mail, sofern sie Erinnerungen nicht in ihrem Profil abgeschaltet haben (`users.gets_reminders`). Spieler mit aktivem Push-Abo bekommen zusätzlich eine App-Erinnerung (siehe unten). - Die Mail wird unter *Administration → Runden-E-Mails versenden* mit Versender „Automailer“ protokolliert. - Vorher werden bei jedem Aufruf alle automatischen Erinnerungen (Versender „Automailer“, Betreff „Fehlende Tipps/Joker“) gelöscht, die älter als einen Monat sind. Das passiert auch dann, wenn gerade keine Erinnerung fällig ist, z.B. in der Sommerpause. Rundmails von Administratoren bleiben immer erhalten. - Ebenfalls bei jedem Aufruf: IBAN, PayPal und Handynummer werden bei Spielern geleert, die in den letzten zwei Saisons nicht mehr bezahlt haben (`User::ACCOUNT_DATA_RETENTION_SEASONS`). Die Daten werden nur für die Auszahlung des Pott gebraucht. Wer noch nie bezahlt hat, bleibt unangetastet – das sind neue Anmeldungen, deren Zahlungseingang noch nicht verbucht ist. Beim Löschen eines Spielers werden die Kontodaten ebenfalls sofort geleert. @@ -264,11 +264,70 @@ Jeder Aufruf innerhalb des 48-Stunden-Fensters verschickt erneut eine Erinnerung | HTTP-Status | Bedeutung | |---|---| -| `200` | Erfolgreich. Zeilen 1–3: Anzahl gelöschter alter Erinnerungen, Fragen/Antworten und Kontodaten. Letzte Zeile: Ergebnis des Versands, z.B. `Runde 17: Erinnerung an 3 Empfänger versendet.` oder `... - nichts zu tun.` | +| `200` | Erfolgreich. Zeilen 1–3: Anzahl gelöschter alter Erinnerungen, Fragen/Antworten und Kontodaten. Letzte Zeile: Ergebnis des Versands, z.B. `Runde 17: Erinnerung an 3 Empfänger versendet.` oder `... - nichts zu tun.` Wurden App-Erinnerungen verschickt, folgt ` Push: 2 gesendet, 0 fehlgeschlagen, 0 abgelaufene Abos entfernt.` | | `500` | Fehler, z.B. Mailserver nicht erreichbar (Meldung steht im Antworttext) | Mit `curl -f` beendet sich curl bei 4xx/5xx mit einem Fehlercode, sodass Cron-Überwachung Fehlschläge bemerkt. +## App-Erinnerungen (Web-Push) + +Zusätzlich zur E-Mail kann der Erinnerungslauf eine Benachrichtigung aufs +Smartphone schicken. Das ist ein eigener Kanal mit eigener Checkbox in den +Einstellungen („Ich möchte Smartphone-Erinnerungen erhalten (App)“), unabhängig +von `users.gets_reminders`. + +**Wie es funktioniert** + +- Der Service Worker (`public/sw.js`) empfängt Push-Nachrichten und zeigt sie + über `showNotification` an; ein Klick öffnet `/index.php?page=tipps`. +- Die Checkbox erscheint **nur in der installierten App** + (`display-mode: standalone` bzw. `navigator.standalone`). Im normalen + Browser-Tab wird sie ausgeblendet. +- Beim Anhaken fragt die Seite die Benachrichtigungs-Erlaubnis ab, erzeugt mit + `pushManager.subscribe()` ein Abo und schickt es an + `POST /index.php?page=push_subscribe`. Abhaken löscht alle Abos des Kontos + (`POST /index.php?page=push_unsubscribe`). +- Ein Spieler kann mehrere Geräte haben (Handy, Tablet). Die Checkbox ist der + Ein/Aus-Schalter fürs Konto; jedes Gerät, auf dem sie anhakt ist, wird + eingetragen. +- Der Versand läuft in `Roundmail::sendReminder` über + `PushSubscription::sendReminder`. Abgelaufene Abos (HTTP 404/410) werden + dabei automatisch entfernt. + +**Verschlüsselung und Schlüssel** + +- `App\Core\WebPush` implementiert RFC 8291 (`aes128gcm`) und RFC 8292 (VAPID) + ohne Composer, nur mit `openssl` und `curl`. +- Schlüssel erzeugen und in `docs/live_credentials.txt` eintragen: + + ```bash + python3 tools/generate_vapid_keys.py --write + ``` + + Beim Deploy landen `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` und + `VAPID_SUBJECT` als `SetEnv` in der `.htaccess`. +- Ohne gültige Schlüssel bleibt die Checkbox unsichtbar, der Rest der App läuft + normal. + +**Datenbank** + +```bash +mysql -h -u -p < tools/migration_push_subscriptions.sql +``` + +Die Tabelle `push_subscriptions` speichert pro Gerät Endpunkt, `p256dh` und +`auth`. Fehlt sie, bleibt das Feature unsichtbar (die Einstellungsseite bricht +nicht ab). + +**Grenzen** + +- iOS braucht iOS 16.4+ und die **installierte** PWA (Teilen → „Zum + Home-Bildschirm“). In Safari als normaler Tab gibt es kein Web-Push. +- Der Push-Dienst des Browsers muss erreichbar sein; Fehler landen im + `php-error.log`. +- Beim Löschen eines Kontos werden die Abos nicht automatisch entfernt + (Endpunkte laufen ins Leere und werden beim nächsten Versand aufgeräumt). + ## PHP-Fehlerlog PHP schreibt Fehler, Warnungen und unbehandelte Exceptions in eine Datei außerhalb @@ -377,6 +436,9 @@ mysql -h -u -p < tools/dumps/tippspiel_live_<...>.sql für Code wäre es zu riskant und wird dort nicht angewendet. Der Deploy meldet „X hochgeladen, Y unverändert übersprungen“. - Beim DB-Sync werden nach dem Import die Zeilenzahlen aller Tabellen geprüft. +- **Schema-Änderungen** sind nicht Teil des Datei-Deploys. Sie werden einmalig + mit dem passenden `tools/migration_*.sql` eingespielt (siehe + [App-Erinnerungen](#app-erinnerungen-web-push)). ## Nützliche Befehle diff --git a/tippspiel/public/index.php b/tippspiel/public/index.php index 6075ac8..beaadb6 100644 --- a/tippspiel/public/index.php +++ b/tippspiel/public/index.php @@ -26,6 +26,7 @@ use App\Core\Auth; use App\Core\ErrorLog; use App\Core\Iban; use App\Core\Mailer; +use App\Core\WebPush; use App\Models\Game; use App\Models\Tipp; use App\Models\User; @@ -39,6 +40,7 @@ use App\Models\Setting; use App\Models\Team; use App\Models\Question; use App\Models\FetcherLog; +use App\Models\PushSubscription; $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $page = $_GET['page'] ?? null; @@ -401,6 +403,55 @@ if ($page === 'reminder') { $entries = FetcherLog::getRange($from, $to); require __DIR__ . '/../src/Views/admin/fetcher_activity.php'; +} elseif ($page === 'push_subscribe' || $page === 'push_unsubscribe') { + // Speichert bzw. löscht das Push-Abo für App-Erinnerungen (JSON, nur eingeloggt). + header('Content-Type: application/json; charset=UTF-8'); + + if (!Auth::check()) { + http_response_code(401); + echo json_encode(['error' => 'Nicht angemeldet.']); + exit; + } + if ($_SERVER['REQUEST_METHOD'] !== 'POST') { + http_response_code(405); + echo json_encode(['error' => 'Nur POST erlaubt.']); + exit; + } + + try { + if (!WebPush::isConfigured() || !PushSubscription::isAvailable()) { + http_response_code(503); + echo json_encode(['error' => 'App-Erinnerungen sind derzeit nicht verfügbar.']); + exit; + } + + if ($page === 'push_unsubscribe') { + PushSubscription::deleteForUser((int)Auth::id()); + echo json_encode(['ok' => true]); + exit; + } + + $input = json_decode(file_get_contents('php://input'), true); + $endpoint = is_array($input) ? (string)($input['endpoint'] ?? '') : ''; + $keys = is_array($input) && is_array($input['keys'] ?? null) ? $input['keys'] : []; + $p256dh = (string)($keys['p256dh'] ?? ''); + $authKey = (string)($keys['auth'] ?? ''); + + if (!WebPush::isValidEndpoint($endpoint) + || !WebPush::isValidKeyMaterial($p256dh, $authKey)) { + http_response_code(400); + echo json_encode(['error' => 'Ungültiges Abo.']); + exit; + } + + PushSubscription::save((int)Auth::id(), $endpoint, $p256dh, $authKey); + echo json_encode(['ok' => true]); + } catch (\Throwable $e) { + error_log('Push-Abo konnte nicht gespeichert werden: ' . $e); + http_response_code(500); + echo json_encode(['error' => 'Speichern fehlgeschlagen.']); + } + exit; } elseif ($page === 'settings') { // Eigene Spielerdaten (Legacy UsersController::useredit / storeUserEdit) Auth::requireLogin(); @@ -409,6 +460,12 @@ if ($page === 'reminder') { $message = $_SESSION['settings_message'] ?? null; unset($_SESSION['settings_message']); + // Zweite Checkbox (nur in der installierten App sichtbar): Zustand des Push-Abos + // und öffentlicher VAPID-Schlüssel für pushManager.subscribe(). Ohne Tabelle + // (Migration noch nicht gelaufen) bleibt die Zeile unsichtbar. + $pushPublicKey = PushSubscription::isAvailable() && WebPush::isConfigured() ? WebPush::publicKey() : null; + $pushEnabled = PushSubscription::hasSubscription((int)$user['id']); + // IBAN für die Anzeige entschlüsseln (in der DB liegt nur der Ciphertext) try { $user['iban'] = \App\Core\Crypto::decrypt($user['iban']); diff --git a/tippspiel/public/sw.js b/tippspiel/public/sw.js index 2aad707..b71c2f4 100644 --- a/tippspiel/public/sw.js +++ b/tippspiel/public/sw.js @@ -3,7 +3,7 @@ // HTML-Seiten werden bewusst NICHT gecacht: Sie enthalten den Login-Status und // würden nach Ablauf der Session eine veraltete, eingeloggte Ansicht zeigen. -const CACHE_NAME = 'tippspiel2027-v6'; +const CACHE_NAME = 'tippspiel2027-v7'; const STATIC_ASSETS = [ '/css/style.css', '/img/icon-192.png', @@ -55,3 +55,47 @@ self.addEventListener('fetch', (event) => { // der Server entscheidet anhand der Session, ob eingeloggt oder nicht. event.respondWith(fetch(event.request)); }); + +// Smartphone-Erinnerungen (Web-Push mit VAPID) +// Die Nutzlast kommt als JSON vom Server (siehe Roundmail::sendReminder). +self.addEventListener('push', (event) => { + let data = {}; + try { + data = event.data ? event.data.json() : {}; + } catch (e) { + data = {}; + } + + const title = data.title || 'Hoschis Tippspiel'; + const options = { + body: data.body || '', + icon: '/img/icon-192.png', + badge: '/img/icon-192.png', + tag: data.tag || undefined, + data: { url: data.url || '/' }, + }; + + event.waitUntil(self.registration.showNotification(title, options)); +}); + +self.addEventListener('notificationclick', (event) => { + event.notification.close(); + const target = (event.notification.data && event.notification.data.url) || '/'; + + event.waitUntil( + clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => { + for (const client of list) { + if (new URL(client.url).origin !== self.location.origin) { + continue; + } + return client.focus().then(() => { + if ('navigate' in client) { + return client.navigate(target); + } + return client; + }); + } + return clients.openWindow(target); + }) + ); +}); diff --git a/tippspiel/src/Core/WebPush.php b/tippspiel/src/Core/WebPush.php new file mode 100644 index 0000000..7c59640 --- /dev/null +++ b/tippspiel/src/Core/WebPush.php @@ -0,0 +1,437 @@ + 1000 || strlen($endpoint) < 10) { + return false; + } + $parts = parse_url($endpoint); + if (!$parts || empty($parts['scheme']) || empty($parts['host'])) { + return false; + } + if (strtolower($parts['scheme']) !== 'https') { + return false; + } + $host = strtolower($parts['host']); + if ($host === 'localhost' || substr($host, -6) === '.local') { + return false; + } + if (filter_var($host, FILTER_VALIDATE_IP)) { + // Keine privaten/reservierten Adressen (SSRF-Schutz). + if (!filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { + return false; + } + } + return true; + } + + /** + * Prüft die Schlüssel eines Abos, bevor es gespeichert wird. + * + * @param string $p256dh base64url des Geräteschlüssels (65 Byte, unkomprimierter Punkt) + * @param string $auth base64url des Auth-Geheimnisses (16 Byte) + * @return bool + */ + public static function isValidKeyMaterial($p256dh, $auth) { + $point = self::base64UrlDecode($p256dh); + $secret = self::base64UrlDecode($auth); + return $point !== false && strlen($point) === 65 && $point[0] === "\x04" + && $secret !== false && strlen($secret) === 16; + } + + /** + * Versendet eine Nachricht an ein Abo. + * + * @param array $subscription ['endpoint' => string, 'p256dh' => string, 'auth' => string] + * @param array $payload Beliebige JSON-Struktur (Titel, Text, URL) + * @return array ['ok' => bool, 'status' => int, 'gone' => bool, 'error' => string] + */ + public static function send(array $subscription, array $payload) { + $result = ['ok' => false, 'status' => 0, 'gone' => false, 'error' => '']; + + if (!self::isConfigured()) { + $result['error'] = 'VAPID ist nicht konfiguriert.'; + return $result; + } + if (!function_exists('curl_init')) { + $result['error'] = 'curl ist nicht verfügbar.'; + return $result; + } + + foreach (['endpoint', 'p256dh', 'auth'] as $field) { + if (empty($subscription[$field])) { + $result['error'] = 'Abo unvollständig (' . $field . ').'; + return $result; + } + } + if (!self::isValidEndpoint($subscription['endpoint'])) { + $result['error'] = 'Ungültiger Push-Endpunkt.'; + return $result; + } + + try { + $body = self::encrypt(json_encode($payload), $subscription['p256dh'], $subscription['auth']); + $headers = self::headers($subscription['endpoint']); + } catch (\Throwable $e) { + $result['error'] = $e->getMessage(); + return $result; + } + + $curl = curl_init($subscription['endpoint']); + curl_setopt_array($curl, [ + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => $body, + CURLOPT_HTTPHEADER => $headers, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => self::TIMEOUT, + CURLOPT_CONNECTTIMEOUT => 5, + CURLOPT_PROTOCOLS => CURLPROTO_HTTPS, + CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTPS, + CURLOPT_FOLLOWLOCATION => false, + ]); + $response = curl_exec($curl); + $status = (int)curl_getinfo($curl, CURLINFO_RESPONSE_CODE); + $error = curl_error($curl); + curl_close($curl); + + $result['status'] = $status; + if ($response === false) { + $result['error'] = $error !== '' ? $error : 'Verbindungsfehler.'; + return $result; + } + if ($status === 201 || $status === 202) { + $result['ok'] = true; + return $result; + } + + $result['gone'] = ($status === 404 || $status === 410); + $result['error'] = 'HTTP ' . $status; + return $result; + } + + /** + * Baut die HTTP-Header inklusive VAPID-Autorisierung. + * + * @param string $endpoint + * @return string[] + */ + private static function headers($endpoint) { + $public = self::publicKey(); + $parts = parse_url($endpoint); + if (!$parts || empty($parts['scheme']) || empty($parts['host'])) { + throw new \InvalidArgumentException('Ungültiger Push-Endpunkt.'); + } + $audience = $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port']) ? ':' . $parts['port'] : ''); + $jwt = self::vapidJwt($audience, $public); + + return [ + 'Content-Type: application/octet-stream', + 'Content-Encoding: aes128gcm', + 'TTL: ' . self::TTL, + 'Urgency: normal', + 'Authorization: vapid t=' . $jwt . ', k=' . $public, + ]; + } + + /** + * Signiert die VAPID-Claims als ES256-JWT. + * + * @param string $audience Origin des Push-Dienstes + * @param string $publicKey base64url des öffentlichen Schlüssels + * @return string + */ + private static function vapidJwt($audience, $publicKey) { + $private = self::privateKey(); + if (!$private) { + throw new \RuntimeException('VAPID_PRIVATE_KEY ist ungültig.'); + } + + $header = self::base64UrlEncode(json_encode(['typ' => 'JWT', 'alg' => 'ES256'])); + $claims = self::base64UrlEncode(json_encode([ + 'aud' => $audience, + 'exp' => time() + 43200, + 'sub' => self::subject(), + ])); + $unsigned = $header . '.' . $claims; + + if (!openssl_sign($unsigned, $signature, $private, OPENSSL_ALGO_SHA256)) { + throw new \RuntimeException('VAPID-Signatur fehlgeschlagen.'); + } + + return $unsigned . '.' . self::base64UrlEncode(self::derToRaw($signature)); + } + + /** + * Verschlüsselt die Nutzlast für ein Abo (RFC 8291, aes128gcm). + * + * @param string $payload + * @param string $p256dh base64url des Geräteschlüssels (65 Byte) + * @param string $auth base64url des Auth-Geheimnisses (16 Byte) + * @return string Binärer Request-Body + */ + public static function encrypt($payload, $p256dh, $auth) { + $uaPublic = self::base64UrlDecode($p256dh); + $authSecret = self::base64UrlDecode($auth); + if ($uaPublic === false || strlen($uaPublic) !== 65) { + throw new \InvalidArgumentException('p256dh ist ungültig.'); + } + if ($authSecret === false || strlen($authSecret) !== 16) { + throw new \InvalidArgumentException('auth ist ungültig.'); + } + + // Einmaliges Server-Schlüsselpaar für diese Nachricht + $ephemeral = openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]); + if (!$ephemeral) { + throw new \RuntimeException('Temporärer EC-Schlüssel konnte nicht erzeugt werden.'); + } + $details = openssl_pkey_get_details($ephemeral); + $asPublic = "\x04" . $details['ec']['x'] . $details['ec']['y']; + + $uaKey = openssl_pkey_get_public(self::publicKeyPem($uaPublic)); + if (!$uaKey) { + throw new \InvalidArgumentException('p256dh ist kein gültiger P-256-Punkt.'); + } + $shared = openssl_pkey_derive($uaKey, $ephemeral, 32); + if ($shared === false) { + throw new \RuntimeException('ECDH-Schlüsselaustausch fehlgeschlagen.'); + } + + $prkKey = hash_hmac('sha256', $shared, $authSecret, true); + $ikm = self::hkdfExpand($prkKey, "WebPush: info\x00" . $uaPublic . $asPublic, 32); + + $salt = random_bytes(16); + $prk = hash_hmac('sha256', $ikm, $salt, true); + $cek = self::hkdfExpand($prk, "Content-Encoding: aes128gcm\x00", 16); + $nonce = self::hkdfExpand($prk, "Content-Encoding: nonce\x00", 12); + + $plain = $payload . "\x02"; + $header = $salt . pack('N', self::RECORD_SIZE) . chr(65) . $asPublic; + $cipher = openssl_encrypt($plain, 'aes-128-gcm', $cek, OPENSSL_RAW_DATA, $nonce, $tag, $header, 16); + if ($cipher === false) { + throw new \RuntimeException('Verschlüsselung fehlgeschlagen.'); + } + + return $header . $cipher . $tag; + } + + /** + * HKDF-Expand mit HMAC-SHA-256 (RFC 5869). + * + * @param string $prk Pseudozufälliger Schlüssel (Extract-Ergebnis) + * @param string $info Kontext + * @param int $length Gewünschte Länge + * @return string + */ + private static function hkdfExpand($prk, $info, $length) { + $output = ''; + $block = ''; + for ($i = 1; strlen($output) < $length; $i++) { + $block = hash_hmac('sha256', $block . $info . chr($i), $prk, true); + $output .= $block; + } + return substr($output, 0, $length); + } + + /** + * Wandelt eine DER-Signatur (SEQUENCE aus r und s) in das für JWS nötige + * Rohformat (32 Byte r || 32 Byte s). + * + * @param string $der + * @return string + */ + private static function derToRaw($der) { + $offset = 2; + if (ord($der[1]) & 0x80) { + $offset += ord($der[1]) & 0x7f; + } + $rLength = ord($der[$offset + 1]); + $r = substr($der, $offset + 2, $rLength); + $sOffset = $offset + 2 + $rLength; + $sLength = ord($der[$sOffset + 1]); + $s = substr($der, $sOffset + 2, $sLength); + + return str_pad(ltrim($r, "\x00"), 32, "\x00", STR_PAD_LEFT) + . str_pad(ltrim($s, "\x00"), 32, "\x00", STR_PAD_LEFT); + } + + /** + * Baut aus dem privaten Skalar und dem öffentlichen Punkt ein SEC1-PEM. + * + * @param string $scalar 32 Byte + * @param string $point Unkomprimierter Punkt (65 Byte) + * @return string + */ + private static function privateKeyPem($scalar, $point) { + // SEC1: parameters [0] enthält nur die Kurve, publicKey [1] den Punkt. + $curve = self::derTlv(0xa0, self::curveOid()); + $public = self::derTlv(0xa1, self::derTlv(0x03, "\x00" . $point)); + $der = self::derTlv(0x30, + self::derTlv(0x02, "\x01") + . self::derTlv(0x04, $scalar) + . $curve + . $public + ); + return self::pem('EC PRIVATE KEY', $der); + } + + /** + * Baut aus einem unkomprimierten Punkt ein SPKI-PEM. + * + * @param string $point 65 Byte + * @return string + */ + private static function publicKeyPem($point) { + $algorithm = self::derTlv(0x30, self::ecOid() . self::curveOid()); + $der = self::derTlv(0x30, $algorithm . self::derTlv(0x03, "\x00" . $point)); + return self::pem('PUBLIC KEY', $der); + } + + private static function ecOid() { + return self::derTlv(0x06, "\x2a\x86\x48\xce\x3d\x02\x01"); + } + + private static function curveOid() { + return self::derTlv(0x06, "\x2a\x86\x48\xce\x3d\x03\x01\x07"); + } + + private static function pem($label, $der) { + return "-----BEGIN " . $label . "-----\n" + . chunk_split(base64_encode($der), 64, "\n") + . "-----END " . $label . "-----\n"; + } + + private static function derTlv($tag, $value) { + return chr($tag) . self::derLength(strlen($value)) . $value; + } + + private static function derLength($length) { + if ($length < 0x80) { + return chr($length); + } + $bytes = ltrim(pack('N', $length), "\x00"); + return chr(0x80 | strlen($bytes)) . $bytes; + } + + private static function base64UrlEncode($data) { + return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); + } + + private static function base64UrlDecode($data) { + if (!is_string($data)) { + return false; + } + $data = strtr($data, '-_', '+/'); + $remainder = strlen($data) % 4; + if ($remainder) { + $data .= str_repeat('=', 4 - $remainder); + } + return base64_decode($data, true); + } +} diff --git a/tippspiel/src/Models/PushSubscription.php b/tippspiel/src/Models/PushSubscription.php new file mode 100644 index 0000000..201e2da --- /dev/null +++ b/tippspiel/src/Models/PushSubscription.php @@ -0,0 +1,177 @@ +query("SELECT 1 FROM push_subscriptions LIMIT 1"); + self::$available = true; + } catch (\PDOException $e) { + self::$available = false; + } + return self::$available; + } + + /** + * Hat der Spieler ein Abo? + * + * @param int $userId + * @return bool + */ + public static function hasSubscription($userId) { + if (!self::isAvailable()) { + return false; + } + $stmt = Database::getConnection()->prepare("SELECT COUNT(*) FROM push_subscriptions WHERE user_id = ?"); + $stmt->execute([(int)$userId]); + return (int)$stmt->fetchColumn() > 0; + } + + /** + * Legt das Abo an bzw. aktualisiert es (gleicher Endpunkt = gleiches Gerät). + * + * @param int $userId + * @param string $endpoint + * @param string $p256dh + * @param string $auth + * @return bool + */ + public static function save($userId, $endpoint, $p256dh, $auth) { + if (!self::isAvailable()) { + return false; + } + $stmt = Database::getConnection()->prepare( + "INSERT INTO push_subscriptions (user_id, endpoint, endpoint_hash, p256dh, auth, created_at, updated_at) + VALUES (:user_id, :endpoint, :endpoint_hash, :p256dh, :auth, NOW(), NOW()) + ON DUPLICATE KEY UPDATE + user_id = :user_id_update, + endpoint = :endpoint_update, + p256dh = :p256dh_update, + auth = :auth_update, + updated_at = NOW()" + ); + return $stmt->execute([ + ':user_id' => (int)$userId, + ':endpoint' => $endpoint, + ':endpoint_hash' => hash('sha256', $endpoint), + ':p256dh' => $p256dh, + ':auth' => $auth, + ':user_id_update' => (int)$userId, + ':endpoint_update' => $endpoint, + ':p256dh_update' => $p256dh, + ':auth_update' => $auth, + ]); + } + + /** + * Löscht alle Abos eines Spielers. + * + * @param int $userId + * @return int Anzahl gelöschter Zeilen + */ + public static function deleteForUser($userId) { + if (!self::isAvailable()) { + return 0; + } + $stmt = Database::getConnection()->prepare("DELETE FROM push_subscriptions WHERE user_id = ?"); + $stmt->execute([(int)$userId]); + return $stmt->rowCount(); + } + + /** + * Löscht ein Abo anhand des Endpunkts (der Push-Dienst meldet 404/410). + * + * @param string $endpoint + * @return int Anzahl gelöschter Zeilen + */ + public static function deleteByEndpoint($endpoint) { + if (!self::isAvailable()) { + return 0; + } + $stmt = Database::getConnection()->prepare("DELETE FROM push_subscriptions WHERE endpoint_hash = ?"); + $stmt->execute([hash('sha256', $endpoint)]); + return $stmt->rowCount(); + } + + /** + * Abos für eine Liste von Spielern. + * + * @param int[] $userIds + * @return array Liste von Abo-Zeilen + */ + public static function getForUsers(array $userIds) { + $userIds = array_values(array_unique(array_map('intval', $userIds))); + if (empty($userIds) || !self::isAvailable()) { + return []; + } + $placeholders = implode(',', array_fill(0, count($userIds), '?')); + $stmt = Database::getConnection()->prepare( + "SELECT * FROM push_subscriptions WHERE user_id IN ($placeholders)" + ); + $stmt->execute($userIds); + return $stmt->fetchAll(\PDO::FETCH_ASSOC); + } + + /** + * Versendet eine Erinnerung an alle Abos der genannten Spieler. + * + * Abgelaufene Abos (HTTP 404/410) werden dabei entfernt, damit die Liste + * nicht mit toten Endpunkten wächst. + * + * @param int[] $userIds + * @param array $payload Titel/Text/URL für die Benachrichtigung + * @return array ['sent' => int, 'removed' => int, 'failed' => int] + */ + public static function sendReminder(array $userIds, array $payload) { + $result = ['sent' => 0, 'removed' => 0, 'failed' => 0]; + if (!WebPush::isConfigured()) { + return $result; + } + + foreach (self::getForUsers($userIds) as $subscription) { + $send = WebPush::send($subscription, $payload); + if ($send['ok']) { + $result['sent']++; + } elseif ($send['gone']) { + self::deleteByEndpoint($subscription['endpoint']); + $result['removed']++; + } else { + $result['failed']++; + error_log(sprintf( + 'Push-Erinnerung an Spieler %d fehlgeschlagen: %s', + (int)$subscription['user_id'], + $send['error'] + )); + } + } + return $result; + } +} diff --git a/tippspiel/src/Models/Roundmail.php b/tippspiel/src/Models/Roundmail.php index bb11bdc..24bd26f 100644 --- a/tippspiel/src/Models/Roundmail.php +++ b/tippspiel/src/Models/Roundmail.php @@ -181,9 +181,11 @@ class Roundmail { } /** - * Erinnerungsmail an alle bezahlten Spieler mit fehlenden Tipps oder Joker in der ersten - * tippbaren Runde (Legacy RoundmailController::checkReminder). Verschickt nur, wenn die Runde - * in weniger als REMINDER_HOURS Stunden sperrt, und nur an Spieler mit gets_reminders = 1. + * Erinnerung an alle bezahlten Spieler mit fehlenden Tipps oder Joker in der ersten + * tippbaren Runde (Legacy RoundmailController::checkReminder). Verschickt nur, wenn die + * Runde in weniger als REMINDER_HOURS Stunden sperrt. E-Mail geht nur an Spieler mit + * gets_reminders = 1, App-Erinnerungen nur an Spieler mit gespeichertem Push-Abo – + * die beiden Kanäle sind unabhängig. * * @param string $appUrl Basis-URL für den Link in der Mail * @return string Ergebnis als Text (für das Log des Cron-Jobs) @@ -204,20 +206,42 @@ class Roundmail { $round['name'], $lockTime->format('d.m.Y H:i'), $warnFrom->format('d.m.Y H:i')); } + // Alle bezahlten, nicht gelöschten Spieler – unabhängig davon, ob sie + // Erinnerungen per E-Mail oder per App wünschen. Erst danach wird je + // Kanal gefiltert. $paid = []; foreach (User::getPaid($season['id']) as $user) { - if ($user['deleted'] === null && $user['gets_reminders'] && !empty($user['email'])) { - $paid[(int)$user['id']] = $user['email']; + if ($user['deleted'] === null) { + $paid[(int)$user['id']] = $user; } } $missing = Tipp::getMissing($round['id'], array_keys($paid)); - $userIds = array_unique(array_merge($missing['tipps'], $missing['joker'])); + $userIds = array_values(array_unique(array_map('intval', array_merge($missing['tipps'], $missing['joker'])))); + if (empty($userIds)) { + return $round['name'] . ': alle Tipps und Joker vollständig - keine Erinnerung nötig.'; + } + + // E-Mail nur an Spieler, die das ausdrücklich wünschen. $recipients = []; foreach ($userIds as $userId) { - $recipients[] = $paid[(int)$userId]; + $user = $paid[$userId]; + if ($user['gets_reminders'] && !empty($user['email'])) { + $recipients[] = $user['email']; + } } - if (empty($recipients)) { - return $round['name'] . ': alle Tipps und Joker vollständig - keine Erinnerung nötig.'; + + // App-Erinnerung ist ein eigener Kanal: Sie hängt an der zweiten + // Checkbox (gespeichertes Push-Abo), nicht an gets_reminders. + $push = PushSubscription::sendReminder($userIds, [ + 'title' => 'Hoschis Tippspiel', + 'body' => 'Es fehlen noch Tipps/Joker für ' . $round['name'] + . '. Die Runde sperrt sich am ' . $lockTime->format('d.m.Y H:i') . '.', + 'url' => rtrim($appUrl, '/') . '/index.php?page=tipps', + 'tag' => 'reminder-' . (int)$round['id'], + ]); + + if (empty($recipients) && $push['sent'] === 0 && $push['failed'] === 0 && $push['removed'] === 0) { + return $round['name'] . ': Erinnerung nötig, aber kein Empfänger aktiviert.'; } $topic = self::REMINDER_TOPIC; @@ -226,16 +250,30 @@ class Roundmail { . '
Die Runde sperrt sich: ' . $lockTime->format('d.m.Y H:i') . '

Link zum Spiel: ( Hier klicken )'; - $failed = Mailer::send($recipients, $topic, $html); - $sent = array_values(array_diff($recipients, $failed)); - if (!empty($sent)) { - self::create(0, $sent, $topic, $html, (int)$season['id']); + $failed = []; + $sent = []; + if (!empty($recipients)) { + $failed = Mailer::send($recipients, $topic, $html); + $sent = array_values(array_diff($recipients, $failed)); + if (!empty($sent)) { + self::create(0, $sent, $topic, $html, (int)$season['id']); + } } - $result = sprintf('%s: Erinnerung an %d Empfänger versendet.', $round['name'], count($sent)); + $result = !empty($recipients) + ? sprintf('%s: Erinnerung an %d Empfänger versendet.', $round['name'], count($sent)) + : sprintf('%s: nur App-Erinnerung (keine E-Mail-Empfänger).', $round['name']); if (!empty($failed)) { $result .= ' Nicht zustellbar: ' . implode(', ', $failed); } + if ($push['sent'] > 0 || $push['failed'] > 0 || $push['removed'] > 0) { + $result .= sprintf( + ' Push: %d gesendet, %d fehlgeschlagen, %d abgelaufene Abos entfernt.', + $push['sent'], + $push['failed'], + $push['removed'] + ); + } return $result; } diff --git a/tippspiel/src/Views/info/privacy.php b/tippspiel/src/Views/info/privacy.php index 6ab85c9..ad6e02c 100644 --- a/tippspiel/src/Views/info/privacy.php +++ b/tippspiel/src/Views/info/privacy.php @@ -22,12 +22,13 @@ require __DIR__ . '/../partials/header.php';
  • Bei der Teilnahme: Tipps, Joker, Antworten auf Zusatzfragen, Teilnahmestatus und Zahlungseingang pro Saison, Zeitstempel.
  • Beim Aufruf der Seiten: Server-Logfiles mit IP-Adresse, Datum und Uhrzeit, aufgerufener Adresse, HTTP-Status und Browserkennung.
  • Für E-Mails: E-Mail-Adresse und der Vermerk, ob Erinnerungen gewünscht sind.
  • +
  • Für App-Erinnerungen (optional): ein technischer Push-Endpunkt des Geräts und zwei Schlüssel, mit denen der Server die Benachrichtigung verschlüsselt. Damit ist keine Telefonnummer und kein Standort verbunden.
  • Wozu und auf welcher Grundlage

    • Durchführung des Tippspiels – Verwaltung der Teilnehmer, Ranglisten, Auszahlung des Pott: Art. 6 Abs. 1 lit. b DSGVO (Vertrag bzw. Teilnahme).
    • -
    • Erinnerungs- und Rundmails – Hinweis auf fehlende Tipps und organisatorische Mitteilungen: Art. 6 Abs. 1 lit. b DSGVO. Erinnerungen lassen sich im Profil abschalten.
    • +
    • Erinnerungs- und Rundmails – Hinweis auf fehlende Tipps und organisatorische Mitteilungen: Art. 6 Abs. 1 lit. b DSGVO. Erinnerungen lassen sich im Profil abschalten (E-Mail und App getrennt).
    • Server-Logfiles – Betriebssicherheit und Fehlersuche: Art. 6 Abs. 1 lit. f DSGVO (berechtigtes Interesse).

    Die Handynummer dient ausschließlich der kurzfristigen Kontaktaufnahme rund um die Auszahlung. IBAN und PayPal-Adresse werden nur für die Auszahlung des Pott verwendet.

    @@ -45,6 +46,7 @@ require __DIR__ . '/../partials/header.php';
  • IBAN, PayPal und Handynummer: werden gelöscht, sobald zwei Saisons lang keine Zahlung mehr erfolgt ist – sie werden nur für die Auszahlung gebraucht. Beim Löschen eines Kontos werden sie sofort entfernt.
  • Name und E-Mail-Adresse: bleiben nach einer Kontolöschung erhalten, damit die Ranglisten vergangener Saisons nachvollziehbar bleiben (Art. 6 Abs. 1 lit. f DSGVO).
  • Server-Logfiles: maximal 30 Tage.
  • +
  • Push-Abo: bis zum Abschalten in den Einstellungen. Meldet der Push-Dienst das Gerät als abgelaufen, wird der Eintrag beim nächsten Erinnerungslauf entfernt.
  • Datensicherungen: regelmäßige Kopien der Datenbank, die nach kurzer Zeit durch neue ersetzt werden.
  • diff --git a/tippspiel/src/Views/settings.php b/tippspiel/src/Views/settings.php index 797d129..c55cfb8 100644 --- a/tippspiel/src/Views/settings.php +++ b/tippspiel/src/Views/settings.php @@ -50,6 +50,15 @@ require __DIR__ . '/partials/header.php'; + + +
    @@ -62,6 +71,151 @@ require __DIR__ . '/partials/header.php'; .settings-form input[readonly] { background: #f4f4f4; color: #666; border: 1px solid #ccc; } .settings-form input.wide { width: 25em; max-width: 100%; } .settings-form button { margin-left: 164px; } +.settings-hint { margin: 0.3em 0 0 164px; font-size: 0.9em; color: #555; } +.settings-hint.is-error { color: #b00020; } +@media (max-width: 600px) { + .settings-form .form-group > label:first-child { width: auto; display: block; } + .settings-form button { margin-left: 0; } + .settings-hint { margin-left: 0; } +} + + diff --git a/tools/deploy_live.py b/tools/deploy_live.py index bae1b47..317e8d3 100755 --- a/tools/deploy_live.py +++ b/tools/deploy_live.py @@ -56,7 +56,7 @@ LOCAL_DB = { "name": "tippspiel2027", } -OPTIONAL_ENV_PREFIXES = ("APIFOOTBALL_", "SMTP_", "MAIL_") +OPTIONAL_ENV_PREFIXES = ("APIFOOTBALL_", "SMTP_", "MAIL_", "VAPID_") HTACCESS_ORDER = ( "DB_HOST", @@ -73,6 +73,9 @@ HTACCESS_ORDER = ( "SMTP_PASS", "MAIL_FROM", "MAIL_FROM_NAME", + "VAPID_PUBLIC_KEY", + "VAPID_PRIVATE_KEY", + "VAPID_SUBJECT", ) FTP_SKIP = {".DS_Store", "Thumbs.db"} @@ -725,6 +728,10 @@ def main(): log(" Hinweis: Kein APIFOOTBALL_KEY gesetzt.") if "SMTP_HOST" not in written_env: log(" Hinweis: Kein SMTP_HOST gesetzt - Mailversand bleibt deaktiviert.") + if "VAPID_PUBLIC_KEY" not in written_env: + log(" Hinweis: Kein VAPID_PUBLIC_KEY gesetzt - App-Erinnerungen bleiben deaktiviert.") + if "VAPID_PRIVATE_KEY" not in written_env: + log(" Hinweis: Kein VAPID_PRIVATE_KEY gesetzt - App-Erinnerungen bleiben deaktiviert.") if args.check: return 0 if smoke_test(args.app_url) else 1 diff --git a/tools/generate_vapid_keys.py b/tools/generate_vapid_keys.py new file mode 100644 index 0000000..8827d73 --- /dev/null +++ b/tools/generate_vapid_keys.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Erzeugt die VAPID-Schlüssel für App-Erinnerungen (Web-Push). + +Die Schlüssel gehören in docs/live_credentials.txt (gitignored). Von dort +schreibt tools/deploy_live.py sie als SetEnv in public/.htaccess. + + python3 tools/generate_vapid_keys.py # nur ausgeben + python3 tools/generate_vapid_keys.py --write # in live_credentials.txt eintragen + +Format (kompatibel zu gängigen Web-Push-Bibliotheken): + VAPID_PUBLIC_KEY base64url, unkomprimierter P-256-Punkt (65 Byte) + VAPID_PRIVATE_KEY base64url, privater Schlüssel (32 Byte) + VAPID_SUBJECT Kontakt-URI, z. B. mailto:admin@example.org +""" + +import argparse +import base64 +import os +import sys + +try: + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import ec +except ImportError: # pragma: no cover - Hinweis statt Traceback + sys.exit("Fehlt: python3-cryptography (apt install python3-cryptography)") + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +CRED_FILE = os.path.join(REPO_ROOT, "docs", "live_credentials.txt") +DEFAULT_SUBJECT = "mailto:volker.geissler@kstamedien.de" + + +def b64url(data): + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +def generate(): + key = ec.generate_private_key(ec.SECP256R1()) + scalar = key.private_numbers().private_value.to_bytes(32, "big") + point = key.public_key().public_bytes( + encoding=serialization.Encoding.X962, + format=serialization.PublicFormat.UncompressedPoint, + ) + return b64url(point), b64url(scalar) + + +def read_env(path): + values = {} + if not os.path.exists(path): + return values + with open(path, "r", encoding="utf-8") as handle: + for line in handle: + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, value = line.partition("=") + values[key.strip()] = value.strip() + return values + + +def write_env(path, values): + """Ersetzt vorhandene VAPID_*-Zeilen, hängt neue an.""" + lines = [] + if os.path.exists(path): + with open(path, "r", encoding="utf-8") as handle: + lines = handle.read().splitlines() + + replaced = set() + out = [] + for line in lines: + key = line.split("=", 1)[0].strip() if "=" in line else "" + if key in values: + out.append("%s=%s" % (key, values[key])) + replaced.add(key) + else: + out.append(line) + + if out and out[-1].strip(): + out.append("") + for key, value in values.items(): + if key not in replaced: + out.append("%s=%s" % (key, value)) + + with open(path, "w", encoding="utf-8") as handle: + handle.write("\n".join(out).rstrip("\n") + "\n") + os.chmod(path, 0o600) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--write", action="store_true", + help="Werte in docs/live_credentials.txt eintragen") + parser.add_argument("--force", action="store_true", + help="vorhandene VAPID-Schlüssel überschreiben") + parser.add_argument("--subject", default=DEFAULT_SUBJECT, + help="VAPID_SUBJECT (Default: %(default)s)") + parser.add_argument("--file", default=CRED_FILE, + help="Zieldatei für --write (Default: docs/live_credentials.txt)") + args = parser.parse_args() + + public, private = generate() + values = { + "VAPID_PUBLIC_KEY": public, + "VAPID_PRIVATE_KEY": private, + "VAPID_SUBJECT": args.subject, + } + + if args.write: + existing = read_env(args.file) + if existing.get("VAPID_PUBLIC_KEY") or existing.get("VAPID_PRIVATE_KEY"): + if not args.force: + sys.exit("VAPID-Schlüssel sind in %s schon vorhanden (--force zum Ersetzen)." % args.file) + write_env(args.file, values) + print("Schlüssel in %s eingetragen." % args.file) + print("Hinweis: Achtung, die Datei enthält Geheimnisse und ist gitignored.") + return + + print("In docs/live_credentials.txt eintragen:\n") + for key, value in values.items(): + print("%s=%s" % (key, value)) + print("\nDanach: python3 tools/deploy_live.py") + print("Achtung: Danach müssen sich alle Geräte neu anmelden (alter Schlüssel ungültig).") + + +if __name__ == "__main__": + main() diff --git a/tools/migration_push_subscriptions.sql b/tools/migration_push_subscriptions.sql new file mode 100644 index 0000000..860bc9c --- /dev/null +++ b/tools/migration_push_subscriptions.sql @@ -0,0 +1,23 @@ +-- Push-Abos für Smartphone-Erinnerungen (Feature "App-Erinnerung"). +-- Einmalig auf der Live-DB ausführen. Idempotent: ein zweiter Lauf ändert nichts. +-- +-- mysql -h -u -p < tools/migration_push_subscriptions.sql +-- +-- Pro Gerät eine Zeile; ein Spieler kann mehrere Geräte haben. Der +-- Endpunkt-Hash verhindert doppelte Zeilen, wenn dasselbe Gerät später mit +-- einem anderen Konto angemeldet wird (der Push-Dienst liefert denselben +-- Endpunkt erneut). + +CREATE TABLE IF NOT EXISTS `push_subscriptions` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `user_id` int(10) unsigned NOT NULL, + `endpoint` varchar(1000) NOT NULL, + `endpoint_hash` char(64) NOT NULL, + `p256dh` varchar(120) NOT NULL, + `auth` varchar(40) NOT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `push_subscriptions_endpoint_hash_unique` (`endpoint_hash`), + KEY `push_subscriptions_user_id_index` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/tools/schema.sql b/tools/schema.sql index 9144d1f..578606b 100644 --- a/tools/schema.sql +++ b/tools/schema.sql @@ -187,3 +187,18 @@ CREATE TABLE `password_resets` ( KEY `password_resets_email_index` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +DROP TABLE IF EXISTS `push_subscriptions`; +CREATE TABLE `push_subscriptions` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `user_id` int(10) unsigned NOT NULL, + `endpoint` varchar(1000) NOT NULL, + `endpoint_hash` char(64) NOT NULL, + `p256dh` varchar(120) NOT NULL, + `auth` varchar(40) NOT NULL, + `created_at` timestamp NULL DEFAULT NULL, + `updated_at` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `push_subscriptions_endpoint_hash_unique` (`endpoint_hash`), + KEY `push_subscriptions_user_id_index` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +