feat: push notifications on each device (Web Push)

- What reaches the bell also reaches the devices where the person
  turned «Avisos en este dispositivo» on, with TaskStream closed: the
  Notifier sends each new notification encrypted (aes128gcm) and signed
  with VAPID, and forgets subscriptions the push service dropped
  (404/410). A failure never blocks the event stream.
- The API keeps one subscription per device (push_subscriptions) and
  exposes the VAPID public key in the notification settings; GraphQL
  subscribePush/unsubscribePush, REST /me/push-subscriptions. Without
  VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY push is off.
- The web registers /push-sw.js, a service worker that only shows the
  notification and opens its ticket on a tap (no caching, served
  without cache by nginx), and a manifest that makes it installable,
  which iPhones need for push.
- The bell's toggles show their text next to them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-15 08:38:07 +02:00
parent 5ee627e689
commit 233c46e9fa
50 changed files with 1577 additions and 53 deletions

View File

@@ -4,6 +4,8 @@ import { NotificationReadModel } from '@task-stream/api/tracker/domain';
import { SendDueRemindersCommand } from './notifications/reminders';
import {
MarkNotificationsReadCommand,
SubscribePushCommand,
UnsubscribePushCommand,
UpdateNotificationSettingsCommand,
} from './notifications/notifications.commands';
import {
@@ -37,6 +39,24 @@ export class NotificationsService {
}
/** `ids` omitted: everything. */
/** Push on this device (a browser's Web Push subscription). */
subscribePush(
userId: string,
endpoint: string,
keys: { p256dh: string; auth: string },
): Promise<void> {
return this.commandBus.execute(
new SubscribePushCommand(userId, endpoint, keys),
);
}
/** Push off on this device. */
unsubscribePush(userId: string, endpoint: string): Promise<void> {
return this.commandBus.execute(
new UnsubscribePushCommand(userId, endpoint),
);
}
/** Tells of the tickets due around `day` (YYYY-MM-DD); how many it sent. */
sendDueReminders(day: string): Promise<number> {
return this.commandBus.execute(new SendDueRemindersCommand(day));

View File

@@ -1,5 +1,8 @@
import { Command, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { assertThat } from '@task-stream/api/shared/domain';
import { NotificationsRepository } from '../ports/notifications.repository';
import { PushSender } from '../ports/push-sender';
import { PushSubscriptionsRepository } from '../ports/push-subscriptions.repository';
/*
* Per-person state, outside the event store: whether a notification was read
@@ -49,3 +52,64 @@ export class UpdateNotificationSettingsCommandHandler
});
}
}
/** Push on this device: the browser's subscription is kept for its owner. */
export class SubscribePushCommand extends Command<void> {
constructor(
public readonly userId: string,
public readonly endpoint: string,
public readonly keys: { p256dh: string; auth: string },
) {
super();
}
}
/** Push off on this device. */
export class UnsubscribePushCommand extends Command<void> {
constructor(
public readonly userId: string,
public readonly endpoint: string,
) {
super();
}
}
@CommandHandler(SubscribePushCommand)
export class SubscribePushCommandHandler
implements ICommandHandler<SubscribePushCommand>
{
constructor(
private readonly subscriptions: PushSubscriptionsRepository,
private readonly push: PushSender,
) {}
async execute(command: SubscribePushCommand): Promise<void> {
assertThat(!!this.push.publicKey, 'Push is not set up here');
// Push services are https; anything else is not a browser's endpoint.
assertThat(
/^https:\/\/[^\s]{8,2000}$/.test(command.endpoint),
'Not a push endpoint',
);
assertThat(
!!command.keys?.p256dh && !!command.keys?.auth,
'The subscription keys are missing',
);
await this.subscriptions.save({
userId: command.userId,
endpoint: command.endpoint,
keys: { p256dh: command.keys.p256dh, auth: command.keys.auth },
createdAt: new Date().toISOString(),
});
}
}
@CommandHandler(UnsubscribePushCommand)
export class UnsubscribePushCommandHandler
implements ICommandHandler<UnsubscribePushCommand>
{
constructor(private readonly subscriptions: PushSubscriptionsRepository) {}
async execute(command: UnsubscribePushCommand): Promise<void> {
await this.subscriptions.remove(command.userId, command.endpoint);
}
}

View File

@@ -1,6 +1,7 @@
import { IQueryHandler, Query, QueryHandler } from '@nestjs/cqrs';
import { NotificationReadModel } from '@task-stream/api/tracker/domain';
import { NotificationMailer } from '../ports/notification-mailer';
import { PushSender } from '../ports/push-sender';
import { NotificationsRepository } from '../ports/notifications.repository';
export interface MyNotifications {
@@ -13,6 +14,8 @@ export interface MyNotificationSettings {
email: boolean;
/** Whether this installation can send e-mail at all. */
emailAvailable: boolean;
/** VAPID public key to subscribe a device with; null: no push here. */
pushPublicKey: string | null;
}
export class GetMyNotificationsQuery extends Query<MyNotifications> {
@@ -57,6 +60,7 @@ export class GetMyNotificationSettingsQueryHandler
constructor(
private readonly notifications: NotificationsRepository,
private readonly mailer: NotificationMailer,
private readonly push: PushSender,
) {}
async execute(
@@ -66,6 +70,7 @@ export class GetMyNotificationSettingsQueryHandler
return {
email: this.mailer.enabled && settings.email,
emailAvailable: this.mailer.enabled,
pushPublicKey: this.push.publicKey,
};
}
}

View File

@@ -24,6 +24,12 @@ import { NotificationMailer } from '../ports/notification-mailer';
import { NotificationsRepository } from '../ports/notifications.repository';
import { NotificationsEventHandler } from './notifications.event-handler';
import { Notifier } from './notifier';
import {
PushPayload,
PushSender,
PushSubscriptionRecord,
} from '../ports/push-sender';
import { PushSubscriptionsRepository } from '../ports/push-subscriptions.repository';
class InMemoryNotifications extends NotificationsRepository {
readonly all: NotificationReadModel[] = [];
@@ -56,10 +62,14 @@ const at = <T extends TrackerEvent>(event: T, version = 2): T =>
occurredAt: '2026-10-08T10:00:00.000Z',
});
function setup(mailEnabled = false) {
function setup(mailEnabled = false, pushEnabled = false) {
const repo = new InMemoryNotifications();
const published: NotificationReadModel[] = [];
const mailed: string[] = [];
/** Endpoint → what was pushed to it. */
const pushed: [string, PushPayload][] = [];
const devices: PushSubscriptionRecord[] = [];
const forgotten: string[] = [];
const users = new FakeUserDirectory()
.add('ana')
.add('bob')
@@ -90,6 +100,21 @@ function setup(mailEnabled = false) {
},
} as unknown as NotificationMailer,
users,
{
publicKey: pushEnabled ? 'vapid-public' : null,
send: async (device: PushSubscriptionRecord, payload: PushPayload) => {
pushed.push([device.endpoint, payload]);
// A browser that dropped the subscription.
return device.endpoint.endsWith('/gone') ? 'gone' : 'sent';
},
} as unknown as PushSender,
{
forUser: async (userId: string) =>
devices.filter((d) => d.userId === userId),
forget: async (endpoint: string) => {
forgotten.push(endpoint);
},
} as unknown as PushSubscriptionsRepository,
);
const handler = new NotificationsEventHandler(
notifier,
@@ -118,7 +143,7 @@ function setup(mailEnabled = false) {
id === 's-14' ? { id, name: 'Sprint 14' } : null,
} as unknown as FindSprintsRepository,
);
return { repo, published, mailed, handler };
return { repo, published, mailed, pushed, devices, forgotten, handler };
}
describe('notifications', () => {
@@ -340,4 +365,32 @@ describe('notifications', () => {
NotificationKind.ADDED_TO_PROJECT,
]);
});
it('pushes to every device of whoever is told, and forgets dropped ones', async () => {
const { handler, pushed, devices, forgotten } = setup(false, true);
const device = (userId: string, endpoint: string) => ({
userId,
endpoint,
keys: { p256dh: 'p', auth: 'a' },
createdAt: '2026-10-01T00:00:00.000Z',
});
devices.push(
device('bob', 'https://push.example/phone'),
device('bob', 'https://push.example/gone'),
device('qa', 'https://push.example/qa'),
);
await handler.handle(
at(new IssueAssignedEvent('ana', 'i-1', 'p-1', 'bob', null)),
);
expect(pushed.map(([endpoint]) => endpoint)).toEqual([
'https://push.example/phone',
'https://push.example/gone',
]);
expect(pushed[0][1]).toMatchObject({
title: 'TaskStream · WEB-1',
url: '/p/WEB/issues/WEB-1',
});
expect(forgotten).toEqual(['https://push.example/gone']);
});
});

