diff --git a/README.md b/README.md index 4073f4d..836295f 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,11 @@ Die Anforderungen stammen aus Zuordnung gebunden. - **Automatische Erinnerungen** 8 Tage vor Mietbeginn, 1 Tag vor Mietbeginn und 1 Tag vor Mietende. Sie entstehen aus den Buchungsdaten, passen sich bei - Terminänderungen an und entfallen bei Stornierung. + Terminänderungen an und entfallen bei Stornierung – sichtbar in der App und + optional als Web-Push auf dem Smartphone. +- **Web Push (VAPID):** In der installierten PWA kann jedes Gerät + Benachrichtigungen autorisieren. Der Admin sieht in der Benutzerverwaltung, + wer Push aktiviert hat und mit wie vielen Geräten. - **Buchungen verwalten**: anlegen, bearbeiten, per Drag & Drop verschieben, anderen Anhänger oder Mitarbeiter zuordnen, stornieren, wiederherstellen und nach Kundenname suchen. @@ -50,6 +54,9 @@ Die App ist als Progressive Web App eingerichtet: Benutzermenü, sobald der Browser die Installation anbietet. - Voraussetzung ist HTTPS (live erfüllt). Lokal funktioniert der Service Worker auch über `http://127.0.0.1`. +- **Web-Push:** Der Service Worker empfängt Benachrichtigungen. Aktiviert wird + Push in der installierten App unter **Mein Konto → App-Erinnerungen** für + jedes Gerät einzeln. Voraussetzung ist ein verknüpftes Mitarbeiterkonto. ## Technik @@ -93,20 +100,65 @@ Für `--install` werden `DIC_ADMIN_FIRST`, `DIC_ADMIN_LAST` und `DIC_ADMIN_PASSWORD` aus der Umgebung gelesen oder interaktiv abgefragt. `install.php` wird nach erfolgreicher Installation vom Server entfernt. -## Erinnerungen per E-Mail (optional) +## Erinnerungen: Push, E-Mail und Cron -Die Erinnerungen sind immer in der App sichtbar. Zusätzlich kann ein täglicher -Digest an Mitarbeiter gehen, deren Benutzerkonto eine E-Mail-Adresse hat: +Die Erinnerungen sind immer in der App sichtbar. Zusätzlich gibt es zwei +Versandkanäle: -1. In `app/config.local.php` `mail_enabled` auf `true` setzen (beim Deployment - aktuell `false`; die Datei wird aus `tools/deploy.sh` erzeugt). -2. Cron einrichten: - ``` - 0 7 * * * /usr/bin/php /pfad/zu/drink-it-cold/tools/send_reminders.php - ``` -3. Alternativ `GET /cron/reminders?token=` aufrufen. +- **Web-Push (VAPID):** In der installierten PWA aktiviert jeder Mitarbeiter + die Benachrichtigungen für sein Gerät unter **Mein Konto → + App-Erinnerungen**. Der zuständige Mitarbeiter erhält die drei Erinnerungen + auf allen Geräten, die er freigeschaltet hat. Abgelaufene Abos (HTTP 404/410) + werden automatisch entfernt. Der Admin sieht in **Verwaltung → Benutzer** die + Anzahl der aktiven Geräte pro Benutzer. Das Abo ist gerätebezogen; auf einem + geteilten Gerät wird es beim nächsten Öffnen dem aktuell angemeldeten Konto + zugeordnet. +- **E-Mail (optional):** Ein täglicher Digest geht an Mitarbeiter, deren + Benutzerkonto eine E-Mail-Adresse hat. Dafür `DIC_MAIL_ENABLED=true` beim + Deployment setzen (Standard: aus). -Jede Erinnerung wird genau einmal versendet (`reminder_mail_log`). +Der Token steht in `docs/credentials.txt` als `DIC_CRON_TOKEN`. **Externer +Cron-Endpoint** (token-geschützt, ohne Login, für cron-job.org o. ä.): + +```bash +curl -fsS "https://drink-it-cold.programmschmiede.de/cron/reminders?token=" +``` + +Beispiel crontab: täglich um 07:00 Uhr. + +``` +0 7 * * * curl -fsS "https://drink-it-cold.programmschmiede.de/cron/reminders?token=" >> /var/log/drink-it-cold-reminder.log 2>&1 +``` + +Alternativ per CLI auf dem Server: + +``` +0 7 * * * /usr/bin/php /pfad/zu/drink-it-cold/tools/send_reminders.php +``` + +Der Lauf verschickt alle heute (und bis zu 7 Tage zuvor) fälligen, noch nicht +erledigten Erinnerungen. Push und E-Mail werden getrennt dedupliziert +(`reminder_push_log`, `reminder_mail_log`), damit niemand doppelte +Benachrichtigungen bekommt. Der Endpoint antwortet mit Klartext und HTTP 200; +bei einem Fehler mit HTTP 500, sodass `curl -f` den Cron-Lauf als Fehler +erkennt. + +**VAPID-Schlüssel** liegen in `docs/credentials.txt` (gitignored) und werden +beim Deployment in `app/config.local.php` übernommen. Neu erzeugen (macht +bestehende Abos ungültig!): + +```bash +python3 tools/generate_vapid_keys.py --write --force +``` + +Die Migration `sql/migrations/002_push_subscriptions.sql` legt die nötigen +Tabellen an. Auf einer bestehenden Installation einmalig ausführen: + +```bash +php tools/migrate.php +``` + +Jede Erinnerung wird pro Kanal genau einmal versendet. ## Sicherheit @@ -117,6 +169,9 @@ Jede Erinnerung wird genau einmal versendet (`reminder_mail_log`). - „Angemeldet bleiben“ über rotierende Tokens; Passwortwechsel und Deaktivierung machen bestehende Sitzungen ungültig. - CSP ohne Inline-JavaScript, `X-Frame-Options: DENY`, `noindex`. +- Push-Endpunkte werden serverseitig auf HTTPS und gültige P-256-Schlüssel + geprüft; private/interne Ziele werden abgewiesen. Abos sind an das + Benutzerkonto gebunden und werden beim Löschen des Kontos mitgelöscht. ## Struktur @@ -125,7 +180,7 @@ app/ Bootstrap, Auth, Datenzugriff, Routing, Admin views/ HTML-Vorlagen web/ DocumentRoot: index.php, Assets sql/ Schema und Grunddaten -tools/ Deployment, lokaler Router, E-Mail-Digest +tools/ Deployment, lokaler Router, Cron, VAPID-/Push-Tests docs/ Anforderungen und Architektur ``` diff --git a/app/admin.php b/app/admin.php index 8da0477..073b100 100644 --- a/app/admin.php +++ b/app/admin.php @@ -48,7 +48,12 @@ function admin_users_list(): void FROM users u LEFT JOIN employees e ON e.id = u.employee_id ORDER BY u.last_name, u.first_name'; $users = db()->query($sql)->fetchAll(); - render_page('admin_users', ['users' => $users], 'Benutzer'); + render_page('admin_users', [ + 'users' => $users, + 'pushCounts' => push_counts_by_user(), + 'pushLastUpdate' => push_last_update_by_user(), + 'pushConfigured' => push_is_configured(), + ], 'Benutzer'); } function admin_user_form(?int $id): void @@ -209,6 +214,8 @@ function admin_user_form(?int $id): void 'values' => $values, 'errors' => $errors, 'employees' => $employees, + 'pushCount' => $editing ? push_subscription_count((int) $editing['id']) : 0, + 'pushAvailable' => push_is_configured(), ], $editing ? 'Benutzer bearbeiten' : 'Benutzer anlegen'); } @@ -377,13 +384,24 @@ function admin_trailers(): void function admin_reminders_send(): void { require_post(); - $result = reminder_send_due(); - if (!$result['enabled']) { - flash('info', 'Der E-Mail-Versand ist in der Konfiguration deaktiviert. Die Erinnerungen bleiben in der App sichtbar.'); - } elseif ($result['errors']) { - flash('error', implode(' ', $result['errors'])); + $push = push_dispatch_due(); + $mail = reminder_send_due(); + $parts = []; + if (push_is_configured()) { + $parts[] = sprintf( + 'Push: %d gesendet, %d fehlgeschlagen, %d abgelaufene Abos entfernt.', + $push['sent'], $push['failed'], $push['removed'] + ); } else { - flash('success', 'E-Mail-Versand ausgeführt: ' . $result['sent'] . ' Erinnerung(en) versendet, ' . $result['skipped'] . ' übersprungen.'); + $parts[] = 'Push ist nicht konfiguriert.'; } + if (!$mail['enabled']) { + $parts[] = 'E-Mail-Versand ist deaktiviert.'; + } elseif ($mail['errors']) { + $parts[] = 'E-Mail-Fehler: ' . implode(' ', $mail['errors']); + } else { + $parts[] = sprintf('E-Mail: %d versendet, %d übersprungen.', $mail['sent'], $mail['skipped']); + } + flash($mail['errors'] ? 'error' : 'success', implode(' ', $parts)); redirect('/reminders'); } diff --git a/app/bootstrap.php b/app/bootstrap.php index a909c24..79d36c6 100644 --- a/app/bootstrap.php +++ b/app/bootstrap.php @@ -27,8 +27,10 @@ ini_set('log_errors', '1'); require DIC_APP . '/util.php'; require DIC_APP . '/db.php'; +require DIC_APP . '/webpush.php'; require DIC_APP . '/auth.php'; require DIC_APP . '/data.php'; +require DIC_APP . '/push.php'; require DIC_APP . '/mail.php'; require DIC_APP . '/pages.php'; require DIC_APP . '/admin.php'; diff --git a/app/config.example.php b/app/config.example.php index 73746a6..aa6b853 100644 --- a/app/config.example.php +++ b/app/config.example.php @@ -12,6 +12,11 @@ return [ 'password' => 'DB_PASSWORD', 'charset' => 'utf8mb4', ], + 'push' => [ + 'public_key' => 'HIER_DEN_VAPID_PUBLIC_KEY_EINTRAGEN', + 'private_key' => 'HIER_DEN_VAPID_PRIVATE_KEY_EINTRAGEN', + 'subject' => 'mailto:drinkitcold@web.de', + ], 'app' => [ // Leer, wenn die App direkt im DocumentRoot der Subdomain liegt. 'base_path' => '', diff --git a/app/data.php b/app/data.php index eb89fa7..6afd0d8 100644 --- a/app/data.php +++ b/app/data.php @@ -290,6 +290,7 @@ function booking_update(int $id, array $data, int $userId): void if ((int) $existing['employee_id'] !== (int) $data['employee_id']) { db()->prepare('DELETE FROM reminder_done WHERE booking_id = ?')->execute([$id]); db()->prepare('DELETE FROM reminder_mail_log WHERE booking_id = ?')->execute([$id]); + db()->prepare('DELETE FROM reminder_push_log WHERE booking_id = ?')->execute([$id]); } // Abgehakte Erinnerungen gelten nur für ihr Fälligkeitsdatum. Bleibt das diff --git a/app/pages.php b/app/pages.php index 0bf3619..2e4bd2a 100644 --- a/app/pages.php +++ b/app/pages.php @@ -57,7 +57,7 @@ function page_handle(string $method, string $path): void $user = auth_user(); if ($user !== null && $user['must_change_password'] === 1 - && !in_array($path, ['/account', '/logout'], true) + && !in_array($path, ['/account', '/logout', '/push/subscribe', '/push/unsubscribe', '/push/test'], true) ) { flash('info', 'Bitte zuerst das eigene Passwort ändern.'); redirect('/account'); @@ -127,6 +127,18 @@ function page_handle(string $method, string $path): void page_reminder_done($user); return; } + if ($path === '/push/subscribe') { + page_push_subscribe($user); + return; + } + if ($path === '/push/unsubscribe') { + page_push_unsubscribe($user); + return; + } + if ($path === '/push/test') { + page_push_test($user); + return; + } if ($path === '/account') { page_account($user, $method); return; @@ -154,13 +166,41 @@ function health_check(): void function cron_reminders(): void { + header('Content-Type: text/plain; charset=utf-8'); + header('Cache-Control: no-store'); $expected = (string) config('app.cron_token', ''); $given = query_string('token'); if ($expected === '' || $given === '' || !hash_equals($expected, $given)) { - abort_page(403, 'Kein Zugriff.'); + http_response_code(403); + echo "Forbidden\n"; + exit; + } + + try { + $push = push_dispatch_due(); + $mail = reminder_send_due(); + echo 'Drink it cold – Erinnerungslauf ' . fmt_datetime(utc_now()) . "\n"; + if (!push_is_configured()) { + echo "Push: nicht konfiguriert (VAPID-Schlüssel fehlen).\n"; + } else { + echo sprintf( + "Push: %d gesendet, %d fehlgeschlagen, %d abgelaufene Abos entfernt, %d ohne Abo.\n", + $push['sent'], $push['failed'], $push['removed'], $push['skipped_no_subscription'] + ); + } + if (!$mail['enabled']) { + echo "E-Mail: deaktiviert.\n"; + } else { + echo sprintf("E-Mail: %d versendet, %d übersprungen.\n", $mail['sent'], $mail['skipped']); + foreach ($mail['errors'] as $error) { + echo 'E-Mail-Fehler: ' . $error . "\n"; + } + } + } catch (Throwable $error) { + error_log('Cron-Erinnerungen: ' . $error->getMessage()); + http_response_code(500); + echo "Fehler: Erinnerungslauf konnte nicht abgeschlossen werden.\n"; } - $result = reminder_send_due(); - json_response($result); } /* --------------------------------------------------------------- Anmeldung */ @@ -715,6 +755,7 @@ function page_reminders(array $user): void 'isAdmin' => ($user['role'] ?? '') === 'admin', 'today' => $today, 'mailEnabled' => (bool) config('app.mail_enabled', false), + 'pushEnabled' => push_is_configured(), ], 'Erinnerungen'); } @@ -785,5 +826,86 @@ function page_account(array $user, string $method): void render_page('account', [ 'errors' => $errors, 'employee' => auth_employee_id($user) > 0 ? employee_find(auth_employee_id($user)) : null, + 'pushEnabled' => push_is_configured(), + 'pushEligible' => auth_employee_id($user) > 0, + 'pushPublicKey' => WebPush::publicKey(), + 'pushDeviceCount' => push_subscription_count((int) $user['id']), + 'pushSubscribeUrl' => url('/push/subscribe'), + 'pushUnsubscribeUrl' => url('/push/unsubscribe'), + 'pushTestUrl' => url('/push/test'), ], 'Mein Konto'); } + +/* ------------------------------------------------------------- Web-Push */ + +function json_body(): array +{ + $raw = file_get_contents('php://input', false, null, 0, 20000); + if (is_string($raw) && $raw !== '') { + $data = json_decode($raw, true); + if (is_array($data)) { + return $data; + } + } + return $_POST; +} + +function page_push_subscribe(array $user): void +{ + require_post(); + $body = json_body(); + $endpoint = trim((string) ($body['endpoint'] ?? '')); + $keys = is_array($body['keys'] ?? null) ? $body['keys'] : []; + $p256dh = trim((string) ($keys['p256dh'] ?? ($body['p256dh'] ?? ''))); + $auth = trim((string) ($keys['auth'] ?? ($body['auth'] ?? ''))); + + if (!WebPush::isValidEndpoint($endpoint) || !WebPush::isValidKeyMaterial($p256dh, $auth)) { + json_response(['ok' => false, 'error' => 'Ungültiges Push-Abo.'], 422); + } + $saved = push_subscription_save( + (int) $user['id'], + $endpoint, + $p256dh, + $auth, + (string) ($_SERVER['HTTP_USER_AGENT'] ?? '') + ); + if (!$saved) { + json_response(['ok' => false, 'error' => 'Abo konnte nicht gespeichert werden.'], 500); + } + json_response(['ok' => true, 'count' => push_subscription_count((int) $user['id'])]); +} + +function page_push_unsubscribe(array $user): void +{ + require_post(); + $body = json_body(); + $endpoint = trim((string) ($body['endpoint'] ?? '')); + if ($endpoint === '') { + json_response(['ok' => false, 'error' => 'Geräte-Endpunkt fehlt.'], 422); + } + $removed = push_subscription_delete((int) $user['id'], $endpoint); + json_response(['ok' => true, 'removed' => $removed, 'count' => push_subscription_count((int) $user['id'])]); +} + +function page_push_test(array $user): void +{ + require_post(); + $body = json_body(); + $endpoint = trim((string) ($body['endpoint'] ?? '')); + $last = (int) ($_SESSION['push_test_at'] ?? 0); + if (time() - $last < 5) { + json_response(['ok' => false, 'error' => 'Bitte kurz warten, bevor erneut getestet wird.'], 429); + } + if (!push_subscription_for_user_endpoint((int) $user['id'], $endpoint)) { + json_response(['ok' => false, 'error' => 'Dieses Gerät ist nicht für Erinnerungen angemeldet.'], 409); + } + $_SESSION['push_test_at'] = time(); + $result = push_send_test((int) $user['id'], $endpoint); + if ($result['sent'] > 0) { + json_response(['ok' => true]); + } + if ($result['removed'] > 0) { + json_response(['ok' => false, 'error' => 'Das Abo ist abgelaufen. Bitte Erinnerungen aus- und wieder einschalten.'], 410); + } + json_response(['ok' => false, 'error' => 'Push-Dienst nicht erreichbar.'], 502); +} diff --git a/app/push.php b/app/push.php new file mode 100644 index 0000000..d0d6b5e --- /dev/null +++ b/app/push.php @@ -0,0 +1,294 @@ +query('SELECT 1 FROM push_subscriptions LIMIT 1'); + $available = true; + } catch (Throwable) { + $available = false; + } + return $available; +} + +function push_is_configured(): bool +{ + return push_is_available() && WebPush::isConfigured(); +} + +function push_subscription_save(int $userId, string $endpoint, string $p256dh, string $auth, string $userAgent = ''): bool +{ + if (!push_is_available() || !WebPush::isValidEndpoint($endpoint) || !WebPush::isValidKeyMaterial($p256dh, $auth)) { + return false; + } + $stmt = db()->prepare( + 'INSERT INTO push_subscriptions + (user_id, endpoint, endpoint_hash, p256dh, auth, user_agent, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + user_id = VALUES(user_id), endpoint = VALUES(endpoint), p256dh = VALUES(p256dh), + auth = VALUES(auth), user_agent = VALUES(user_agent), updated_at = VALUES(updated_at), + last_error = NULL' + ); + return $stmt->execute([ + $userId, $endpoint, hash('sha256', $endpoint), $p256dh, $auth, + mb_substr($userAgent, 0, 255), utc_now(), utc_now(), + ]); +} + +function push_subscription_delete(int $userId, string $endpoint): int +{ + if (!push_is_available() || $endpoint === '') { + return 0; + } + $stmt = db()->prepare('DELETE FROM push_subscriptions WHERE user_id = ? AND endpoint_hash = ?'); + $stmt->execute([$userId, hash('sha256', $endpoint)]); + return $stmt->rowCount(); +} + +function push_subscription_delete_all(int $userId): int +{ + if (!push_is_available()) { + return 0; + } + $stmt = db()->prepare('DELETE FROM push_subscriptions WHERE user_id = ?'); + $stmt->execute([$userId]); + return $stmt->rowCount(); +} + +function push_subscription_count(int $userId): int +{ + if (!push_is_available()) { + return 0; + } + $stmt = db()->prepare('SELECT COUNT(*) FROM push_subscriptions WHERE user_id = ?'); + $stmt->execute([$userId]); + return (int) $stmt->fetchColumn(); +} + +/** @return array user_id => Anzahl Geräte */ +function push_counts_by_user(): array +{ + if (!push_is_available()) { + return []; + } + $rows = db()->query('SELECT user_id, COUNT(*) AS devices FROM push_subscriptions GROUP BY user_id')->fetchAll(); + $out = []; + foreach ($rows as $row) { + $out[(int) $row['user_id']] = (int) $row['devices']; + } + return $out; +} + +function push_last_update_by_user(): array +{ + if (!push_is_available()) { + return []; + } + $rows = db()->query('SELECT user_id, MAX(updated_at) AS last_update FROM push_subscriptions GROUP BY user_id')->fetchAll(); + $out = []; + foreach ($rows as $row) { + $out[(int) $row['user_id']] = (string) $row['last_update']; + } + return $out; +} + +function push_subscriptions_for_user(int $userId): array +{ + if (!push_is_available()) { + return []; + } + $stmt = db()->prepare('SELECT * FROM push_subscriptions WHERE user_id = ? ORDER BY updated_at DESC'); + $stmt->execute([$userId]); + return $stmt->fetchAll(); +} + +function push_subscription_for_user_endpoint(int $userId, string $endpoint): ?array +{ + if (!push_is_available() || $endpoint === '') { + return null; + } + $stmt = db()->prepare('SELECT * FROM push_subscriptions WHERE user_id = ? AND endpoint_hash = ? LIMIT 1'); + $stmt->execute([$userId, hash('sha256', $endpoint)]); + $row = $stmt->fetch(); + return $row ?: null; +} + +function push_delete_subscription_row(int $id): void +{ + if (!push_is_available()) { + return; + } + db()->prepare('DELETE FROM push_subscriptions WHERE id = ?')->execute([$id]); +} + +function push_mark_result(int $id, bool $ok, string $error = ''): void +{ + if (!push_is_available()) { + return; + } + if ($ok) { + db()->prepare('UPDATE push_subscriptions SET last_success_at = ?, last_error = NULL WHERE id = ?') + ->execute([utc_now(), $id]); + } else { + db()->prepare('UPDATE push_subscriptions SET last_error = ? WHERE id = ?') + ->execute([mb_substr($error, 0, 255), $id]); + } +} + +/** @return array{sent:int,failed:int,removed:int} */ +function push_send_to_user(int $userId, array $payload): array +{ + $result = ['sent' => 0, 'failed' => 0, 'removed' => 0]; + if (!push_is_configured()) { + return $result; + } + foreach (push_subscriptions_for_user($userId) as $subscription) { + $send = WebPush::send($subscription, $payload); + if ($send['ok']) { + $result['sent']++; + push_mark_result((int) $subscription['id'], true); + } elseif ($send['gone']) { + $result['removed']++; + push_delete_subscription_row((int) $subscription['id']); + } else { + $result['failed']++; + push_mark_result((int) $subscription['id'], false, (string) $send['error']); + } + } + return $result; +} + +/** @return int[] Benutzer-IDs, die dem Mitarbeiter zugeordnet sind */ +function push_users_for_employee(int $employeeId): array +{ + $stmt = db()->prepare("SELECT id FROM users WHERE employee_id = ? AND status = 'active'"); + $stmt->execute([$employeeId]); + return array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN)); +} + +function push_payload_for_reminder(array $booking, array $reminder): array +{ + $body = $reminder['message'] . ' ' + . $booking['customer_name'] . ' · ' . $booking['trailer_label'] . ' · ' + . fmt_date_range($booking['start_date'], $booking['end_date']); + return [ + 'title' => 'Drink it cold – ' . $reminder['label'], + 'body' => $body, + 'url' => '/bookings/' . (int) $booking['id'], + 'tag' => 'dic-reminder-' . (int) $booking['id'] . '-' . $reminder['kind'], + 'icon' => '/assets/icons/icon-192.png', + 'badge' => '/assets/icons/icon-192.png', + ]; +} + +/** + * Verschickt alle fälligen, noch nicht erledigten Erinnerungen per Push. + * Dedupliziert über reminder_push_log (Buchung + Art + Fälligkeitsdatum). + * + * @return array{sent:int,failed:int,removed:int,skipped_done:int,skipped_user:int,skipped_no_subscription:int,logged:int} + */ +function push_dispatch_due(int $lookbackDays = 7): array +{ + $result = [ + 'sent' => 0, 'failed' => 0, 'removed' => 0, + 'skipped_done' => 0, 'skipped_user' => 0, 'skipped_no_subscription' => 0, 'logged' => 0, + ]; + if (!push_is_configured()) { + return $result; + } + + $today = today_iso(); + $from = add_days($today, -max(1, $lookbackDays)); + $rows = reminder_list($from, $today, 0, false); + if (!$rows) { + return $result; + } + + // Alte Dedupe-Einträge gelegentlich aufräumen. + db()->prepare('DELETE FROM reminder_push_log WHERE due_date < ?')->execute([add_days($today, -365)]); + + foreach ($rows as $row) { + $booking = $row['booking']; + $userIds = push_users_for_employee((int) $booking['employee_id']); + if (!$userIds) { + $result['skipped_user']++; + continue; + } + + $stmt = db()->prepare('SELECT 1 FROM reminder_push_log WHERE booking_id = ? AND kind = ? AND due_date = ?'); + $stmt->execute([(int) $booking['id'], $row['kind'], $row['due_date']]); + if ($stmt->fetchColumn()) { + $result['skipped_done']++; + continue; + } + + $payload = push_payload_for_reminder($booking, $row); + $delivered = 0; + $removed = 0; + $failed = 0; + foreach ($userIds as $userId) { + $send = push_send_to_user($userId, $payload); + $delivered += $send['sent']; + $removed += $send['removed']; + $failed += $send['failed']; + } + $result['removed'] += $removed; + $result['failed'] += $failed; + + if ($delivered === 0) { + if ($removed === 0 && $failed === 0) { + $result['skipped_no_subscription']++; + } + continue; + } + + $result['sent'] += $delivered; + db()->prepare( + 'INSERT IGNORE INTO reminder_push_log (booking_id, kind, due_date, employee_id, user_id, sent_at) + VALUES (?, ?, ?, ?, ?, ?)' + )->execute([ + (int) $booking['id'], $row['kind'], $row['due_date'], + (int) $booking['employee_id'], $userIds[0], utc_now(), + ]); + $result['logged']++; + } + + return $result; +} + +/** @return array{sent:int,failed:int,removed:int} */ +function push_send_test(int $userId, string $endpoint): array +{ + $result = ['sent' => 0, 'failed' => 0, 'removed' => 0]; + $subscription = push_subscription_for_user_endpoint($userId, $endpoint); + if (!$subscription || !push_is_configured()) { + return $result; + } + $send = WebPush::send($subscription, [ + 'title' => 'Drink it cold – Test-Erinnerung', + 'body' => 'Push-Benachrichtigungen sind auf diesem Gerät aktiv. Erinnerungen erscheinen künftig hier.', + 'url' => '/reminders', + 'tag' => 'dic-push-test', + 'icon' => '/assets/icons/icon-192.png', + 'badge' => '/assets/icons/icon-192.png', + ]); + if ($send['ok']) { + $result['sent'] = 1; + push_mark_result((int) $subscription['id'], true); + } elseif ($send['gone']) { + $result['removed'] = 1; + push_delete_subscription_row((int) $subscription['id']); + } else { + $result['failed'] = 1; + push_mark_result((int) $subscription['id'], false, (string) $send['error']); + } + return $result; +} diff --git a/app/util.php b/app/util.php index 5061ce3..ed2fd71 100644 --- a/app/util.php +++ b/app/util.php @@ -89,7 +89,7 @@ function url(string $path = '/'): string } /** Cache-Buster: bei Änderungen an app.css/app.js erhöhen. */ -const DIC_ASSET_VERSION = '2'; +const DIC_ASSET_VERSION = '3'; function asset(string $path): string { diff --git a/app/webpush.php b/app/webpush.php new file mode 100644 index 0000000..b015b59 --- /dev/null +++ b/app/webpush.php @@ -0,0 +1,441 @@ + 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) + * @param string|null $salt Nur für Tests: feste Salt statt Zufall + * @param \OpenSSLAsymmetricKey|resource|null $ephemeral Nur für Tests: festes Server-Schlüsselpaar + * @return string Binärer Request-Body + */ + public static function encrypt($payload, $p256dh, $auth, $salt = null, $ephemeral = null) { + $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 + if ($ephemeral === null) { + $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 = $salt === null ? random_bytes(16) : $salt; + if (strlen($salt) !== 16) { + throw new \InvalidArgumentException('Salt muss 16 Byte lang sein.'); + } + $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; + // RFC 8188, Abschnitt 2.1: AAD ist ausdrücklich leer. Der Header wird + // nur übertragen, nicht authentifiziert. + $cipher = openssl_encrypt($plain, 'aes-128-gcm', $cek, OPENSSL_RAW_DATA, $nonce, $tag, '', 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/docs/architecture.md b/docs/architecture.md index dc55c8b..bf71b90 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -32,6 +32,8 @@ Browser | `bookings` | Buchung inkl. Zeitraum, Beträge, Rechnungsflag, Art, Kundendaten, Status | | `reminder_done` | Abgehakte Erinnerung, Schlüssel `(booking_id, kind, due_date)` | | `reminder_mail_log` | Versandprotokoll, verhindert doppelte E-Mails | +| `push_subscriptions` | Web-Push-Abos pro Gerät (Endpoint-Hash, p256dh, auth, letzter Erfolg/Fehler) | +| `reminder_push_log` | Dedupe für versendete Push-Erinnerungen (`booking_id`, `kind`, `due_date`) | | `auth_tokens` | Remember-Me-Tokens (Selector + Hash, rotierend) | | `login_attempts` | Ratenbegrenzung des Logins | | `schema_migrations` | Installationsversion | @@ -127,6 +129,37 @@ sind die primäre Anzeige und funktionieren ohne Mailversand. | 9. Übersicht | Dashboard mit Auslastung, freien Anhängern, Übergaben/Rücknahmen, Erinnerungen | | Benutzerverwaltung tippspiel2027 | Admin-only, Vorname/Nachname/Passwort, keine Selbstregistrierung | +## Web Push (VAPID) + +- **Aktivierung:** Nur in der installierten PWA (`display-mode: standalone` + bzw. `navigator.standalone`). Die Karte **Mein Konto → App-Erinnerungen** + fragt die Benachrichtigungs-Erlaubnis ab, erzeugt mit + `pushManager.subscribe()` ein Abo und schickt es an + `POST /push/subscribe`. `POST /push/unsubscribe` entfernt genau dieses Gerät; + `POST /push/test` sendet eine Test-Erinnerung an das Gerät. +- **Voraussetzung:** Der Benutzer muss mit einem Mitarbeiterkonto verknüpft + sein, sonst gibt es keine zuzuordnenden Erinnerungen. Der Admin sieht in + **Verwaltung → Benutzer** die Anzahl aktiver Geräte und in der + Benutzerbearbeitung den Status. +- **Gerätebezug:** Ein Gerät hat ein Abo; beim Öffnen der App wird es dem + aktuell angemeldeten Konto zugeordnet (ein Endpunkt-Hash = eine Zeile). Auf + einem geteilten Gerät ersetzt das neue Konto damit das alte. +- **Versand:** `push_dispatch_due()` liest alle heute (plus 7 Tage Rückstand) + fälligen, offenen Erinnerungen, ermittelt den zuständigen Mitarbeiter und + dessen verknüpften Benutzer und sendet an alle dessen Abos. Erfolgreiche + Erinnerungen werden in `reminder_push_log` dedupliziert; 404/410 entfernt das + tote Abo. Titel, Text, URL und Tag kommen aus + `push_payload_for_reminder()`. +- **Verschlüsselung:** `app/webpush.php` implementiert RFC 8291 + (`aes128gcm`) und RFC 8292 (VAPID/ES256) ohne Composer, nur mit + openssl/curl. `tools/test_webpush_rfc8291.php` prüft den RFC-Testvektor. +- **Schlüssel:** `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, `VAPID_SUBJECT` in + `docs/credentials.txt`; `tools/deploy.sh` schreibt sie in die + Server-Konfiguration. Ein Schlüsselwechsel macht bestehende Abos ungültig. +- **Cron:** `GET /cron/reminders?token=` (ohne Login) ruft + Push- und E-Mail-Versand auf und antwortet mit Klartext. Alternativ + `php tools/send_reminders.php`. + ## PWA - **Manifest:** `web/manifest.webmanifest` (Name, Theme `#196abc`, Icons in @@ -139,7 +172,9 @@ sind die primäre Anzeige und funktionieren ohne Mailversand. - Authentifizierte HTML-Seiten, Formulare und API-Antworten werden bewusst nicht gecacht. Die App zeigt online immer den aktuellen Buchungsstand. - Der Service Worker wird in `web/assets/app.js` registriert; die Icons liegen - als PNG (192/512, maskable) und SVG vor, dazu ein Apple-Touch-Icon. + als PNG (192/512, maskable) und SVG vor, dazu ein Apple-Touch-Icon. Er + empfängt außerdem Web-Push-Nachrichten und öffnet beim Klick die passende + Buchung. - Bei Änderungen an CSS/JS `DIC_ASSET_VERSION` in `app/util.php` und `VERSION` in `web/sw.js` erhöhen. Der Deploy lädt die Dateien per FTP hoch; Apache liefert `sw.js` mit `no-cache` aus. diff --git a/sql/migrations/002_push_subscriptions.sql b/sql/migrations/002_push_subscriptions.sql new file mode 100644 index 0000000..7ba87f1 --- /dev/null +++ b/sql/migrations/002_push_subscriptions.sql @@ -0,0 +1,34 @@ +-- Web-Push-Abos (VAPID) und Versandprotokoll für Kühlwagen-Erinnerungen. +-- Idempotent: kann auch auf einer bestehenden Installation ausgeführt werden. + +CREATE TABLE IF NOT EXISTS push_subscriptions ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + user_id BIGINT UNSIGNED NOT NULL, + endpoint VARCHAR(1000) NOT NULL, + endpoint_hash CHAR(64) NOT NULL, + p256dh VARCHAR(120) NOT NULL, + auth VARCHAR(40) NOT NULL, + user_agent VARCHAR(255) NULL, + created_at DATETIME NOT NULL, + updated_at DATETIME NOT NULL, + last_success_at DATETIME NULL, + last_error VARCHAR(255) NULL, + PRIMARY KEY (id), + UNIQUE KEY uq_push_endpoint (endpoint_hash), + KEY idx_push_user (user_id, updated_at), + CONSTRAINT fk_push_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS reminder_push_log ( + booking_id BIGINT UNSIGNED NOT NULL, + kind ENUM('start_8', 'start_1', 'end_1') NOT NULL, + due_date DATE NOT NULL, + employee_id BIGINT UNSIGNED NULL, + user_id BIGINT UNSIGNED NULL, + sent_at DATETIME NOT NULL, + PRIMARY KEY (booking_id, kind, due_date), + KEY idx_reminder_push_due (due_date), + CONSTRAINT fk_reminder_push_booking FOREIGN KEY (booking_id) REFERENCES bookings (id) ON DELETE CASCADE, + CONSTRAINT fk_reminder_push_employee FOREIGN KEY (employee_id) REFERENCES employees (id) ON DELETE SET NULL, + CONSTRAINT fk_reminder_push_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/sql/schema.sql b/sql/schema.sql index f8ef064..a145ee3 100644 --- a/sql/schema.sql +++ b/sql/schema.sql @@ -161,3 +161,37 @@ INSERT IGNORE INTO employees (name, sort_order, created_at) VALUES ('M. Schmitz', 30, UTC_TIMESTAMP()); INSERT IGNORE INTO schema_migrations (version, applied_at) VALUES (1, UTC_TIMESTAMP()); +INSERT IGNORE INTO schema_migrations (version, applied_at) VALUES (2, UTC_TIMESTAMP()); + +-- Web-Push-Abos (VAPID) und Versandprotokoll für Erinnerungen. +CREATE TABLE IF NOT EXISTS push_subscriptions ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + user_id BIGINT UNSIGNED NOT NULL, + endpoint VARCHAR(1000) NOT NULL, + endpoint_hash CHAR(64) NOT NULL, + p256dh VARCHAR(120) NOT NULL, + auth VARCHAR(40) NOT NULL, + user_agent VARCHAR(255) NULL, + created_at DATETIME NOT NULL, + updated_at DATETIME NOT NULL, + last_success_at DATETIME NULL, + last_error VARCHAR(255) NULL, + PRIMARY KEY (id), + UNIQUE KEY uq_push_endpoint (endpoint_hash), + KEY idx_push_user (user_id, updated_at), + CONSTRAINT fk_push_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS reminder_push_log ( + booking_id BIGINT UNSIGNED NOT NULL, + kind ENUM('start_8', 'start_1', 'end_1') NOT NULL, + due_date DATE NOT NULL, + employee_id BIGINT UNSIGNED NULL, + user_id BIGINT UNSIGNED NULL, + sent_at DATETIME NOT NULL, + PRIMARY KEY (booking_id, kind, due_date), + KEY idx_reminder_push_due (due_date), + CONSTRAINT fk_reminder_push_booking FOREIGN KEY (booking_id) REFERENCES bookings (id) ON DELETE CASCADE, + CONSTRAINT fk_reminder_push_employee FOREIGN KEY (employee_id) REFERENCES employees (id) ON DELETE SET NULL, + CONSTRAINT fk_reminder_push_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/tools/deploy.sh b/tools/deploy.sh index f23a1d6..cf3640b 100755 --- a/tools/deploy.sh +++ b/tools/deploy.sh @@ -44,6 +44,10 @@ FTP_URL="$(cred FTP_URL)" FTP_USER="$(cred FTP_USER)" FTP_PASSWORD="$(cred FTP_PASSWORD)" DB_HOST="$(cred DB_HOST)" +VAPID_PUBLIC_KEY="$(cred VAPID_PUBLIC_KEY)" +VAPID_PRIVATE_KEY="$(cred VAPID_PRIVATE_KEY)" +VAPID_SUBJECT="$(cred VAPID_SUBJECT)" +CRON_TOKEN="$(cred DIC_CRON_TOKEN)" DB_NAME="$(cred DB_NAME)" DB_USER="$(cred DB_USER)" DB_PASSWORD="$(cred DB_PASSWORD)" @@ -87,6 +91,7 @@ make_config() { DIC_INSTALL_TOKEN="$token" DIC_CRON_TOKEN="$cron_token" DIC_PUBLIC_URL="$PUBLIC_URL" \ DIC_MAIL_ENABLED="${DIC_MAIL_ENABLED:-false}" \ DIC_MAIL_FROM="${DIC_MAIL_FROM:-Drink it cold }" \ + VAPID_PUBLIC_KEY="$VAPID_PUBLIC_KEY" VAPID_PRIVATE_KEY="$VAPID_PRIVATE_KEY" VAPID_SUBJECT="$VAPID_SUBJECT" \ DB_HOST="${DB_HOST:-localhost}" DB_NAME="$DB_NAME" DB_USER="$DB_USER" DB_PASSWORD="$DB_PASSWORD" \ python3 - "$TMP_DIR/config.local.php" <<'PY' import os @@ -101,6 +106,11 @@ config = f""" [ + 'public_key' => {php(os.environ.get('VAPID_PUBLIC_KEY', ''))}, + 'private_key' => {php(os.environ.get('VAPID_PRIVATE_KEY', ''))}, + 'subject' => {php(os.environ.get('VAPID_SUBJECT') or 'mailto:drinkitcold@web.de')}, + ], 'db' => [ 'host' => {php(os.environ.get('DB_HOST') or 'localhost')}, 'port' => 3306, @@ -148,7 +158,7 @@ upload_tree() { do_sync() { local token cron_token token="$(openssl rand -hex 24)" - cron_token="$(openssl rand -hex 24)" + cron_token="${CRON_TOKEN:-$(openssl rand -hex 24)}" make_config "$token" "$cron_token" echo "Lade Anwendung hoch …" @@ -158,6 +168,7 @@ do_sync() { upload_tree "$REPO_ROOT/web" "" echo "Lade Cron-Skript und Konfiguration hoch …" ftp_put "$REPO_ROOT/tools/send_reminders.php" "tools/send_reminders.php" + ftp_put "$REPO_ROOT/tools/migrate.php" "tools/migrate.php" ftp_put "$REPO_ROOT/tools/.htaccess" "tools/.htaccess" ftp_put "$TMP_DIR/config.local.php" "app/config.local.php" ftp_chmod 600 "app/config.local.php" @@ -166,6 +177,9 @@ do_sync() { printf '' > "$TMP_DIR/.gitkeep" ftp_put "$TMP_DIR/.gitkeep" "storage/logs/.gitkeep" ftp_put "$REPO_ROOT/storage/.htaccess" "storage/.htaccess" + if [[ -z "$VAPID_PUBLIC_KEY" || -z "$VAPID_PRIVATE_KEY" ]]; then + echo "WARNUNG: VAPID-Schlüssel fehlen in docs/credentials.txt – Push bleibt deaktiviert." >&2 + fi echo "Sync fertig. Install-Token liegt nur auf dem Server." } diff --git a/tools/generate_vapid_keys.py b/tools/generate_vapid_keys.py new file mode 100755 index 0000000..130d96e --- /dev/null +++ b/tools/generate_vapid_keys.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Erzeugt VAPID-Schlüssel für Web-Push und schreibt sie in docs/credentials.txt. + + python3 tools/generate_vapid_keys.py --write + python3 tools/generate_vapid_keys.py --write --force --subject mailto:name@example.de + +Vorhandene Schlüssel nur mit --force ersetzen: Ein Wechsel macht alle +bestehenden Push-Abos ungültig. +""" + +import argparse +import base64 +import os +import sys + +try: + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import ec +except ImportError: + 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", "credentials.txt") +DEFAULT_SUBJECT = "mailto:drinkitcold@web.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): + 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="in docs/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") + 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")) and 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) + return + + for key, value in values.items(): + print("%s=%s" % (key, value)) + + +if __name__ == "__main__": + main() diff --git a/tools/migrate.php b/tools/migrate.php new file mode 100644 index 0000000..3106a46 --- /dev/null +++ b/tools/migrate.php @@ -0,0 +1,57 @@ +exec( + 'CREATE TABLE IF NOT EXISTS schema_migrations ( + version INT UNSIGNED NOT NULL, + applied_at DATETIME NOT NULL, + PRIMARY KEY (version) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci' +); + +$applied = array_map('intval', $pdo->query('SELECT version FROM schema_migrations')->fetchAll(PDO::FETCH_COLUMN)); +$files = glob(__DIR__ . '/../sql/migrations/*.sql') ?: []; +sort($files, SORT_STRING); + +$count = 0; +foreach ($files as $file) { + $name = basename($file); + if (!preg_match('/^(\d+)_/', $name, $match)) { + fwrite(STDERR, "Überspringe Datei ohne Versionsnummer: $name\n"); + continue; + } + $version = (int) $match[1]; + if (in_array($version, $applied, true)) { + continue; + } + + echo "Migration $version: $name\n"; + $sql = preg_replace('/^\s*--.*$/m', '', (string) file_get_contents($file)) ?? ''; + foreach (array_filter(array_map('trim', explode(';', $sql))) as $statement) { + if ($statement !== '') { + $pdo->exec($statement); + } + } + $pdo->prepare('INSERT IGNORE INTO schema_migrations (version, applied_at) VALUES (?, ?)') + ->execute([$version, utc_now()]); + $count++; +} + +echo $count === 0 ? "Keine ausstehenden Migrationen.\n" : "$count Migration(en) angewendet.\n"; diff --git a/tools/send_reminders.php b/tools/send_reminders.php index 390c96d..67d5ea9 100644 --- a/tools/send_reminders.php +++ b/tools/send_reminders.php @@ -2,14 +2,13 @@ declare(strict_types=1); /** - * Täglicher Erinnerungs-Digest per E-Mail. + * Täglicher Erinnerungslauf (Push + optional E-Mail). * * Cron-Beispiel (täglich 07:00): * 0 7 * * * /usr/bin/php /pfad/zu/drink-it-cold/tools/send_reminders.php * - * Voraussetzung: app.mail_enabled = true und Benutzer mit E-Mail-Adresse, - * die mit einem Mitarbeiterkonto verknüpft sind. Die In-App-Erinnerungen - * funktionieren unabhängig davon. + * Alternativ von außen über den token-geschützten Endpoint: + * https://…/cron/reminders?token= */ require __DIR__ . '/../app/bootstrap.php'; @@ -21,22 +20,28 @@ foreach ($argv ?? [] as $arg) { } } -$result = reminder_send_due($lookback); +$push = push_dispatch_due($lookback); +$mail = reminder_send_due($lookback); -if (!$result['enabled']) { - fwrite(STDOUT, "E-Mail-Versand ist deaktiviert (app.mail_enabled = false).\n"); - exit(0); +if (!push_is_configured()) { + fwrite(STDOUT, "Push: nicht konfiguriert (VAPID-Schlüssel fehlen).\n"); +} else { + fwrite(STDOUT, sprintf( + "Push: %d gesendet, %d fehlgeschlagen, %d abgelaufene Abos entfernt, %d ohne Abo.\n", + $push['sent'], $push['failed'], $push['removed'], $push['skipped_no_subscription'] + )); } -fwrite(STDOUT, sprintf( - "Erinnerungen: %d versendet, %d übersprungen.\n", - $result['sent'], - $result['skipped'] -)); -foreach ($result['details'] as $detail) { - fwrite(STDOUT, ' ' . $detail . "\n"); +if (!$mail['enabled']) { + fwrite(STDOUT, "E-Mail: deaktiviert.\n"); +} else { + fwrite(STDOUT, sprintf("E-Mail: %d versendet, %d übersprungen.\n", $mail['sent'], $mail['skipped'])); + foreach ($mail['details'] as $detail) { + fwrite(STDOUT, ' ' . $detail . "\n"); + } + foreach ($mail['errors'] as $error) { + fwrite(STDERR, ' Fehler: ' . $error . "\n"); + } } -foreach ($result['errors'] as $error) { - fwrite(STDERR, ' Fehler: ' . $error . "\n"); -} -exit($result['errors'] ? 1 : 0); + +exit(($mail['errors'] || $push['failed'] > 0) ? 1 : 0); diff --git a/tools/test_webpush_rfc8291.php b/tools/test_webpush_rfc8291.php new file mode 100644 index 0000000..1f59969 --- /dev/null +++ b/tools/test_webpush_rfc8291.php @@ -0,0 +1,55 @@ +setAccessible(true); +$ephemeral = openssl_pkey_get_private($method->invoke(null, $asPrivate, $asPublic)); +if (!$ephemeral) { + fwrite(STDERR, "Der Server-Schlüssel aus dem RFC ließ sich nicht laden.\n"); + exit(1); +} + +$body = WebPush::encrypt($plaintext, test_b64u_encode($uaPublic), test_b64u_encode($auth), $salt, $ephemeral); +if (test_b64u_encode($body) === $expected) { + echo "OK: RFC-8291-Testvektor stimmt.\n"; + exit(0); +} + +fwrite(STDERR, "FEHLER: Der verschlüsselte Body weicht vom RFC-8291-Testvektor ab.\n"); +exit(1); diff --git a/views/account.php b/views/account.php index 2725535..6338cad 100644 --- a/views/account.php +++ b/views/account.php @@ -1,6 +1,13 @@
@@ -66,3 +73,58 @@ $mustChange = (int) ($user['must_change_password'] ?? 0) === 1;
+ + +
+
+
+

