diff --git a/controller/acp_controller.php b/controller/acp_controller.php
index 1f611d3..1196be9 100644
--- a/controller/acp_controller.php
+++ b/controller/acp_controller.php
@@ -240,6 +240,15 @@ protected function save_settings()
return;
}
+ // Store VAPID keys in the unpadded Base64URL form reported by browsers.
+ foreach (['wpn_webpush_vapid_public', 'wpn_webpush_vapid_private'] as $key_name)
+ {
+ if (isset($config_array[$key_name]))
+ {
+ $config_array[$key_name] = rtrim($config_array[$key_name], '=');
+ }
+ }
+
$this->log->add('admin', $this->user->data['user_id'], $this->user->ip, 'LOG_CONFIG_WEBPUSH');
foreach (array_keys($display_settings) as $config_name)
diff --git a/language/en/webpushnotifications_module_acp.php b/language/en/webpushnotifications_module_acp.php
index 7ef3224..12ded60 100644
--- a/language/en/webpushnotifications_module_acp.php
+++ b/language/en/webpushnotifications_module_acp.php
@@ -43,7 +43,7 @@
'WEBPUSH_ENABLE' => 'Enable Web Push',
'WEBPUSH_ENABLE_EXPLAIN' => 'Allow users to receive notifications in their browser or device via Web Push. To utilise Web Push, you must input or generate valid VAPID identification keys.',
'WEBPUSH_VAPID_CREDENTIALS' => 'VAPID credentials',
- 'WEBPUSH_VAPID_CREDENTIALS_EXPLAIN'=> 'These keys identify your board to push services. Generate a new key pair or enter an existing pair below.',
+ 'WEBPUSH_VAPID_CREDENTIALS_EXPLAIN'=> 'Voluntary Application Server Identification (VAPID) keys identify your board to push services. Generate a new key pair or enter an existing pair below.',
'WEBPUSH_VAPID_KEYS_CONFIGURED'=> 'Keys configured',
'WEBPUSH_VAPID_KEYS_REQUIRED' => 'Setup required',
'WEBPUSH_VAPID_KEYS_PENDING' => 'Unsaved keys',
@@ -65,7 +65,7 @@
'WEBPUSH_HIDE_PRIVATE_KEY' => 'Hide private key',
'WEBPUSH_METHOD_ENABLED' => 'Enable user-based web push notifications by default',
'WEBPUSH_METHOD_ENABLED_EXPLAIN'=> 'When this setting is enabled, users who have also enabled and allowed browser notifications will start receiving them automatically. They can visit the UCP Notification settings to disable any unwanted notifications.
If this setting is disabled, users will not receive any notifications, even if they have enabled push notifications, until they visit the UCP Notification settings to allow the specific notifications they wish to receive.',
- 'WEBPUSH_DROPDOWN_SUBSCRIBE' => 'Show web push settings in the notification dropdown',
+ 'WEBPUSH_DROPDOWN_SUBSCRIBE' => 'Show subscription toggle in notification dropdown',
'WEBPUSH_DROPDOWN_SUBSCRIBE_EXPLAIN'=> 'Show or hide the “Enable Web Push” toggle switch in the notification dropdown. This allows users to easily enable or disable push notifications from any page of the forum.',
'WEBPUSH_POPUP_PROMPT' => 'Show popup prompt for unsubscribed members',
'WEBPUSH_POPUP_PROMPT_EXPLAIN' => 'Display a popup message asking registered members if they want to receive push notifications. The popup will only appear to members who are not currently subscribed and have not previously denied.',
diff --git a/notification/method/webpush.php b/notification/method/webpush.php
index 264ef0d..5572fb7 100644
--- a/notification/method/webpush.php
+++ b/notification/method/webpush.php
@@ -198,7 +198,7 @@ protected function notify_using_webpush(): void
// Load all the users we need
$notify_users = array_diff($user_ids, $banned_users);
- // If we have no users (e.g. all recipients are banned) empty queue and exit
+ // Empty the queue and exit if there are no users (e.g. all recipients are banned).
if (empty($notify_users))
{
$this->empty_queue();
@@ -304,6 +304,7 @@ protected function notify_using_webpush(): void
// List to fill with expired subscriptions based on return
$expired_endpoints = [];
+ $delivery_failures = [];
try
{
@@ -321,8 +322,7 @@ protected function notify_using_webpush(): void
}
else
{
- $report_data = json_sanitizer::sanitize($report->jsonSerialize());
- $this->log->add('admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, [$report_data['reason']]);
+ $this->add_delivery_failure($delivery_failures, $report);
}
}
}
@@ -332,6 +332,8 @@ protected function notify_using_webpush(): void
$this->log->add('critical', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, [$exception->getMessage()]);
}
+ $this->log_delivery_failures($delivery_failures);
+
// We're done, empty the queue
$this->empty_queue();
@@ -596,4 +598,45 @@ protected function is_endpoint_permanently_removed(string $endpoint): bool
$host = parse_url($endpoint, PHP_URL_HOST);
return is_string($host) && substr($host, -strlen('.invalid')) === '.invalid';
}
+
+ /**
+ * Group a delivery failure by response category
+ *
+ * @param array $failures Grouped delivery failures
+ * @param \Minishlink\WebPush\MessageSentReport $report Failed delivery report
+ * @return void
+ */
+ protected function add_delivery_failure(array &$failures, \Minishlink\WebPush\MessageSentReport $report): void
+ {
+ $response = $report->getResponse();
+ $category = $response ? 'http:' . $response->getStatusCode() : 'network';
+
+ if (!isset($failures[$category]))
+ {
+ $report_data = json_sanitizer::sanitize(['reason' => $report->getReason()]);
+ $failures[$category] = [
+ 'count' => 0,
+ 'reason' => (string) ($report_data['reason'] ?? ''),
+ ];
+ }
+
+ $failures[$category]['count']++;
+ }
+
+ /**
+ * Log delivery failures once per response category
+ *
+ * @param array $failures Grouped delivery failures
+ * @return void
+ */
+ protected function log_delivery_failures(array $failures): void
+ {
+ foreach ($failures as $failure)
+ {
+ $reason = $failure['count'] > 1
+ ? $failure['count'] . ' × ' . $failure['reason']
+ : $failure['reason'];
+ $this->log->add('admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, [$reason]);
+ }
+ }
}
diff --git a/subscription/validator.php b/subscription/validator.php
index f57a4dd..3130943 100644
--- a/subscription/validator.php
+++ b/subscription/validator.php
@@ -35,6 +35,7 @@ public static function is_valid_vapid_keys(string $public_key, string $private_k
try
{
$vapid = VAPID::validate([
+ // Placeholder required by VAPID::validate(); delivery uses the configured board URL.
'subject' => 'https://example.com',
'publicKey' => $public_key,
'privateKey' => $private_key,
diff --git a/tests/controller/controller_acp_test.php b/tests/controller/controller_acp_test.php
index ff38c1f..2fd5342 100644
--- a/tests/controller/controller_acp_test.php
+++ b/tests/controller/controller_acp_test.php
@@ -238,6 +238,36 @@ public function webpush_save_data(): array
],
true,
],
+ 'padded VAPID keys are stored without padding' => [
+ array_merge($valid, [
+ 'wpn_webpush_vapid_public' => self::VALID_VAPID_PUBLIC_KEY . '=',
+ 'wpn_webpush_vapid_private' => self::VALID_VAPID_PRIVATE_KEY . '=',
+ ]),
+ [
+ 'S_ERROR' => false,
+ 'ERROR_MSG' => '',
+ ],
+ [
+ 'wpn_webpush_vapid_public' => self::VALID_VAPID_PUBLIC_KEY,
+ 'wpn_webpush_vapid_private' => self::VALID_VAPID_PRIVATE_KEY,
+ ],
+ true,
+ ],
+ 'excessive VAPID key padding is rejected' => [
+ array_merge($valid, [
+ 'wpn_webpush_vapid_public' => self::VALID_VAPID_PUBLIC_KEY . '==',
+ 'wpn_webpush_vapid_private' => self::VALID_VAPID_PRIVATE_KEY . '=',
+ ]),
+ [
+ 'S_ERROR' => true,
+ 'ERROR_MSG' => 'WEBPUSH_VAPID_KEYS_INVALID',
+ ],
+ [
+ 'wpn_webpush_vapid_public' => self::VALID_VAPID_PUBLIC_KEY,
+ 'wpn_webpush_vapid_private' => self::VALID_VAPID_PRIVATE_KEY,
+ ],
+ false,
+ ],
'blank existing private key is preserved' => [
array_merge($valid, [
'wpn_webpush_vapid_private' => '',
diff --git a/tests/controller/controller_webpush_test.php b/tests/controller/controller_webpush_test.php
index 1bc2835..1f0becd 100644
--- a/tests/controller/controller_webpush_test.php
+++ b/tests/controller/controller_webpush_test.php
@@ -559,6 +559,45 @@ public function test_subscribe_replaces_previous_subscription()
], $subscriptions[0]);
}
+ public function test_subscribe_keeps_only_newest_subscriptions_for_current_user(): void
+ {
+ $subscriptions = [];
+ for ($i = 0; $i < 1021; $i++)
+ {
+ $subscriptions[] = [
+ 'user_id' => 2,
+ 'endpoint' => 'https://fcm.googleapis.com/fcm/send/old_' . $i,
+ 'expiration_time' => 0,
+ 'p256dh' => self::VALID_PUBLIC_KEY,
+ 'auth' => self::VALID_AUTH_TOKEN,
+ ];
+ }
+ for ($i = 0; $i < 3; $i++)
+ {
+ $subscriptions[] = [
+ 'user_id' => 3,
+ 'endpoint' => 'https://fcm.googleapis.com/fcm/send/other_' . $i,
+ 'expiration_time' => 0,
+ 'p256dh' => self::VALID_PUBLIC_KEY,
+ 'auth' => self::VALID_AUTH_TOKEN,
+ ];
+ }
+ $this->db->sql_multi_insert('phpbb_wpn_push_subscriptions', $subscriptions);
+
+ $endpoint = 'https://fcm.googleapis.com/fcm/send/newest';
+ $response = $this->controller->subscribe($this->create_subscription_request(json_encode([
+ 'endpoint' => $endpoint,
+ 'expiration_time' => 0,
+ 'keys' => ['p256dh' => self::VALID_PUBLIC_KEY, 'auth' => self::VALID_AUTH_TOKEN],
+ ])));
+
+ self::assertInstanceOf(JsonResponse::class, $response);
+ $user_subscriptions = $this->get_all_subscriptions(2);
+ self::assertCount(webpush::MAX_SUBSCRIPTIONS_PER_USER, $user_subscriptions);
+ self::assertContains($endpoint, array_column($user_subscriptions, 'endpoint'));
+ self::assertCount(3, $this->get_all_subscriptions(3));
+ }
+
public function test_subscribe_invalid_payload_preserves_existing_subscription()
{
$this->form_helper->method('check_form_tokens')->willReturn(true);
diff --git a/tests/notification/webpush_branches_test.php b/tests/notification/webpush_branches_test.php
index 372ab70..138d3df 100644
--- a/tests/notification/webpush_branches_test.php
+++ b/tests/notification/webpush_branches_test.php
@@ -135,6 +135,64 @@ public function test_invalid_vapid_config_logs_failure_without_throwing(): void
self::assertSame([], $method->get_queue());
}
+ public function test_delivery_failures_are_logged_once_per_category(): void
+ {
+ $log = $this->createMock(\phpbb\log\log_interface::class);
+ $log->expects(self::exactly(3))->method('add')->withConsecutive(
+ ['admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, ['3 × Unauthorized']],
+ ['admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, ['2 × Forbidden']],
+ ['admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, ['2 × DNS failure one']]
+ );
+ $method = $this->create_method($log);
+ $reports = [
+ $this->create_failed_report(401, 'Unauthorized'),
+ $this->create_failed_report(401, 'Unauthorized again'),
+ $this->create_failed_report(401, 'Unauthorized once more'),
+ $this->create_failed_report(403, 'Forbidden'),
+ $this->create_failed_report(403, 'Forbidden again'),
+ $this->create_failed_report(null, 'DNS failure one'),
+ $this->create_failed_report(null, 'DNS failure two'),
+ ];
+
+ $method->log_delivery_failures_for_test($reports);
+ }
+
+ public function test_single_delivery_failure_keeps_original_reason(): void
+ {
+ $log = $this->createMock(\phpbb\log\log_interface::class);
+ $log->expects(self::once())->method('add')->with(
+ 'admin',
+ ANONYMOUS,
+ '',
+ 'LOG_WEBPUSH_MESSAGE_FAIL',
+ false,
+ ['Too Many Requests']
+ );
+
+ $this->create_method($log)->log_delivery_failures_for_test([
+ $this->create_failed_report(429, 'Too Many Requests'),
+ ]);
+ }
+
+ private function create_failed_report(?int $status_code, string $reason): \Minishlink\WebPush\MessageSentReport
+ {
+ $uri = $this->createMock(\Psr\Http\Message\UriInterface::class);
+ $uri->method('__toString')->willReturn('https://push.example.test/endpoint');
+ $body = $this->createMock(\Psr\Http\Message\StreamInterface::class);
+ $body->method('getContents')->willReturn('payload');
+ $request = $this->createMock(\Psr\Http\Message\RequestInterface::class);
+ $request->method('getUri')->willReturn($uri);
+ $request->method('getBody')->willReturn($body);
+ $response = null;
+ if ($status_code !== null)
+ {
+ $response = $this->createMock(\Psr\Http\Message\ResponseInterface::class);
+ $response->method('getStatusCode')->willReturn($status_code);
+ }
+
+ return new \Minishlink\WebPush\MessageSentReport($request, $response, false, $reason);
+ }
+
private function create_method($log = null, $user_loader = null, $assets_version = 1): testable_webpush
{
global $config, $phpbb_root_path, $phpEx, $user;
@@ -197,6 +255,16 @@ public function set_push_token($type_id, $item_id, $user_id, $token): void
$property->setValue($this, [$type_id => [$item_id => [$user_id => $token]]]);
}
+ public function log_delivery_failures_for_test(array $reports): void
+ {
+ $failures = [];
+ foreach ($reports as $report)
+ {
+ $this->add_delivery_failure($failures, $report);
+ }
+ $this->log_delivery_failures($failures);
+ }
+
protected function get_user_subscription_map(array $notify_users): array
{
return $this->subscriptions;
diff --git a/ucp/controller/webpush.php b/ucp/controller/webpush.php
index 81156b5..43e147a 100644
--- a/ucp/controller/webpush.php
+++ b/ucp/controller/webpush.php
@@ -37,6 +37,12 @@ class webpush
/** @var string UCP form token name */
public const FORM_TOKEN_UCP = 'ucp_webpush';
+ /** @var int Maximum number of stored subscriptions per user */
+ public const MAX_SUBSCRIPTIONS_PER_USER = 20;
+
+ /** @var int Maximum number of surplus subscriptions removed per query */
+ private const SUBSCRIPTION_PRUNE_BATCH_SIZE = 100;
+
/** @var array Allowed push service endpoint hosts https://github.com/pushpad/known-push-services */
public const PUSH_SERVICE_WHITELIST = [
'android.googleapis.com',
@@ -430,12 +436,43 @@ public function subscribe(symfony_request $symfony_request): JsonResponse
$this->db->sql_query($sql);
}
+ $this->prune_user_subscriptions($this->user->id());
+
return new JsonResponse([
'success' => true,
'form_tokens' => $this->form_helper->get_form_tokens(self::FORM_TOKEN_UCP),
]);
}
+ /**
+ * Keep only the newest subscriptions for a user
+ *
+ * @param int $user_id User id
+ * @return void
+ */
+ protected function prune_user_subscriptions(int $user_id): void
+ {
+ do
+ {
+ $sql = 'SELECT subscription_id
+ FROM ' . $this->push_subscriptions_table . '
+ WHERE user_id = ' . $user_id . '
+ ORDER BY subscription_id DESC';
+ $result = $this->db->sql_query_limit($sql, self::SUBSCRIPTION_PRUNE_BATCH_SIZE, self::MAX_SUBSCRIPTIONS_PER_USER);
+ $surplus = array_map('intval', array_column($this->db->sql_fetchrowset($result), 'subscription_id'));
+ $this->db->sql_freeresult($result);
+
+ if (!empty($surplus))
+ {
+ $sql = 'DELETE FROM ' . $this->push_subscriptions_table . '
+ WHERE user_id = ' . $user_id . '
+ AND ' . $this->db->sql_in_set('subscription_id', $surplus);
+ $this->db->sql_query($sql);
+ }
+ }
+ while (count($surplus) === self::SUBSCRIPTION_PRUNE_BATCH_SIZE);
+ }
+
/**
* Validate and normalize subscription data for database writes
*