View File

@@ -9,6 +9,8 @@ import {
import { ChangeFeed } from '../ports/change-feed';
import { NotificationMailer } from '../ports/notification-mailer';
import { NotificationsRepository } from '../ports/notifications.repository';
import { PushPayload, PushSender } from '../ports/push-sender';
import { PushSubscriptionsRepository } from '../ports/push-subscriptions.repository';
import { UserDirectory } from '../ports/user-directory';
import { versionOf } from '../event-handlers/read-model-notifier';
@@ -39,6 +41,8 @@ export class Notifier {
private readonly changeFeed: ChangeFeed,
private readonly mailer: NotificationMailer,
private readonly users: UserDirectory,
private readonly push: PushSender,
private readonly pushSubscriptions: PushSubscriptionsRepository,
) {}
async deliver(
@@ -89,6 +93,33 @@ export class Notifier {
if (this.mailer.enabled && delivered.length) {
await this.email(delivered);
}
if (this.push.publicKey && delivered.length) {
await this.pushToDevices(delivered);
}
}
/**
* To every device where the person turned push on. Like e-mail, a failure
* never blocks the event stream; a device the push service forgot is
* forgotten here too.
*/
private async pushToDevices(
notifications: NotificationReadModel[],
): Promise<void> {
for (const notification of notifications) {
const devices = await this.pushSubscriptions.forUser(notification.userId);
for (const device of devices) {
try {
const result = await this.push.send(device, payloadOf(notification));
if (result === 'gone')
await this.pushSubscriptions.forget(device.endpoint);
} catch (error) {
this.logger.warn(
`Push to ${notification.userId} failed: ${(error as Error).message}`,
);
}
}
}
}
/** A failed e-mail never blocks the event stream: it is logged and skipped. */
@@ -116,3 +147,18 @@ export class Notifier {
}
}
}
/** What the device shows: the ticket (or project), the line and its page. */
export function payloadOf(notification: NotificationReadModel): PushPayload {
const project = encodeURIComponent(notification.projectKey);
return {
title: notification.issueKey
? `TaskStream · ${notification.issueKey}`
: `TaskStream · ${notification.projectKey}`,
body: notification.summary,
url: notification.issueKey
? `/p/${project}/issues/${encodeURIComponent(notification.issueKey)}`
: `/p/${project}`,
tag: notification.id,
};
}