App-Erinnerungen

+

Übergaben und Rücknahmen direkt aufs Smartphone – 8 Tage vor Mietbeginn, 1 Tag vor Mietbeginn und 1 Tag vor Mietende.

+
+ + 0 ? $pushDeviceCount . ' Gerät' . ($pushDeviceCount === 1 ? '' : 'e') . ' aktiv' : 'nicht aktiviert' ?> + +
+ + +
+ +
Kein Mitarbeiterkonto verknüpft. Push-Erinnerungen werden über das zuständige Mitarbeiterkonto zugeordnet. Ein Administrator kann das in der Benutzerverwaltung nachholen.
+
+ +
+ +
Push ist noch nicht eingerichtet. Der Administrator muss zuerst die VAPID-Schlüssel hinterlegen.
+
+ +
+ +
+ Nur in der installierten App verfügbar. +

Installiere Drink it cold über das Browser-Menü bzw. auf dem iPhone über „Zum Home-Bildschirm“. Danach kannst du hier Push-Erinnerungen für dieses Gerät aktivieren.

+
+
+ + + +
diff --git a/views/admin_user_form.php b/views/admin_user_form.php index 7dd36b0..8db43c9 100644 --- a/views/admin_user_form.php +++ b/views/admin_user_form.php @@ -3,6 +3,8 @@ /** @var array $values */ /** @var array $errors */ /** @var array $employees */ +/** @var int $pushCount */ +/** @var bool $pushAvailable */ $isSelf = $editing !== null && (int) $editing['id'] === (int) auth_user()['id']; $fieldError = static fn (string $key): string => (string) ($errors[$key] ?? ''); ?> @@ -130,6 +132,17 @@ $fieldError = static fn (string $key): string => (string) ($errors[$key] ?? '');
Nachname
Rolle
Status
+ +
App-Erinnerungen
+ 0): ?> + Gerät + + nicht aktiviert + + Push nicht konfiguriert + +
+
diff --git a/views/admin_users.php b/views/admin_users.php index 96f42ba..278c795 100644 --- a/views/admin_users.php +++ b/views/admin_users.php @@ -1,5 +1,8 @@
@@ -30,6 +33,7 @@ Rolle Mitarbeiterkonto Status + App-Erinnerungen Letzte Anmeldung Aktionen @@ -47,6 +51,19 @@ + + + 0): ?> + + + Gerät + + + nicht aktiviert + + – + + Bearbeiten diff --git a/views/reminders.php b/views/reminders.php index eaf9291..4656b33 100644 --- a/views/reminders.php +++ b/views/reminders.php @@ -9,6 +9,7 @@ /** @var bool $isAdmin */ /** @var string $today */ /** @var bool $mailEnabled */ +/** @var bool $pushEnabled */ $rangeUrl = static function (string $r) use ($employeeFilter, $showDone): string { $params = ['range' => $r]; if ($employeeFilter > 0) { @@ -33,10 +34,10 @@ foreach ($rows as $row) {

Automatisch aus Mietbeginn und Mietende berechnet – für den zuständigen Mitarbeiter.

- -
+ + - +
Kalender diff --git a/web/assets/app.css b/web/assets/app.css index 34a1d0c..c744c8e 100644 --- a/web/assets/app.css +++ b/web/assets/app.css @@ -59,6 +59,7 @@ } *, *::before, *::after { box-sizing: border-box; } +[hidden] { display: none !important; } html { -webkit-text-size-adjust: 100%; } body { margin: 0; @@ -724,6 +725,28 @@ a .ico, button .ico { pointer-events: none; } /* --------------------------------------------------------------- Account */ .account-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; align-items: start; } +.ico--inline { display: inline-block; width: 18px; height: 18px; vertical-align: -3px; margin-right: 2px; } +.push-card { margin-top: 16px; } +.push-browser-hint { + display: flex; align-items: flex-start; gap: 11px; + padding: 13px 15px; border-radius: 12px; + background: var(--ice-50); border: 1px solid var(--ice-200); color: var(--brand-800); + font-size: .86rem; +} +.push-browser-hint .ico { width: 20px; height: 20px; margin-top: 1px; } +.push-browser-hint p { color: var(--ink-2); margin-top: 3px; } +.push-controls { display: grid; gap: 12px; } +.push-controls[hidden] { display: none; } +.push-toggle { width: 100%; padding: 14px 15px; } +.push-toggle > span { display: flex; flex-direction: column; gap: 2px; } +.push-toggle strong { font-size: .9rem; color: var(--ink); } +.push-toggle small { font-size: .77rem; color: var(--muted); font-weight: 500; } +.push-status { min-height: 0; font-size: .82rem; color: var(--muted); } +.push-status:empty { display: none; } +.push-status.is-error { color: #9e2f25; font-weight: 600; } +.push-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } +.push-actions .muted { font-size: .76rem; } + /* --------------------------------------------------------------- Auth */ .auth-page { background: var(--white); margin: 0; } .auth-shell { display: grid; grid-template-columns: 1.05fr .95fr; min-height: 100vh; } diff --git a/web/assets/app.js b/web/assets/app.js index 042606a..8c9db37 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -524,3 +524,209 @@ }); }); })(); + +/* ------------------------------------------------------- Web-Push (VAPID) */ +(() => { + const card = document.querySelector('[data-push]'); + if (!card) return; + + const toggle = card.querySelector('[data-push-toggle]'); + const controls = card.querySelector('[data-push-controls]'); + const browserHint = card.querySelector('[data-push-browser-hint]'); + const statusEl = card.querySelector('[data-push-status]'); + const testButton = card.querySelector('[data-push-test]'); + const countEl = card.querySelector('[data-push-count]'); + const vapidKey = card.dataset.vapidKey || ''; + const subscribeUrl = card.dataset.subscribeUrl; + const unsubscribeUrl = card.dataset.unsubscribeUrl; + const testUrl = card.dataset.testUrl; + const csrf = document.querySelector('meta[name="csrf-token"]')?.content || ''; + if (!toggle || !controls || !statusEl || !testButton || !subscribeUrl || !unsubscribeUrl || !testUrl) { + return; + } + + const standalone = window.matchMedia('(display-mode: standalone)').matches + || window.navigator.standalone === true; + const supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window; + + const setStatus = (text, isError = false) => { + statusEl.textContent = text || ''; + statusEl.classList.toggle('is-error', isError); + }; + + const updateCount = (count) => { + if (!countEl || typeof count !== 'number') return; + countEl.textContent = count > 0 + ? `${count} Gerät${count === 1 ? '' : 'e'} aktiv` + : 'nicht aktiviert'; + countEl.classList.toggle('pill--green', count > 0); + countEl.classList.toggle('pill--grey', count === 0); + }; + + const postJson = async (url, payload) => { + const response = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json;charset=UTF-8', + 'Accept': 'application/json', + 'X-Requested-With': 'fetch', + 'X-CSRF-Token': csrf + }, + credentials: 'same-origin', + body: JSON.stringify(payload || {}) + }); + const type = response.headers.get('content-type') || ''; + if (!type.includes('application/json')) { + throw new Error('Die Sitzung ist abgelaufen. Bitte die Seite neu laden.'); + } + const data = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(data.error || `Server meldet HTTP ${response.status}.`); + } + return data; + }; + + const keyToBytes = (base64url) => { + const padding = '='.repeat((4 - (base64url.length % 4)) % 4); + const base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/'); + const raw = window.atob(base64); + const bytes = new Uint8Array(raw.length); + for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i); + return bytes; + }; + + if (!supported || !vapidKey) { + if (browserHint) { + browserHint.innerHTML = '
Push wird von diesem Browser nicht unterstützt.

Bitte die installierte App auf einem aktuellen Android-Gerät oder iPhone verwenden.

'; + } + return; + } + + if (!standalone) { + controls.hidden = true; + if (browserHint) browserHint.hidden = false; + return; + } + + if (browserHint) browserHint.hidden = true; + controls.hidden = false; + + let registration = null; + + const getRegistration = async () => { + if (!registration) { + registration = await navigator.serviceWorker.ready; + } + return registration; + }; + + const getSubscription = async () => { + const reg = await getRegistration(); + return reg.pushManager.getSubscription(); + }; + + const subscribe = async () => { + const reg = await getRegistration(); + let subscription = await reg.pushManager.getSubscription(); + if (subscription) return subscription; + + try { + subscription = await reg.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: keyToBytes(vapidKey) + }); + } catch (error) { + if (error && error.name === 'InvalidStateError') { + const old = await reg.pushManager.getSubscription(); + if (old) await old.unsubscribe(); + subscription = await reg.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: keyToBytes(vapidKey) + }); + } else { + throw error; + } + } + return subscription; + }; + + const syncExisting = async () => { + const subscription = await getSubscription(); + toggle.checked = !!subscription; + testButton.hidden = !subscription; + if (subscription) { + // Gerät beim Öffnen dem aktuell angemeldeten Konto zuordnen. + try { + const data = await postJson(subscribeUrl, subscription.toJSON()); + updateCount(data.count); + } catch (error) { + setStatus('Das bestehende Abo konnte nicht zugeordnet werden. Bitte aus- und wieder einschalten.', true); + } + } + }; + + if (Notification.permission === 'denied') { + toggle.disabled = true; + setStatus('Benachrichtigungen sind für diese App blockiert. Bitte in den Systemeinstellungen erlauben.', true); + return; + } + + syncExisting().catch(() => { + setStatus('Push konnte nicht initialisiert werden.', true); + }); + + toggle.addEventListener('change', async () => { + toggle.disabled = true; + testButton.disabled = true; + setStatus(toggle.checked ? 'Erinnerungen werden aktiviert …' : 'Erinnerungen werden deaktiviert …'); + try { + if (toggle.checked) { + const permission = await Notification.requestPermission(); + if (permission !== 'granted') { + throw new Error('Benachrichtigungen wurden nicht erlaubt. Bitte in den Einstellungen freigeben.'); + } + const subscription = await subscribe(); + const data = await postJson(subscribeUrl, subscription.toJSON()); + updateCount(data.count); + testButton.hidden = false; + setStatus('Aktiviert. Erinnerungen erscheinen jetzt auf diesem Gerät.'); + } else { + const subscription = await getSubscription(); + const endpoint = subscription ? subscription.endpoint : ''; + if (subscription) { + await subscription.unsubscribe(); + } + const data = await postJson(unsubscribeUrl, { endpoint }); + updateCount(data.count); + testButton.hidden = true; + setStatus('Erinnerungen sind auf diesem Gerät ausgeschaltet.'); + } + } catch (error) { + const subscription = await getSubscription().catch(() => null); + toggle.checked = !!subscription; + testButton.hidden = !subscription; + setStatus(error && error.message ? error.message : 'Aktion fehlgeschlagen.', true); + } finally { + toggle.disabled = false; + testButton.disabled = false; + } + }); + + testButton.addEventListener('click', async () => { + if (testButton.disabled) return; + testButton.disabled = true; + setStatus('Test-Erinnerung wird gesendet …'); + try { + const subscription = await getSubscription(); + if (!subscription) { + throw new Error('Dieses Gerät ist noch nicht angemeldet.'); + } + await postJson(testUrl, { endpoint: subscription.endpoint }); + setStatus('Test-Erinnerung gesendet. Sie sollte jetzt erscheinen.'); + } catch (error) { + setStatus(error && error.message ? error.message : 'Test fehlgeschlagen.', true); + } finally { + testButton.disabled = false; + } + }); +})(); diff --git a/web/sw.js b/web/sw.js index 5671747..39a0199 100644 --- a/web/sw.js +++ b/web/sw.js @@ -6,7 +6,7 @@ * zwischengespeichert, damit niemand veraltete Buchungen sieht. */ -const VERSION = 'dic-v2'; +const VERSION = 'dic-v3'; const CACHE = VERSION; const BASE = new URL(self.registration.scope).pathname.replace(/\/$/, ''); @@ -138,3 +138,52 @@ self.addEventListener('fetch', (event) => { event.respondWith(cacheFirst(event, request)); } }); + +/* ---------------------------------------------------------- Web-Push */ +self.addEventListener('push', (event) => { + let data = {}; + try { + data = event.data ? event.data.json() : {}; + } catch (error) { + data = {}; + } + + const title = data.title || 'Drink it cold – Erinnerung'; + const target = data.url || `${BASE}/reminders`; + const options = { + body: data.body || '', + icon: data.icon || `${BASE}/assets/icons/icon-192.png`, + badge: data.badge || `${BASE}/assets/icons/icon-192.png`, + tag: data.tag || 'dic-reminder', + lang: 'de', + data: { url: target }, + timestamp: Date.now() + }; + + event.waitUntil(self.registration.showNotification(title, options)); +}); + +self.addEventListener('notificationclick', (event) => { + event.notification.close(); + const raw = (event.notification.data && event.notification.data.url) || `${BASE}/reminders`; + let target; + try { + const url = new URL(raw, self.location.origin); + target = url.origin === self.location.origin ? url.href : `${self.location.origin}${BASE}/reminders`; + } catch (error) { + target = `${self.location.origin}${BASE}/reminders`; + } + + event.waitUntil( + self.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 self.clients.openWindow(target); + }) + ); +});