You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Implement reliable Web Push delivery with VAPID, retries, and subscription cleanup #1720
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.
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.
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';importwebPushfrom'web-push';import{db}from'../db/connection.js';importloggerfrom'../utils/logger.js';import{getNotificationPreferences}from'./notificationPreferencesService.js';import{getUnreadNotificationCount}from'./notificationService.js';importtype{NotificationCategory}from'@propr/shared';constmaxAttempts=5;letconfigured=false;letrunning=false;functionconfigureTransport(): boolean{if(configured)returntrue;constsubject=process.env.WEB_PUSH_VAPID_SUBJECT?.trim();constpublicKey=process.env.WEB_PUSH_VAPID_PUBLIC_KEY?.trim();constprivateKey=process.env.WEB_PUSH_VAPID_PRIVATE_KEY?.trim();if(!subject||!publicKey||!privateKey)returnfalse;// 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://')){thrownewError('WEB_PUSH_VAPID_SUBJECT must be a mailto: or https: URI');}webPush.setVapidDetails(subject,publicKey,privateKey);configured=true;returntrue;}functionminuteInTimezone(timezone: string,date: Date): number{constparts=newIntl.DateTimeFormat('en-GB',{timeZone: timezone,hour: '2-digit',minute: '2-digit',hourCycle: 'h23',}).formatToParts(date);consthour=Number(parts.find(part=>part.type==='hour')?.value??0);constminute=Number(parts.find(part=>part.type==='minute')?.value??0);returnhour*60+minute;}functionparseClock(value: string): number{const[hour,minute]=value.split(':').map(Number);returnhour*60+minute;}functioninQuietHours(start: string|null,end: string|null,timezone: string,now: Date): boolean{if(!start||!end||start===end)returnfalse;constcurrent=minuteInTimezone(timezone,now);constfrom=parseClock(start);constto=parseClock(end);// An overnight range such as 22:00-07:00 wraps across midnight.returnfrom<to ? current>=from&¤t<to : current>=from||current<to;}functionretryAt(attempt: number): string{constdelayMs=Math.min(60*60*1000,30_000*2**Math.max(0,attempt-1));returnnewDate(Date.now()+delayMs).toISOString();}asyncfunctionensureDelivery(eventId: string,subscriptionId: string): Promise<void>{constnow=newDate().toISOString();awaitdb('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();}asyncfunctionseedDeliveries(): Promise<void>{constevents=awaitdb('notification_events').where('occurred_at','>=',newDate(Date.now()-24*60*60*1000).toISOString()).select('id','category');constsubscriptions=awaitdb('push_subscriptions').whereNull('revoked_at').select('id','user_id');for(constsubscriptionofsubscriptions){constpreferences=awaitgetNotificationPreferences(subscription.user_id);if(!preferences.enabled||!preferences.pushEnabled)continue;for(consteventofevents){if(preferences.categories[event.categoryasNotificationCategory]){awaitensureDelivery(event.id,subscription.id);}}}}asyncfunctiondeliver(row: Record<string,any>): Promise<void>{constpreferences=awaitgetNotificationPreferences(row.user_id);if(inQuietHours(preferences.quietHoursStart,preferences.quietHoursEnd,preferences.timezone,newDate())){awaitdb('notification_deliveries').where({id: row.delivery_id}).update({status: 'pending',next_attempt_at: newDate(Date.now()+15*60*1000).toISOString(),updated_at: newDate().toISOString(),});return;}constunreadCount=awaitgetUnreadNotificationCount(row.user_id);constpayload=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{awaitwebPush.sendNotification({endpoint: row.endpoint,keys: {p256dh: row.p256dh,auth: row.auth},},payload,{TTL: 24*60*60,urgency: row.kind.includes('failed') ? 'high' : 'normal'});awaitdb('notification_deliveries').where({id: row.delivery_id}).update({status: 'delivered',delivered_at: newDate().toISOString(),updated_at: newDate().toISOString(),last_error: null,});}catch(error){conststatusCode=Number((erroras{statusCode?: number}).statusCode??0);if(statusCode===404||statusCode===410){awaitdb('push_subscriptions').where({id: row.subscription_id}).update({revoked_at: newDate().toISOString()});}constattempts=Number(row.attempt_count)+1;constretryable=!statusCode||statusCode===429||statusCode>=500;awaitdb('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: newDate().toISOString(),});}}exportasyncfunctiondispatchWebPushBatch(limit=50): Promise<number>{if(!configureTransport())return0;if(running)return0;running=true;try{awaitseedDeliveries();constnow=newDate().toISOString();constrows=awaitdb('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(constrowofrows)awaitdeliver(row);returnrows.length;}finally{running=false;}}exportfunctionstartWebPushDispatcher(): ()=>void{if(!configureTransport()){logger.warn('Web Push is disabled because VAPID configuration is incomplete');return()=>undefined;}construn=()=>voiddispatchWebPushBatch().catch(error=>{logger.warn({error: (errorasError).message},'Web Push dispatch failed');});run();consttimer=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.
Activity
propr-dev commentedon Aug 2, 2026
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.jsonWhy this file: Push signing and encryption should use the maintained Web Push implementation rather than custom cryptography.
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.
File:
packages/core/src/index.tsWhy this file: The API startup path needs to start and stop the dispatcher cleanly.
File:
packages/api/server.tsWhy this file: Start delivery after migrations and stop it during graceful shutdown.
propr-dev commentedon Aug 24, 2026
🤖 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:
codexgpt-5.6-sol1720/gpt-5.6-sol-implement-reliable-web-pu-20260824-0119-50h1716-epic-failed-to-3m8issue-1720-20260824-0119-gpt-5.6-sol-50h🔍 Track Task Execution
fix(ai): Resolve issue #1720 - Implement reliable Web Push delivery w…
fix(ai): Resolve issue #1720 - Implement reliable Web Push delivery w…
[Epic] PWA & Web push (#1731)