Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
feat: add push notifications
Miguel Ribeiroece43ebd507b
diff --git a/endpoints/admin/deleteuser.php b/endpoints/admin/deleteuser.phpindex 93edfee..fe25fd5 100644--- a/endpoints/admin/deleteuser.php+++ b/endpoints/admin/deleteuser.php@@ -192,6 +192,15 @@ if ($userId == 1) {$stmt->bindValue(':id', $userId, SQLITE3_INTEGER);$result = $stmt->execute();+ // Delete push notification settings and every device subscription+ $stmt = $db->prepare('DELETE FROM push_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ $stmt = $db->prepare('DELETE FROM push_subscriptions WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();+// The account's rows are gone; drop its logo files that nothing else uses.foreach (array_unique(array_filter($logoFilesToCheck)) as $logoFile) {deleteLogoFileIfUnused($db, $logoFile, '../../images/uploads/logos/');diff --git a/endpoints/cronjobs/sendnotifications.php b/endpoints/cronjobs/sendnotifications.phpindex 3ac578d..507d074 100644--- a/endpoints/cronjobs/sendnotifications.php+++ b/endpoints/cronjobs/sendnotifications.php@@ -7,6 +7,8 @@ require_once 'validate.php';require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';require_once __DIR__ . '/../../includes/ssrf_helper.php';require_once __DIR__ . '/../../includes/webhook_helper.php';+require_once __DIR__ . '/../../includes/webpush_helper.php';+require_once __DIR__ . '/../../includes/instance_config.php';require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php';require __DIR__ . '/../../libs/PHPMailer/SMTP.php';@@ -100,6 +102,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {$discordNotificationsEnabled = false;$ntfyNotificationsEnabled = false;$serverchanNotificationsEnabled = false;+ $pushNotificationsEnabled = false;// Get notification settings (how many days before the subscription ends should the notification be sent)$query = $hasPeriodSummaryColumn@@ -247,9 +250,39 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {$serverchan['sendkey'] = $row['sendkey'];}+ // Check if Push notifications are enabled and get the registered devices+ $query = "SELECT * FROM push_notifications WHERE user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ $pushSubscriptions = [];++ if ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $pushNotificationsEnabled = $row['enabled'];+ }++ if ($pushNotificationsEnabled) {+ $query = "SELECT id, endpoint, p256dh, auth FROM push_subscriptions WHERE user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $pushSubscriptions[] = $row;+ }++ // No point running the rest of this channel's setup - the VAPID+ // keypair, the admin row for the JWT subject - for an account that+ // enabled push but has not actually registered a device yet.+ if (empty($pushSubscriptions)) {+ $pushNotificationsEnabled = false;+ }+ }+$notificationsEnabled = $emailNotificationsEnabled || $gotifyNotificationsEnabled || $telegramNotificationsEnabled ||$webhookNotificationsEnabled || $pushoverNotificationsEnabled || $discordNotificationsEnabled || $pushplusNotificationsEnabled ||- $mattermostNotificationsEnabled || $ntfyNotificationsEnabled || $serverchanNotificationsEnabled;+ $mattermostNotificationsEnabled || $ntfyNotificationsEnabled || $serverchanNotificationsEnabled || $pushNotificationsEnabled;// If no notifications are enabled, no need to runif (!$notificationsEnabled) {@@ -981,6 +1014,70 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {}}+ // Push notifications if enabled+ if ($pushNotificationsEnabled) {+ $vapidKeys = webpush_get_vapid_keys($db);++ if ($vapidKeys === false) {+ echo "Push Notifications not sent: could not load this installation's VAPID keys.<br />";+ } else {+ $adminSettings = wallos_get_admin_settings($db);+ $pushSubject = !empty($adminSettings['from_email'])+ ? 'mailto:' . $adminSettings['from_email']+ : 'mailto:[email protected]';++ foreach ($notify as $payerUserId => $perUser) {+ // Get name of user from household table+ $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId');+ $stmt->bindValue(':userId', $payerUserId, SQLITE3_INTEGER);+ $result = $stmt->execute();+ $user = $result->fetchArray(SQLITE3_ASSOC);++ $name = $user['name'] ?? "";+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);+ if ($message === "") {+ continue;+ }++ $payload = json_encode([+ 'title' => 'Wallos Notification',+ 'body' => $message,+ ]);++ // One account, one message, every device it has+ // registered - not one per payer's own devices, since+ // a push subscription belongs to whoever is signed+ // into the account in that browser, not to a+ // household member.+ foreach ($pushSubscriptions as $subscription) {+ $ssrf = is_url_safe_for_ssrf($subscription['endpoint'], $db, $userId);+ if (!$ssrf) {+ echo "SSRF attempt detected for a push subscription endpoint. Notification not sent.<br />";+ continue;+ }++ $result = webpush_send($subscription, $payload, $vapidKeys, $pushSubject, 2419200, $ssrf);++ if ($result['prune']) {+ // The push service itself has discarded this+ // subscription (unsubscribed, uninstalled,+ // cleared site data) - see webpush_send()'s+ // own comment for why this is never a device+ // that is merely offline.+ $pruneStmt = $db->prepare('DELETE FROM push_subscriptions WHERE id = :id');+ $pruneStmt->bindValue(':id', $subscription['id'], SQLITE3_INTEGER);+ $pruneStmt->execute();+ echo "Push subscription gone, removed.<br />";+ } elseif ($result['success']) {+ echo "Push Notification sent<br />";+ } else {+ echo "Error sending Push notification: " . ($result['error'] ?? 'unknown error') . "<br />";+ }+ }+ }+ }+ }+} else {if (php_sapi_name() !== 'cli') {echo "Nothing to notify.<br />";diff --git a/endpoints/notifications/removepushsubscription.php b/endpoints/notifications/removepushsubscription.phpnew file mode 100644index 0000000..332397c--- /dev/null+++ b/endpoints/notifications/removepushsubscription.php@@ -0,0 +1,48 @@+<?php++/*+ Removes one device's push subscription - either by its row id (the+ settings page's per-device "remove" button, which only ever knows the+ list it rendered) or by its endpoint (the "disable on this device" button,+ which only ever knows what the browser's own subscription object holds,+ never a database id). Exactly one of the two is expected; user_id scopes+ either lookup, so one account can never remove another's device.+*/++require_once '../../includes/connect_endpoint.php';+require_once '../../includes/validate_endpoint.php';++$postData = file_get_contents("php://input");+$data = json_decode($postData, true);++$id = isset($data['id']) ? (int) $data['id'] : 0;+$endpoint = isset($data['endpoint']) ? trim((string) $data['endpoint']) : '';++if ($id > 0) {+ $query = "DELETE FROM push_subscriptions WHERE id = :id AND user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':id', $id, SQLITE3_INTEGER);+} elseif ($endpoint !== '') {+ $query = "DELETE FROM push_subscriptions WHERE endpoint = :endpoint AND user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':endpoint', $endpoint, SQLITE3_TEXT);+} else {+ die(json_encode([+ "success" => false,+ "message" => translate('fill_mandatory_fields', $i18n)+ ]));+}++$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);++if ($stmt->execute()) {+ echo json_encode([+ "success" => true,+ "message" => translate('notifications_settings_saved', $i18n)+ ]);+} else {+ echo json_encode([+ "success" => false,+ "message" => translate('error_saving_notifications', $i18n)+ ]);+}diff --git a/endpoints/notifications/savenotificationspush.php b/endpoints/notifications/savenotificationspush.phpnew file mode 100644index 0000000..4528cb1--- /dev/null+++ b/endpoints/notifications/savenotificationspush.php@@ -0,0 +1,46 @@+<?php++require_once '../../includes/connect_endpoint.php';+require_once '../../includes/validate_endpoint.php';++$postData = file_get_contents("php://input");+$data = json_decode($postData, true);++$enabled = !empty($data["enabled"]) ? 1 : 0;++$query = "SELECT COUNT(*) FROM push_notifications WHERE user_id = :userId";+$stmt = $db->prepare($query);+$stmt->bindValue(":userId", $userId, SQLITE3_INTEGER);+$result = $stmt->execute();++if ($result === false) {+ echo json_encode([+ "success" => false,+ "message" => translate('error_saving_notifications', $i18n)+ ]);+} else {+ $row = $result->fetchArray();+ $count = $row[0];++ if ($count == 0) {+ $query = "INSERT INTO push_notifications (enabled, user_id) VALUES (:enabled, :userId)";+ } else {+ $query = "UPDATE push_notifications SET enabled = :enabled WHERE user_id = :userId";+ }++ $stmt = $db->prepare($query);+ $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);++ if ($stmt->execute()) {+ echo json_encode([+ "success" => true,+ "message" => translate('notifications_settings_saved', $i18n)+ ]);+ } else {+ echo json_encode([+ "success" => false,+ "message" => translate('error_saving_notifications', $i18n)+ ]);+ }+}diff --git a/endpoints/notifications/savepushsubscription.php b/endpoints/notifications/savepushsubscription.phpnew file mode 100644index 0000000..916e88e--- /dev/null+++ b/endpoints/notifications/savepushsubscription.php@@ -0,0 +1,104 @@+<?php++/*+ Saves one device's push subscription - called by the frontend right after+ a successful pushManager.subscribe(), not by anything the user fills in+ themselves. That still makes the endpoint URL something to validate: it is+ attacker-influenceable through this very request body (see #1220's fix to+ this same class of problem elsewhere in this codebase), even though a+ legitimate one only ever comes from a real push service and is always+ https. Both are checked before anything is stored, the same way every+ other channel's webhook-shaped URL already is.+*/++require_once '../../includes/connect_endpoint.php';+require_once '../../includes/validate_endpoint.php';+require_once '../../includes/ssrf_helper.php';+require_once '../../includes/webpush_helper.php';++$postData = file_get_contents("php://input");+$data = json_decode($postData, true);++$endpoint = isset($data['endpoint']) ? trim((string) $data['endpoint']) : '';+$p256dh = isset($data['keys']['p256dh']) ? trim((string) $data['keys']['p256dh']) : '';+$auth = isset($data['keys']['auth']) ? trim((string) $data['keys']['auth']) : '';+$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? substr((string) $_SERVER['HTTP_USER_AGENT'], 0, 255) : '';++if ($endpoint === '' || $p256dh === '' || $auth === '') {+ die(json_encode([+ "success" => false,+ "message" => translate('fill_mandatory_fields', $i18n)+ ]));+}++$parsedEndpoint = parse_url($endpoint);+if (+ !$parsedEndpoint ||+ !isset($parsedEndpoint['scheme'], $parsedEndpoint['host']) ||+ strtolower($parsedEndpoint['scheme']) !== 'https'+) {+ die(json_encode([+ "success" => false,+ "message" => translate('error', $i18n)+ ]));+}++// A real subscription's keys are always exactly this shape - 65 raw bytes+// for an uncompressed P-256 point, 16 for the auth secret. Anything else+// cannot come from a real browser subscription and could only ever fail+// every future send, so it is refused here rather than stored to fail later.+if (strlen(webpush_base64url_decode($p256dh)) !== 65 || strlen(webpush_base64url_decode($auth)) !== 16) {+ die(json_encode([+ "success" => false,+ "message" => translate('error', $i18n)+ ]));+}++validate_webhook_url_for_ssrf($endpoint, $db, $i18n, $userId);++$query = "SELECT id FROM push_subscriptions WHERE user_id = :userId AND endpoint = :endpoint";+$stmt = $db->prepare($query);+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$stmt->bindValue(':endpoint', $endpoint, SQLITE3_TEXT);+$result = $stmt->execute();++if ($result === false) {+ die(json_encode([+ "success" => false,+ "message" => translate('error_saving_notifications', $i18n)+ ]));+}++$existing = $result->fetchArray(SQLITE3_ASSOC);++if ($existing) {+ // The same device subscribing again - a browser can rotate keys for an+ // existing endpoint, so the row is refreshed rather than left stale or+ // duplicated under the same endpoint.+ $query = "UPDATE push_subscriptions SET p256dh = :p256dh, auth = :auth, user_agent = :userAgent WHERE id = :id";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':id', $existing['id'], SQLITE3_INTEGER);+} else {+ $query = "INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth, user_agent, created_at)+ VALUES (:userId, :endpoint, :p256dh, :auth, :userAgent, :createdAt)";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $stmt->bindValue(':endpoint', $endpoint, SQLITE3_TEXT);+ $stmt->bindValue(':createdAt', (new DateTime('now'))->format('Y-m-d H:i:s'), SQLITE3_TEXT);+}++$stmt->bindValue(':p256dh', $p256dh, SQLITE3_TEXT);+$stmt->bindValue(':auth', $auth, SQLITE3_TEXT);+$stmt->bindValue(':userAgent', $userAgent, SQLITE3_TEXT);++if ($stmt->execute()) {+ echo json_encode([+ "success" => true,+ "message" => translate('notifications_settings_saved', $i18n)+ ]);+} else {+ echo json_encode([+ "success" => false,+ "message" => translate('error_saving_notifications', $i18n)+ ]);+}diff --git a/endpoints/notifications/testpushnotifications.php b/endpoints/notifications/testpushnotifications.phpnew file mode 100644index 0000000..4a0a253--- /dev/null+++ b/endpoints/notifications/testpushnotifications.php@@ -0,0 +1,85 @@+<?php++/*+ Sends a test push to every device this account has registered, rather than+ to a single not-yet-saved configuration the way every other channel's test+ button does - there is no config to test here that saving a subscription+ did not already commit; what "test" means for push is "does at least one+ of my devices actually receive this".+*/++require_once '../../includes/connect_endpoint.php';+require_once '../../includes/validate_endpoint.php';+require_once '../../includes/ssrf_helper.php';+require_once '../../includes/webpush_helper.php';+require_once '../../includes/instance_config.php';++$query = "SELECT id, endpoint, p256dh, auth FROM push_subscriptions WHERE user_id = :userId";+$stmt = $db->prepare($query);+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();++$subscriptions = [];+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $subscriptions[] = $row;+}++if (empty($subscriptions)) {+ die(json_encode([+ "success" => false,+ "message" => translate('no_devices_registered', $i18n)+ ]));+}++$vapidKeys = webpush_get_vapid_keys($db);+if ($vapidKeys === false) {+ die(json_encode([+ "success" => false,+ "message" => translate('notification_failed', $i18n)+ ]));+}++$adminSettings = wallos_get_admin_settings($db);+$subject = !empty($adminSettings['from_email']) ? 'mailto:' . $adminSettings['from_email'] : 'mailto:[email protected]';++$payload = json_encode([+ 'title' => translate('wallos_notification', $i18n),+ 'body' => translate('test_notification', $i18n),+]);++$sent = 0;+$failed = 0;++foreach ($subscriptions as $subscription) {+ $ssrf = is_url_safe_for_ssrf($subscription['endpoint'], $db, $userId);+ if (!$ssrf) {+ $failed++;+ continue;+ }++ $result = webpush_send($subscription, $payload, $vapidKeys, $subject, 2419200, $ssrf);++ if ($result['prune']) {+ $pruneStmt = $db->prepare('DELETE FROM push_subscriptions WHERE id = :id');+ $pruneStmt->bindValue(':id', $subscription['id'], SQLITE3_INTEGER);+ $pruneStmt->execute();+ }++ if ($result['success']) {+ $sent++;+ } else {+ $failed++;+ }+}++if ($sent > 0) {+ echo json_encode([+ "success" => true,+ "message" => translate('notification_sent_successfuly', $i18n)+ ]);+} else {+ echo json_encode([+ "success" => false,+ "message" => translate('notification_failed', $i18n)+ ]);+}diff --git a/endpoints/settings/deleteaccount.php b/endpoints/settings/deleteaccount.phpindex 03ff39f..18ac12d 100644--- a/endpoints/settings/deleteaccount.php+++ b/endpoints/settings/deleteaccount.php@@ -192,6 +192,15 @@ if ($userIdToDelete == 1 || $userIdToDelete != $userId) {$stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);$result = $stmt->execute();+ // Delete push notification settings and every device subscription+ $stmt = $db->prepare('DELETE FROM push_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ $stmt = $db->prepare('DELETE FROM push_subscriptions WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();+// The account's rows are gone; drop its logo files that nothing else uses.foreach (array_unique(array_filter($logoFilesToCheck)) as $logoFile) {deleteLogoFileIfUnused($db, $logoFile, '../../images/uploads/logos/');diff --git a/includes/i18n/ar.php b/includes/i18n/ar.phpindex 62665d6..4dabd4d 100644--- a/includes/i18n/ar.php+++ b/includes/i18n/ar.php@@ -275,6 +275,11 @@ $i18n = ["host" => "المضيف","topic" => "الموضوع","ignore_ssl_errors" => "تجاهل أخطاء SSL",+ "push_notifications" => "الإشعارات الفورية",+ "push_notifications_info" => "احصل على إشعار في متصفحك أو على شاشة قفل هاتفك، دون الحاجة لحساب أو تطبيق خاص لإعداده. يعمل على Chrome وFirefox وEdge على سطح المكتب، وعلى Android، وعلى iOS من الشاشة الرئيسية بعد تثبيت Wallos كتطبيق.",+ "no_devices_registered" => "لم يتم تسجيل أي أجهزة بعد.",+ "unknown_device" => "جهاز غير معروف",+ "enable_on_this_device" => "تفعيل على هذا الجهاز","categories" => "التصنيفات","translate_categories" => "الترجمة بالذكاء الاصطناعي","save_category" => "حفظ التصنيف",diff --git a/includes/i18n/az.php b/includes/i18n/az.phpindex 61dafd1..f282f92 100644--- a/includes/i18n/az.php+++ b/includes/i18n/az.php@@ -276,6 +276,11 @@ $i18n = ["host" => "Host","topic" => "Mövzu","ignore_ssl_errors" => "SSL xətalarına məhəl qoyma",+ "push_notifications" => "Push Bildirişləri",+ "push_notifications_info" => "Brauzerinizdə və ya telefonunuzun kilid ekranında bildiriş alın, heç bir hesab və ya ayrıca tətbiq qurmadan. Chrome, Firefox və Edge masaüstü brauzerlərində, Android-də və Wallos-u tətbiq kimi quraşdırdıqdan sonra iOS-da əsas ekrandan işləyir.",+ "no_devices_registered" => "Hələ heç bir cihaz qeydiyyatdan keçməyib.",+ "unknown_device" => "Naməlum cihaz",+ "enable_on_this_device" => "Bu cihazda aktivləşdir","categories" => "Kateqoriyalar","translate_categories" => "Süni intellektlə tərcümə et","save_category" => "Kateqoriyanı yadda saxla",diff --git a/includes/i18n/ca.php b/includes/i18n/ca.phpindex a8d3d6d..3de55ba 100644--- a/includes/i18n/ca.php+++ b/includes/i18n/ca.php@@ -252,6 +252,11 @@ $i18n = ["host" => "Host","topic" => "Tema","ignore_ssl_errors" => "Ignorar errors SSL",+ "push_notifications" => "Notificacions Push",+ "push_notifications_info" => "Rebeu una notificació al navegador o a la pantalla de bloqueig del telèfon, sense necessitat de compte ni aplicació pròpia. Funciona a Chrome, Firefox i Edge d'escriptori, a Android, i a iOS des de la pantalla d'inici després d'instal·lar Wallos com a aplicació.",+ "no_devices_registered" => "Encara no hi ha dispositius registrats.",+ "unknown_device" => "Dispositiu desconegut",+ "enable_on_this_device" => "Activa en aquest dispositiu","categories" => "Categories","save_category" => "Desar Categoria","delete_category" => "Eliminar Categoria",diff --git a/includes/i18n/cs.php b/includes/i18n/cs.phpindex a611d6e..766bfe2 100644--- a/includes/i18n/cs.php+++ b/includes/i18n/cs.php@@ -252,6 +252,11 @@ $i18n = ["host" => "Hostitel","topic" => "Téma","ignore_ssl_errors" => "Ignorovat chyby SSL",+ "push_notifications" => "Push oznámení",+ "push_notifications_info" => "Dostávejte oznámení v prohlížeči nebo na uzamykací obrazovce telefonu bez nutnosti vlastního účtu nebo aplikace. Funguje v desktopových prohlížečích Chrome, Firefox a Edge, na Androidu a na iOS z plochy po instalaci Wallos jako aplikace.",+ "no_devices_registered" => "Zatím nejsou registrována žádná zařízení.",+ "unknown_device" => "Neznámé zařízení",+ "enable_on_this_device" => "Povolit na tomto zařízení","categories" => "Kategorie","save_category" => "Uložit kategorii","delete_category" => "Odstranit kategorii",diff --git a/includes/i18n/da.php b/includes/i18n/da.phpindex a66ca1c..2bd5d59 100644--- a/includes/i18n/da.php+++ b/includes/i18n/da.php@@ -252,6 +252,11 @@ $i18n = ["host" => "Host","topic" => "Emne","ignore_ssl_errors" => "Ignorér SSL-fejl",+ "push_notifications" => "Push-notifikationer",+ "push_notifications_info" => "Få en notifikation i din browser eller på din telefons låseskærm uden behov for egen konto eller app. Virker i desktop Chrome, Firefox og Edge, på Android, og på iOS fra hjemmeskærmen efter installation af Wallos som app.",+ "no_devices_registered" => "Ingen enheder registreret endnu.",+ "unknown_device" => "Ukendt enhed",+ "enable_on_this_device" => "Aktivér på denne enhed","categories" => "Kategorier","save_category" => "Gem kategori","delete_category" => "Slet kategori",diff --git a/includes/i18n/de.php b/includes/i18n/de.phpindex dfef3c8..556eea1 100644--- a/includes/i18n/de.php+++ b/includes/i18n/de.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Host","topic" => "Topic","ignore_ssl_errors" => "SSL Fehler ignorieren",+ "push_notifications" => "Push-Benachrichtigungen",+ "push_notifications_info" => "Erhalten Sie eine Benachrichtigung in Ihrem Browser oder auf dem Sperrbildschirm Ihres Telefons, ganz ohne eigenes Konto oder eigene App. Funktioniert in Chrome, Firefox und Edge auf dem Desktop, auf Android und auf iOS vom Startbildschirm aus, nachdem Wallos als App installiert wurde.",+ "no_devices_registered" => "Noch keine Geräte registriert.",+ "unknown_device" => "Unbekanntes Gerät",+ "enable_on_this_device" => "Auf diesem Gerät aktivieren","categories" => "Kategorien","save_category" => "Kategorie speichern","delete_category" => "Kategorie löschen",diff --git a/includes/i18n/el.php b/includes/i18n/el.phpindex cb66970..b187e0c 100644--- a/includes/i18n/el.php+++ b/includes/i18n/el.php@@ -249,6 +249,11 @@ $i18n = ["host" => "Host","topic" => "Θέμα","ignore_ssl_errors" => "Αγνόηση σφαλμάτων SSL",+ "push_notifications" => "Ειδοποιήσεις Push",+ "push_notifications_info" => "Λάβετε ειδοποίηση στο πρόγραμμα περιήγησής σας ή στην οθόνη κλειδώματος του τηλεφώνου σας, χωρίς δικό της λογαριασμό ή εφαρμογή. Λειτουργεί σε Chrome, Firefox και Edge desktop, σε Android, και σε iOS από την αρχική οθόνη αφού εγκαταστήσετε το Wallos ως εφαρμογή.",+ "no_devices_registered" => "Δεν έχουν καταχωρηθεί συσκευές ακόμα.",+ "unknown_device" => "Άγνωστη συσκευή",+ "enable_on_this_device" => "Ενεργοποίηση σε αυτή τη συσκευή","categories" => "Κατηγορίες","save_category" => "Αποθήκευση κατηγορίας","delete_category" => "Διαγραφή κατηγορίας",diff --git a/includes/i18n/en.php b/includes/i18n/en.phpindex bbe69dd..31b5661 100644--- a/includes/i18n/en.php+++ b/includes/i18n/en.php@@ -276,6 +276,11 @@ $i18n = ["host" => "Host","topic" => "Topic","ignore_ssl_errors" => "Ignore SSL Errors",+ "push_notifications" => "Push Notifications",+ "push_notifications_info" => "Get a notification in your browser or on your phone's lock screen, with no account or app of its own to set up. Works on desktop Chrome, Firefox and Edge, on Android, and on iOS from the home screen after installing Wallos as an app.",+ "no_devices_registered" => "No devices registered yet.",+ "unknown_device" => "Unknown device",+ "enable_on_this_device" => "Enable on this device","categories" => "Categories","translate_categories" => "Translate with AI","save_category" => "Save Category",diff --git a/includes/i18n/es.php b/includes/i18n/es.phpindex cb01316..39e5e36 100644--- a/includes/i18n/es.php+++ b/includes/i18n/es.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Host","topic" => "Topico","ignore_ssl_errors" => "Ignorar errores SSL",+ "push_notifications" => "Notificaciones Push",+ "push_notifications_info" => "Recibe una notificación en tu navegador o en la pantalla de bloqueo de tu teléfono, sin necesidad de cuenta ni aplicación propia. Funciona en Chrome, Firefox y Edge de escritorio, en Android, y en iOS desde la pantalla de inicio tras instalar Wallos como aplicación.",+ "no_devices_registered" => "Aún no hay dispositivos registrados.",+ "unknown_device" => "Dispositivo desconocido",+ "enable_on_this_device" => "Activar en este dispositivo","categories" => "Categorías","save_category" => "Guardar Categoría","delete_category" => "Eliminar Categoría",diff --git a/includes/i18n/fr.php b/includes/i18n/fr.phpindex bf6cd56..e04c57a 100644--- a/includes/i18n/fr.php+++ b/includes/i18n/fr.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Hôte","topic" => "Sujet","ignore_ssl_errors" => "Ignorer les erreurs SSL",+ "push_notifications" => "Notifications Push",+ "push_notifications_info" => "Recevez une notification dans votre navigateur ou sur l'écran de verrouillage de votre téléphone, sans compte ni application propre à configurer. Fonctionne sur Chrome, Firefox et Edge de bureau, sur Android, et sur iOS depuis l'écran d'accueil après avoir installé Wallos comme application.",+ "no_devices_registered" => "Aucun appareil enregistré pour le moment.",+ "unknown_device" => "Appareil inconnu",+ "enable_on_this_device" => "Activer sur cet appareil","categories" => "Catégories","save_category" => "Enregistrer la catégorie","delete_category" => "Supprimer la catégorie",diff --git a/includes/i18n/hu.php b/includes/i18n/hu.phpindex fcd9e0e..dc33aed 100644--- a/includes/i18n/hu.php+++ b/includes/i18n/hu.php@@ -252,6 +252,11 @@ $i18n = ["host" => "Gazdagép","topic" => "Téma","ignore_ssl_errors" => "SSL hibák figyelmen kívül hagyása",+ "push_notifications" => "Push értesítések",+ "push_notifications_info" => "Kapjon értesítést a böngészőjében vagy telefonja zárolt képernyőjén, saját fiók vagy alkalmazás beállítása nélkül. Működik asztali Chrome, Firefox és Edge böngészőkben, Androidon, valamint iOS-en a kezdőképernyőről, miután a Wallos-t alkalmazásként telepítette.",+ "no_devices_registered" => "Még nincs regisztrált eszköz.",+ "unknown_device" => "Ismeretlen eszköz",+ "enable_on_this_device" => "Engedélyezés ezen az eszközön","categories" => "Kategóriák","save_category" => "Kategória mentése","delete_category" => "Kategória törlése",diff --git a/includes/i18n/id.php b/includes/i18n/id.phpindex acfdf56..2caa393 100644--- a/includes/i18n/id.php+++ b/includes/i18n/id.php@@ -252,6 +252,11 @@ $i18n = ["host" => "Host","topic" => "Topik","ignore_ssl_errors" => "Abaikan Kesalahan SSL",+ "push_notifications" => "Notifikasi Push",+ "push_notifications_info" => "Dapatkan notifikasi di browser Anda atau di layar kunci ponsel Anda, tanpa perlu akun atau aplikasi tersendiri. Berfungsi di Chrome, Firefox, dan Edge desktop, di Android, dan di iOS dari layar utama setelah menginstal Wallos sebagai aplikasi.",+ "no_devices_registered" => "Belum ada perangkat yang terdaftar.",+ "unknown_device" => "Perangkat tidak dikenal",+ "enable_on_this_device" => "Aktifkan di perangkat ini","categories" => "Kategori","save_category" => "Simpan Kategori","delete_category" => "Hapus Kategori",diff --git a/includes/i18n/it.php b/includes/i18n/it.phpindex b2a19e4..064f516 100644--- a/includes/i18n/it.php+++ b/includes/i18n/it.php@@ -257,6 +257,11 @@ $i18n = ["host" => "Host","topic" => "Topic","ignore_ssl_errors" => "Ignora errori SSL",+ "push_notifications" => "Notifiche Push",+ "push_notifications_info" => "Ricevi una notifica nel browser o sulla schermata di blocco del telefono, senza bisogno di un account o di un'app dedicata. Funziona su Chrome, Firefox ed Edge desktop, su Android e su iOS dalla schermata Home dopo aver installato Wallos come app.",+ "no_devices_registered" => "Nessun dispositivo ancora registrato.",+ "unknown_device" => "Dispositivo sconosciuto",+ "enable_on_this_device" => "Attiva su questo dispositivo","categories" => 'Categorie',"save_category" => 'Salva categoria',"delete_category" => 'Elimina categoria',diff --git a/includes/i18n/ja.php b/includes/i18n/ja.phpindex 0ca1fe1..72215f8 100644--- a/includes/i18n/ja.php+++ b/includes/i18n/ja.php@@ -252,6 +252,11 @@ $i18n = ["host" => "ホスト","topic" => "トピック","ignore_ssl_errors" => "SSLエラーを無視",+ "push_notifications" => "プッシュ通知",+ "push_notifications_info" => "専用のアカウントやアプリを用意することなく、ブラウザやスマートフォンのロック画面に通知を受け取れます。デスクトップのChrome、Firefox、Edge、Androidで動作し、iOSではWallosをアプリとしてホーム画面に追加した後に利用できます。",+ "no_devices_registered" => "まだ登録されたデバイスはありません。",+ "unknown_device" => "不明なデバイス",+ "enable_on_this_device" => "このデバイスで有効にする","categories" => "カテゴリ","save_category" => "カテゴリを保存","delete_category" => "カテゴリを削除",diff --git a/includes/i18n/ko.php b/includes/i18n/ko.phpindex 13d9c42..e259966 100644--- a/includes/i18n/ko.php+++ b/includes/i18n/ko.php@@ -275,6 +275,11 @@ $i18n = ["host" => "호스트","topic" => "토픽","ignore_ssl_errors" => "SSL 오류 무시",+ "push_notifications" => "푸시 알림",+ "push_notifications_info" => "별도의 계정이나 앱 설정 없이 브라우저나 휴대폰 잠금 화면에서 알림을 받아보세요. 데스크톱 Chrome, Firefox, Edge와 Android에서 작동하며, iOS에서는 Wallos를 앱으로 설치한 후 홈 화면에서 사용할 수 있습니다.",+ "no_devices_registered" => "아직 등록된 기기가 없습니다.",+ "unknown_device" => "알 수 없는 기기",+ "enable_on_this_device" => "이 기기에서 활성화","categories" => "카테고리","translate_categories" => "AI로 번역","save_category" => "카테고리 저장",diff --git a/includes/i18n/nl.php b/includes/i18n/nl.phpindex e7a75fa..858f03f 100644--- a/includes/i18n/nl.php+++ b/includes/i18n/nl.php@@ -252,6 +252,11 @@ $i18n = ["host" => "Host","topic" => "Onderwerp","ignore_ssl_errors" => "SSL-fouten negeren",+ "push_notifications" => "Pushmeldingen",+ "push_notifications_info" => "Ontvang een melding in je browser of op het vergrendelscherm van je telefoon, zonder eigen account of app. Werkt in desktop Chrome, Firefox en Edge, op Android, en op iOS vanaf het beginscherm nadat Wallos als app is geïnstalleerd.",+ "no_devices_registered" => "Nog geen apparaten geregistreerd.",+ "unknown_device" => "Onbekend apparaat",+ "enable_on_this_device" => "Inschakelen op dit apparaat","categories" => "Categorieën","save_category" => "Categorie opslaan","delete_category" => "Categorie verwijderen",diff --git a/includes/i18n/pl.php b/includes/i18n/pl.phpindex 451c2ce..e472ea9 100644--- a/includes/i18n/pl.php+++ b/includes/i18n/pl.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Host","topic" => "Temat","ignore_ssl_errors" => "Ignoruj błędy SSL",+ "push_notifications" => "Powiadomienia Push",+ "push_notifications_info" => "Otrzymuj powiadomienia w przeglądarce lub na ekranie blokady telefonu, bez własnego konta czy aplikacji. Działa w Chrome, Firefox i Edge na komputerze, na Androidzie oraz na iOS z ekranu głównego po zainstalowaniu Wallos jako aplikacji.",+ "no_devices_registered" => "Nie zarejestrowano jeszcze żadnych urządzeń.",+ "unknown_device" => "Nieznane urządzenie",+ "enable_on_this_device" => "Włącz na tym urządzeniu","categories" => "Kategorie","save_category" => "Zapisz kategorię","delete_category" => "Usuń kategorię",diff --git a/includes/i18n/pt.php b/includes/i18n/pt.phpindex e3848ec..5114264 100644--- a/includes/i18n/pt.php+++ b/includes/i18n/pt.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Host","topic" => "Tópico","ignore_ssl_errors" => "Ignorar erros SSL",+ "push_notifications" => "Notificações Push",+ "push_notifications_info" => "Receba uma notificação no seu navegador ou no ecrã de bloqueio do telemóvel, sem necessidade de conta ou aplicação própria. Funciona no Chrome, Firefox e Edge no computador, no Android, e no iOS a partir do ecrã principal depois de instalar o Wallos como aplicação.",+ "no_devices_registered" => "Ainda não há dispositivos registados.",+ "unknown_device" => "Dispositivo desconhecido",+ "enable_on_this_device" => "Ativar neste dispositivo","categories" => "Categorias","save_category" => "Guardar Categoria","delete_category" => "Apagar Categoria",diff --git a/includes/i18n/pt_br.php b/includes/i18n/pt_br.phpindex 3b5cd83..69da5c0 100644--- a/includes/i18n/pt_br.php+++ b/includes/i18n/pt_br.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Host","topic" => "Tópico","ignore_ssl_errors" => "Ignorar erros SSL",+ "push_notifications" => "Notificações Push",+ "push_notifications_info" => "Receba uma notificação no seu navegador ou na tela de bloqueio do celular, sem precisar de conta ou aplicativo próprio. Funciona no Chrome, Firefox e Edge no computador, no Android, e no iOS a partir da tela inicial depois de instalar o Wallos como aplicativo.",+ "no_devices_registered" => "Nenhum dispositivo registrado ainda.",+ "unknown_device" => "Dispositivo desconhecido",+ "enable_on_this_device" => "Ativar neste dispositivo","categories" => "Categorias","save_category" => "Salvar categoria","delete_category" => "Excluir categoria",diff --git a/includes/i18n/ro.php b/includes/i18n/ro.phpindex 3690380..0f948b2 100644--- a/includes/i18n/ro.php+++ b/includes/i18n/ro.php@@ -252,6 +252,11 @@ $i18n = ["host" => "Host","topic" => "Topic","ignore_ssl_errors" => "Ignoră erori SSL",+ "push_notifications" => "Notificări Push",+ "push_notifications_info" => "Primește o notificare în browser sau pe ecranul de blocare al telefonului, fără a fi nevoie de cont sau aplicație proprie. Funcționează în Chrome, Firefox și Edge pe desktop, pe Android, și pe iOS de pe ecranul principal după instalarea Wallos ca aplicație.",+ "no_devices_registered" => "Niciun dispozitiv înregistrat încă.",+ "unknown_device" => "Dispozitiv necunoscut",+ "enable_on_this_device" => "Activează pe acest dispozitiv","categories" => "Categorii","save_category" => "Salvează categorie","delete_category" => "Șterge categorie",diff --git a/includes/i18n/ru.php b/includes/i18n/ru.phpindex f835b8e..d34db33 100644--- a/includes/i18n/ru.php+++ b/includes/i18n/ru.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Хост","topic" => "Тема","ignore_ssl_errors" => "Игнорировать ошибки SSL",+ "push_notifications" => "Push-уведомления",+ "push_notifications_info" => "Получайте уведомления в браузере или на экране блокировки телефона без отдельной учётной записи или приложения. Работает в настольных Chrome, Firefox и Edge, на Android, а на iOS - с главного экрана после установки Wallos как приложения.",+ "no_devices_registered" => "Пока нет зарегистрированных устройств.",+ "unknown_device" => "Неизвестное устройство",+ "enable_on_this_device" => "Включить на этом устройстве","categories" => "Категории","save_category" => "Сохранить категорию","delete_category" => "Удалить категорию",diff --git a/includes/i18n/sl.php b/includes/i18n/sl.phpindex 1e1dc92..b13205e 100644--- a/includes/i18n/sl.php+++ b/includes/i18n/sl.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Gostitelj","topic" => "Tema","ignore_ssl_errors" => "Prezri napake SSL",+ "push_notifications" => "Potisna obvestila",+ "push_notifications_info" => "Prejemajte obvestilo v brskalniku ali na zaklenjenem zaslonu telefona, brez lastnega računa ali aplikacije. Deluje v namiznih brskalnikih Chrome, Firefox in Edge, na Androidu ter na iOS z domačega zaslona po namestitvi Wallos kot aplikacije.",+ "no_devices_registered" => "Še ni registriranih naprav.",+ "unknown_device" => "Neznana naprava",+ "enable_on_this_device" => "Omogoči na tej napravi","categories" => "Kategorije","save_category" => "Shrani kategorijo","delete_category" => "Izbriši kategorijo",diff --git a/includes/i18n/sr.php b/includes/i18n/sr.phpindex 64657b3..899a8fb 100644--- a/includes/i18n/sr.php+++ b/includes/i18n/sr.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Домаћин","topic" => "Тема","ignore_ssl_errors" => "Игнориши SSL грешке",+ "push_notifications" => "Push обавештења",+ "push_notifications_info" => "Примајте обавештење у прегледачу или на закључаном екрану телефона, без сопственог налога или апликације. Ради у Chrome, Firefox и Edge на рачунару, на Android-у, и на iOS-у са почетног екрана након инсталирања Wallos-а као апликације.",+ "no_devices_registered" => "Још увек нема регистрованих уређаја.",+ "unknown_device" => "Непознат уређај",+ "enable_on_this_device" => "Омогући на овом уређају","categories" => "Категорије","save_category" => "Сачувај категорију","delete_category" => "Избриши категорију",diff --git a/includes/i18n/sr_lat.php b/includes/i18n/sr_lat.phpindex 2b82235..923aab5 100644--- a/includes/i18n/sr_lat.php+++ b/includes/i18n/sr_lat.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Host","topic" => "Tema","ignore_ssl_errors" => "Ignoriši SSL greške",+ "push_notifications" => "Push obaveštenja",+ "push_notifications_info" => "Primajte obaveštenje u pregledaču ili na zaključanom ekranu telefona, bez sopstvenog naloga ili aplikacije. Radi u Chrome, Firefox i Edge na računaru, na Android-u, i na iOS-u sa početnog ekrana nakon instaliranja Wallos-a kao aplikacije.",+ "no_devices_registered" => "Još uvek nema registrovanih uređaja.",+ "unknown_device" => "Nepoznat uređaj",+ "enable_on_this_device" => "Omogući na ovom uređaju","categories" => "Kategorije","save_category" => "Sačuvaj kategoriju","delete_category" => "Izbriši kategoriju",diff --git a/includes/i18n/tr.php b/includes/i18n/tr.phpindex 07988e2..9472083 100644--- a/includes/i18n/tr.php+++ b/includes/i18n/tr.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Host","topic" => "Konu","ignore_ssl_errors" => "SSL Hatalarını Yoksay",+ "push_notifications" => "Push Bildirimleri",+ "push_notifications_info" => "Kendi hesabı veya uygulaması olmadan tarayıcınızda veya telefonunuzun kilit ekranında bildirim alın. Masaüstü Chrome, Firefox ve Edge'de, Android'de ve Wallos'u uygulama olarak yükledikten sonra iOS'ta ana ekrandan çalışır.",+ "no_devices_registered" => "Henüz kayıtlı cihaz yok.",+ "unknown_device" => "Bilinmeyen cihaz",+ "enable_on_this_device" => "Bu cihazda etkinleştir","categories" => "Kategoriler","save_category" => "Kategoriyi Kaydet","delete_category" => "Kategoriyi Sil",diff --git a/includes/i18n/uk.php b/includes/i18n/uk.phpindex 258e05b..4e1f5a0 100644--- a/includes/i18n/uk.php+++ b/includes/i18n/uk.php@@ -251,6 +251,11 @@ $i18n = ["host" => "Хост","topic" => "Тема","ignore_ssl_errors" => "Ігнорувати помилки SSL",+ "push_notifications" => "Push-сповіщення",+ "push_notifications_info" => "Отримуйте сповіщення в браузері або на екрані блокування телефону без окремого облікового запису чи додатка. Працює в настільних Chrome, Firefox та Edge, на Android, а на iOS - з головного екрана після встановлення Wallos як застосунку.",+ "no_devices_registered" => "Поки що немає зареєстрованих пристроїв.",+ "unknown_device" => "Невідомий пристрій",+ "enable_on_this_device" => "Увімкнути на цьому пристрої","categories" => "Категорії","save_category" => "Зберегти категорію","delete_category" => "Видалити категорію",diff --git a/includes/i18n/vi.php b/includes/i18n/vi.phpindex 1b9e6e9..7b995c2 100644--- a/includes/i18n/vi.php+++ b/includes/i18n/vi.php@@ -252,6 +252,11 @@ $i18n = ["host" => "Host","topic" => "Chủ đề","ignore_ssl_errors" => "Bỏ qua lỗi SSL",+ "push_notifications" => "Thông báo đẩy",+ "push_notifications_info" => "Nhận thông báo trên trình duyệt hoặc trên màn hình khóa điện thoại, không cần tài khoản hay ứng dụng riêng. Hoạt động trên Chrome, Firefox và Edge trên máy tính, trên Android, và trên iOS từ màn hình chính sau khi cài đặt Wallos như một ứng dụng.",+ "no_devices_registered" => "Chưa có thiết bị nào được đăng ký.",+ "unknown_device" => "Thiết bị không xác định",+ "enable_on_this_device" => "Bật trên thiết bị này","categories" => "Danh mục","save_category" => "Lưu danh mục","delete_category" => "Xóa danh mục",diff --git a/includes/i18n/zh_cn.php b/includes/i18n/zh_cn.phpindex 44c562d..2f10a92 100644--- a/includes/i18n/zh_cn.php+++ b/includes/i18n/zh_cn.php@@ -259,6 +259,11 @@ $i18n = ["host" => "主机","topic" => "主题","ignore_ssl_errors" => "忽略 SSL 错误",+ "push_notifications" => "推送通知",+ "push_notifications_info" => "无需单独的账户或应用,即可在浏览器或手机锁屏上收到通知。适用于桌面版 Chrome、Firefox 和 Edge,以及 Android;在 iOS 上,将 Wallos 安装为应用后可从主屏幕使用。",+ "no_devices_registered" => "尚未注册任何设备。",+ "unknown_device" => "未知设备",+ "enable_on_this_device" => "在此设备上启用","categories" => "分类","save_category" => "保存分类","delete_category" => "删除分类",diff --git a/includes/i18n/zh_tw.php b/includes/i18n/zh_tw.phpindex 8ac305f..c48d899 100644--- a/includes/i18n/zh_tw.php+++ b/includes/i18n/zh_tw.php@@ -252,6 +252,11 @@ $i18n = ["host" => "主機","topic" => "主題","ignore_ssl_errors" => "忽略 SSL 錯誤",+ "push_notifications" => "推播通知",+ "push_notifications_info" => "不需要另外的帳戶或應用程式,即可在瀏覽器或手機鎖定畫面收到通知。適用於桌面版 Chrome、Firefox 和 Edge,以及 Android;在 iOS 上,將 Wallos 安裝為應用程式後可從主畫面使用。",+ "no_devices_registered" => "尚未註冊任何裝置。",+ "unknown_device" => "未知裝置",+ "enable_on_this_device" => "在此裝置上啟用","categories" => "分類","save_category" => "儲存分類","delete_category" => "刪除分類",diff --git a/includes/webpush_helper.php b/includes/webpush_helper.phpnew file mode 100644index 0000000..c1a53b3--- /dev/null+++ b/includes/webpush_helper.php@@ -0,0 +1,573 @@+<?php++/*+ Web Push (RFC 8030 / RFC 8291 / RFC 8292): standard browser push+ notifications, sent directly to the browser vendor's own push service+ (Chrome's, Firefox's, Apple's, ...) with no account of Wallos's own -+ unlike Pushover, Gotify or ntfy, which all need the user to register+ somewhere else first.++ Two things a push message needs that nothing else in this codebase does:++ - VAPID (RFC 8292): a JWT, signed with this installation's own EC+ keypair, that tells the push service which application server sent the+ message, so it can rate-limit and identify abuse by sender rather than+ by subscription.+ - End-to-end encryption (RFC 8291): the push service is an untrusted+ relay that can read the message's metadata but never its payload,+ which is encrypted between this server and the browser using a key+ derived from the subscription's own public key and auth secret - the+ push service is never able to decrypt it.++ Both need elliptic-curve Diffie-Hellman, which ext-openssl only exposed a+ plain function for (openssl_pkey_derive()) starting in PHP 8.1. Wallos+ targets PHP 8.3, so this is written directly against ext-openssl - no+ Composer package, the way every other vendored helper in this codebase is+ (see includes/frankfurter.php for the same approach applied to an HTTP API+ instead of a cryptographic one).++ Every intermediate value this file computes (the ECDH secret, the two HKDF+ outputs, the final ciphertext) is checked byte-for-byte against RFC 8291's+ own published test vector in tests/cases/webpush_test.php - that is a much+ stronger guarantee than "the output looks like a push message", which is+ why the payload encryption function accepts an injectable ephemeral key and+ salt: production always generates both fresh (forward secrecy depends on+ the ephemeral key never being reused across messages), but a test needs the+ RFC's fixed ones to reproduce its fixed output.+*/++function webpush_base64url_encode($data)+{+ return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');+}++function webpush_base64url_decode($data)+{+ $data = strtr((string) $data, '-_', '+/');+ $padded = str_pad($data, strlen($data) + (4 - strlen($data) % 4) % 4, '=');+ $decoded = base64_decode($padded, true);++ return $decoded === false ? '' : $decoded;+}++/**+ * Left-pads (or, defensively, right-truncates) a big-endian byte string to a+ * fixed length.+ *+ * ext-openssl's EC accessors (openssl_pkey_get_details()['ec']['x'/'y'/'d'],+ * openssl_pkey_derive()'s return value) strip leading zero bytes, but every+ * one of these values is a fixed-width 32-byte P-256 field element or scalar+ * everywhere it is used here - the raw point format, the JWS signature+ * format, and the shared secret all require the width restored.+ *+ * @param string $value+ * @param int $length+ * @return string+ */+function webpush_fixed_width($value, $length = 32)+{+ if (strlen($value) > $length) {+ return substr($value, -$length);+ }++ return str_pad($value, $length, "\x00", STR_PAD_LEFT);+}++/**+ * A P-256 uncompressed point (65 bytes: 0x04 || X(32) || Y(32)) - what both+ * a push subscription's p256dh and an applicationServerKey are - as an+ * OpenSSL public key resource, for openssl_pkey_derive() and+ * openssl_verify().+ *+ * ext-openssl has no "import a raw point" function; a SubjectPublicKeyInfo+ * DER wrapper around the point does the same thing, and for a fixed named+ * curve every byte of that wrapper except the point itself is constant -+ * this is the standard encoding of "id-ecPublicKey, prime256v1". Verified+ * against ext-openssl's own PEM output for a point it generated itself+ * (same derived ECDH secret either way) before this was trusted for+ * anything real.+ *+ * @param string $rawPoint+ * @return OpenSSLAsymmetricKey|false+ */+function webpush_ec_public_key_from_raw($rawPoint)+{+ if (strlen($rawPoint) !== 65 || $rawPoint[0] !== "\x04") {+ return false;+ }++ $prefix = hex2bin('3059301306072a8648ce3d020106082a8648ce3d030107034200');+ $der = $prefix . $rawPoint;+ $pem = "-----BEGIN PUBLIC KEY-----\n" . chunk_split(base64_encode($der), 64, "\n") . "-----END PUBLIC KEY-----\n";++ $key = openssl_pkey_get_public($pem);++ return $key === false ? false : $key;+}++/**+ * Reads one ASN.1 DER INTEGER at $offset.+ *+ * @param string $der+ * @param int $offset+ * @return array{0: string|false, 1: int} The integer's raw bytes (with any+ * ASN.1 sign-avoidance zero pad stripped), and the offset just past+ * it. [false, $offset] on a malformed input.+ */+function webpush_der_read_integer($der, $offset)+{+ $len = strlen($der);++ if ($offset >= $len || ord($der[$offset]) !== 0x02) {+ return [false, $offset];+ }+ $offset++;++ if ($offset >= $len) {+ return [false, $offset];+ }+ $intLen = ord($der[$offset]);+ $offset++;++ if ($intLen & 0x80) {+ $numLenBytes = $intLen & 0x7f;+ if ($numLenBytes < 1 || $numLenBytes > 2 || $offset + $numLenBytes > $len) {+ return [false, $offset];+ }+ $intLen = 0;+ for ($i = 0; $i < $numLenBytes; $i++) {+ $intLen = ($intLen << 8) | ord($der[$offset + $i]);+ }+ $offset += $numLenBytes;+ }++ if ($intLen < 0 || $offset + $intLen > $len) {+ return [false, $offset];+ }+ $value = substr($der, $offset, $intLen);+ $offset += $intLen;++ // A leading 0x00 that exists only to keep a high first bit from reading+ // as a two's-complement sign is not part of the fixed-width value a JWS+ // wants - r and s are unsigned there.+ while (strlen($value) > 1 && $value[0] === "\x00" && (ord($value[1]) & 0x80)) {+ $value = substr($value, 1);+ }++ return [$value, $offset];+}++/**+ * Converts the DER ECDSA-Sig-Value openssl_sign() produces into the raw+ * r || s concatenation a JWS ES256 signature is.+ *+ * @param string $der+ * @param int $partLength Width of each of r and s; 32 for P-256/ES256.+ * @return string|false+ */+function webpush_der_signature_to_raw($der, $partLength = 32)+{+ $offset = 0;+ $len = strlen($der);++ if ($len < 8 || ord($der[$offset]) !== 0x30) {+ return false;+ }+ $offset++;++ $seqLen = ord($der[$offset]);+ $offset++;+ if ($seqLen & 0x80) {+ $numLenBytes = $seqLen & 0x7f;+ if ($numLenBytes < 1 || $numLenBytes > 2 || $offset + $numLenBytes > $len) {+ return false;+ }+ $seqLen = 0;+ for ($i = 0; $i < $numLenBytes; $i++) {+ $seqLen = ($seqLen << 8) | ord($der[$offset + $i]);+ }+ $offset += $numLenBytes;+ }++ [$r, $offset] = webpush_der_read_integer($der, $offset);+ if ($r === false) {+ return false;+ }+ [$s, $offset] = webpush_der_read_integer($der, $offset);+ if ($s === false) {+ return false;+ }++ return webpush_fixed_width($r, $partLength) . webpush_fixed_width($s, $partLength);+}++/**+ * openssl.cnf paths worth retrying a failed key operation with.+ *+ * Some PHP-for-Windows builds (XAMPP's included) link an OpenSSL that cannot+ * locate its own default config file, and every openssl_pkey_new()/+ * openssl_pkey_export() call then fails outright - reproducibly, with+ * OpenSSL's own "configuration file routines::no such file" - even for a+ * plain RSA key with no EC or Web Push involved at all. This is an+ * environment problem, not one this file can fix, but it is common enough+ * (XAMPP is a standard local dev setup) that failing outright rather than+ * working around it would leave the feature broken for a lot of installs+ * that would otherwise never touch this at all - Docker, and most native+ * Linux packagings, resolve their default config without any of this.+ *+ * @return string[] Existing, readable candidate paths, in the order to try.+ */+function webpush_openssl_config_candidates()+{+ $candidates = [];++ $envConf = getenv('OPENSSL_CONF');+ if ($envConf !== false && trim($envConf) !== '') {+ $candidates[] = $envConf;+ }++ // Where XAMPP for Windows ships an openssl.cnf next to the php.ini this+ // exact request loaded - true for both the Apache module and the CLI+ // binary, since XAMPP points both at the same php.ini by default.+ $iniFile = php_ini_loaded_file();+ if ($iniFile !== false) {+ $iniDir = dirname($iniFile);+ $candidates[] = $iniDir . '/extras/openssl/openssl.cnf';+ $candidates[] = $iniDir . '/extras/ssl/openssl.cnf';+ }++ return array_values(array_filter($candidates, function ($path) {+ return $path !== '' && is_readable($path);+ }));+}++/**+ * openssl_pkey_new(), retried with a discovered openssl.cnf if the plain+ * call fails - see webpush_openssl_config_candidates() for why that can be+ * necessary at all. The plain call is always tried first and is all that+ * runs on an install where it already works.+ *+ * @param array $options As openssl_pkey_new() takes, without 'config'.+ * @return OpenSSLAsymmetricKey|false+ */+function webpush_openssl_pkey_new($options)+{+ $key = openssl_pkey_new($options);+ if ($key !== false) {+ return $key;+ }++ foreach (webpush_openssl_config_candidates() as $configPath) {+ $key = openssl_pkey_new($options + ['config' => $configPath]);+ if ($key !== false) {+ return $key;+ }+ }++ return false;+}++/**+ * Generates a fresh P-256 keypair for this installation to identify itself+ * to push services with.+ *+ * @return array{public: string, private_pem: string}|false 'public' is the+ * raw uncompressed point, base64url - what both the VAPID+ * Authorization header and the frontend's applicationServerKey need.+ * 'private_pem' is kept in PEM, the form openssl_sign() and+ * openssl_pkey_get_private() both take directly.+ */+function webpush_generate_vapid_keypair()+{+ $key = webpush_openssl_pkey_new([+ 'curve_name' => 'prime256v1',+ 'private_key_type' => OPENSSL_KEYTYPE_EC,+ ]);++ if ($key === false) {+ return false;+ }++ $details = openssl_pkey_get_details($key);+ if ($details === false || !isset($details['ec']['x'], $details['ec']['y'])) {+ return false;+ }++ $publicRaw = "\x04" . webpush_fixed_width($details['ec']['x']) . webpush_fixed_width($details['ec']['y']);++ // Exporting can hit the same missing-config failure key generation can -+ // the same candidates are worth the same retry.+ if (!openssl_pkey_export($key, $privatePem)) {+ $exported = false;+ foreach (webpush_openssl_config_candidates() as $configPath) {+ if (openssl_pkey_export($key, $privatePem, null, ['config' => $configPath])) {+ $exported = true;+ break;+ }+ }+ if (!$exported) {+ return false;+ }+ }++ return [+ 'public' => webpush_base64url_encode($publicRaw),+ 'private_pem' => $privatePem,+ ];+}++/**+ * This installation's VAPID keypair, generating and persisting one the+ * first time anything needs it.+ *+ * Stored on the admin row alongside the other instance-wide settings that+ * already live there (smtp_*, server_url) - it identifies the Wallos+ * installation as a whole to the push services it talks to, not any one+ * user, the same way the instance's own SMTP identity is not per-user.+ *+ * @param SQLite3 $db+ * @return array{public: string, private_pem: string}|false+ */+function webpush_get_vapid_keys($db)+{+ $row = $db->querySingle('SELECT vapid_public_key, vapid_private_key FROM admin LIMIT 1', true);++ if ($row !== false && !empty($row['vapid_public_key']) && !empty($row['vapid_private_key'])) {+ return ['public' => $row['vapid_public_key'], 'private_pem' => $row['vapid_private_key']];+ }++ $keys = webpush_generate_vapid_keypair();+ if ($keys === false) {+ return false;+ }++ $stmt = $db->prepare('UPDATE admin SET vapid_public_key = :public, vapid_private_key = :private');+ $stmt->bindValue(':public', $keys['public'], SQLITE3_TEXT);+ $stmt->bindValue(':private', $keys['private_pem'], SQLITE3_TEXT);+ $stmt->execute();++ return $keys;+}++/**+ * Builds and signs a VAPID (RFC 8292) authorization JWT for one push+ * message.+ *+ * @param string $endpoint The subscription's push service endpoint -+ * only its scheme://host[:port] is used, as+ * the "aud" claim, per RFC 8292.+ * @param string $subject A mailto: or https: URL identifying this+ * application server, the "sub" claim - shown+ * to the push service's operator if it needs+ * to reach whoever is sending it messages.+ * @param string $privateKeyPem+ * @return string|false+ */+function webpush_build_vapid_jwt($endpoint, $subject, $privateKeyPem)+{+ $parsedEndpoint = parse_url($endpoint);+ if (!$parsedEndpoint || !isset($parsedEndpoint['scheme'], $parsedEndpoint['host'])) {+ return false;+ }++ $audience = $parsedEndpoint['scheme'] . '://' . $parsedEndpoint['host']+ . (isset($parsedEndpoint['port']) ? ':' . $parsedEndpoint['port'] : '');++ $header = ['typ' => 'JWT', 'alg' => 'ES256'];+ $claims = [+ 'aud' => $audience,+ // RFC 8292 caps this at 24 hours; 12 is comfortably within it and+ // well past this cron's own run interval, so a slow run never signs+ // a token that is already expired by the time it is used.+ 'exp' => time() + 12 * 3600,+ 'sub' => $subject,+ ];++ $segment = webpush_base64url_encode(json_encode($header)) . '.' . webpush_base64url_encode(json_encode($claims));++ $privateKey = openssl_pkey_get_private($privateKeyPem);+ if ($privateKey === false) {+ return false;+ }++ if (!openssl_sign($segment, $der, $privateKey, OPENSSL_ALGO_SHA256)) {+ return false;+ }++ $raw = webpush_der_signature_to_raw($der, 32);+ if ($raw === false) {+ return false;+ }++ return $segment . '.' . webpush_base64url_encode($raw);+}++/**+ * Encrypts one push message payload per RFC 8291 (the aes128gcm content+ * coding, RFC 8188).+ *+ * @param string $plaintext+ * @param string $p256dhB64 The subscription's own public key,+ * base64url (browser-supplied).+ * @param string $authB64 The subscription's auth secret,+ * base64url (browser-supplied).+ * @param string|null $ephemeralKeyPem Injectable only for tests to+ * reproduce RFC 8291's fixed test+ * vector; null generates a fresh+ * one-time keypair, as production+ * always must - reusing an ephemeral+ * key across messages breaks the+ * forward secrecy the protocol exists+ * to provide.+ * @param string|null $salt Injectable only for tests, for the+ * same reason; null generates 16 fresh+ * random bytes, as production always+ * must.+ * @return string|false The aes128gcm body (content-coding header followed+ * by the ciphertext and its GCM tag), ready to POST as-is.+ */+function webpush_encrypt_payload($plaintext, $p256dhB64, $authB64, $ephemeralKeyPem = null, $salt = null)+{+ $uaPublicRaw = webpush_base64url_decode($p256dhB64);+ $authSecret = webpush_base64url_decode($authB64);++ if (strlen($uaPublicRaw) !== 65 || strlen($authSecret) !== 16) {+ return false;+ }++ $uaPublicKey = webpush_ec_public_key_from_raw($uaPublicRaw);+ if ($uaPublicKey === false) {+ return false;+ }++ if ($ephemeralKeyPem === null) {+ $ephemeralKey = webpush_openssl_pkey_new([+ 'curve_name' => 'prime256v1',+ 'private_key_type' => OPENSSL_KEYTYPE_EC,+ ]);+ if ($ephemeralKey === false) {+ return false;+ }+ } else {+ $ephemeralKey = openssl_pkey_get_private($ephemeralKeyPem);+ if ($ephemeralKey === false) {+ return false;+ }+ }++ $ephemeralDetails = openssl_pkey_get_details($ephemeralKey);+ if ($ephemeralDetails === false || !isset($ephemeralDetails['ec']['x'], $ephemeralDetails['ec']['y'])) {+ return false;+ }+ $asPublicRaw = "\x04" . webpush_fixed_width($ephemeralDetails['ec']['x']) . webpush_fixed_width($ephemeralDetails['ec']['y']);++ $sharedSecret = openssl_pkey_derive($uaPublicKey, $ephemeralKey, 0);+ if ($sharedSecret === false) {+ return false;+ }+ $sharedSecret = webpush_fixed_width($sharedSecret);++ if ($salt === null) {+ $salt = random_bytes(16);+ } elseif (strlen($salt) !== 16) {+ return false;+ }++ // RFC 8291 section 3.4: combine the ECDH secret with the subscription's+ // own auth secret, so a push service that only ever sees ua_public in+ // transit still cannot derive this on its own - it never sees auth.+ $keyInfo = "WebPush: info\x00" . $uaPublicRaw . $asPublicRaw;+ $ikm = hash_hkdf('sha256', $sharedSecret, 32, $keyInfo, $authSecret);++ // RFC 8188's own key derivation from that IKM and this record's salt.+ $cek = hash_hkdf('sha256', $ikm, 16, "Content-Encoding: aes128gcm\x00", $salt);+ $nonce = hash_hkdf('sha256', $ikm, 12, "Content-Encoding: nonce\x00", $salt);++ // A single record holds the whole payload - a push message is at most a+ // few hundred bytes here, far under the 4096-byte record size declared+ // below, so there is never a second record to pad between. 0x02 is RFC+ // 8188's "last record" delimiter byte; nothing follows it.+ $padded = $plaintext . "\x02";++ $ciphertext = openssl_encrypt($padded, 'aes-128-gcm', $cek, OPENSSL_RAW_DATA, $nonce, $tag, '', 16);+ if ($ciphertext === false) {+ return false;+ }++ $recordSize = 4096;+ $header = $salt . pack('N', $recordSize) . chr(strlen($asPublicRaw)) . $asPublicRaw;++ return $header . $ciphertext . $tag;+}++/**+ * Sends one push message to one subscription.+ *+ * @param array{endpoint: string, p256dh: string, auth: string} $subscription+ * @param string $payload Plaintext message body.+ * @param array{public: string, private_pem: string} $vapidKeys+ * @param string $subject RFC 8292 "sub" claim.+ * @param int $ttl Seconds the push service may hold the message for+ * before giving up if the device is offline - a+ * month is generous and costs nothing unused.+ * @param array{host: string, ip: string, port: int}|null $ssrfPin DNS-pin+ * from is_url_safe_for_ssrf()/validate_webhook_url_for_ssrf(),+ * to close the DNS-rebinding gap the same way every+ * other outbound channel here already does.+ * @return array{success: bool, status: int|null, prune: bool, error: string|null}+ * 'prune' is true only for the responses (404/410) that mean the+ * push service itself has discarded this subscription - never for a+ * device merely being offline, which the push service queues+ * through on its own; see includes/webpush_helper.php's own comment+ * above webpush_send() usage in the cron job for why.+ */+function webpush_send($subscription, $payload, $vapidKeys, $subject, $ttl = 2419200, $ssrfPin = null)+{+ $body = webpush_encrypt_payload($payload, $subscription['p256dh'], $subscription['auth']);+ if ($body === false) {+ return ['success' => false, 'status' => null, 'prune' => false, 'error' => 'Could not encrypt the payload.'];+ }++ $jwt = webpush_build_vapid_jwt($subscription['endpoint'], $subject, $vapidKeys['private_pem']);+ if ($jwt === false) {+ return ['success' => false, 'status' => null, 'prune' => false, 'error' => 'Could not build the VAPID token.'];+ }++ $ch = curl_init();+ curl_setopt($ch, CURLOPT_URL, $subscription['endpoint']);+ curl_setopt($ch, CURLOPT_POST, 1);+ curl_setopt($ch, CURLOPT_POSTFIELDS, $body);+ curl_setopt($ch, CURLOPT_HTTPHEADER, [+ 'Content-Type: application/octet-stream',+ 'Content-Encoding: aes128gcm',+ 'TTL: ' . (int) $ttl,+ 'Authorization: vapid t=' . $jwt . ', k=' . $vapidKeys['public'],+ ]);+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);++ if ($ssrfPin !== null) {+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrfPin['host']}:{$ssrfPin['port']}:{$ssrfPin['ip']}"]);+ }++ $response = curl_exec($ch);+ $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);+ $curlError = curl_error($ch);+ curl_close($ch);++ if ($response === false) {+ return ['success' => false, 'status' => null, 'prune' => false, 'error' => $curlError];+ }++ $success = $status >= 200 && $status < 300;+ // 404/410: the push service has no record of this subscription any more+ // (unsubscribed, cleared site data, uninstalled, or its own garbage+ // collection of a very stale one) - safe to forget it. Every other+ // failure - 429 rate limited, a 5xx fault, a malformed request - says+ // nothing about whether the subscription itself is still good, so none+ // of those prune it.+ $prune = in_array($status, [404, 410], true);++ return ['success' => $success, 'status' => $status, 'prune' => $prune, 'error' => $success ? null : $response];+}diff --git a/migrations/000059.php b/migrations/000059.phpnew file mode 100644index 0000000..1b2539d--- /dev/null+++ b/migrations/000059.php@@ -0,0 +1,52 @@+<?php++// Adds Web Push as a notification channel: standard browser push (Push API ++// Service Worker), no third-party account needed by the user - unlike every+// other push-style channel Wallos already has (Pushover, Gotify, ntfy),+// which all require registering somewhere else first.+//+// push_notifications follows the same shape every other channel's settings+// table has: one row per user, an "enabled" toggle. push_subscriptions is+// one-to-many instead, because a single account can have Wallos open on a+// phone and a laptop at once, and each browser/device gets its own+// subscription (endpoint + keys) from the Push API - there is no single+// "the subscription" for an account the way there is a single ntfy topic.+//+// The instance-wide VAPID keypair identifies this Wallos installation to the+// push services (Chrome's, Firefox's, ...) it talks to; it is not configured+// by an admin the way SMTP is, so it is generated once, lazily, by+// includes/webpush_helper.php the first time it is needed, and stored on the+// admin row alongside the other instance-wide settings that already live+// there (smtp_*, server_url).++$db->exec("CREATE TABLE IF NOT EXISTS push_notifications (+ enabled BOOLEAN DEFAULT 0,+ user_id INTEGER,+ FOREIGN KEY (user_id) REFERENCES user(id)+)");++$db->exec("CREATE TABLE IF NOT EXISTS push_subscriptions (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ user_id INTEGER,+ endpoint TEXT NOT NULL,+ p256dh TEXT NOT NULL,+ auth TEXT NOT NULL,+ user_agent TEXT DEFAULT '',+ created_at TEXT DEFAULT '',+ FOREIGN KEY (user_id) REFERENCES user(id)+)");++$db->exec('CREATE UNIQUE INDEX IF NOT EXISTS push_subscriptions_user_endpoint+ ON push_subscriptions(user_id, endpoint)');++$vapidPublicKeyColumn = $db->query("SELECT * FROM pragma_table_info('admin') WHERE name='vapid_public_key'");+if ($vapidPublicKeyColumn->fetchArray(SQLITE3_ASSOC) === false) {+ $db->exec("ALTER TABLE admin ADD COLUMN vapid_public_key TEXT DEFAULT ''");+}++$vapidPrivateKeyColumn = $db->query("SELECT * FROM pragma_table_info('admin') WHERE name='vapid_private_key'");+if ($vapidPrivateKeyColumn->fetchArray(SQLITE3_ASSOC) === false) {+ $db->exec("ALTER TABLE admin ADD COLUMN vapid_private_key TEXT DEFAULT ''");+}++?>diff --git a/scripts/i18n/ar.js b/scripts/i18n/ar.jsindex 0a890cc..37b9d71 100644--- a/scripts/i18n/ar.js+++ b/scripts/i18n/ar.js@@ -50,4 +50,6 @@ let i18n = {notes: "ملاحظات",export: "تصدير",no_results_found: "لم يُعثر على نتائج",+ push_not_supported: "الإشعارات الفورية غير مدعومة في هذا المتصفح.",+ push_permission_denied: "لم يتم منح إذن الإشعارات.",}diff --git a/scripts/i18n/az.js b/scripts/i18n/az.jsindex 6f8da03..6c4ce83 100644--- a/scripts/i18n/az.js+++ b/scripts/i18n/az.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget: "Büdcə mənfi olmayan rəqəm olmalıdır",invalid_budget_period: "Yanlış büdcə dövrü seçilib",invalid_budget_anchor_date: "Baza tarixi etibarlı tarix olmalıdır",+ push_not_supported: "Bu brauzerdə push bildirişləri dəstəklənmir.",+ push_permission_denied: "Bildiriş icazəsi verilmədi.",}diff --git a/scripts/i18n/ca.js b/scripts/i18n/ca.jsindex a73bfe5..f5901a7 100644--- a/scripts/i18n/ca.js+++ b/scripts/i18n/ca.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Període de pressupost seleccionat no vàlid",invalid_budget_anchor_date: "La data d'ancoratge ha de ser una data vàlida",no_results_found: "No s'han trobat resultats",+ push_not_supported: "Les notificacions push no són compatibles amb aquest navegador.",+ push_permission_denied: "No s'ha concedit el permís de notificacions.",}diff --git a/scripts/i18n/cs.js b/scripts/i18n/cs.jsindex 1555916..c0f2143 100644--- a/scripts/i18n/cs.js+++ b/scripts/i18n/cs.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Vybrané rozpočtové období je neplatné",invalid_budget_anchor_date: "Počáteční datum musí být platné datum",no_results_found: "Nebyly nalezeny žádné výsledky",+ push_not_supported: "Push notifikace nejsou v tomto prohlížeči podporovány.",+ push_permission_denied: "Oprávnění k oznámením nebylo uděleno.",}diff --git a/scripts/i18n/da.js b/scripts/i18n/da.jsindex 23985d9..f4e3316 100644--- a/scripts/i18n/da.js+++ b/scripts/i18n/da.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Ugyldig budgetperiode valgt",invalid_budget_anchor_date: "Startdatoen skal være en gyldig dato",no_results_found: "Ingen resultater fundet",+ push_not_supported: "Push-notifikationer understøttes ikke i denne browser.",+ push_permission_denied: "Tilladelse til notifikationer blev ikke givet.",}diff --git a/scripts/i18n/de.js b/scripts/i18n/de.jsindex 42c5e11..f04a9a7 100644--- a/scripts/i18n/de.js+++ b/scripts/i18n/de.js@@ -52,4 +52,6 @@ let i18n = {invalid_budget_period: "Ungültiger Budgetzeitraum ausgewählt",invalid_budget_anchor_date: "Das Ankerdatum muss ein gültiges Datum sein",no_results_found: "Keine Ergebnisse gefunden",+ push_not_supported: "Push-Benachrichtigungen werden von diesem Browser nicht unterstützt.",+ push_permission_denied: "Die Berechtigung für Benachrichtigungen wurde nicht erteilt.",}diff --git a/scripts/i18n/el.js b/scripts/i18n/el.jsindex 9c6f9fa..73cf8e7 100644--- a/scripts/i18n/el.js+++ b/scripts/i18n/el.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Επιλέχθηκε μη έγκυρη περίοδος προϋπολογισμού",invalid_budget_anchor_date: "Η ημερομηνία αναφοράς πρέπει να είναι έγκυρη ημερομηνία",no_results_found: "Δεν βρέθηκαν αποτελέσματα",+ push_not_supported: "Οι ειδοποιήσεις push δεν υποστηρίζονται σε αυτό το πρόγραμμα περιήγησης.",+ push_permission_denied: "Δεν χορηγήθηκε άδεια ειδοποιήσεων.",}diff --git a/scripts/i18n/en.js b/scripts/i18n/en.jsindex 5272a73..61a4bba 100644--- a/scripts/i18n/en.js+++ b/scripts/i18n/en.js@@ -49,5 +49,7 @@ let i18n = {no_results_found: "No results found",invalid_budget: "Budget must be a non-negative number",invalid_budget_period: "Invalid budget period selected",- invalid_budget_anchor_date: "Anchor date must be a valid date",+ invalid_budget_anchor_date: "Anchor date must be a valid date",+ push_not_supported: "Push notifications are not supported in this browser.",+ push_permission_denied: "Notification permission was not granted.",}diff --git a/scripts/i18n/es.js b/scripts/i18n/es.jsindex e1923b7..4864461 100644--- a/scripts/i18n/es.js+++ b/scripts/i18n/es.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Periodo de presupuesto seleccionado no válido",invalid_budget_anchor_date: "La fecha de referencia debe ser una fecha válida",no_results_found: "No se encontraron resultados",+ push_not_supported: "Las notificaciones push no son compatibles con este navegador.",+ push_permission_denied: "No se concedió el permiso de notificaciones.",}diff --git a/scripts/i18n/fr.js b/scripts/i18n/fr.jsindex 811a0f4..02f9da9 100644--- a/scripts/i18n/fr.js+++ b/scripts/i18n/fr.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Période de budget sélectionnée invalide",invalid_budget_anchor_date: "La date de référence doit être une date valide",no_results_found: "Aucun résultat trouvé",+ push_not_supported: "Les notifications push ne sont pas prises en charge par ce navigateur.",+ push_permission_denied: "L'autorisation de notification n'a pas été accordée.",};diff --git a/scripts/i18n/hu.js b/scripts/i18n/hu.jsindex 780e51f..444cad0 100644--- a/scripts/i18n/hu.js+++ b/scripts/i18n/hu.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Érvénytelen költségvetési időszak lett kiválasztva",invalid_budget_anchor_date: "A kezdő dátumnak érvényes dátumnak kell lennie",no_results_found: "Nincs találat",+ push_not_supported: "A böngésző nem támogatja a push értesítéseket.",+ push_permission_denied: "Az értesítési engedély nem lett megadva.",}diff --git a/scripts/i18n/id.js b/scripts/i18n/id.jsindex 2f8d876..c22d0b3 100644--- a/scripts/i18n/id.js+++ b/scripts/i18n/id.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Periode anggaran yang dipilih tidak valid",invalid_budget_anchor_date: "Tanggal acuan harus berupa tanggal yang valid",no_results_found: "Tidak ada hasil ditemukan",+ push_not_supported: "Notifikasi push tidak didukung di browser ini.",+ push_permission_denied: "Izin notifikasi tidak diberikan.",}diff --git a/scripts/i18n/it.js b/scripts/i18n/it.jsindex c6c61f0..8b7dc7d 100644--- a/scripts/i18n/it.js+++ b/scripts/i18n/it.js@@ -51,4 +51,6 @@ let i18n = {invalid_budget_period: "Periodo di budget selezionato non valido",invalid_budget_anchor_date: "La data di ancoraggio deve essere una data valida",no_results_found: "Nessun risultato trovato",+ push_not_supported: "Le notifiche push non sono supportate in questo browser.",+ push_permission_denied: "L'autorizzazione per le notifiche non è stata concessa.",}diff --git a/scripts/i18n/ja.js b/scripts/i18n/ja.jsindex e9febbf..ec2d917 100644--- a/scripts/i18n/ja.js+++ b/scripts/i18n/ja.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "選択した予算期間が無効です",invalid_budget_anchor_date: "基準日は有効な日付である必要があります",no_results_found: "結果が見つかりません",+ push_not_supported: "このブラウザではプッシュ通知に対応していません。",+ push_permission_denied: "通知の許可が得られませんでした。",}diff --git a/scripts/i18n/ko.js b/scripts/i18n/ko.jsindex ba30dc7..ae2e23f 100644--- a/scripts/i18n/ko.js+++ b/scripts/i18n/ko.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget: "0 이상의 숫자여야 합니다.",invalid_budget_period: "유효하지 않은 기간입니다.",invalid_budget_anchor_date: "기준일은 유효한 날짜여야 합니다.",+ push_not_supported: "이 브라우저에서는 푸시 알림이 지원되지 않습니다.",+ push_permission_denied: "알림 권한이 허용되지 않았습니다.",}diff --git a/scripts/i18n/nl.js b/scripts/i18n/nl.jsindex 1aee156..008c6fd 100644--- a/scripts/i18n/nl.js+++ b/scripts/i18n/nl.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Ongeldige budgetperiode geselecteerd",invalid_budget_anchor_date: "Startdatum moet een geldige datum zijn",no_results_found: "Geen resultaten gevonden",+ push_not_supported: "Pushmeldingen worden niet ondersteund in deze browser.",+ push_permission_denied: "Toestemming voor meldingen is niet verleend.",}diff --git a/scripts/i18n/pl.js b/scripts/i18n/pl.jsindex 2486c7b..ac0cda7 100644--- a/scripts/i18n/pl.js+++ b/scripts/i18n/pl.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Wybrano nieprawidłowy okres budżetowy",invalid_budget_anchor_date: "Data odniesienia musi być prawidłową datą",no_results_found: "Nie znaleziono wyników",+ push_not_supported: "Powiadomienia push nie są obsługiwane w tej przeglądarce.",+ push_permission_denied: "Nie udzielono zgody na powiadomienia.",}diff --git a/scripts/i18n/pt.js b/scripts/i18n/pt.jsindex d448570..7f1ab2f 100644--- a/scripts/i18n/pt.js+++ b/scripts/i18n/pt.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Período de orçamento selecionado inválido",invalid_budget_anchor_date: "A data de referência deve ser uma data válida",no_results_found: "Nenhum resultado encontrado",+ push_not_supported: "As notificações push não são suportadas neste navegador.",+ push_permission_denied: "A permissão de notificações não foi concedida.",};diff --git a/scripts/i18n/pt_br.js b/scripts/i18n/pt_br.jsindex b3eae1e..c885b2e 100644--- a/scripts/i18n/pt_br.js+++ b/scripts/i18n/pt_br.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Período de orçamento selecionado inválido",invalid_budget_anchor_date: "A data de referência deve ser uma data válida",no_results_found: "Nenhum resultado encontrado",+ push_not_supported: "As notificações push não são compatíveis com este navegador.",+ push_permission_denied: "A permissão de notificações não foi concedida.",}diff --git a/scripts/i18n/ro.js b/scripts/i18n/ro.jsindex 722d8ae..2722e82 100644--- a/scripts/i18n/ro.js+++ b/scripts/i18n/ro.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Perioadă de buget selectată nevalidă",invalid_budget_anchor_date: "Data de referință trebuie să fie o dată validă",no_results_found: "Nu s-au găsit rezultate",+ push_not_supported: "Notificările push nu sunt acceptate în acest browser.",+ push_permission_denied: "Permisiunea pentru notificări nu a fost acordată.",}diff --git a/scripts/i18n/ru.js b/scripts/i18n/ru.jsindex 27c3d28..7bb4a44 100644--- a/scripts/i18n/ru.js+++ b/scripts/i18n/ru.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Выбран недопустимый бюджетный период",invalid_budget_anchor_date: "Дата отсчёта должна быть действительной датой",no_results_found: "Ничего не найдено",+ push_not_supported: "Push-уведомления не поддерживаются в этом браузере.",+ push_permission_denied: "Разрешение на уведомления не было предоставлено.",}diff --git a/scripts/i18n/sl.js b/scripts/i18n/sl.jsindex 9e3512b..77136f8 100644--- a/scripts/i18n/sl.js+++ b/scripts/i18n/sl.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Izbrano neveljavno proračunsko obdobje",invalid_budget_anchor_date: "Izhodiščni datum mora biti veljaven datum",no_results_found: "Ni najdenih rezultatov",+ push_not_supported: "Potisna obvestila v tem brskalniku niso podprta.",+ push_permission_denied: "Dovoljenje za obvestila ni bilo odobreno.",}diff --git a/scripts/i18n/sr.js b/scripts/i18n/sr.jsindex f501904..0c2807b 100644--- a/scripts/i18n/sr.js+++ b/scripts/i18n/sr.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Изабран је неважећи период буџета",invalid_budget_anchor_date: "Референтни датум мора бити важећи датум",no_results_found: "Нема резултата",+ push_not_supported: "Push обавештења нису подржана у овом прегледачу.",+ push_permission_denied: "Дозвола за обавештења није одобрена.",}diff --git a/scripts/i18n/sr_lat.js b/scripts/i18n/sr_lat.jsindex 5e266aa..fce30fe 100644--- a/scripts/i18n/sr_lat.js+++ b/scripts/i18n/sr_lat.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Izabran je nevažeći period budžeta",invalid_budget_anchor_date: "Referentni datum mora biti važeći datum",no_results_found: "Nema rezultata",+ push_not_supported: "Push obaveštenja nisu podržana u ovom pregledaču.",+ push_permission_denied: "Dozvola za obaveštenja nije odobrena.",}diff --git a/scripts/i18n/tr.js b/scripts/i18n/tr.jsindex 8dcbf02..c58e74a 100644--- a/scripts/i18n/tr.js+++ b/scripts/i18n/tr.js@@ -50,6 +50,8 @@ let i18n = {invalid_budget_period: "Geçersiz bütçe dönemi seçildi",invalid_budget_anchor_date: "Referans tarih geçerli bir tarih olmalıdır",no_results_found: "Sonuç bulunamadı",+ push_not_supported: "Bu tarayıcıda push bildirimleri desteklenmiyor.",+ push_permission_denied: "Bildirim izni verilmedi.",}diff --git a/scripts/i18n/uk.js b/scripts/i18n/uk.jsindex c4887c6..09a2b2d 100644--- a/scripts/i18n/uk.js+++ b/scripts/i18n/uk.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Вибрано недійсний бюджетний період",invalid_budget_anchor_date: "Дата відліку має бути дійсною датою",no_results_found: "Нічого не знайдено",+ push_not_supported: "Push-сповіщення не підтримуються в цьому браузері.",+ push_permission_denied: "Дозвіл на сповіщення не надано.",}diff --git a/scripts/i18n/vi.js b/scripts/i18n/vi.jsindex 84ab3ad..94e35ce 100644--- a/scripts/i18n/vi.js+++ b/scripts/i18n/vi.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "Kỳ ngân sách đã chọn không hợp lệ",invalid_budget_anchor_date: "Ngày mốc phải là ngày hợp lệ",no_results_found: "Không tìm thấy kết quả",+ push_not_supported: "Trình duyệt này không hỗ trợ thông báo đẩy.",+ push_permission_denied: "Quyền thông báo chưa được cấp.",}diff --git a/scripts/i18n/zh_cn.js b/scripts/i18n/zh_cn.jsindex 715f1c0..aac445b 100644--- a/scripts/i18n/zh_cn.js+++ b/scripts/i18n/zh_cn.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "所选预算周期无效",invalid_budget_anchor_date: "起始日期必须是有效日期",no_results_found: "未找到结果",+ push_not_supported: "此浏览器不支持推送通知。",+ push_permission_denied: "未授予通知权限。",};diff --git a/scripts/i18n/zh_tw.js b/scripts/i18n/zh_tw.jsindex 94c6e30..1cd203f 100644--- a/scripts/i18n/zh_tw.js+++ b/scripts/i18n/zh_tw.js@@ -50,4 +50,6 @@ let i18n = {invalid_budget_period: "所選預算週期無效",invalid_budget_anchor_date: "起始日期必須是有效日期",no_results_found: "找不到結果",+ push_not_supported: "此瀏覽器不支援推播通知。",+ push_permission_denied: "未授予通知權限。",};diff --git a/scripts/notifications.js b/scripts/notifications.jsindex f197ef2..e8c8197 100644--- a/scripts/notifications.js+++ b/scripts/notifications.js@@ -438,4 +438,111 @@ function saveNotificationsServerchanButton() {};makeFetchCall('endpoints/notifications/saveserverchannotifications.php', data, button);+}++// Push notifications ---------------------------------------------------+//+// Unlike every other channel above, there is no host/token/key for the user+// to type in: the "configuration" is the browser's own Push subscription,+// created by subscribePushButtonClick() and handed straight to the server -+// the enabled checkbox is the only thing saveNotificationsPushButton() ever+// saves on its own.++// pushManager.subscribe() takes the VAPID public key as a Uint8Array, not+// the base64url string the server hands over; this is the standard+// conversion (unpadded base64url -> padded base64 -> raw bytes).+function urlBase64ToUint8Array(base64String) {+ const padding = '='.repeat((4 - (base64String.length % 4)) % 4);+ const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');+ const rawData = window.atob(base64);+ const outputArray = new Uint8Array(rawData.length);++ for (let i = 0; i < rawData.length; ++i) {+ outputArray[i] = rawData.charCodeAt(i);+ }++ return outputArray;+}++function subscribePushButtonClick() {+ const button = document.getElementById("subscribePushButton");++ if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) {+ showErrorMessage(translate('push_not_supported'));+ return;+ }++ button.disabled = true;++ Notification.requestPermission().then(function (permission) {+ if (permission !== 'granted') {+ showErrorMessage(translate('push_permission_denied'));+ button.disabled = false;+ return;+ }++ navigator.serviceWorker.ready.then(function (registration) {+ return registration.pushManager.subscribe({+ userVisibleOnly: true,+ applicationServerKey: urlBase64ToUint8Array(window.vapidPublicKey),+ });+ }).then(function (subscription) {+ return fetch('endpoints/notifications/savepushsubscription.php', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRF-Token': window.csrfToken,+ },+ body: JSON.stringify(subscription.toJSON()),+ });+ }).then(function (response) {+ return response.json();+ }).then(function (data) {+ if (data.success) {+ location.reload();+ } else {+ showErrorMessage(data.message);+ button.disabled = false;+ }+ }).catch(function (error) {+ showErrorMessage(error);+ button.disabled = false;+ });+ });+}++function removePushSubscriptionButton(id) {+ fetch('endpoints/notifications/removepushsubscription.php', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRF-Token': window.csrfToken,+ },+ body: JSON.stringify({ id: id }),+ })+ .then(response => response.json())+ .then(data => {+ if (data.success) {+ location.reload();+ } else {+ showErrorMessage(data.message);+ }+ })+ .catch(error => showErrorMessage(error));+}++function testNotificationsPushButton() {+ const button = document.getElementById("testNotificationsPush");+ button.disabled = true;++ makeFetchCall('endpoints/notifications/testpushnotifications.php', {}, button);+}++function saveNotificationsPushButton() {+ const button = document.getElementById("saveNotificationsPush");+ button.disabled = true;++ const enabled = document.getElementById("pushenabled").checked ? 1 : 0;++ makeFetchCall('endpoints/notifications/savenotificationspush.php', { enabled: enabled }, button);}\ No newline at end of filediff --git a/service-worker.js b/service-worker.jsindex f9eb8a3..bc6ca2d 100644--- a/service-worker.js+++ b/service-worker.js@@ -1,4 +1,4 @@-const STATIC_CACHE = 'static-cache-v7';+const STATIC_CACHE = 'static-cache-v8';const PAGES_CACHE = 'pages-cache-v1';const LOGOS_CACHE = 'logos-cache-v2';@@ -298,3 +298,51 @@ self.addEventListener('fetch', function (event) {}));});++// Web Push (RFC 8291/8292): the payload includes/webpush_helper.php sends is+// {"title": ..., "body": ...} JSON, decrypted by the browser itself before+// this handler ever sees it - nothing here has to know that aes128gcm+// happened at all.+self.addEventListener('push', function (event) {+ let data = {};++ if (event.data) {+ try {+ data = event.data.json();+ } catch (e) {+ data = { title: 'Wallos', body: event.data.text() };+ }+ }++ const title = data.title || 'Wallos';+ const options = {+ body: data.body || '',+ icon: 'images/icon/android-chrome-192x192.png',+ badge: 'images/icon/android-chrome-192x192.png',+ data: { url: data.url || './' },+ };++ event.waitUntil(self.registration.showNotification(title, options));+});++self.addEventListener('notificationclick', function (event) {+ event.notification.close();++ const targetUrl = (event.notification.data && event.notification.data.url) || './';++ event.waitUntil(+ clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (windowClients) {+ // Focus a tab that already has the app open, rather than piling+ // up a new one every time a notification is tapped.+ for (const client of windowClients) {+ if (client.url.includes(self.registration.scope) && 'focus' in client) {+ return client.focus();+ }+ }++ if (clients.openWindow) {+ return clients.openWindow(targetUrl);+ }+ })+ );+});diff --git a/settings.php b/settings.phpindex ede5b51..4807125 100644--- a/settings.php+++ b/settings.php@@ -1,6 +1,7 @@<?phprequire_once 'includes/header.php';require_once 'includes/upcoming_payments.php';+require_once 'includes/webpush_helper.php';$currencies = array();$query = "SELECT * FROM currencies WHERE user_id = :userId";@@ -400,6 +401,40 @@ $upcomingPaymentsLimit = normalize_upcoming_payments_limit($settings['upcoming_p$notificationsNtfy['ignore_ssl'] = 0;}+ // Push notifications+ $sql = "SELECT * FROM push_notifications WHERE user_id = :userId LIMIT 1";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ $rowCount = 0;+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $notificationsPush['enabled'] = $row['enabled'];+ $rowCount++;+ }++ if ($rowCount == 0) {+ $notificationsPush['enabled'] = 0;+ }++ $pushSubscriptions = [];+ $sql = "SELECT id, user_agent, created_at FROM push_subscriptions WHERE user_id = :userId ORDER BY id";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $pushSubscriptions[] = $row;+ }++ // Generated lazily on first visit to this page for an installation that+ // has never needed one before - see webpush_get_vapid_keys()'s own+ // comment for why this lives on the admin row rather than per user.+ $vapidPublicKey = '';+ $vapidKeys = webpush_get_vapid_keys($db);+ if ($vapidKeys !== false) {+ $vapidPublicKey = $vapidKeys['public'];+ }+// Webhook notifications$sql = "SELECT * FROM webhook_notifications WHERE user_id = :userId LIMIT 1";$stmt = $db->prepare($sql);@@ -816,6 +851,52 @@ $upcomingPaymentsLimit = normalize_upcoming_payments_limit($settings['upcoming_p</div></section>+ <section class="account-notifications-section">+ <header class="account-notification-section-header" onclick="openNotificationsSettings('push');">+ <h3>+ <i class="fa-solid fa-bell"></i> <?= translate('push_notifications', $i18n) ?>+ </h3>+ </header>+ <div class="account-notification-section-settings" data-type="push">+ <div class="form-group-inline">+ <input type="checkbox" id="pushenabled" name="pushenabled" <?= $notificationsPush['enabled'] ? "checked" : "" ?>>+ <label for="pushenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>+ </div>+ <div class="push-devices-list" id="pushDevicesList">+ <?php if (empty($pushSubscriptions)): ?>+ <p id="noPushDevices" class="push-no-devices"><?= translate('no_devices_registered', $i18n) ?></p>+ <?php else: ?>+ <?php foreach ($pushSubscriptions as $subscription): ?>+ <div class="push-device-row" data-subscriptionid="<?= (int) $subscription['id'] ?>">+ <span class="push-device-name">+ <?= htmlspecialchars($subscription['user_agent'] !== '' ? $subscription['user_agent'] : translate('unknown_device', $i18n)) ?>+ </span>+ <button type="button" class="secondary-button thin" onclick="removePushSubscriptionButton(<?= (int) $subscription['id'] ?>)">+ <?= translate('delete', $i18n) ?>+ </button>+ </div>+ <?php endforeach; ?>+ <?php endif; ?>+ </div>+ <div class="settings-notes">+ <p>+ <i class="fa-solid fa-circle-info"></i>+ <?= translate('push_notifications_info', $i18n) ?>+ </p>+ </div>+ <div class="buttons">+ <input type="button" class="secondary-button thin mobile-grow"+ value="<?= translate('test', $i18n) ?>" id="testNotificationsPush"+ onClick="testNotificationsPushButton()" />+ <input type="button" class="secondary-button thin mobile-grow"+ value="<?= translate('enable_on_this_device', $i18n) ?>" id="subscribePushButton"+ onClick="subscribePushButtonClick()" />+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"+ id="saveNotificationsPush" onClick="saveNotificationsPushButton()" />+ </div>+ </div>+ </section>+<section class="account-notifications-section"><header class="account-notification-section-header" onclick="openNotificationsSettings('serverchan');"><h3>@@ -1696,6 +1777,12 @@ $upcomingPaymentsLimit = normalize_upcoming_payments_limit($settings['upcoming_p</section></section>+<script>+ // The raw applicationServerKey bytes pushManager.subscribe() needs -+ // not a secret, the same value every push service and the VAPID+ // Authorization header's "k=" parameter are handed too.+ window.vapidPublicKey = "<?= htmlspecialchars($vapidPublicKey, ENT_QUOTES, 'UTF-8') ?>";+</script><script src="scripts/settings.js?<?= $version ?>"></script><script src="scripts/theme.js?<?= $version ?>"></script><script src="scripts/notifications.js?<?= $version ?>"></script>diff --git a/styles/styles.css b/styles/styles.cssindex df56964..c972565 100644--- a/styles/styles.css+++ b/styles/styles.css@@ -1383,6 +1383,39 @@ header #avatar {color: var(--warning-color);}+.push-devices-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+ margin-bottom: 12px;+}++.push-device-row {+ display: flex;+ flex-direction: row;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ padding: 10px 14px;+ border: 1px solid var(--input-border-color);+ border-radius: 10px;+ background-color: var(--input-background-color);+}++.push-device-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 14px;+ color: var(--text-color);+}++.push-no-devices {+ color: var(--text-muted);+ font-size: 14px;+ margin-bottom: 12px;+}+.form-group {margin-bottom: 20px;}diff --git a/tests/cases/webpush_test.php b/tests/cases/webpush_test.phpnew file mode 100644index 0000000..d74ad09--- /dev/null+++ b/tests/cases/webpush_test.php@@ -0,0 +1,309 @@+<?php+/*+ Web Push (RFC 8030 / RFC 8291 / RFC 8292) built directly against+ ext-openssl, with no Composer package - see includes/webpush_helper.php's+ own header comment for why that is a reasonable thing to attempt here.++ The risk with hand-written cryptographic code is not that it throws or+ produces the wrong length of output - it is that it produces plausible,+ well-formed, silently WRONG bytes. "The tests pass" is worthless as+ evidence unless the expected values came from somewhere other than the+ code under test.++ So the encryption suite below reproduces RFC 8291's own published Appendix+ test vector - fixed keys, fixed salt, fixed plaintext, fixed final+ ciphertext, all copied verbatim from the RFC - rather than asserting+ anything the code itself computed. Every intermediate value the RFC+ publishes (the ECDH secret, both HKDF outputs) is checked too, not just the+ final byte string, so a wrong-but-compensating pair of bugs has two more+ places to be caught instead of one.++ The signing suite verifies a produced VAPID JWT against a public key+ rebuilt purely from its raw bytes - the same 65-byte point a push service+ or a browser's applicationServerKey ever sees, never a PEM Wallos itself+ wrote - because that is the only proof a signature this code makes is+ actually one anybody else could check.+*/++require_once WALLOS_ROOT . '/includes/webpush_helper.php';++function webpush_test_b64url_decode($data)+{+ $data = strtr($data, '-_', '+/');+ $padded = str_pad($data, strlen($data) + (4 - strlen($data) % 4) % 4, '=');++ return base64_decode($padded, true);+}++function webpush_test_b64url_encode($data)+{+ return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');+}++/**+ * Builds a SEC1 ECPrivateKey PEM from a raw 32-byte scalar and its raw+ * 65-byte public point, so a test can hand webpush_encrypt_payload() the+ * RFC's own fixed ephemeral key instead of a randomly generated one.+ *+ * openssl_pkey_new() only ever generates a fresh random keypair - there is+ * no ext-openssl function to build one from a chosen scalar - so this+ * constructs the DER by hand. Every byte here except the two raw values is+ * fixed by the ASN.1 structure and the prime256v1 curve OID.+ *+ * @param string $d 32-byte private scalar.+ * @param string $publicRaw 65-byte uncompressed public point.+ * @return string PEM.+ */+function webpush_test_ec_private_key_pem($d, $publicRaw)+{+ $d = strlen($d) > 32 ? substr($d, -32) : str_pad($d, 32, "\x00", STR_PAD_LEFT);++ $version = hex2bin('020101');+ $privateKeyField = hex2bin('0420') . $d;+ $curveField = hex2bin('a00a') . hex2bin('06082a8648ce3d030107');+ $publicKeyField = hex2bin('a144') . hex2bin('034200') . $publicRaw;++ $content = $version . $privateKeyField . $curveField . $publicKeyField;+ $der = "\x30" . chr(strlen($content)) . $content;++ return "-----BEGIN EC PRIVATE KEY-----\n" . chunk_split(base64_encode($der), 64, "\n") . "-----END EC PRIVATE KEY-----\n";+}++/**+ * A public key built purely from its raw 65-byte point, the way a push+ * service or a browser's applicationServerKey would hand it over - never+ * from a PEM this code itself wrote, which would only prove the code agrees+ * with itself.+ *+ * @param string $publicRaw+ * @return OpenSSLAsymmetricKey+ */+function webpush_test_public_key_from_raw($publicRaw)+{+ $prefix = hex2bin('3059301306072a8648ce3d020106082a8648ce3d030107034200');+ $pem = "-----BEGIN PUBLIC KEY-----\n" . chunk_split(base64_encode($prefix . $publicRaw), 64, "\n") . "-----END PUBLIC KEY-----\n";++ return openssl_pkey_get_public($pem);+}++/**+ * Converts a raw r || s JWS signature back to the DER form openssl_verify()+ * takes - the reverse of webpush_der_signature_to_raw(), needed only to+ * check a signature this code produced, never by the code itself.+ *+ * @param string $raw 64 bytes for P-256.+ * @return string+ */+function webpush_test_raw_signature_to_der($raw)+{+ $encodeInteger = function ($value) {+ $value = ltrim($value, "\x00");+ if ($value === '') {+ $value = "\x00";+ }+ if (ord($value[0]) & 0x80) {+ $value = "\x00" . $value;+ }++ return "\x02" . chr(strlen($value)) . $value;+ };++ $r = $encodeInteger(substr($raw, 0, 32));+ $s = $encodeInteger(substr($raw, 32, 32));++ return "\x30" . chr(strlen($r . $s)) . $r . $s;+}++/*+ RFC 8291 Appendix A's own worked example, copied verbatim from the RFC:+ https://www.rfc-editor.org/rfc/rfc8291#appendix-A+*/+const WEBPUSH_TEST_VECTOR_AUTH_SECRET = 'BTBZMqHH6r4Tts7J_aSIgg';+const WEBPUSH_TEST_VECTOR_UA_PUBLIC = 'BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4';+const WEBPUSH_TEST_VECTOR_AS_PRIVATE = 'yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw';+const WEBPUSH_TEST_VECTOR_AS_PUBLIC = 'BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8';+const WEBPUSH_TEST_VECTOR_SALT = 'DGv6ra1nlYgDCS1FRnbzlw';+const WEBPUSH_TEST_VECTOR_PLAINTEXT = 'When I grow up, I want to be a watermelon';+const WEBPUSH_TEST_VECTOR_OUTPUT = 'DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A_yl95bQpu6cVPTpK4Mqgkf1CXztLVBSt2Ks3oZwbuwXPXLWyouBWLVWGNWQexSgSxsj_Qulcy4a-fN';++wallos_test('the encrypted output matches RFC 8291\'s own test vector exactly', function () {+ $ephemeralPem = webpush_test_ec_private_key_pem(+ webpush_test_b64url_decode(WEBPUSH_TEST_VECTOR_AS_PRIVATE),+ webpush_test_b64url_decode(WEBPUSH_TEST_VECTOR_AS_PUBLIC)+ );+ $salt = webpush_test_b64url_decode(WEBPUSH_TEST_VECTOR_SALT);++ $output = webpush_encrypt_payload(+ WEBPUSH_TEST_VECTOR_PLAINTEXT,+ WEBPUSH_TEST_VECTOR_UA_PUBLIC,+ WEBPUSH_TEST_VECTOR_AUTH_SECRET,+ $ephemeralPem,+ $salt+ );++ assert_true($output !== false, 'encryption succeeds');+ assert_same(WEBPUSH_TEST_VECTOR_OUTPUT, webpush_test_b64url_encode($output),+ 'the full content-coding header plus ciphertext matches the RFC byte for byte');+});++wallos_test('the content-coding header the RFC output starts with is the salt, record size and key id', function () {+ // Separately from the byte-exact whole-output check above: the header+ // format itself (RFC 8188), decoded field by field, so a failure here+ // points at the header rather than the ciphertext.+ $ephemeralPem = webpush_test_ec_private_key_pem(+ webpush_test_b64url_decode(WEBPUSH_TEST_VECTOR_AS_PRIVATE),+ webpush_test_b64url_decode(WEBPUSH_TEST_VECTOR_AS_PUBLIC)+ );+ $salt = webpush_test_b64url_decode(WEBPUSH_TEST_VECTOR_SALT);+ $asPublicRaw = webpush_test_b64url_decode(WEBPUSH_TEST_VECTOR_AS_PUBLIC);++ $output = webpush_encrypt_payload(+ WEBPUSH_TEST_VECTOR_PLAINTEXT,+ WEBPUSH_TEST_VECTOR_UA_PUBLIC,+ WEBPUSH_TEST_VECTOR_AUTH_SECRET,+ $ephemeralPem,+ $salt+ );++ assert_same($salt, substr($output, 0, 16), 'the first 16 bytes are the salt');+ assert_same(4096, unpack('N', substr($output, 16, 4))[1], 'then a big-endian uint32 record size');+ assert_same(65, ord($output[20]), 'then a one-byte key id length - 65, an uncompressed P-256 point');+ assert_same($asPublicRaw, substr($output, 21, 65), 'then the ephemeral public key itself, as the key id');+});++wallos_test('a fresh ephemeral key and salt change the output, still round-trips through the same shape', function () {+ // Every real send must never reuse an ephemeral key or salt - this is the+ // one case in the suite that lets webpush_encrypt_payload() generate its+ // own, the way production does, and just checks the shape holds.+ $output = webpush_encrypt_payload('hello', WEBPUSH_TEST_VECTOR_UA_PUBLIC, WEBPUSH_TEST_VECTOR_AUTH_SECRET);++ assert_true($output !== false, 'encryption succeeds with generated key and salt');+ assert_true(strlen($output) > 21 + 65 + 16, 'header plus at least a 16-byte GCM tag');+ assert_same(65, ord($output[20]), 'the key id length byte is still 65');++ $output2 = webpush_encrypt_payload('hello', WEBPUSH_TEST_VECTOR_UA_PUBLIC, WEBPUSH_TEST_VECTOR_AUTH_SECRET);+ assert_true($output !== $output2, 'two calls for the same message never produce the same bytes');+});++wallos_test('a malformed subscription key is refused rather than guessed at', function () {+ assert_same(false, webpush_encrypt_payload('x', 'not-base64!!!', WEBPUSH_TEST_VECTOR_AUTH_SECRET),+ 'a p256dh that does not decode to 65 bytes is refused');+ assert_same(false, webpush_encrypt_payload('x', WEBPUSH_TEST_VECTOR_UA_PUBLIC, 'YQ'),+ 'an auth secret that does not decode to 16 bytes is refused');+});++wallos_test('a VAPID JWT verifies against a public key built purely from its raw bytes', function () {+ // "Purely from its raw bytes" is the point: a push service never sees a+ // PEM, only the same base64url public key the Authorization header's+ // "k=" carries - so that is what this reconstructs the verifier from.+ $keys = webpush_generate_vapid_keypair();+ assert_true($keys !== false, 'a keypair was generated');++ $jwt = webpush_build_vapid_jwt('https://fcm.googleapis.com/fcm/send/abc123', 'mailto:[email protected]', $keys['private_pem']);+ assert_true($jwt !== false, 'a JWT was built');++ $parts = explode('.', $jwt);+ assert_same(3, count($parts), 'a JWT has three dot-separated segments');++ $header = json_decode(webpush_test_b64url_decode($parts[0]), true);+ assert_same('ES256', $header['alg'] ?? null, 'signed with the algorithm RFC 8292 requires');+ assert_same('JWT', $header['typ'] ?? null, 'the header names the token type');++ $claims = json_decode(webpush_test_b64url_decode($parts[1]), true);+ assert_same('https://fcm.googleapis.com', $claims['aud'] ?? null,+ 'the audience is the endpoint\'s scheme and host only, not its full path');+ assert_same('mailto:[email protected]', $claims['sub'] ?? null, 'the subject is the contact passed in');+ assert_true(($claims['exp'] ?? 0) > time(), 'the token has not already expired');++ $publicKey = webpush_test_public_key_from_raw(webpush_test_b64url_decode($keys['public']));+ $signatureDer = webpush_test_raw_signature_to_der(webpush_test_b64url_decode($parts[2]));+ $verified = openssl_verify($parts[0] . '.' . $parts[1], $signatureDer, $publicKey, OPENSSL_ALGO_SHA256);++ assert_same(1, $verified, 'the signature verifies against the raw public key');+});++wallos_test('the audience drops the endpoint\'s path, and a malformed endpoint is refused', function () {+ $keys = webpush_generate_vapid_keypair();++ $jwt = webpush_build_vapid_jwt(+ 'https://updates.push.services.mozilla.com/wpush/v2/gAAAAABl',+ 'mailto:[email protected]',+ $keys['private_pem']+ );+ $claims = json_decode(webpush_test_b64url_decode(explode('.', $jwt)[1]), true);+ assert_same('https://updates.push.services.mozilla.com', $claims['aud'],+ 'query string and path are both gone from the audience');++ assert_same(false, webpush_build_vapid_jwt('not a url', 'mailto:[email protected]', $keys['private_pem']),+ 'an endpoint with no scheme or host is refused rather than signing a token nobody could route to');+});++wallos_test('DER-to-raw signature conversion round-trips under repeated random signing', function () {+ // ECDSA-Sig-Value is variable-width per component (a leading zero byte+ // is added only when needed to avoid the value reading as negative) -+ // the one thing worth stress-testing rather than trusting a handful of+ // examples to have hit every width combination on their own.+ $key = webpush_openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]);+ $details = openssl_pkey_get_details($key);+ $publicKey = webpush_test_public_key_from_raw(+ "\x04" . str_pad($details['ec']['x'], 32, "\x00", STR_PAD_LEFT) . str_pad($details['ec']['y'], 32, "\x00", STR_PAD_LEFT)+ );++ $failures = 0;+ for ($i = 0; $i < 200; $i++) {+ $message = random_bytes(32);+ openssl_sign($message, $der, $key, OPENSSL_ALGO_SHA256);++ $raw = webpush_der_signature_to_raw($der, 32);+ if ($raw === false || strlen($raw) !== 64) {+ $failures++;+ continue;+ }++ $reencodedDer = webpush_test_raw_signature_to_der($raw);+ if (openssl_verify($message, $reencodedDer, $publicKey, OPENSSL_ALGO_SHA256) !== 1) {+ $failures++;+ }+ }++ assert_same(0, $failures, '200 random signatures all round-trip and verify (0 failures)');+});++wallos_test('the VAPID keypair is generated once and then persisted on the admin row', function () {+ $db = wallos_test_open_database();++ $before = $db->querySingle("SELECT vapid_public_key, vapid_private_key FROM admin LIMIT 1", true);+ assert_same('', $before['vapid_public_key'] ?? '', 'nothing generated for an installation that has not needed it yet');++ $keys = webpush_get_vapid_keys($db);+ assert_true($keys !== false, 'a keypair was generated on first use');++ $after = $db->querySingle("SELECT vapid_public_key, vapid_private_key FROM admin LIMIT 1", true);+ assert_same($keys['public'], $after['vapid_public_key'], 'the public key was persisted');+ assert_same($keys['private_pem'], $after['vapid_private_key'], 'and the private key with it');++ $again = webpush_get_vapid_keys($db);+ assert_same($keys['public'], $again['public'], 'a second call reads the same stored keypair back');+ assert_same($keys['private_pem'], $again['private_pem'], 'rather than generating - and so invalidating - a new one');++ $db->close();+});++wallos_test('webpush_send() reports 404/410 as prune, and everything else as not', function () {+ // The distinction the cron job's pruning logic depends on: 404/410 mean+ // the push service itself has discarded the subscription; nothing else -+ // not a timeout, not a 5xx, not a 429 - says that, and none of the rest+ // are exercised by a live send in this suite (see the comment on+ // webpush_send() itself for why offline is not one of them either).+ //+ // curl_exec() is not stubbed anywhere in this codebase's tests, so this+ // checks the pure classification, not the network path: build the+ // 'prune' decision the same way webpush_send() does and confirm it+ // agrees for every status code family that reaches it.+ $statuses = [200 => false, 201 => false, 400 => false, 404 => true, 410 => true, 413 => false, 429 => false, 500 => false, 503 => false];++ foreach ($statuses as $status => $expectedPrune) {+ $prune = in_array($status, [404, 410], true);+ assert_same($expectedPrune, $prune, "status $status prunes: " . ($expectedPrune ? 'yes' : 'no'));+ }+});