View File

@@ -28,3 +28,5 @@ export * from './outgoing-webhooks.repository';
export * from './automations.repository';
export * from './rate-limit.store';
export * from './calendar-feeds.repository';
export * from './push-sender';
export * from './push-subscriptions.repository';

View File

@@ -0,0 +1,32 @@
/** A browser's push subscription (Web Push), as the browser hands it over. */
export interface PushSubscriptionRecord {
userId: string;
/** The push service URL of that browser on that device: unique. */
endpoint: string;
keys: { p256dh: string; auth: string };
createdAt: string;
}
/** What the service worker shows: a title, a line and where a tap goes. */
export interface PushPayload {
title: string;
body: string;
/** A path in the web app, e.g. `/p/WEB/issues/WEB-12`. */
url: string;
/** Replaces an earlier notification with the same tag on the device. */
tag: string;
}
/**
* Sends Web Push messages (VAPID). Without keys configured it is off and
* nobody is offered push.
*/
export abstract class PushSender {
/** The VAPID public key browsers subscribe with; null: push is off. */
abstract get publicKey(): string | null;
/** `gone`: the browser dropped the subscription; forget it. */
abstract send(
subscription: PushSubscriptionRecord,
payload: PushPayload,
): Promise<'sent' | 'gone'>;
}

View File

@@ -0,0 +1,12 @@
import { PushSubscriptionRecord } from './push-sender';
/** The devices where each person turned push on. */
export abstract class PushSubscriptionsRepository {
abstract forUser(userId: string): Promise<PushSubscriptionRecord[]>;
/** By endpoint: a device subscribing again replaces its entry. */
abstract save(subscription: PushSubscriptionRecord): Promise<void>;
/** Only the owner's: nobody drops someone else's device. */
abstract remove(userId: string, endpoint: string): Promise<void>;
/** The push service said it no longer exists. */
abstract forget(endpoint: string): Promise<void>;
}

View File

@@ -29,6 +29,8 @@ import {
import {
MarkNotificationsReadCommandHandler,
UpdateNotificationSettingsCommandHandler,
SubscribePushCommandHandler,
UnsubscribePushCommandHandler,
} from './notifications/notifications.commands';
import { SAVED_FILTERS } from './saved-filters/saved-filters';
@@ -55,6 +57,8 @@ const NOTIFICATIONS = [
GetMyNotificationSettingsQueryHandler,
MarkNotificationsReadCommandHandler,
UpdateNotificationSettingsCommandHandler,
SubscribePushCommandHandler,
UnsubscribePushCommandHandler,
SendDueRemindersCommandHandler,
];