Push-Benachrichtigungen, Rechtstexte und Barrierefreiheitserklärung
Push: - Abos mit Themen (Neuigkeiten, Schließzeiten), jederzeit abbestellbar; iPhone-Hinweis zur Installation; VAPID-Schlüssel automatisch erzeugt - Meldungen mit „Benachrichtigung senden“ gehen beim Erscheinen raus (auch zeitgesteuert), Schließzeiten automatisch am Nachmittag davor - Redaktionsseite „Benachrichtigungen“ mit Vorschau, Empfängerzahlen und Verlauf; abgelaufene Abos werden entfernt, doppeltes Senden verhindert - Automatische Nachrichten ohne Empfänger werden nicht als gesendet verbucht (sonst verpasste Schließzeit-Erinnerung) Rechtliches (eigener Server): - Angaben zur Einrichtung in den Einstellungen; Impressum (§ 5 DDG, § 18 MStV) und Datenschutzerklärung aus Vorlagen, die genau beschreiben, was die App verarbeitet – fehlende Angaben gelb markiert - Seite „Barrierefreiheit“ mit Erklärung und Formular „Barriere melden“, Meldungen gekennzeichnet und filterbar im Postfach - Vorlesen bevorzugt Stimmen auf dem Gerät (keine Online-Stimme, wenn vermeidbar) Geprüft: Push Ende-zu-Ende gegen nachgebauten Push-Dienst (Entschlüsselung, VAPID, 410-Abbau), axe-Audit aller Seiten ohne Befund. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
3230618596
commit
0dfb787d06
29 changed files with 1119 additions and 43 deletions
180
src/lib/server/push.ts
Normal file
180
src/lib/server/push.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
import webpush from 'web-push';
|
||||
import { and, eq, gt, isNull, lte } from 'drizzle-orm';
|
||||
import { db } from './db';
|
||||
import { events, posts, pushMessages, pushSubscriptions, settings } from './db/schema';
|
||||
import { getSettings } from './settings';
|
||||
import { addDays, formatLong, TZ, today } from '$lib/dates';
|
||||
import { PUSH_TOPICS, type PushTopic } from '$lib/push';
|
||||
|
||||
// ─── Schlüssel ────────────────────────────────────────────────────────────────
|
||||
|
||||
type Keys = { publicKey: string; privateKey: string };
|
||||
let keys: Keys | null = null;
|
||||
|
||||
/** VAPID-Schlüssel aus der .env oder – beim ersten Mal – erzeugt und gespeichert */
|
||||
function vapid(): Keys {
|
||||
if (keys) return keys;
|
||||
if (process.env.VAPID_PUBLIC_KEY && process.env.VAPID_PRIVATE_KEY) {
|
||||
keys = { publicKey: process.env.VAPID_PUBLIC_KEY, privateKey: process.env.VAPID_PRIVATE_KEY };
|
||||
} else {
|
||||
const row = db.select().from(settings).where(eq(settings.key, 'vapid')).get();
|
||||
if (row) keys = row.value as Keys;
|
||||
else {
|
||||
keys = webpush.generateVAPIDKeys();
|
||||
db.insert(settings).values({ key: 'vapid', value: keys }).run();
|
||||
}
|
||||
}
|
||||
const s = getSettings();
|
||||
const subject = s.contactEmail ? `mailto:${s.contactEmail}` : (process.env.ORIGIN ?? 'mailto:admin@example.org');
|
||||
webpush.setVapidDetails(subject, keys.publicKey, keys.privateKey);
|
||||
return keys;
|
||||
}
|
||||
|
||||
export const publicKey = () => vapid().publicKey;
|
||||
|
||||
// ─── Abos ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type BrowserSubscription = { endpoint: string; keys: { p256dh: string; auth: string } };
|
||||
|
||||
const cleanTopics = (topics: unknown): PushTopic[] =>
|
||||
Array.isArray(topics) ? [...new Set(topics.filter((t): t is PushTopic => typeof t === 'string' && t in PUSH_TOPICS))] : [];
|
||||
|
||||
export function saveSubscription(sub: BrowserSubscription, topics: unknown) {
|
||||
const t = cleanTopics(topics);
|
||||
db.insert(pushSubscriptions)
|
||||
.values({ endpoint: sub.endpoint, p256dh: sub.keys.p256dh, auth: sub.keys.auth, topics: t })
|
||||
.onConflictDoUpdate({ target: pushSubscriptions.endpoint, set: { p256dh: sub.keys.p256dh, auth: sub.keys.auth, topics: t } })
|
||||
.run();
|
||||
return t;
|
||||
}
|
||||
|
||||
export function removeSubscription(endpoint: string) {
|
||||
db.delete(pushSubscriptions).where(eq(pushSubscriptions.endpoint, endpoint)).run();
|
||||
}
|
||||
|
||||
export function subscriberCounts() {
|
||||
const rows = db.select({ topics: pushSubscriptions.topics }).from(pushSubscriptions).all();
|
||||
const counts = Object.fromEntries(Object.keys(PUSH_TOPICS).map((k) => [k, 0])) as Record<PushTopic, number>;
|
||||
for (const r of rows) for (const t of r.topics) if (t in counts) counts[t as PushTopic]++;
|
||||
return { total: rows.length, byTopic: counts };
|
||||
}
|
||||
|
||||
// ─── Versand ──────────────────────────────────────────────────────────────────
|
||||
|
||||
type Payload = { title: string; body?: string; url?: string };
|
||||
|
||||
/**
|
||||
* Sendet an alle Abos eines Themas. Mit `dedupeKey` wird dieselbe Nachricht
|
||||
* garantiert nur einmal verschickt (z. B. nach einem Neustart).
|
||||
*/
|
||||
export async function sendToTopic(
|
||||
topic: PushTopic | 'all',
|
||||
payload: Payload,
|
||||
opts: { automatic?: boolean; dedupeKey?: string; sentBy?: number } = {}
|
||||
) {
|
||||
vapid();
|
||||
const subs = db
|
||||
.select()
|
||||
.from(pushSubscriptions)
|
||||
.all()
|
||||
.filter((s) => (topic === 'all' ? s.topics.length > 0 : s.topics.includes(topic)));
|
||||
|
||||
// Automatische Nachrichten ohne Empfänger nicht als „gesendet“ vermerken –
|
||||
// sonst wäre z. B. eine Schließzeit-Erinnerung verbraucht, bevor jemand abonniert hat
|
||||
if (opts.automatic && subs.length === 0) return null;
|
||||
|
||||
let messageId: number;
|
||||
try {
|
||||
messageId = db
|
||||
.insert(pushMessages)
|
||||
.values({
|
||||
topic,
|
||||
title: payload.title,
|
||||
body: payload.body ?? '',
|
||||
url: payload.url ?? '/',
|
||||
automatic: opts.automatic ?? false,
|
||||
dedupeKey: opts.dedupeKey ?? null,
|
||||
sentBy: opts.sentBy ?? null
|
||||
})
|
||||
.returning({ id: pushMessages.id })
|
||||
.get().id;
|
||||
} catch {
|
||||
return null; // schon gesendet (dedupeKey)
|
||||
}
|
||||
|
||||
const body = JSON.stringify({ title: payload.title, body: payload.body ?? '', url: payload.url ?? '/' });
|
||||
let ok = 0,
|
||||
failed = 0;
|
||||
// in kleinen Gruppen senden, damit der Server nicht überlastet
|
||||
for (let i = 0; i < subs.length; i += 10) {
|
||||
await Promise.all(
|
||||
subs.slice(i, i + 10).map(async (s) => {
|
||||
try {
|
||||
await webpush.sendNotification({ endpoint: s.endpoint, keys: { p256dh: s.p256dh, auth: s.auth } }, body, {
|
||||
TTL: 60 * 60 * 24,
|
||||
urgency: 'normal'
|
||||
});
|
||||
ok++;
|
||||
} catch (e) {
|
||||
failed++;
|
||||
const status = (e as { statusCode?: number }).statusCode;
|
||||
// Abo existiert nicht mehr (App deinstalliert, Berechtigung entzogen)
|
||||
if (status === 404 || status === 410) removeSubscription(s.endpoint);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
db.update(pushMessages).set({ recipients: ok, failures: failed }).where(eq(pushMessages.id, messageId)).run();
|
||||
return { recipients: ok, failures: failed };
|
||||
}
|
||||
|
||||
// ─── Automatische Benachrichtigungen ──────────────────────────────────────────
|
||||
|
||||
/** Meldungen mit „Benachrichtigung senden“, die jetzt erschienen sind */
|
||||
export async function sendDuePosts() {
|
||||
const due = db
|
||||
.select()
|
||||
.from(posts)
|
||||
.where(
|
||||
and(
|
||||
eq(posts.notify, true),
|
||||
isNull(posts.notifiedAt),
|
||||
eq(posts.published, true),
|
||||
lte(posts.publishedAt, new Date()),
|
||||
// ältere nicht mehr nachträglich verschicken
|
||||
gt(posts.publishedAt, new Date(Date.now() - 2 * 864e5))
|
||||
)
|
||||
)
|
||||
.all();
|
||||
for (const p of due) {
|
||||
db.update(posts).set({ notifiedAt: new Date() }).where(eq(posts.id, p.id)).run();
|
||||
await sendToTopic('news', { title: p.title, body: p.teaser, url: `/meldungen/${p.slug}` }, { automatic: true, dedupeKey: `post-${p.id}` });
|
||||
}
|
||||
}
|
||||
|
||||
/** Erinnerung am Nachmittag vor einer Schließzeit */
|
||||
export async function sendClosureReminders() {
|
||||
const hour = Number(new Intl.DateTimeFormat('de-DE', { hour: 'numeric', hour12: false, timeZone: TZ }).format(new Date()));
|
||||
if (hour < 14) return;
|
||||
const tomorrow = addDays(today(), 1);
|
||||
const closures = db
|
||||
.select()
|
||||
.from(events)
|
||||
.where(and(eq(events.kind, 'closure'), eq(events.published, true), eq(events.startDate, tomorrow)))
|
||||
.all();
|
||||
for (const c of closures) {
|
||||
const until = c.endDate && c.endDate !== c.startDate ? ` bis ${formatLong(c.endDate)}` : '';
|
||||
await sendToTopic(
|
||||
'closures',
|
||||
{ title: `Morgen geschlossen: ${c.title}`, body: `Die Werkstatt ist ab ${formatLong(c.startDate)}${until} geschlossen.`, url: '/termine?zeige=schliesszeiten' },
|
||||
{ automatic: true, dedupeKey: `closure-${c.id}-${c.startDate}` }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function startPushScheduler() {
|
||||
const run = () =>
|
||||
Promise.all([sendDuePosts(), sendClosureReminders()]).catch((e) => console.error('[push] Fehler im Zeitplan:', e));
|
||||
run();
|
||||
setInterval(run, 5 * 60e3).unref();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue