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:
@@ -0,0 +1,51 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import {
|
||||
PushSubscriptionRecord,
|
||||
PushSubscriptionsRepository,
|
||||
} from '@task-stream/api/tracker/application';
|
||||
import { Model } from 'mongoose';
|
||||
import { PushSubscriptionDoc, ReadModels } from './read-model.schemas';
|
||||
|
||||
/** Endpoints are long URLs: their hash makes a tidy, unique `id`. */
|
||||
const idOf = (endpoint: string) =>
|
||||
createHash('sha256').update(endpoint).digest('hex');
|
||||
|
||||
@Injectable()
|
||||
export class MongoPushSubscriptionsRepository extends PushSubscriptionsRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.PushSubscription)
|
||||
private readonly subscriptions: Model<PushSubscriptionDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async forUser(userId: string): Promise<PushSubscriptionRecord[]> {
|
||||
const docs = await this.subscriptions
|
||||
.find({ userId })
|
||||
.lean<PushSubscriptionDoc[]>();
|
||||
return docs.map(({ userId: owner, endpoint, keys, createdAt }) => ({
|
||||
userId: owner,
|
||||
endpoint,
|
||||
keys,
|
||||
createdAt,
|
||||
}));
|
||||
}
|
||||
|
||||
async save(subscription: PushSubscriptionRecord): Promise<void> {
|
||||
await this.subscriptions.updateOne(
|
||||
{ id: idOf(subscription.endpoint) },
|
||||
{ $set: subscription },
|
||||
{ upsert: true },
|
||||
);
|
||||
}
|
||||
|
||||
async remove(userId: string, endpoint: string): Promise<void> {
|
||||
await this.subscriptions.deleteOne({ id: idOf(endpoint), userId });
|
||||
}
|
||||
|
||||
async forget(endpoint: string): Promise<void> {
|
||||
await this.subscriptions.deleteOne({ id: idOf(endpoint) });
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,14 @@ export interface GitIntegrationDoc {
|
||||
secret?: string;
|
||||
createdAt?: string;
|
||||
}
|
||||
export interface PushSubscriptionDoc {
|
||||
/** sha256 of the endpoint. */
|
||||
id: string;
|
||||
userId: string;
|
||||
endpoint: string;
|
||||
keys: { p256dh: string; auth: string };
|
||||
createdAt: string;
|
||||
}
|
||||
export interface CalendarFeedDoc {
|
||||
/** The user's id. */
|
||||
id: string;
|
||||
@@ -92,6 +100,7 @@ export const ReadModels = {
|
||||
Automation: 'Automation',
|
||||
AutomationRun: 'AutomationRun',
|
||||
CalendarFeed: 'CalendarFeed',
|
||||
PushSubscription: 'PushSubscription',
|
||||
} as const;
|
||||
|
||||
/*
|
||||
@@ -347,6 +356,20 @@ class CalendarFeedDocument {
|
||||
export const CalendarFeedSchema =
|
||||
SchemaFactory.createForClass(CalendarFeedDocument);
|
||||
|
||||
/** The devices where each person turned push on. */
|
||||
@Schema({ ...LOOSE, collection: 'push_subscriptions' })
|
||||
class PushSubscriptionDocument {
|
||||
/** sha256 of the endpoint. */
|
||||
@Prop({ type: String, required: true, unique: true }) id!: string;
|
||||
@Prop({ type: String, index: true }) userId!: string;
|
||||
@Prop({ type: String }) endpoint!: string;
|
||||
@Prop({ type: Object }) keys!: { p256dh: string; auth: string };
|
||||
@Prop({ type: String }) createdAt!: string;
|
||||
}
|
||||
export const PushSubscriptionSchema = SchemaFactory.createForClass(
|
||||
PushSubscriptionDocument,
|
||||
);
|
||||
|
||||
// Redeliveries happen within minutes; a month of memory is plenty.
|
||||
AutomationRunSchema.index({ at: 1 }, { expireAfterSeconds: 30 * 86_400 });
|
||||
|
||||
@@ -366,6 +389,7 @@ export const READ_MODEL_SCHEMAS = [
|
||||
{ name: ReadModels.NotificationSettings, schema: NotificationSettingsSchema },
|
||||
{ name: ReadModels.SavedFilter, schema: SavedFilterSchema },
|
||||
{ name: ReadModels.CalendarFeed, schema: CalendarFeedSchema },
|
||||
{ name: ReadModels.PushSubscription, schema: PushSubscriptionSchema },
|
||||
];
|
||||
|
||||
/** A document as the model it holds: Mongo's own `_id` left out. */
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { createECDH, randomBytes } from 'node:crypto';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import * as webpush from 'web-push';
|
||||
import { WebPushSender } from './web-push.sender';
|
||||
|
||||
// The real library, but nothing leaves the machine.
|
||||
jest.mock('web-push', () => ({
|
||||
...jest.requireActual('web-push'),
|
||||
sendNotification: jest.fn(),
|
||||
}));
|
||||
const sendNotification = webpush.sendNotification as jest.MockedFunction<
|
||||
typeof webpush.sendNotification
|
||||
>;
|
||||
|
||||
/** What a browser hands over: its P-256 public key and an auth secret. */
|
||||
function device(endpoint = 'https://push.example/abc') {
|
||||
const ecdh = createECDH('prime256v1');
|
||||
ecdh.generateKeys();
|
||||
return {
|
||||
userId: 'ana',
|
||||
endpoint,
|
||||
keys: {
|
||||
p256dh: ecdh.getPublicKey().toString('base64url'),
|
||||
auth: randomBytes(16).toString('base64url'),
|
||||
},
|
||||
createdAt: '2026-10-15T00:00:00.000Z',
|
||||
};
|
||||
}
|
||||
|
||||
const VAPID = webpush.generateVAPIDKeys();
|
||||
|
||||
function sender(withKeys = true) {
|
||||
const values: Record<string, string> = withKeys
|
||||
? {
|
||||
VAPID_PUBLIC_KEY: VAPID.publicKey,
|
||||
VAPID_PRIVATE_KEY: VAPID.privateKey,
|
||||
VAPID_SUBJECT: 'mailto:test@example.org',
|
||||
}
|
||||
: {};
|
||||
return new WebPushSender({
|
||||
get: (key: string) => values[key],
|
||||
} as unknown as ConfigService);
|
||||
}
|
||||
|
||||
const PAYLOAD = {
|
||||
title: 'TaskStream · WEB-1',
|
||||
body: 'Ana te asignó WEB-1',
|
||||
url: '/p/WEB/issues/WEB-1',
|
||||
tag: 'n-1',
|
||||
};
|
||||
|
||||
describe('WebPushSender', () => {
|
||||
afterEach(() => sendNotification.mockReset());
|
||||
|
||||
it('is off without VAPID keys, on with them', () => {
|
||||
expect(sender(false).publicKey).toBeNull();
|
||||
expect(sender().publicKey).toBe(VAPID.publicKey);
|
||||
});
|
||||
|
||||
it('builds an encrypted, VAPID-signed message for the device', () => {
|
||||
sender();
|
||||
const subscriber = device();
|
||||
const request = webpush.generateRequestDetails(
|
||||
{ endpoint: subscriber.endpoint, keys: subscriber.keys },
|
||||
JSON.stringify(PAYLOAD),
|
||||
{ TTL: 86_400 },
|
||||
);
|
||||
expect(request.headers['Content-Encoding']).toBe('aes128gcm');
|
||||
expect(String(request.headers['Authorization'])).toMatch(
|
||||
new RegExp(`^vapid t=.+, k=${VAPID.publicKey}$`),
|
||||
);
|
||||
// Encrypted: nothing of the text travels in the clear.
|
||||
expect(String(request.body)).not.toContain('WEB-1');
|
||||
});
|
||||
|
||||
it('sends the payload as JSON and keeps it a day', async () => {
|
||||
sendNotification.mockResolvedValue({
|
||||
statusCode: 201,
|
||||
body: '',
|
||||
headers: {},
|
||||
});
|
||||
expect(await sender().send(device(), PAYLOAD)).toBe('sent');
|
||||
const [target, body, options] = sendNotification.mock.calls[0];
|
||||
expect(target.endpoint).toBe('https://push.example/abc');
|
||||
expect(JSON.parse(String(body))).toEqual(PAYLOAD);
|
||||
expect(options).toMatchObject({ TTL: 86_400 });
|
||||
});
|
||||
|
||||
it('tells a subscription the push service dropped (404, 410)', async () => {
|
||||
for (const status of [404, 410]) {
|
||||
sendNotification.mockRejectedValueOnce(
|
||||
new webpush.WebPushError(
|
||||
'gone',
|
||||
status,
|
||||
{},
|
||||
'',
|
||||
'https://push.example/abc',
|
||||
),
|
||||
);
|
||||
expect(await sender().send(device(), PAYLOAD)).toBe('gone');
|
||||
}
|
||||
});
|
||||
|
||||
it('lets other failures through, to be logged', async () => {
|
||||
sendNotification.mockRejectedValue(
|
||||
new webpush.WebPushError('busy', 503, {}, '', 'https://push.example/abc'),
|
||||
);
|
||||
await expect(sender().send(device(), PAYLOAD)).rejects.toThrow('busy');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import {
|
||||
PushPayload,
|
||||
PushSender,
|
||||
PushSubscriptionRecord,
|
||||
} from '@task-stream/api/tracker/application';
|
||||
import * as webpush from 'web-push';
|
||||
|
||||
/**
|
||||
* Web Push with VAPID keys (VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY and
|
||||
* VAPID_SUBJECT, a `mailto:` or https URL the push services can reach
|
||||
* someone at). Make the keys once with `npx web-push generate-vapid-keys`;
|
||||
* changing them drops every subscription. Without them push is off.
|
||||
*/
|
||||
@Injectable()
|
||||
export class WebPushSender extends PushSender {
|
||||
private readonly logger = new Logger(WebPushSender.name);
|
||||
private readonly key: string | null;
|
||||
|
||||
constructor(config: ConfigService) {
|
||||
super();
|
||||
const publicKey = config.get<string>('VAPID_PUBLIC_KEY') || '';
|
||||
const privateKey = config.get<string>('VAPID_PRIVATE_KEY') || '';
|
||||
const subject =
|
||||
config.get<string>('VAPID_SUBJECT') || 'mailto:no-reply@pireon.dev';
|
||||
this.key = publicKey && privateKey ? publicKey : null;
|
||||
if (this.key) {
|
||||
webpush.setVapidDetails(subject, publicKey, privateKey);
|
||||
this.logger.log('Push notifications enabled');
|
||||
}
|
||||
}
|
||||
|
||||
get publicKey(): string | null {
|
||||
return this.key;
|
||||
}
|
||||
|
||||
async send(
|
||||
subscription: PushSubscriptionRecord,
|
||||
payload: PushPayload,
|
||||
): Promise<'sent' | 'gone'> {
|
||||
if (!this.key) return 'sent';
|
||||
try {
|
||||
await webpush.sendNotification(
|
||||
{ endpoint: subscription.endpoint, keys: subscription.keys },
|
||||
JSON.stringify(payload),
|
||||
// Kept a day by the push service while the device is off.
|
||||
{ TTL: 86_400, urgency: 'normal' },
|
||||
);
|
||||
return 'sent';
|
||||
} catch (error) {
|
||||
// 404 / 410: that browser dropped the subscription for good.
|
||||
if (
|
||||
error instanceof webpush.WebPushError &&
|
||||
(error.statusCode === 404 || error.statusCode === 410)
|
||||
)
|
||||
return 'gone';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
NotificationMailer,
|
||||
NotificationsRepository,
|
||||
CalendarFeedsRepository,
|
||||
PushSubscriptionsRepository,
|
||||
PushSender,
|
||||
SavedFiltersRepository,
|
||||
GitIntegrationsRepository,
|
||||
OutgoingWebhooksRepository,
|
||||
@@ -67,6 +69,8 @@ import { RedisChangeFeed } from './realtime/redis-change-feed';
|
||||
import { RedisRateLimitStore } from './redis/redis-rate-limit.store';
|
||||
import { MongoNotificationsRepository } from './mongo/notifications.repository';
|
||||
import { MongoCalendarFeedsRepository } from './mongo/calendar-feeds.repository';
|
||||
import { MongoPushSubscriptionsRepository } from './mongo/push-subscriptions.repository';
|
||||
import { WebPushSender } from './push/web-push.sender';
|
||||
import { MongoSavedFiltersRepository } from './mongo/saved-filters.repository';
|
||||
import { MongoGitIntegrationsRepository } from './mongo/git-integrations.repository';
|
||||
import { MongoOutgoingWebhooksRepository } from './mongo/outgoing-webhooks.repository';
|
||||
@@ -133,6 +137,11 @@ const PORTS = [
|
||||
// Notifications → MongoDB (per person), copies by e-mail → SMTP (optional)
|
||||
{ provide: NotificationsRepository, useClass: MongoNotificationsRepository },
|
||||
{ provide: CalendarFeedsRepository, useClass: MongoCalendarFeedsRepository },
|
||||
{
|
||||
provide: PushSubscriptionsRepository,
|
||||
useClass: MongoPushSubscriptionsRepository,
|
||||
},
|
||||
{ provide: PushSender, useClass: WebPushSender },
|
||||
{ provide: SavedFiltersRepository, useClass: MongoSavedFiltersRepository },
|
||||
{
|
||||
provide: GitIntegrationsRepository,
|
||||
|
||||
Reference in New Issue
Block a user