PWA-Benachrichtigungen mit VAPID und Testnachricht ergänzen
This commit is contained in:
parent
7e589b58cd
commit
920b8e895a
13 changed files with 1207 additions and 2 deletions
|
|
@ -8,3 +8,8 @@ DB_PORT=3306
|
|||
DB_DATABASE=motorradig
|
||||
DB_USERNAME=mig_user
|
||||
DB_PASSWORD=mig_password
|
||||
|
||||
# Web-Push / PWA-Benachrichtigungen (Schlüssel mit tools/generate_vapid_keys.py erzeugen)
|
||||
VAPID_PUBLIC_KEY=
|
||||
VAPID_PRIVATE_KEY=
|
||||
VAPID_SUBJECT=mailto:ig@fischergruppe.de
|
||||
|
|
|
|||
|
|
@ -28,6 +28,21 @@ Geschützte Dateien unter `/img_storage/` werden bewusst nicht gecacht.
|
|||
Bei Änderungen an den vorgeladenen Dateien `CACHE_VERSION` in `public/sw.js`
|
||||
erhöhen, damit alte Caches ersetzt werden.
|
||||
|
||||
### Push-Benachrichtigungen (VAPID)
|
||||
|
||||
Auf dem Smartphone können Benutzer in ihren eigenen Profil-Einstellungen
|
||||
Benachrichtigungen für neue Touren und Absagen aktivieren. Der Versand läuft
|
||||
über Web-Push mit VAPID (RFC 8291/8292) und benötigt:
|
||||
|
||||
- `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` und `VAPID_SUBJECT` in `.env`
|
||||
(erzeugen mit `python3 tools/generate_vapid_keys.py --write`),
|
||||
- die Tabelle `push_subscriptions` (wird von `bin/migrate.php` angelegt),
|
||||
- die Push-Handler im Service Worker (`public/sw.js`).
|
||||
|
||||
In den Einstellungen gibt es zusätzlich einen Button **„Test-Nachricht senden“**,
|
||||
der eine Nachricht an genau das aktuell verwendete Gerät schickt. Damit lässt
|
||||
sich das VAPID-Signalling direkt prüfen, ohne auf eine neue Tour zu warten.
|
||||
|
||||
## Struktur
|
||||
|
||||
```
|
||||
|
|
|
|||
|
|
@ -121,6 +121,26 @@ if (!tableExists($pdo, 'password_resets')) {
|
|||
$out("Tabelle 'password_resets' existiert bereits (übersprungen)");
|
||||
}
|
||||
|
||||
// Tabelle für Web-Push-Abos (PWA-Benachrichtigungen)
|
||||
if (!tableExists($pdo, 'push_subscriptions')) {
|
||||
$pdo->exec('CREATE TABLE `push_subscriptions` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`user_id` bigint(20) 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 COLLATE=utf8mb4_unicode_ci;');
|
||||
$out("Tabelle 'push_subscriptions' angelegt");
|
||||
} else {
|
||||
$out("Tabelle 'push_subscriptions' existiert bereits (übersprungen)");
|
||||
}
|
||||
|
||||
// Unbenutzte Tabellen entfernen
|
||||
foreach (['migrations', 'failed_jobs', 'galleries', 'gallery_items'] as $table) {
|
||||
if (tableExists($pdo, $table)) {
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@
|
|||
*/
|
||||
'use strict';
|
||||
|
||||
var CACHE_VERSION = 'motorradig-static-v1';
|
||||
var CACHE_VERSION = 'motorradig-static-v2';
|
||||
var OFFLINE_URL = '/offline.html';
|
||||
|
||||
var PRECACHE_URLS = [
|
||||
|
|
@ -166,3 +166,54 @@ self.addEventListener('fetch', function (event) {
|
|||
event.respondWith(staleWhileRevalidate(request, event));
|
||||
}
|
||||
});
|
||||
|
||||
// Benachrichtigungen per Web-Push (VAPID). Die Nutzlast kommt als JSON
|
||||
// (Titel, Text, URL, optional Tag) vom Server.
|
||||
self.addEventListener('push', function (event) {
|
||||
var data = {};
|
||||
|
||||
try {
|
||||
data = event.data ? event.data.json() : {};
|
||||
} catch (error) {
|
||||
data = {};
|
||||
}
|
||||
|
||||
var title = data.title || 'Motorrad-IG';
|
||||
var options = {
|
||||
body: data.body || '',
|
||||
icon: '/pwa-192x192.png',
|
||||
badge: '/pwa-192x192.png',
|
||||
tag: data.tag || undefined,
|
||||
data: { url: data.url || '/' }
|
||||
};
|
||||
|
||||
event.waitUntil(self.registration.showNotification(title, options));
|
||||
});
|
||||
|
||||
self.addEventListener('notificationclick', function (event) {
|
||||
event.notification.close();
|
||||
|
||||
var target = (event.notification.data && event.notification.data.url) || '/';
|
||||
|
||||
event.waitUntil(
|
||||
clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) {
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
var client = list[i];
|
||||
|
||||
if (new URL(client.url).origin !== self.location.origin) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return client.focus().then(function () {
|
||||
if ('navigate' in client) {
|
||||
return client.navigate(target);
|
||||
}
|
||||
|
||||
return client;
|
||||
});
|
||||
}
|
||||
|
||||
return clients.openWindow(target);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
|
|
|||
104
motorradig/src/Controllers/PushController.php
Normal file
104
motorradig/src/Controllers/PushController.php
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Auth;
|
||||
use App\Core\WebPush;
|
||||
use App\Models\PushSubscription;
|
||||
|
||||
/**
|
||||
* Endpunkte für Web-Push-Abos (JSON).
|
||||
*
|
||||
* Wird von der PWA-Einstellungsseite auf dem Smartphone aufgerufen. Die
|
||||
* CSRF-Prüfung erfolgt im Router; das Token kommt per X-CSRF-Token-Header.
|
||||
*/
|
||||
class PushController
|
||||
{
|
||||
public function subscribe(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$endpoint = (string) ($input['endpoint'] ?? '');
|
||||
$keys = is_array($input['keys'] ?? null) ? $input['keys'] : [];
|
||||
$p256dh = (string) ($keys['p256dh'] ?? '');
|
||||
$auth = (string) ($keys['auth'] ?? '');
|
||||
|
||||
if (!WebPush::isConfigured() || !PushSubscription::isAvailable()) {
|
||||
$this->respond(['error' => 'App-Benachrichtigungen sind derzeit nicht verfügbar.'], 503);
|
||||
}
|
||||
|
||||
if (!WebPush::isValidEndpoint($endpoint) || !WebPush::isValidKeyMaterial($p256dh, $auth)) {
|
||||
$this->respond(['error' => 'Ungültiges Abo.'], 400);
|
||||
}
|
||||
|
||||
PushSubscription::save((int) Auth::id(), $endpoint, $p256dh, $auth);
|
||||
|
||||
$this->respond(['ok' => true]);
|
||||
}
|
||||
|
||||
public function unsubscribe(): void
|
||||
{
|
||||
PushSubscription::deleteForUser((int) Auth::id());
|
||||
|
||||
$this->respond(['ok' => true]);
|
||||
}
|
||||
|
||||
public function test(): void
|
||||
{
|
||||
$input = $this->input();
|
||||
$endpoint = (string) ($input['endpoint'] ?? '');
|
||||
|
||||
if (!WebPush::isConfigured() || !PushSubscription::isAvailable()) {
|
||||
$this->respond(['error' => 'App-Benachrichtigungen sind derzeit nicht verfügbar.'], 503);
|
||||
}
|
||||
|
||||
$now = time();
|
||||
|
||||
if (isset($_SESSION['push_test_at']) && $now - (int) $_SESSION['push_test_at'] < 5) {
|
||||
$this->respond(['error' => 'Bitte kurz warten, dann erneut testen.'], 429);
|
||||
}
|
||||
|
||||
$_SESSION['push_test_at'] = $now;
|
||||
|
||||
$subscription = PushSubscription::findForUserAndEndpoint((int) Auth::id(), $endpoint);
|
||||
|
||||
if ($subscription === null) {
|
||||
$this->respond(['error' => 'Dieses Gerät ist nicht als Abo hinterlegt. Bitte den Haken aus- und wieder einschalten.'], 409);
|
||||
}
|
||||
|
||||
$send = WebPush::send($subscription, [
|
||||
'title' => 'Motorrad-IG',
|
||||
'body' => 'Testnachricht: Push-Benachrichtigungen funktionieren.',
|
||||
'url' => '/',
|
||||
'tag' => 'push-test',
|
||||
]);
|
||||
|
||||
if ($send['ok']) {
|
||||
$this->respond(['ok' => true, 'sent' => 1]);
|
||||
}
|
||||
|
||||
if ($send['gone']) {
|
||||
PushSubscription::deleteByEndpoint($endpoint);
|
||||
$this->respond(['error' => 'Das Abo ist abgelaufen und wurde entfernt. Bitte den Haken aus- und wieder einschalten.'], 410);
|
||||
}
|
||||
|
||||
$this->respond(['error' => 'Push-Dienst nicht erreichbar: ' . $send['error']], 502);
|
||||
}
|
||||
|
||||
private function input(): array
|
||||
{
|
||||
$raw = file_get_contents('php://input');
|
||||
$data = $raw === false ? null : json_decode($raw, true);
|
||||
|
||||
return is_array($data) ? $data : [];
|
||||
}
|
||||
|
||||
private function respond(array $data, int $status = 200): void
|
||||
{
|
||||
http_response_code($status);
|
||||
header('Content-Type: application/json; charset=UTF-8');
|
||||
echo json_encode($data, JSON_UNESCAPED_UNICODE);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ namespace App\Controllers;
|
|||
use App\Core\Auth;
|
||||
use App\Core\Image;
|
||||
use App\Models\Booking;
|
||||
use App\Models\PushSubscription;
|
||||
use App\Models\Tour;
|
||||
use App\Models\TourRoom;
|
||||
use App\Models\User;
|
||||
|
|
@ -217,9 +218,38 @@ class TourController
|
|||
}
|
||||
}
|
||||
|
||||
$this->notifyEvent($tour, false);
|
||||
|
||||
redirect('/tour');
|
||||
}
|
||||
|
||||
/** Informiert alle Push-Abos über eine neue oder abgesagte Tour. */
|
||||
private function notifyEvent(Tour $tour, bool $cancelled): void
|
||||
{
|
||||
try {
|
||||
PushSubscription::sendToAll($cancelled
|
||||
? [
|
||||
'title' => 'Tour abgesagt: ' . $tour->name,
|
||||
'body' => 'Der Termin am ' . german_date($tour->start) . ' fällt aus.',
|
||||
'url' => '/tour/' . $tour->id,
|
||||
'tag' => 'tour-' . $tour->id . '-cancelled',
|
||||
]
|
||||
: [
|
||||
'title' => 'Neue Tour: ' . $tour->name,
|
||||
'body' => german_date($tour->start) . ' – jetzt im Tourenplan ansehen.',
|
||||
'url' => '/tour/' . $tour->id,
|
||||
'tag' => 'tour-' . $tour->id,
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
app_log('error', 'Push-Benachrichtigung zur Tour fehlgeschlagen', [
|
||||
'tour_id' => (int) $tour->id,
|
||||
'cancelled' => $cancelled,
|
||||
'exception' => $e::class,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function show(string $id): void
|
||||
{
|
||||
$tour = Tour::find((int) $id);
|
||||
|
|
@ -326,6 +356,7 @@ class TourController
|
|||
}
|
||||
|
||||
$current = Auth::user();
|
||||
$wasCancelled = (bool) $tour->is_cancelled;
|
||||
|
||||
validate([
|
||||
'tour_id' => 'required',
|
||||
|
|
@ -369,6 +400,10 @@ class TourController
|
|||
$tour->updated_at = now();
|
||||
$tour->save();
|
||||
|
||||
if ($tour->is_cancelled && !$wasCancelled) {
|
||||
$this->notifyEvent($tour, true);
|
||||
}
|
||||
|
||||
redirect('/tour/' . $tourId . '/edit');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ namespace App\Controllers;
|
|||
|
||||
use App\Core\Auth;
|
||||
use App\Core\Image;
|
||||
use App\Core\WebPush;
|
||||
use App\Models\PushSubscription;
|
||||
use App\Models\User;
|
||||
|
||||
class UserController
|
||||
|
|
@ -81,7 +83,13 @@ class UserController
|
|||
redirect('/member');
|
||||
}
|
||||
|
||||
view('users.edit', ['user' => $user]);
|
||||
$pushAvailable = PushSubscription::isAvailable() && WebPush::isConfigured();
|
||||
|
||||
view('users.edit', [
|
||||
'user' => $user,
|
||||
'pushPublicKey' => $pushAvailable ? WebPush::publicKey() : null,
|
||||
'pushEnabled' => $pushAvailable && PushSubscription::hasSubscription((int) $user->id),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(string $id): void
|
||||
|
|
|
|||
448
motorradig/src/Core/WebPush.php
Normal file
448
motorradig/src/Core/WebPush.php
Normal file
|
|
@ -0,0 +1,448 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
/**
|
||||
* Web-Push ohne externe Abhängigkeiten.
|
||||
*
|
||||
* Verschlüsselung nach RFC 8291 (Content-Encoding `aes128gcm`) und
|
||||
* Authentifizierung nach RFC 8292 (VAPID, JWT mit ES256). Beides baut nur auf
|
||||
* Erweiterungen auf, die auf dem Shared Host vorhanden sind (openssl, curl).
|
||||
*
|
||||
* Konfiguration über Umgebungsvariablen in der .env-Datei:
|
||||
* VAPID_PUBLIC_KEY base64url des unkomprimierten P-256-Punkts (65 Byte)
|
||||
* VAPID_PRIVATE_KEY base64url des privaten Schlüssels (32 Byte)
|
||||
* VAPID_SUBJECT Kontakt-URI, z. B. mailto:ig@fischergruppe.de
|
||||
*
|
||||
* Erzeugt werden die Schlüssel mit tools/generate_vapid_keys.py.
|
||||
*/
|
||||
class WebPush {
|
||||
|
||||
/** Wie lange der Push-Dienst eine Nachricht aufbewahren darf, wenn das Gerät offline ist. */
|
||||
const TTL = 86400;
|
||||
|
||||
/** Maximale Größe eines verschlüsselten Datensatzes (RFC 8188). */
|
||||
const RECORD_SIZE = 4096;
|
||||
|
||||
/** Timeout für den Versand (einzelnes Abo, nicht der ganze Lauf) */
|
||||
const TIMEOUT = 10;
|
||||
|
||||
/**
|
||||
* Sind alle für den Versand nötigen Werte konfiguriert?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function isConfigured() {
|
||||
$public = self::publicKey();
|
||||
if ($public === null) {
|
||||
return false;
|
||||
}
|
||||
$point = self::base64UrlDecode($public);
|
||||
return $point !== false && strlen($point) === 65 && self::privateKey() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Öffentlicher VAPID-Schlüssel als base64url (für `applicationServerKey` im Browser).
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public static function publicKey() {
|
||||
$key = getenv('VAPID_PUBLIC_KEY');
|
||||
if ($key === false || trim($key) === '') {
|
||||
return null;
|
||||
}
|
||||
return trim($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kontakt-URI für den VAPID-Claim `sub`. Fällt auf APP_URL zurück.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function subject() {
|
||||
$subject = getenv('VAPID_SUBJECT');
|
||||
if ($subject !== false && trim($subject) !== '') {
|
||||
return trim($subject);
|
||||
}
|
||||
$appUrl = getenv('APP_URL');
|
||||
if ($appUrl !== false && trim($appUrl) !== '') {
|
||||
return trim($appUrl);
|
||||
}
|
||||
return 'https://hoschis-tippspiel.de';
|
||||
}
|
||||
|
||||
/**
|
||||
* Privaten Schlüssel laden. Unterstützt das gespeicherte Format
|
||||
* (base64url des 32-Byte-Skalars) und direkt hinterlegtes PEM.
|
||||
*
|
||||
* @return \OpenSSLAsymmetricKey|resource|null
|
||||
*/
|
||||
private static function privateKey() {
|
||||
$raw = getenv('VAPID_PRIVATE_KEY');
|
||||
if ($raw === false || trim($raw) === '') {
|
||||
return null;
|
||||
}
|
||||
$raw = trim($raw);
|
||||
|
||||
if (strpos($raw, 'BEGIN') !== false) {
|
||||
$key = openssl_pkey_get_private(str_replace('\n', "\n", $raw));
|
||||
return $key === false ? null : $key;
|
||||
}
|
||||
|
||||
$scalar = self::base64UrlDecode($raw);
|
||||
$public = self::publicKey();
|
||||
if ($scalar === false || strlen($scalar) !== 32 || $public === null) {
|
||||
return null;
|
||||
}
|
||||
$point = self::base64UrlDecode($public);
|
||||
if ($point === false || strlen($point) !== 65) {
|
||||
return null;
|
||||
}
|
||||
$key = openssl_pkey_get_private(self::privateKeyPem($scalar, $point));
|
||||
return $key === false ? null : $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft einen Push-Endpunkt: HTTPS, plausibler Host, kein internes Ziel.
|
||||
*
|
||||
* @param string $endpoint
|
||||
* @return bool
|
||||
*/
|
||||
public static function isValidEndpoint($endpoint) {
|
||||
if (!is_string($endpoint) || strlen($endpoint) > 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);
|
||||
}
|
||||
}
|
||||
169
motorradig/src/Models/PushSubscription.php
Normal file
169
motorradig/src/Models/PushSubscription.php
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Core\WebPush;
|
||||
|
||||
/**
|
||||
* Push-Abos für Smartphone-Benachrichtigungen (Web-Push mit VAPID).
|
||||
*
|
||||
* Ein Benutzer kann auf mehreren Geräten Abos haben (Handy, Tablet). Die
|
||||
* Checkbox in den Einstellungen ist der Ein/Aus-Schalter für das Konto:
|
||||
* Abhaken löscht alle Abos. Ein Abo wird über den Endpunkt-Hash identifiziert,
|
||||
* damit dasselbe Gerät nicht doppelt eingetragen wird.
|
||||
*
|
||||
* Fehlt die Tabelle (z. B. direkt nach einem Deploy vor der Migration),
|
||||
* liefern die Methoden leere Ergebnisse, statt die Seite mit einem Fehler
|
||||
* abzubrechen.
|
||||
*/
|
||||
class PushSubscription
|
||||
{
|
||||
/** Ergebnis von isAvailable(), damit die fehlende Tabelle nur einmal geprüft wird. */
|
||||
private static ?bool $available = null;
|
||||
|
||||
public static function isAvailable(): bool
|
||||
{
|
||||
if (self::$available !== null) {
|
||||
return self::$available;
|
||||
}
|
||||
|
||||
try {
|
||||
db()->fetchOne('SELECT 1 FROM `push_subscriptions` LIMIT 1');
|
||||
self::$available = true;
|
||||
} catch (\PDOException $e) {
|
||||
self::$available = false;
|
||||
}
|
||||
|
||||
return self::$available;
|
||||
}
|
||||
|
||||
public static function hasSubscription(int $userId): bool
|
||||
{
|
||||
if (!self::isAvailable()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$row = db()->fetchOne(
|
||||
'SELECT COUNT(*) AS `count` FROM `push_subscriptions` WHERE user_id = ?',
|
||||
[$userId]
|
||||
);
|
||||
|
||||
return $row !== null && (int) $row['count'] > 0;
|
||||
}
|
||||
|
||||
/** Legt das Abo an bzw. aktualisiert es (gleicher Endpunkt = gleiches Gerät). */
|
||||
public static function save(int $userId, string $endpoint, string $p256dh, string $auth): bool
|
||||
{
|
||||
if (!self::isAvailable()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
db()->execute(
|
||||
'INSERT INTO `push_subscriptions`
|
||||
(user_id, endpoint, endpoint_hash, p256dh, auth, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
user_id = ?, endpoint = ?, p256dh = ?, auth = ?, updated_at = ?',
|
||||
[
|
||||
$userId,
|
||||
$endpoint,
|
||||
hash('sha256', $endpoint),
|
||||
$p256dh,
|
||||
$auth,
|
||||
now(),
|
||||
now(),
|
||||
$userId,
|
||||
$endpoint,
|
||||
$p256dh,
|
||||
$auth,
|
||||
now(),
|
||||
]
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Ein bestimmtes Gerät eines Benutzers (für den Test-Knopf). */
|
||||
public static function findForUserAndEndpoint(int $userId, string $endpoint): ?array
|
||||
{
|
||||
if (!self::isAvailable() || $endpoint === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return db()->fetchOne(
|
||||
'SELECT * FROM `push_subscriptions` WHERE user_id = ? AND endpoint_hash = ?',
|
||||
[$userId, hash('sha256', $endpoint)]
|
||||
);
|
||||
}
|
||||
|
||||
/** Löscht alle Abos eines Benutzers. */
|
||||
public static function deleteForUser(int $userId): int
|
||||
{
|
||||
if (!self::isAvailable()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return db()->execute('DELETE FROM `push_subscriptions` WHERE user_id = ?', [$userId]);
|
||||
}
|
||||
|
||||
/** Löscht ein Abo anhand des Endpunkts (der Push-Dienst meldet 404/410). */
|
||||
public static function deleteByEndpoint(string $endpoint): int
|
||||
{
|
||||
if (!self::isAvailable()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return db()->execute(
|
||||
'DELETE FROM `push_subscriptions` WHERE endpoint_hash = ?',
|
||||
[hash('sha256', $endpoint)]
|
||||
);
|
||||
}
|
||||
|
||||
/** Alle Abos (für Event-Benachrichtigungen an alle angemeldeten Geräte). */
|
||||
public static function all(): array
|
||||
{
|
||||
if (!self::isAvailable()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return db()->fetchAll('SELECT * FROM `push_subscriptions`');
|
||||
}
|
||||
|
||||
/**
|
||||
* Versendet eine Nachricht an alle Abos.
|
||||
*
|
||||
* Abgelaufene Abos (HTTP 404/410) werden entfernt, damit die Liste nicht
|
||||
* mit toten Endpunkten wächst.
|
||||
*
|
||||
* @return array{sent: int, removed: int, failed: int}
|
||||
*/
|
||||
public static function sendToAll(array $payload): array
|
||||
{
|
||||
$result = ['sent' => 0, 'removed' => 0, 'failed' => 0];
|
||||
|
||||
if (!WebPush::isConfigured()) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
foreach (self::all() as $subscription) {
|
||||
$send = WebPush::send($subscription, $payload);
|
||||
|
||||
if ($send['ok']) {
|
||||
$result['sent']++;
|
||||
} elseif ($send['gone']) {
|
||||
self::deleteByEndpoint((string) $subscription['endpoint']);
|
||||
$result['removed']++;
|
||||
} else {
|
||||
$result['failed']++;
|
||||
app_log('warning', 'Push-Benachrichtigung fehlgeschlagen', [
|
||||
'user_id' => (int) $subscription['user_id'],
|
||||
'error' => $send['error'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
|
@ -10,6 +10,7 @@ use App\Controllers\TourController;
|
|||
use App\Controllers\GalleryController;
|
||||
use App\Controllers\AdminController;
|
||||
use App\Controllers\ImageController;
|
||||
use App\Controllers\PushController;
|
||||
|
||||
$router = new Router();
|
||||
|
||||
|
|
@ -92,4 +93,9 @@ $router->post('/password/email', [AuthController::class, 'sendResetLinkEmail']);
|
|||
$router->get('/password/reset/{token}', [AuthController::class, 'showResetForm']);
|
||||
$router->post('/password/reset', [AuthController::class, 'resetPassword']);
|
||||
|
||||
// Web-Push (PWA-Benachrichtigungen, nur auf dem Smartphone sichtbar)
|
||||
$router->post('/push/subscribe', [PushController::class, 'subscribe'], true);
|
||||
$router->post('/push/unsubscribe', [PushController::class, 'unsubscribe'], true);
|
||||
$router->post('/push/test', [PushController::class, 'test'], true);
|
||||
|
||||
$router->run();
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
<?php
|
||||
$current = auth_check() ? user() : null;
|
||||
$flashError = flash_pull('error');
|
||||
$pushPublicKey = $pushPublicKey ?? null;
|
||||
$pushEnabled = $pushEnabled ?? false;
|
||||
$isOwnProfile = $current !== null && (int) $current->id === (int) $user->id;
|
||||
?>
|
||||
|
||||
<div class="container text-center text-light mt-5">
|
||||
|
|
@ -79,6 +82,216 @@
|
|||
<form id="destroy-user-form" action="/admin/destroy_user/<?= e($user->id) ?>" method="POST" style="display:none;">
|
||||
<?= csrf_field() ?>
|
||||
</form>
|
||||
|
||||
<?php if ($isOwnProfile && $pushPublicKey !== null): ?>
|
||||
<div class="card text-dark mt-4 text-left" id="push-settings" hidden
|
||||
data-vapid-key="<?= e($pushPublicKey) ?>"
|
||||
data-push-enabled="<?= $pushEnabled ? '1' : '0' ?>">
|
||||
<div class="card-body">
|
||||
<h2 class="h5 mb-2">Benachrichtigungen (App)</h2>
|
||||
<p class="text-muted mb-3">
|
||||
Diese Einstellung ist nur auf dem Smartphone sichtbar. Du erhältst eine
|
||||
Nachricht, wenn eine neue Tour veröffentlicht oder eine Tour abgesagt wird.
|
||||
</p>
|
||||
|
||||
<div class="form-check mb-2">
|
||||
<input class="form-check-input" type="checkbox" id="push-events" <?= $pushEnabled ? 'checked' : '' ?>>
|
||||
<label class="form-check-label" for="push-events">
|
||||
Bei neuen Touren und Absagen benachrichtigen
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p class="small text-muted mb-2" id="push-hint"></p>
|
||||
|
||||
<button type="button" class="btn btn-sm btn-outline-primary" id="push-test" <?= $pushEnabled ? '' : 'hidden' ?>>
|
||||
Test-Nachricht senden
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var group = document.getElementById('push-settings');
|
||||
var box = document.getElementById('push-events');
|
||||
var hint = document.getElementById('push-hint');
|
||||
var testButton = document.getElementById('push-test');
|
||||
|
||||
if (!group || !box || !hint || !testButton) {
|
||||
return;
|
||||
}
|
||||
|
||||
var vapidKey = group.getAttribute('data-vapid-key') || '';
|
||||
var ua = navigator.userAgent || '';
|
||||
var isMobile = /Android|iPhone|iPad|iPod|Mobile|Windows Phone/i.test(ua)
|
||||
|| (/Macintosh/i.test(ua) && navigator.maxTouchPoints > 1);
|
||||
var isStandalone = window.matchMedia('(display-mode: standalone)').matches
|
||||
|| window.navigator.standalone === true;
|
||||
var supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;
|
||||
|
||||
// Nur auf Smartphones (bzw. in der installierten App) anzeigen.
|
||||
if ((!isMobile && !isStandalone) || !supported || !vapidKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
group.hidden = false;
|
||||
|
||||
function setHint(text, isError) {
|
||||
hint.textContent = text || '';
|
||||
hint.className = 'small mb-2 ' + (isError ? 'text-danger' : 'text-muted');
|
||||
}
|
||||
|
||||
function syncTestButton() {
|
||||
testButton.hidden = !box.checked;
|
||||
}
|
||||
|
||||
function keyToBytes(base64url) {
|
||||
var padding = new Array((4 - (base64url.length % 4)) % 4 + 1).join('=');
|
||||
var base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
var raw = window.atob(base64);
|
||||
var bytes = new Uint8Array(raw.length);
|
||||
|
||||
for (var i = 0; i < raw.length; i++) {
|
||||
bytes[i] = raw.charCodeAt(i);
|
||||
}
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function post(path, payload) {
|
||||
var token = document.querySelector('meta[name="csrf-token"]');
|
||||
var headers = {'Content-Type': 'application/json'};
|
||||
|
||||
if (token) {
|
||||
headers['X-CSRF-Token'] = token.getAttribute('content');
|
||||
}
|
||||
|
||||
return fetch(path, {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify(payload || {})
|
||||
}).then(function (response) {
|
||||
return response.json().catch(function () {
|
||||
return {};
|
||||
}).then(function (data) {
|
||||
if (!response.ok) {
|
||||
throw new Error(data && data.error ? data.error : 'Server meldet HTTP ' + response.status + '.');
|
||||
}
|
||||
|
||||
return data;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function createSubscription(registration) {
|
||||
return registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: keyToBytes(vapidKey)
|
||||
});
|
||||
}
|
||||
|
||||
function subscribe() {
|
||||
return navigator.serviceWorker.ready.then(function (registration) {
|
||||
return registration.pushManager.getSubscription().then(function (existing) {
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
return createSubscription(registration).catch(function (error) {
|
||||
// Abo mit einem alten VAPID-Schlüssel: erneuern.
|
||||
if (error && error.name === 'InvalidStateError') {
|
||||
return registration.pushManager.getSubscription().then(function (old) {
|
||||
return old ? old.unsubscribe() : null;
|
||||
}).then(function () {
|
||||
return createSubscription(registration);
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
box.addEventListener('change', function () {
|
||||
if (box.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
box.disabled = true;
|
||||
setHint('');
|
||||
|
||||
var action;
|
||||
|
||||
if (box.checked) {
|
||||
action = Notification.requestPermission().then(function (permission) {
|
||||
if (permission !== 'granted') {
|
||||
throw new Error('Benachrichtigungen sind blockiert. Bitte in den Systemeinstellungen erlauben.');
|
||||
}
|
||||
|
||||
return subscribe();
|
||||
}).then(function (subscription) {
|
||||
if (!subscription) {
|
||||
throw new Error('Abo konnte nicht angelegt werden.');
|
||||
}
|
||||
|
||||
return post('/push/subscribe', subscription.toJSON());
|
||||
}).then(function () {
|
||||
setHint('Benachrichtigungen sind jetzt auf diesem Gerät aktiv.');
|
||||
});
|
||||
} else {
|
||||
action = navigator.serviceWorker.ready.then(function (registration) {
|
||||
return registration.pushManager.getSubscription();
|
||||
}).then(function (subscription) {
|
||||
return subscription ? subscription.unsubscribe() : null;
|
||||
}).then(function () {
|
||||
return post('/push/unsubscribe', {});
|
||||
}).then(function () {
|
||||
setHint('Benachrichtigungen sind ausgeschaltet.');
|
||||
});
|
||||
}
|
||||
|
||||
action.catch(function (error) {
|
||||
if (box.checked) {
|
||||
box.checked = false;
|
||||
}
|
||||
|
||||
setHint(error && error.message ? error.message : 'Aktion fehlgeschlagen.', true);
|
||||
}).then(function () {
|
||||
box.disabled = false;
|
||||
syncTestButton();
|
||||
});
|
||||
});
|
||||
|
||||
testButton.addEventListener('click', function () {
|
||||
if (testButton.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
testButton.disabled = true;
|
||||
setHint('Test-Nachricht wird gesendet …');
|
||||
|
||||
navigator.serviceWorker.ready.then(function (registration) {
|
||||
return registration.pushManager.getSubscription();
|
||||
}).then(function (subscription) {
|
||||
if (!subscription) {
|
||||
throw new Error('Dieses Gerät hat noch kein Abo. Bitte den Haken aus- und wieder einschalten.');
|
||||
}
|
||||
|
||||
return post('/push/test', {endpoint: subscription.endpoint});
|
||||
}).then(function () {
|
||||
setHint('Test-Nachricht gesendet. Sie sollte jetzt auf diesem Gerät erscheinen.');
|
||||
}).catch(function (error) {
|
||||
setHint(error && error.message ? error.message : 'Test fehlgeschlagen.', true);
|
||||
}).then(function () {
|
||||
testButton.disabled = false;
|
||||
});
|
||||
});
|
||||
|
||||
syncTestButton();
|
||||
})();
|
||||
</script>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
|
|
|
|||
116
tools/generate_vapid_keys.py
Normal file
116
tools/generate_vapid_keys.py
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Erzeugt VAPID-Schlüssel für PWA-Benachrichtigungen (Web-Push).
|
||||
|
||||
Die Schlüssel werden in die .env-Datei von motorradig/ geschrieben (nicht im Git).
|
||||
Auf dem Live-Server müssen sie ebenfalls in /motorradig/.env stehen.
|
||||
|
||||
python3 tools/generate_vapid_keys.py # nur ausgeben
|
||||
python3 tools/generate_vapid_keys.py --write # in motorradig/.env eintragen
|
||||
"""
|
||||
|
||||
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__)))
|
||||
ENV_FILE = os.path.join(REPO_ROOT, "motorradig", ".env")
|
||||
DEFAULT_SUBJECT = "mailto:ig@fischergruppe.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 motorradig/.env 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)")
|
||||
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(ENV_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)." % ENV_FILE)
|
||||
|
||||
write_env(ENV_FILE, values)
|
||||
print("Schlüssel in %s eingetragen." % ENV_FILE)
|
||||
print("Hinweis: Die Datei enthält Geheimnisse und ist gitignored.")
|
||||
return
|
||||
|
||||
print("In motorradig/.env eintragen:\n")
|
||||
for key, value in values.items():
|
||||
print("%s=%s" % (key, value))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -84,6 +84,21 @@ MIGRATIONS = [
|
|||
KEY `password_resets_email_index` (`email`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci''',
|
||||
|
||||
# Web-Push-Abos für PWA-Benachrichtigungen
|
||||
'''CREATE TABLE IF NOT EXISTS `push_subscriptions` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`user_id` bigint(20) 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 COLLATE=utf8mb4_unicode_ci''',
|
||||
|
||||
# Annahme-Felder für bestehende Installationen ergänzen (idempotent)
|
||||
'''SET @has_accepted_at := (SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'membership_applications' AND COLUMN_NAME = 'accepted_at');
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue