Skip to content

Add notification preferences and Web Push subscription APIs #1718

Closed

Description

@propr-dev

Context

Push permission is browser- and device-specific, while notification preferences belong to an authenticated ProPR user. The backend must store both without ever exposing VAPID private-key material.

Requirements

  • Add core helpers to read and update notification preferences.
  • Validate category values, HH:mm quiet-hour values, and IANA timezone identifiers.
  • Add endpoints for reading notification capability/configuration and preferences.
  • Add endpoints to create or refresh a browser push subscription and revoke it by endpoint.
  • Derive the subscription owner from the authenticated session.
  • Reject non-HTTPS push endpoints except localhost development endpoints.
  • Upsert by endpoint so repeated browser enrollment is idempotent.
  • Return only the VAPID public key to the browser.
  • Keep push disabled until the user explicitly opts in.

Acceptance Criteria

  • A new user receives documented default preferences.
  • Updating one preference does not silently reset unrelated categories.
  • Invalid timezones, quiet-hour values, or subscription keys return 400.
  • Resubscribing the same endpoint updates its keys and clears revoked_at.
  • Revocation affects only the authenticated user's matching endpoint.
  • The VAPID private key never appears in API responses or logs.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Aug 2, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Store preferences separately from browser subscriptions because one user may install the PWA on several devices with different push endpoints. The browser subscription is treated as a replaceable transport credential; preferences are the durable user-level policy. Storing the whole PushSubscription JSON blob was considered but rejected because explicit columns make endpoint uniqueness, expiration, and revocation easier to query safely.

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

    Why this file: This module normalizes persistence defaults and prevents route handlers or delivery jobs from interpreting preference JSON differently.

    import { randomUUID } from 'node:crypto';
    import { db } from '../db/connection.js';
    import {
      DEFAULT_NOTIFICATION_PREFERENCES,
      type NotificationCategory,
      type NotificationPreferences,
      type WebPushSubscriptionInput,
    } from '@propr/shared';
    
    const categories = ['plans', 'tasks', 'pull_requests', 'indexing', 'system'] as const;
    
    const parseCategories = (raw: string | undefined): NotificationPreferences['categories'] => {
      try {
        return { ...DEFAULT_NOTIFICATION_PREFERENCES.categories, ...JSON.parse(raw ?? '{}') };
      } catch {
        return { ...DEFAULT_NOTIFICATION_PREFERENCES.categories };
      }
    };
    
    export async function getNotificationPreferences(userId: string): Promise<NotificationPreferences> {
      const row = await db('notification_preferences').where({ user_id: userId }).first();
      if (!row) return structuredClone(DEFAULT_NOTIFICATION_PREFERENCES);
      return {
        enabled: Boolean(row.enabled),
        pushEnabled: Boolean(row.push_enabled),
        badgeEnabled: Boolean(row.badge_enabled),
        quietHoursStart: row.quiet_hours_start,
        quietHoursEnd: row.quiet_hours_end,
        timezone: row.timezone,
        categories: parseCategories(row.categories_json),
      };
    }
    
    export async function saveNotificationPreferences(
      userId: string,
      preferences: NotificationPreferences,
    ): Promise<NotificationPreferences> {
      const now = new Date().toISOString();
      await db('notification_preferences').insert({
        user_id: userId,
        enabled: preferences.enabled,
        push_enabled: preferences.pushEnabled,
        badge_enabled: preferences.badgeEnabled,
        quiet_hours_start: preferences.quietHoursStart,
        quiet_hours_end: preferences.quietHoursEnd,
        timezone: preferences.timezone,
        categories_json: JSON.stringify(preferences.categories),
        updated_at: now,
      }).onConflict('user_id').merge();
      return getNotificationPreferences(userId);
    }
    
    export function validateNotificationPreferences(value: unknown): NotificationPreferences {
      if (!value || typeof value !== 'object') throw new Error('Preferences must be an object');
      const input = value as Partial<NotificationPreferences>;
      const timePattern = /^([01][0-9]|2[0-3]):[0-5][0-9]$/;
      for (const candidate of [input.quietHoursStart, input.quietHoursEnd]) {
        if (candidate !== null && candidate !== undefined && !timePattern.test(candidate)) {
          throw new Error('Quiet hours must use HH:mm in 24-hour time');
        }
      }
      try {
        new Intl.DateTimeFormat('en', { timeZone: input.timezone ?? 'UTC' }).format();
      } catch {
        throw new Error('timezone must be a valid IANA timezone');
      }
      const normalizedCategories = { ...DEFAULT_NOTIFICATION_PREFERENCES.categories };
      for (const category of categories) {
        const selected = input.categories?.[category as NotificationCategory];
        if (selected !== undefined && typeof selected !== 'boolean') {
          throw new Error(`Category ${category} must be boolean`);
        }
        if (selected !== undefined) normalizedCategories[category] = selected;
      }
      return {
        enabled: input.enabled ?? true,
        pushEnabled: input.pushEnabled ?? false,
        badgeEnabled: input.badgeEnabled ?? true,
        quietHoursStart: input.quietHoursStart ?? null,
        quietHoursEnd: input.quietHoursEnd ?? null,
        timezone: input.timezone ?? 'UTC',
        categories: normalizedCategories,
      };
    }
    
    export async function upsertPushSubscription(
      userId: string,
      subscription: WebPushSubscriptionInput,
      userAgent?: string,
    ): Promise<void> {
      const now = new Date().toISOString();
      await db('push_subscriptions').insert({
        id: randomUUID(),
        user_id: userId,
        endpoint: subscription.endpoint,
        p256dh: subscription.keys.p256dh,
        auth: subscription.keys.auth,
        expiration_time: subscription.expirationTime,
        user_agent: userAgent ?? null,
        created_at: now,
        updated_at: now,
        revoked_at: null,
      }).onConflict('endpoint').merge({
        // Ownership follows the current authenticated enrollment. This permits a
        // browser profile to be re-associated after an account switch without
        // retaining delivery access for the prior user.
        user_id: userId,
        p256dh: subscription.keys.p256dh,
        auth: subscription.keys.auth,
        expiration_time: subscription.expirationTime,
        user_agent: userAgent ?? null,
        updated_at: now,
        revoked_at: null,
      });
    }
    
    export async function revokePushSubscription(userId: string, endpoint: string): Promise<boolean> {
      return (await db('push_subscriptions')
        .where({ user_id: userId, endpoint })
        .update({ revoked_at: new Date().toISOString() })) > 0;
    }

    File: packages/core/src/index.ts

    Why this file: The API and delivery dispatcher need the same normalized preference helpers.

    --- a/packages/core/src/index.ts
    +++ b/packages/core/src/index.ts
    @@ -1,3 +1,11 @@
    +export {
    +  getNotificationPreferences,
    +  saveNotificationPreferences,
    +  validateNotificationPreferences,
    +  upsertPushSubscription,
    +  revokePushSubscription,
    +} from './services/notificationPreferencesService.js';

    File: packages/api/routes/notifications.ts

    Why this file: Preferences and subscriptions belong beside the Inbox routes under one authenticated resource namespace.

    --- a/packages/api/routes/notifications.ts
    +++ b/packages/api/routes/notifications.ts
    @@ -1,8 +1,15 @@
     import {
    +  getNotificationPreferences,
    +  revokePushSubscription,
    +  saveNotificationPreferences,
    +  upsertPushSubscription,
    +  validateNotificationPreferences,
     } from '@propr/core';
    +import type { WebPushSubscriptionInput } from '@propr/shared';
    @@ -30,6 +37,75 @@
    +router.get('/config', (request, response) => {
    +  const userId = requireUser(request, response);
    +  if (!userId) return;
    +  const publicKey = process.env.WEB_PUSH_VAPID_PUBLIC_KEY?.trim() || null;
    +  const privateKeyConfigured = Boolean(process.env.WEB_PUSH_VAPID_PRIVATE_KEY?.trim());
    +  response.json({
    +    // Report configured only when both halves exist so the UI does not invite
    +    // enrollment into a deployment that cannot deliver messages.
    +    configured: Boolean(publicKey && privateKeyConfigured),
    +    vapidPublicKey: publicKey,
    +  });
    +});
    +
    +router.get('/preferences', async (request, response, next) => {
    +  try {
    +    const userId = requireUser(request, response);
    +    if (!userId) return;
    +    response.json(await getNotificationPreferences(userId));
    +  } catch (error) {
    +    next(error);
    +  }
    +});
    +
    +router.put('/preferences', async (request, response, next) => {
    +  try {
    +    const userId = requireUser(request, response);
    +    if (!userId) return;
    +    response.json(await saveNotificationPreferences(
    +      userId,
    +      validateNotificationPreferences(request.body),
    +    ));
    +  } catch (error) {
    +    if (error instanceof Error && /Preferences|Quiet hours|timezone|Category/.test(error.message)) {
    +      response.status(400).json({ error: error.message });
    +      return;
    +    }
    +    next(error);
    +  }
    +});
    +
    +router.post('/subscriptions', async (request, response, next) => {
    +  try {
    +    const userId = requireUser(request, response);
    +    if (!userId) return;
    +    const subscription = request.body as WebPushSubscriptionInput;
    +    const endpoint = new URL(subscription.endpoint);
    +    const localhost = endpoint.hostname === 'localhost' || endpoint.hostname === '127.0.0.1';
    +    if ((endpoint.protocol !== 'https:' && !localhost) || !subscription.keys?.p256dh || !subscription.keys?.auth) {
    +      response.status(400).json({ error: 'Invalid Web Push subscription' });
    +      return;
    +    }
    +    await upsertPushSubscription(userId, subscription, request.get('user-agent'));
    +    response.status(201).json({ success: true });
    +  } catch (error) {
    +    if (error instanceof TypeError) {
    +      response.status(400).json({ error: 'Invalid Web Push endpoint URL' });
    +      return;
    +    }
    +    next(error);
    +  }
    +});
    +
    +router.delete('/subscriptions', async (request, response, next) => {
    +  try {
    +    const userId = requireUser(request, response);
    +    if (!userId) return;
    +    if (typeof request.body?.endpoint !== 'string') {
    +      response.status(400).json({ error: 'endpoint is required' });
    +      return;
    +    }
    +    await revokePushSubscription(userId, request.body.endpoint);
    +    response.status(204).end();
    +  } catch (error) {
    +    next(error);
    +  }
    +});
  2. propr-dev commented on Aug 2, 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: 1718/gpt-5.6-sol-add-notification-preferen-20260802-1158-5gv
    • Base Branch: 1716-epic-failed-to-3m8
    • Worktree: issue-1718-20260802-1158-gpt-5.6-sol-5gv

    🔍 Track Task Execution

  3. added a commit that references this issue on Aug 2, 2026
  4. added a commit that references this issue on Aug 2, 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