Skip to content

Implement reliable Web Push delivery with VAPID, retries, and subscription cleanup #1720

Closed

Description

@propr-dev

Context

Persisting notifications does not alert users while the PWA is closed. This issue adds server-side Web Push delivery using standard VAPID credentials. Delivery must be reliable enough for operational alerts without allowing a failed push provider to disrupt task execution.

Requirements

  • Add the web-push dependency to the server package that owns delivery.
  • Validate WEB_PUSH_VAPID_SUBJECT, WEB_PUSH_VAPID_PUBLIC_KEY, and WEB_PUSH_VAPID_PRIVATE_KEY at dispatcher startup.
  • Fan out eligible notification events to each active subscription whose user preferences permit the category.
  • Respect global enablement, push enablement, category toggles, and quiet hours.
  • Include only lock-screen-safe summary data in push payloads.
  • Include the authenticated UI deep link, API base URL, unread count, and at most two notification-surface actions.
  • Retry transient delivery failures with capped exponential backoff.
  • Revoke subscriptions on 404 or 410 responses.
  • Prevent concurrent dispatcher runs from delivering the same event twice.
  • Never log endpoints, subscription keys, VAPID keys, prompt text, or full payload bodies.

Acceptance Criteria

  • A subscribed user receives an allowed notification outside quiet hours.
  • A category-disabled user receives no push for that category while the Inbox event remains visible.
  • A 410 Gone response revokes the subscription.
  • A 429 or 5xx response becomes retryable with a future next_attempt_at.
  • Delivery attempts stop after the configured maximum and retain a safe error summary.
  • Missing VAPID configuration disables the dispatcher with one warning rather than crashing the API.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Aug 2, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Use a database-backed delivery ledger and a short polling dispatcher. Directly sending push inside task completion code was rejected because it would couple agent execution to an external push service and lose retry state on restart. A dedicated new worker container would provide stronger isolation but is unnecessary for the focused first release; the dispatcher is written as a service so it can move to a separate process later.

    File: packages/core/package.json

    Why this file: Push signing and encryption should use the maintained Web Push implementation rather than custom cryptography.

    --- a/packages/core/package.json
    +++ b/packages/core/package.json
    @@ -20,6 +20,7 @@
       "dependencies": {
    +    "web-push": "^3.6.7"
       },
       "devDependencies": {
    +    "@types/web-push": "^3.6.4"
       }

    File: packages/core/src/services/webPushDispatcher.ts (new file)

    Why this file: This service owns fan-out policy, quiet-hour evaluation, retry behavior, and transport-specific cleanup without leaking those concerns into notification creation.

    import { randomUUID } from 'node:crypto';
    import webPush from 'web-push';
    import { db } from '../db/connection.js';
    import logger from '../utils/logger.js';
    import { getNotificationPreferences } from './notificationPreferencesService.js';
    import { getUnreadNotificationCount } from './notificationService.js';
    import type { NotificationCategory } from '@propr/shared';
    
    const maxAttempts = 5;
    let configured = false;
    let running = false;
    
    function configureTransport(): boolean {
      if (configured) return true;
      const subject = process.env.WEB_PUSH_VAPID_SUBJECT?.trim();
      const publicKey = process.env.WEB_PUSH_VAPID_PUBLIC_KEY?.trim();
      const privateKey = process.env.WEB_PUSH_VAPID_PRIVATE_KEY?.trim();
      if (!subject || !publicKey || !privateKey) return false;
      // VAPID requires a contact URI. Rejecting an arbitrary string early produces
      // clearer diagnostics than a provider-specific delivery error later.
      if (!subject.startsWith('mailto:') && !subject.startsWith('https://')) {
        throw new Error('WEB_PUSH_VAPID_SUBJECT must be a mailto: or https: URI');
      }
      webPush.setVapidDetails(subject, publicKey, privateKey);
      configured = true;
      return true;
    }
    
    function minuteInTimezone(timezone: string, date: Date): number {
      const parts = new Intl.DateTimeFormat('en-GB', {
        timeZone: timezone,
        hour: '2-digit',
        minute: '2-digit',
        hourCycle: 'h23',
      }).formatToParts(date);
      const hour = Number(parts.find(part => part.type === 'hour')?.value ?? 0);
      const minute = Number(parts.find(part => part.type === 'minute')?.value ?? 0);
      return hour * 60 + minute;
    }
    
    function parseClock(value: string): number {
      const [hour, minute] = value.split(':').map(Number);
      return hour * 60 + minute;
    }
    
    function inQuietHours(start: string | null, end: string | null, timezone: string, now: Date): boolean {
      if (!start || !end || start === end) return false;
      const current = minuteInTimezone(timezone, now);
      const from = parseClock(start);
      const to = parseClock(end);
      // An overnight range such as 22:00-07:00 wraps across midnight.
      return from < to ? current >= from && current < to : current >= from || current < to;
    }
    
    function retryAt(attempt: number): string {
      const delayMs = Math.min(60 * 60 * 1000, 30_000 * 2 ** Math.max(0, attempt - 1));
      return new Date(Date.now() + delayMs).toISOString();
    }
    
    async function ensureDelivery(eventId: string, subscriptionId: string): Promise<void> {
      const now = new Date().toISOString();
      await db('notification_deliveries').insert({
        id: randomUUID(),
        event_id: eventId,
        subscription_id: subscriptionId,
        status: 'pending',
        attempt_count: 0,
        next_attempt_at: now,
        updated_at: now,
      }).onConflict(['event_id', 'subscription_id']).ignore();
    }
    
    async function seedDeliveries(): Promise<void> {
      const events = await db('notification_events')
        .where('occurred_at', '>=', new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString())
        .select('id', 'category');
      const subscriptions = await db('push_subscriptions').whereNull('revoked_at').select('id', 'user_id');
      for (const subscription of subscriptions) {
        const preferences = await getNotificationPreferences(subscription.user_id);
        if (!preferences.enabled || !preferences.pushEnabled) continue;
        for (const event of events) {
          if (preferences.categories[event.category as NotificationCategory]) {
            await ensureDelivery(event.id, subscription.id);
          }
        }
      }
    }
    
    async function deliver(row: Record<string, any>): Promise<void> {
      const preferences = await getNotificationPreferences(row.user_id);
      if (inQuietHours(preferences.quietHoursStart, preferences.quietHoursEnd, preferences.timezone, new Date())) {
        await db('notification_deliveries').where({ id: row.delivery_id }).update({
          status: 'pending',
          next_attempt_at: new Date(Date.now() + 15 * 60 * 1000).toISOString(),
          updated_at: new Date().toISOString(),
        });
        return;
      }
    
      const unreadCount = await getUnreadNotificationCount(row.user_id);
      const payload = JSON.stringify({
        id: row.event_id,
        kind: row.kind,
        title: row.title,
        body: row.body,
        deepLink: row.deep_link,
        prUrl: row.pr_url,
        apiBaseUrl: process.env.API_PUBLIC_URL ?? '',
        unreadCount,
        // Keep notification-surface actions intentionally small and safe. Mutating
        // workflow actions open the app and require confirmation there.
        actions: ['view', 'dismiss'],
      });
    
      try {
        await webPush.sendNotification({
          endpoint: row.endpoint,
          keys: { p256dh: row.p256dh, auth: row.auth },
        }, payload, { TTL: 24 * 60 * 60, urgency: row.kind.includes('failed') ? 'high' : 'normal' });
        await db('notification_deliveries').where({ id: row.delivery_id }).update({
          status: 'delivered',
          delivered_at: new Date().toISOString(),
          updated_at: new Date().toISOString(),
          last_error: null,
        });
      } catch (error) {
        const statusCode = Number((error as { statusCode?: number }).statusCode ?? 0);
        if (statusCode === 404 || statusCode === 410) {
          await db('push_subscriptions').where({ id: row.subscription_id }).update({ revoked_at: new Date().toISOString() });
        }
        const attempts = Number(row.attempt_count) + 1;
        const retryable = !statusCode || statusCode === 429 || statusCode >= 500;
        await db('notification_deliveries').where({ id: row.delivery_id }).update({
          status: retryable && attempts < maxAttempts ? 'pending' : 'failed',
          attempt_count: attempts,
          next_attempt_at: retryAt(attempts),
          // Store only a transport status; provider errors can contain endpoint data.
          last_error: statusCode ? `HTTP ${statusCode}` : 'Push transport error',
          updated_at: new Date().toISOString(),
        });
      }
    }
    
    export async function dispatchWebPushBatch(limit = 50): Promise<number> {
      if (!configureTransport()) return 0;
      if (running) return 0;
      running = true;
      try {
        await seedDeliveries();
        const now = new Date().toISOString();
        const rows = await db('notification_deliveries as delivery')
          .join('notification_events as event', 'event.id', 'delivery.event_id')
          .join('push_subscriptions as subscription', 'subscription.id', 'delivery.subscription_id')
          .where({ 'delivery.status': 'pending' })
          .whereNull('subscription.revoked_at')
          .andWhere('delivery.next_attempt_at', '<=', now)
          .limit(limit)
          .select(
            'delivery.id as delivery_id',
            'delivery.attempt_count',
            'delivery.subscription_id',
            'event.id as event_id',
            'event.kind',
            'event.title',
            'event.body',
            'event.deep_link',
            'event.pr_url',
            'subscription.user_id',
            'subscription.endpoint',
            'subscription.p256dh',
            'subscription.auth',
          );
        for (const row of rows) await deliver(row);
        return rows.length;
      } finally {
        running = false;
      }
    }
    
    export function startWebPushDispatcher(): () => void {
      if (!configureTransport()) {
        logger.warn('Web Push is disabled because VAPID configuration is incomplete');
        return () => undefined;
      }
      const run = () => void dispatchWebPushBatch().catch(error => {
        logger.warn({ error: (error as Error).message }, 'Web Push dispatch failed');
      });
      run();
      const timer = setInterval(run, 15_000);
      timer.unref();
      return () => clearInterval(timer);
    }

    File: packages/core/src/index.ts

    Why this file: The API startup path needs to start and stop the dispatcher cleanly.

    --- a/packages/core/src/index.ts
    +++ b/packages/core/src/index.ts
    @@ -1,3 +1,4 @@
    +export { dispatchWebPushBatch, startWebPushDispatcher } from './services/webPushDispatcher.js';

    File: packages/api/server.ts

    Why this file: Start delivery after migrations and stop it during graceful shutdown.

    --- a/packages/api/server.ts
    +++ b/packages/api/server.ts
    @@ -1,5 +1,6 @@
    +import { startWebPushDispatcher } from '@propr/core';
    @@ -224,6 +225,7 @@
    +const stopWebPushDispatcher = startWebPushDispatcher();
    @@ -266,6 +268,7 @@
    +  stopWebPushDispatcher();
  2. propr-dev commented on Aug 24, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: codex
    • Model: gpt-5.6-sol
    • Branch: 1720/gpt-5.6-sol-implement-reliable-web-pu-20260824-0119-50h
    • Base Branch: 1716-epic-failed-to-3m8
    • Worktree: issue-1720-20260824-0119-gpt-5.6-sol-50h

    🔍 Track Task Execution

  3. added a commit that references this issue on Aug 24, 2026
  4. added a commit that references this issue on Aug 24, 2026
  5. added a commit that references this issue on Aug 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions