feat(notifications): Web Push delivers notifications to every device, even with TREK closed

A fourth built-in channel next to email, webhook and ntfy. Browsers
register per device, the server encrypts per RFC 8291 and signs per RFC
8292 with node:crypto and sends only to known push services through the
SSRF guard. The event matrix decides per category what arrives by push;
admins switch the channel on under Notifications.

VAPID keys come from the environment or are generated once, only while
neither stored row exists, and kept encrypted. A pair that does not
decrypt or match is never overwritten and never swapped for another one:
push stays off with an error in the log and every device stays
registered until the key is fixed. The subject is VAPID_SUBJECT, then an
https APP_URL, then the project URL.

Only chat messages collapse into one notification per trip, and a
replacement still alerts. A 403 removes a device only after three
failures in a row; 404 and 410 remove it at once. Password change, reset
and an admin setting a password drop the user's devices with the other
credentials. The request log redacts subscriptions and endpoints, boot
errors print *** for every secret variable, and logout forgets the
device with a plain fetch so an expired session cannot redirect midway.

Addresses discussion #894.
This commit is contained in:
Maurice
2026-09-24 23:17:03 +00:00
parent 7ce31756a3
commit 650451bdf7
177 changed files with 7809 additions and 271 deletions
@@ -1,4 +1,4 @@
// FE-ADMNOT-001 to FE-ADMNOT-043
// FE-ADMNOT-001 to FE-ADMNOT-046
import { http, HttpResponse } from 'msw';
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -571,4 +571,47 @@ describe('AdminNotificationsTab', () => {
expect(screen.queryByRole('heading', { name: 'Admin Webhook' })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Admin Ntfy' })).not.toBeInTheDocument();
});
it('FE-ADMNOT-044: Web Push has its own card after Ntfy, before In-App', () => {
renderTab({ smtpValues: { notification_channels: 'email' } });
const headings = screen.getAllByRole('heading').map(h => h.textContent);
expect(headings.indexOf('Web Push')).toBe(headings.indexOf('Ntfy') + 1);
expect(headings.indexOf('In-App')).toBe(headings.indexOf('Web Push') + 1);
expect(within(card('Web Push')).getByText(/receive notifications on their phones/)).toBeInTheDocument();
expect(within(card('Web Push')).getByRole('button', { name: 'Web Push' })).toHaveAttribute('aria-pressed', 'false');
});
it('FE-ADMNOT-045: switching Web Push on adds push to the list and keeps the rest', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
const admin = renderTab({ smtpValues: { notification_channels: 'email,plugin-gotify' } });
fireEvent.click(within(card('Web Push')).getByRole('button', { name: 'Web Push' }));
await waitFor(() => expect(body).toEqual({ notification_channels: 'email,push,plugin-gotify' }));
expect(replaySmtp(admin.setSmtpValues, 0).notification_channels).toBe('email,push,plugin-gotify');
});
it('FE-ADMNOT-046: an active push channel shows its switch on, and switching it off keeps email', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
renderTab({ smtpValues: { notification_channels: 'email,push' } });
const toggle = within(card('Web Push')).getByRole('button', { name: 'Web Push' });
expect(toggle).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(toggle);
await waitFor(() => expect(body).toEqual({ notification_channels: 'email' }));
});
});
@@ -4,43 +4,39 @@ import { Save } from 'lucide-react'
import type { TranslationFn } from '../../types'
import type { useAdmin } from './useAdmin'
import AdminNotificationsPanel from './AdminNotificationsPanel'
import { SWITCH_ONLY_CHANNELS, useNotificationChannels } from '../../components/Admin/useNotificationChannels'
interface AdminNotificationsTabProps {
admin: ReturnType<typeof useAdmin>
t: TranslationFn
}
// "Notifications" admin tab: email/webhook/ntfy channel toggles, SMTP credentials,
// trip reminders, admin webhook + ntfy targets, and the per-event preference matrix.
// Derives channel state from smtpValues exactly as the original inline IIFE did.
/** The on/off switch at the right of a channel card. */
function ChannelSwitch({ on, label, onToggle }: { on: boolean; label: string; onToggle: () => void }): React.ReactElement {
return (
<button type="button"
onClick={onToggle}
aria-pressed={on}
aria-label={label}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${on ? 'bg-content' : 'bg-edge'}`}
>
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-surface-card transition-transform duration-200"
style={{ transform: on ? 'translateX(20px)' : 'translateX(0)' }} />
</button>
)
}
// "Notifications" admin tab: email/webhook/ntfy/web push channel toggles, SMTP
// credentials, trip reminders, admin webhook + ntfy targets, and the per-event
// preference matrix. The channel switches come from useNotificationChannels,
// which the phone section shares.
export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTabProps): React.ReactElement {
const { toast, smtpValues, setSmtpValues, smtpLoaded, setTripRemindersEnabled, managed } = admin
// Derive active channels from smtpValues.notification_channels (plural)
// with fallback to notification_channel (singular) for existing installs
const rawChannels = smtpValues.notification_channels ?? smtpValues.notification_channel ?? 'none'
const activeChans = rawChannels === 'none' ? [] : rawChannels.split(',').map((c: string) => c.trim())
const emailActive = activeChans.includes('email')
const webhookActive = activeChans.includes('webhook')
const ntfyActive = activeChans.includes('ntfy')
const channels = useNotificationChannels(admin, t)
const emailActive = channels.isActive('email')
const tripRemindersActive = smtpValues.notify_trip_reminder !== 'false'
const setChannels = async (email: boolean, webhook: boolean, ntfy: boolean) => {
// Preserve any id this toggle doesn't know about instead of rebuilding the CSV from
// just these three booleans — that used to silently DROP anything else stored here.
const others = activeChans.filter((c: string) => c !== 'email' && c !== 'webhook' && c !== 'ntfy')
const chans = [email && 'email', webhook && 'webhook', ntfy && 'ntfy', ...others].filter(Boolean).join(',') || 'none'
setSmtpValues(prev => ({ ...prev, notification_channels: chans }))
try {
await authApi.updateAppSettings({ notification_channels: chans })
} catch {
// Revert state on failure
const reverted = [emailActive && 'email', webhookActive && 'webhook', ntfyActive && 'ntfy', ...others].filter(Boolean).join(',') || 'none'
setSmtpValues(prev => ({ ...prev, notification_channels: reverted }))
toast.error(t('common.error'))
}
}
const smtpConfigured = !!(smtpValues.smtp_host?.trim())
const saveNotifications = async () => {
// Saves credentials only — channel activation is auto-saved by the toggle
@@ -64,7 +60,7 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa
pairs cards row by row and leaves a hole under the shorter one, and the SMTP
card is taller than all the toggle rows together. Grouped by audience, not by
height — the channels a user can receive on the left, everything the operator
sends or receives themselves on the right. The three channel switches stay
sends or receives themselves on the right. The channel switches stay
together because they all write the same notification_channels list.
On a managed install the two admin-target cards are gone and the right column
is the matrix alone — still a column, so the grid keeps working. */}
@@ -81,13 +77,7 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa
<h2 className="font-semibold text-slate-900">{t('admin.notifications.emailPanel.title')}</h2>
<p className="text-xs text-slate-400 mt-1">{t('admin.smtp.hint')}</p>
</div>
<button type="button"
onClick={() => setChannels(!emailActive, webhookActive, ntfyActive)}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${emailActive ? 'bg-content' : 'bg-edge'}`}
>
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
style={{ transform: emailActive ? 'translateX(20px)' : 'translateX(0)' }} />
</button>
<ChannelSwitch on={emailActive} label={t('admin.notifications.emailPanel.title')} onToggle={() => channels.toggle('email')} />
</div>
<div className={`p-6 space-y-3 ${!emailActive ? 'opacity-50 pointer-events-none' : ''}`}>
{smtpLoaded && [
@@ -152,39 +142,18 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa
</div>
</>)}
{/* Webhook Panel */}
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
<div className="px-6 py-4 flex items-center justify-between">
<div>
<h2 className="font-semibold text-slate-900">{t('admin.notifications.webhookPanel.title')}</h2>
<p className="text-xs text-slate-400 mt-1">{t('admin.webhook.hint')}</p>
{/* Webhook, Ntfy and Web Push: a title, a hint and the switch each */}
{SWITCH_ONLY_CHANNELS.map(ch => (
<div key={ch.id} className="bg-surface-card rounded-xl border border-edge overflow-hidden">
<div className="px-6 py-4 flex items-center justify-between">
<div>
<h2 className="font-semibold text-content">{t(ch.titleKey)}</h2>
<p className="text-caption text-content-faint mt-1">{t(ch.hintKey)}</p>
</div>
<ChannelSwitch on={channels.isActive(ch.id)} label={t(ch.titleKey)} onToggle={() => channels.toggle(ch.id)} />
</div>
<button type="button"
onClick={() => setChannels(emailActive, !webhookActive, ntfyActive)}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${webhookActive ? 'bg-content' : 'bg-edge'}`}
>
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
style={{ transform: webhookActive ? 'translateX(20px)' : 'translateX(0)' }} />
</button>
</div>
</div>
{/* Ntfy Panel */}
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
<div className="px-6 py-4 flex items-center justify-between">
<div>
<h2 className="font-semibold text-slate-900">{t('admin.notifications.ntfy')}</h2>
<p className="text-xs text-slate-400 mt-1">{t('admin.ntfy.hint') || 'Allow users to configure their own ntfy topics for push notifications.'}</p>
</div>
<button type="button"
onClick={() => setChannels(emailActive, webhookActive, !ntfyActive)}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${ntfyActive ? 'bg-content' : 'bg-edge'}`}
>
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
style={{ transform: ntfyActive ? 'translateX(20px)' : 'translateX(0)' }} />
</button>
</div>
</div>
))}
{/* In-App Panel */}
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">