Web-Push mit VAPID und Erinnerungs-Endpoint
This commit is contained in:
parent
67a1614081
commit
b50267e4f0
24 changed files with 1703 additions and 50 deletions
|
|
@ -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');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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' => '',
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
130
app/pages.php
130
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);
|
||||
}
|
||||
|
|
|
|||
294
app/push.php
Normal file
294
app/push.php
Normal file
|
|
@ -0,0 +1,294 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Web-Push-Abos, Versand und Admin-Auswertung (VAPID). */
|
||||
|
||||
function push_is_available(): bool
|
||||
{
|
||||
static $available = null;
|
||||
if ($available !== null) {
|
||||
return $available;
|
||||
}
|
||||
try {
|
||||
db()->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<int,int> 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;
|
||||
}
|
||||
|
|
@ -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
|
||||
{
|
||||
|
|
|
|||
441
app/webpush.php
Normal file
441
app/webpush.php
Normal file
|
|
@ -0,0 +1,441 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* 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 app/config.local.php:
|
||||
* push.public_key base64url des unkomprimierten P-256-Punkts (65 Byte)
|
||||
* push.private_key base64url des privaten Schlüssels (32 Byte)
|
||||
* push.subject Kontakt-URI, z. B. mailto:admin@example.org
|
||||
*
|
||||
* Die Schlüssel werden beim Deployment aus docs/credentials.txt übernommen.
|
||||
*/
|
||||
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 = config('push.public_key');
|
||||
if (!is_string($key) || 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 = config('push.subject');
|
||||
if (!is_string($subject) || trim($subject) === '') {
|
||||
$subject = config('app.public_url', 'https://drink-it-cold.programmschmiede.de');
|
||||
}
|
||||
return trim((string) $subject);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 = config('push.private_key');
|
||||
if (!is_string($raw) || 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);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue