Skip to content

Add the notification persistence service and authenticated Inbox API #1717

Closed

Description

@propr-dev

Context

The mobile Inbox needs a stable API for listing, counting, reading, and dismissing notification events. These operations must be authenticated and must never trust a user identifier supplied by the browser.

Requirements

  • Add a core notification service for idempotent event creation and paginated listing.
  • Join per-user receipts into list results.
  • Exclude dismissed items by default while allowing an explicit historical query.
  • Add authenticated routes for list, unread count, mark-read, and dismiss.
  • Use cursor pagination based on occurred_at plus event ID.
  • Clamp request limits to avoid unbounded database reads.
  • Marking or dismissing an event must be idempotent.
  • Do not expose notification data through demo-mode write exceptions; list/count remain readable while mutations follow existing demo-mode middleware policy.

Acceptance Criteria

  • GET /api/notifications returns newest-first items and an unread count.
  • GET /api/notifications/unread-count returns the same count used by icon badging.
  • POST /api/notifications/:id/read and /dismiss affect only the authenticated user's receipt.
  • A different authenticated user does not inherit another user's read/dismiss state.
  • Invalid cursors and limits return 400 rather than causing SQL errors.
  • Duplicate event creation returns the original event ID.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Aug 2, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Keep SQL and row parsing in packages/core, while Express is responsible only for authentication, input validation, and HTTP status mapping. This keeps notification semantics reusable by the push dispatcher and CLI in the future. Offset pagination was considered but rejected because new events arriving during scrolling would move rows and cause duplicates; a stable timestamp/ID cursor avoids that behavior.

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

    Why this file: This is the single persistence boundary for event creation and per-user Inbox state. Push delivery and API routes will reuse it instead of duplicating SQL.

    import { randomUUID } from 'node:crypto';
    import { db } from '../db/connection.js';
    import type {
      NotificationAction,
      NotificationCategory,
      NotificationEvent,
      NotificationKind,
      NotificationTargetType,
    } from '@propr/shared';
    
    export interface CreateNotificationEventInput {
      kind: NotificationKind;
      category: NotificationCategory;
      title: string;
      body: string;
      targetType: NotificationTargetType;
      targetId: string;
      projectSlug?: string | null;
      deepLink: string;
      prUrl?: string | null;
      actions?: NotificationAction[];
      metadata?: Record<string, unknown>;
      dedupeKey: string;
      occurredAt?: string;
    }
    
    interface NotificationRow {
      id: string;
      kind: NotificationKind;
      category: NotificationCategory;
      title: string;
      body: string;
      target_type: NotificationTargetType;
      target_id: string;
      project_slug: string | null;
      deep_link: string;
      pr_url: string | null;
      actions_json: string;
      metadata_json: string;
      occurred_at: string;
      read_at: string | null;
      dismissed_at: string | null;
    }
    
    const safeJson = <T>(value: string, fallback: T): T => {
      try {
        return JSON.parse(value) as T;
      } catch {
        // Old or manually edited rows must not make the entire Inbox unavailable.
        return fallback;
      }
    };
    
    const toEvent = (row: NotificationRow): NotificationEvent => ({
      id: row.id,
      kind: row.kind,
      category: row.category,
      title: row.title,
      body: row.body,
      targetType: row.target_type,
      targetId: row.target_id,
      projectSlug: row.project_slug,
      deepLink: row.deep_link,
      prUrl: row.pr_url,
      actions: safeJson<NotificationAction[]>(row.actions_json, []),
      metadata: safeJson<Record<string, unknown>>(row.metadata_json, {}),
      occurredAt: row.occurred_at,
      readAt: row.read_at,
      dismissedAt: row.dismissed_at,
    });
    
    export async function createNotificationEvent(input: CreateNotificationEventInput): Promise<string> {
      const existing = await db('notification_events')
        .select('id')
        .where({ dedupe_key: input.dedupeKey })
        .first<{ id: string }>();
      if (existing) return existing.id;
    
      const id = randomUUID();
      const now = new Date().toISOString();
      try {
        await db('notification_events').insert({
          id,
          kind: input.kind,
          category: input.category,
          title: input.title,
          body: input.body,
          target_type: input.targetType,
          target_id: input.targetId,
          project_slug: input.projectSlug ?? null,
          deep_link: input.deepLink,
          pr_url: input.prUrl ?? null,
          actions_json: JSON.stringify(input.actions ?? []),
          metadata_json: JSON.stringify(input.metadata ?? {}),
          dedupe_key: input.dedupeKey,
          occurred_at: input.occurredAt ?? now,
          created_at: now,
        });
        return id;
      } catch (error) {
        // Two workers can observe the same transition concurrently. The unique key
        // decides the winner; return it instead of surfacing a false failure.
        const raced = await db('notification_events')
          .select('id')
          .where({ dedupe_key: input.dedupeKey })
          .first<{ id: string }>();
        if (raced) return raced.id;
        throw error;
      }
    }
    
    export interface ListNotificationOptions {
      limit: number;
      cursor?: { occurredAt: string; id: string };
      includeDismissed?: boolean;
    }
    
    export async function listNotifications(userId: string, options: ListNotificationOptions) {
      const query = db('notification_events as event')
        .leftJoin('notification_receipts as receipt', function joinReceipt() {
          this.on('receipt.event_id', '=', 'event.id').andOnVal('receipt.user_id', '=', userId);
        })
        .select(
          'event.*',
          'receipt.read_at',
          'receipt.dismissed_at',
        )
        .orderBy('event.occurred_at', 'desc')
        .orderBy('event.id', 'desc')
        .limit(options.limit + 1);
    
      if (!options.includeDismissed) query.whereNull('receipt.dismissed_at');
      if (options.cursor) {
        query.where(builder => {
          builder.where('event.occurred_at', '<', options.cursor!.occurredAt)
            .orWhere(inner => inner
              .where('event.occurred_at', '=', options.cursor!.occurredAt)
              .andWhere('event.id', '<', options.cursor!.id));
        });
      }
    
      const rows = await query as NotificationRow[];
      const hasMore = rows.length > options.limit;
      const visible = rows.slice(0, options.limit).map(toEvent);
      const last = visible[visible.length - 1];
      return {
        notifications: visible,
        unreadCount: await getUnreadNotificationCount(userId),
        nextCursor: hasMore && last
          ? Buffer.from(JSON.stringify({ occurredAt: last.occurredAt, id: last.id })).toString('base64url')
          : null,
      };
    }
    
    export async function getUnreadNotificationCount(userId: string): Promise<number> {
      const row = await db('notification_events as event')
        .leftJoin('notification_receipts as receipt', function joinReceipt() {
          this.on('receipt.event_id', '=', 'event.id').andOnVal('receipt.user_id', '=', userId);
        })
        .whereNull('receipt.read_at')
        .whereNull('receipt.dismissed_at')
        .count<{ count: number | string }[]>({ count: 'event.id' })
        .first();
      return Number(row?.count ?? 0);
    }
    
    async function updateReceipt(userId: string, eventId: string, values: Record<string, string>): Promise<boolean> {
      const exists = await db('notification_events').where({ id: eventId }).first('id');
      if (!exists) return false;
      await db('notification_receipts')
        .insert({ event_id: eventId, user_id: userId, ...values })
        .onConflict(['event_id', 'user_id'])
        .merge(values);
      return true;
    }
    
    export const markNotificationRead = (userId: string, eventId: string) =>
      updateReceipt(userId, eventId, { read_at: new Date().toISOString() });
    
    export const dismissNotification = (userId: string, eventId: string) => {
      const now = new Date().toISOString();
      // Dismissal also marks the item read so the badge cannot remain inflated.
      return updateReceipt(userId, eventId, { read_at: now, dismissed_at: now });
    };

    File: packages/core/src/index.ts

    Why this file: API and delivery packages consume core services through the public barrel.

    --- a/packages/core/src/index.ts
    +++ b/packages/core/src/index.ts
    @@ -1,3 +1,11 @@
    +export {
    +  createNotificationEvent,
    +  listNotifications,
    +  getUnreadNotificationCount,
    +  markNotificationRead,
    +  dismissNotification,
    +} from './services/notificationService.js';
    +export type { CreateNotificationEventInput, ListNotificationOptions } from './services/notificationService.js';

    File: packages/api/routes/notifications.ts (new file)

    Why this file: This route translates authenticated HTTP requests into the core service calls. The user ID is derived from the session, never from query or body data.

    import { Router, type Request, type Response } from 'express';
    import {
      dismissNotification,
      listNotifications,
      getUnreadNotificationCount,
      markNotificationRead,
    } from '@propr/core';
    
    const router = Router();
    
    type AuthenticatedRequest = Request & {
      user?: { id?: string | number; login?: string };
    };
    
    const userIdFor = (request: Request): string | null => {
      const user = (request as AuthenticatedRequest).user;
      // Prefer the immutable provider ID; login is retained for compatibility with
      // existing session shapes until every deployment has refreshed its session.
      return user?.id !== undefined ? String(user.id) : user?.login ?? null;
    };
    
    const requireUser = (request: Request, response: Response): string | null => {
      const userId = userIdFor(request);
      if (!userId) response.status(401).json({ error: 'Authentication required' });
      return userId;
    };
    
    const parseCursor = (value: unknown): { occurredAt: string; id: string } | undefined => {
      if (!value) return undefined;
      const parsed = JSON.parse(Buffer.from(String(value), 'base64url').toString('utf8')) as Record<string, unknown>;
      if (typeof parsed.occurredAt !== 'string' || typeof parsed.id !== 'string') {
        throw new Error('Invalid cursor');
      }
      return { occurredAt: parsed.occurredAt, id: parsed.id };
    };
    
    router.get('/', async (request, response, next) => {
      try {
        const userId = requireUser(request, response);
        if (!userId) return;
        const requestedLimit = Number(request.query.limit ?? 30);
        if (!Number.isInteger(requestedLimit) || requestedLimit < 1) {
          response.status(400).json({ error: 'limit must be a positive integer' });
          return;
        }
        response.json(await listNotifications(userId, {
          limit: Math.min(requestedLimit, 100),
          cursor: parseCursor(request.query.cursor),
          includeDismissed: request.query.includeDismissed === 'true',
        }));
      } catch (error) {
        if ((error as Error).message === 'Invalid cursor') {
          response.status(400).json({ error: 'Invalid notification cursor' });
          return;
        }
        next(error);
      }
    });
    
    router.get('/unread-count', async (request, response, next) => {
      try {
        const userId = requireUser(request, response);
        if (!userId) return;
        response.json({ unreadCount: await getUnreadNotificationCount(userId) });
      } catch (error) {
        next(error);
      }
    });
    
    for (const [path, operation] of [
      ['read', markNotificationRead],
      ['dismiss', dismissNotification],
    ] as const) {
      router.post(`/:id/${path}`, async (request, response, next) => {
        try {
          const userId = requireUser(request, response);
          if (!userId) return;
          const updated = await operation(userId, request.params.id);
          if (!updated) {
            response.status(404).json({ error: 'Notification not found' });
            return;
          }
          response.json({ success: true, unreadCount: await getUnreadNotificationCount(userId) });
        } catch (error) {
          next(error);
        }
      });
    }
    
    export default router;

    File: packages/api/server.ts

    Why this file: The new router must be mounted behind the same session and demo-mode middleware used by existing authenticated API routes.

    --- a/packages/api/server.ts
    +++ b/packages/api/server.ts
    @@ -1,5 +1,6 @@
    +import notificationRoutes from './routes/notifications.js';
    @@ -120,6 +121,9 @@
    +// Mount after authentication so notification receipt mutations can only use
    +// the server-verified session identity.
    +app.use('/api/notifications', notificationRoutes);
  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: 1717/gpt-5.6-sol-add-the-notification-pers-20260802-1128-zjd
    • Base Branch: 1716-epic-failed-to-3m8
    • Worktree: issue-1717-20260802-1128-gpt-5.6-sol-zjd

    🔍 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