diff --git a/.env.example b/.env.example index c40e613..788715e 100644 --- a/.env.example +++ b/.env.example @@ -1,9 +1,23 @@ # Speicherort der SQLite-Datenbank und der Uploads DATA_DIR=./data -# Öffentliche URL der App (für Cookies, Links, Manifest) -ORIGIN=http://localhost:3000 +# Öffentliche URL der App (Pflicht in Produktion: Formulare, Links in E-Mails) +ORIGIN=https://app.example.org # Erster Admin-Zugang – wird beim ersten Start angelegt, falls noch kein Benutzer existiert ADMIN_EMAIL=admin@example.org ADMIN_PASSWORD=bitte-aendern + +# E-Mail-Versand (für „Passwort vergessen“). Ohne SMTP_HOST steht der Link nur im Server-Log. +SMTP_HOST= +SMTP_PORT=587 +SMTP_SECURE=false +SMTP_USER= +SMTP_PASS= +SMTP_FROM="Werkstatt-App " + +# Push-Benachrichtigungen: Schlüssel werden beim ersten Start automatisch erzeugt und +# in der Datenbank gespeichert. Nur setzen, wenn eigene Schlüssel verwendet werden sollen +# (erzeugen mit: npx web-push generate-vapid-keys). +VAPID_PUBLIC_KEY= +VAPID_PRIVATE_KEY= diff --git a/README.md b/README.md index ddb6734..a0f54de 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,9 @@ Tablet und Desktop. **Leichte Sprache** pro Seite/Meldung - **Vorlesen** jeder Seite (Knopf in der Kopfzeile) oder eines Artikels: satzweise, der gelesene Satz wird markiert und mitgescrollt, mit Pause, Satz vor/zurück und langsamem Tempo +- **Push-Benachrichtigungen** zu Neuigkeiten und Schließzeiten (Themen frei wählbar, jederzeit abbestellbar) - Merkliste (lokal auf dem Gerät), Teilen, offline lesbar, als App installierbar +- Seite **Barrierefreiheit** mit Erklärung und Formular „Barriere melden“ - Keine Werbung, kein Tracking, keine externen Schriften oder CDNs **Redaktion (`/admin`)** @@ -33,6 +35,13 @@ Tablet und Desktop. Startseiten-Bereiche, Mediathek, Postfach - Text-Editor mit Formatierungen, Links und Bildern - Bilder werden automatisch gedreht, verkleinert und als WebP gespeichert +- **Benachrichtigungen:** beim Erscheinen einer Meldung (auch zeitgesteuert), automatisch am Vortag einer + Schließzeit, oder von Hand – mit Vorschau und Verlauf +- **Rechtliches:** Impressum und Datenschutzerklärung aus Vorlagen, die genau beschreiben, was die App + verarbeitet (bitte trotzdem prüfen lassen); Erklärung zur Barrierefreiheit; Barriere-Meldungen im Postfach +- **Sicherheit:** Zwei-Faktor-Anmeldung (Authenticator-App, Wiederherstellungscodes, für Admins + verpflichtend schaltbar), „Passwort vergessen“ per E-Mail, dauerhafte Sperren gegen Durchprobieren, + Content-Security-Policy - Rollen: **Redakteur** (Inhalte) und **Administrator** (zusätzlich Benutzer & Einstellungen) - Einstellungen: App-Name, Logo, Farbpaar (Haupt- und Akzentfarbe), Titelbild, Texte, Impressum, Datenschutz – das App-Symbol wird daraus automatisch erzeugt @@ -78,6 +87,8 @@ Ohne Docker: `npm ci && npm run build && ORIGIN=https://… BODY_SIZE_LIMIT=30M | `DATA_DIR` | Ordner für `app.db` und `uploads/` (Standard `./data`) | | `ADMIN_EMAIL` / `ADMIN_PASSWORD` | Erster Admin, wird angelegt, solange es noch keinen Benutzer gibt | | `BODY_SIZE_LIMIT` | Max. Upload-Größe (im Docker-Image auf 30M gesetzt) | +| `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASS`, `SMTP_FROM` | E-Mail-Versand für „Passwort vergessen“. Ohne SMTP steht der Link im Server-Log | +| `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | Optional – sonst werden die Push-Schlüssel automatisch erzeugt und gespeichert | ## Erweitern diff --git a/docker-compose.yml b/docker-compose.yml index 15fe5c7..469c0ef 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,6 +8,12 @@ services: ORIGIN: ${ORIGIN:-http://localhost:3000} ADMIN_EMAIL: ${ADMIN_EMAIL:-} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} + SMTP_HOST: ${SMTP_HOST:-} + SMTP_PORT: ${SMTP_PORT:-587} + SMTP_SECURE: ${SMTP_SECURE:-false} + SMTP_USER: ${SMTP_USER:-} + SMTP_PASS: ${SMTP_PASS:-} + SMTP_FROM: ${SMTP_FROM:-} volumes: - ./data:/data mem_limit: 384m diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 46e4bb3..68f69aa 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -2,6 +2,7 @@ import type { Handle, ServerInit } from '@sveltejs/kit'; import { redirect } from '@sveltejs/kit'; import { SESSION_COOKIE, ensureInitialAdmin, purgeExpiredSessions, validateSession } from '$lib/server/auth'; import { purgeRateLimits } from '$lib/server/ratelimit'; +import { startPushScheduler } from '$lib/server/push'; import { getSettings } from '$lib/server/settings'; import { PREFS_COOKIE, parsePrefs } from '$lib/prefs'; @@ -13,6 +14,7 @@ export const init: ServerInit = async () => { }; cleanup(); setInterval(cleanup, 6 * 3600e3).unref(); + startPushScheduler(); }; export const handle: Handle = async ({ event, resolve }) => { diff --git a/src/lib/admin/EditForm.svelte b/src/lib/admin/EditForm.svelte index b3aec00..a430805 100644 --- a/src/lib/admin/EditForm.svelte +++ b/src/lib/admin/EditForm.svelte @@ -29,7 +29,8 @@ method="POST" action="?/save" use:enhance={({ submitter, cancel }) => { - if (submitter?.getAttribute('formaction')?.includes('delete') && !confirm(deleteConfirm)) { + const question = submitter?.getAttribute('formaction')?.includes('delete') ? deleteConfirm : submitter?.getAttribute('data-confirm'); + if (question && !confirm(question)) { cancel(); return; } diff --git a/src/lib/components/MenuSheet.svelte b/src/lib/components/MenuSheet.svelte index 7131115..9cc0025 100644 --- a/src/lib/components/MenuSheet.svelte +++ b/src/lib/components/MenuSheet.svelte @@ -3,6 +3,8 @@ import Users from '@lucide/svelte/icons/users'; import Mail from '@lucide/svelte/icons/mail'; import SlidersHorizontal from '@lucide/svelte/icons/sliders-horizontal'; + import Bell from '@lucide/svelte/icons/bell'; + import Accessibility from '@lucide/svelte/icons/accessibility'; import ExternalLink from '@lucide/svelte/icons/external-link'; import Scale from '@lucide/svelte/icons/scale'; import ShieldCheck from '@lucide/svelte/icons/shield-check'; @@ -70,8 +72,10 @@ { href: '/kontakte', label: 'Ansprechpartner', icon: Users }, { href: '/kontakt', label: 'Nachricht schreiben', icon: Mail }, { href: '/einstellungen', label: 'Einstellungen', icon: SlidersHorizontal }, + { href: '/einstellungen#benachrichtigungen', label: 'Benachrichtigungen', icon: Bell }, { href: '/impressum', label: 'Impressum', icon: Scale }, - { href: '/datenschutz', label: 'Datenschutz', icon: ShieldCheck } + { href: '/datenschutz', label: 'Datenschutz', icon: ShieldCheck }, + { href: '/barrierefreiheit', label: 'Barrierefreiheit', icon: Accessibility } ] as l (l.href)}
  • diff --git a/src/lib/components/PushSettings.svelte b/src/lib/components/PushSettings.svelte new file mode 100644 index 0000000..3db0c3a --- /dev/null +++ b/src/lib/components/PushSettings.svelte @@ -0,0 +1,68 @@ + + +
    +
    + +
    +

    Benachrichtigungen

    +

    Wir melden uns nur, wenn es wichtig ist. Du kannst sie jederzeit wieder ausschalten.

    +
    +
    + + {#if push.status === 'loading'} +

    Wird geprüft …

    + {:else if push.status === 'ios-install'} +

    + Auf dem iPhone funktionieren Benachrichtigungen nur in der installierten App: + Tippe unten auf und dann auf „Zum Home-Bildschirm“. + Öffne die App danach über das neue Symbol. +

    + {:else if push.status === 'unsupported'} +

    Dieser Browser unterstützt leider keine Benachrichtigungen.

    + {:else if push.status === 'denied'} +

    + Benachrichtigungen sind für diese Seite blockiert. Du kannst das in den Einstellungen deines Browsers oder Handys wieder erlauben. +

    + {:else} +
    + Worüber möchtest du benachrichtigt werden? + {#each pushTopicKeys as t (t)} + + {/each} +
    + {#if push.subscribed} +

    Benachrichtigungen sind eingeschaltet.

    + + {:else} + + {/if} + {#if push.error}{/if} + {/if} +
    diff --git a/src/lib/push.svelte.ts b/src/lib/push.svelte.ts new file mode 100644 index 0000000..267c832 --- /dev/null +++ b/src/lib/push.svelte.ts @@ -0,0 +1,96 @@ +import type { PushTopic } from './push'; + +const TOPICS_KEY = 'wa_push_topics'; + +function urlBase64ToUint8Array(base64: string) { + const padding = '='.repeat((4 - (base64.length % 4)) % 4); + const raw = atob((base64 + padding).replace(/-/g, '+').replace(/_/g, '/')); + return Uint8Array.from(raw, (c) => c.charCodeAt(0)); +} + +/** Push-Benachrichtigungen im Browser abonnieren und verwalten */ +class PushState { + /** unsupported | ios-install | default | denied | granted */ + status = $state<'loading' | 'unsupported' | 'ios-install' | 'default' | 'denied' | 'granted'>('loading'); + subscribed = $state(false); + topics = $state(['news', 'closures']); + busy = $state(false); + error = $state(''); + + async init() { + const ios = /iphone|ipad|ipod/i.test(navigator.userAgent); + const standalone = matchMedia('(display-mode: standalone)').matches || (navigator as { standalone?: boolean }).standalone; + if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) { + this.status = ios && !standalone ? 'ios-install' : 'unsupported'; + return; + } + this.status = Notification.permission; + try { + const saved = JSON.parse(localStorage.getItem(TOPICS_KEY) ?? 'null'); + if (Array.isArray(saved)) this.topics = saved; + } catch { + /* ohne Speicher */ + } + const reg = await navigator.serviceWorker.getRegistration(); + const sub = await reg?.pushManager.getSubscription(); + this.subscribed = !!sub && Notification.permission === 'granted'; + } + + async subscribe(topics: PushTopic[] = this.topics) { + this.busy = true; + this.error = ''; + try { + const permission = await Notification.requestPermission(); + this.status = permission; + if (permission !== 'granted') return false; + const reg = await navigator.serviceWorker.ready; + const { publicKey } = await (await fetch('/api/push')).json(); + const sub = + (await reg.pushManager.getSubscription()) ?? + (await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(publicKey) })); + const res = await fetch('/api/push', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ subscription: sub.toJSON(), topics }) + }); + if (!res.ok) throw new Error(); + this.topics = (await res.json()).topics; + this.subscribed = true; + try { + localStorage.setItem(TOPICS_KEY, JSON.stringify(this.topics)); + } catch { + /* ohne Speicher */ + } + return true; + } catch { + this.error = 'Das Einschalten hat nicht geklappt. Bitte später noch einmal versuchen.'; + return false; + } finally { + this.busy = false; + } + } + + async setTopic(topic: PushTopic, on: boolean) { + const next = on ? [...new Set([...this.topics, topic])] : this.topics.filter((t) => t !== topic); + if (!next.length) return this.unsubscribe(); + if (this.subscribed) await this.subscribe(next); + else this.topics = next; + } + + async unsubscribe() { + this.busy = true; + try { + const reg = await navigator.serviceWorker.getRegistration(); + const sub = await reg?.pushManager.getSubscription(); + if (sub) { + await fetch('/api/push', { method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ endpoint: sub.endpoint }) }); + await sub.unsubscribe(); + } + this.subscribed = false; + } finally { + this.busy = false; + } + } +} + +export const push = new PushState(); diff --git a/src/lib/push.ts b/src/lib/push.ts new file mode 100644 index 0000000..a07c706 --- /dev/null +++ b/src/lib/push.ts @@ -0,0 +1,8 @@ +/** Themen für Push-Benachrichtigungen (Server und Browser) */ +export const PUSH_TOPICS = { + news: { label: 'Neuigkeiten', hint: 'Wichtige Meldungen aus den Werkstätten' }, + closures: { label: 'Schließzeiten', hint: 'Erinnerung am Tag vorher, wenn die Werkstatt geschlossen ist' } +} as const; + +export type PushTopic = keyof typeof PUSH_TOPICS; +export const pushTopicKeys = Object.keys(PUSH_TOPICS) as PushTopic[]; diff --git a/src/lib/server/legal.ts b/src/lib/server/legal.ts new file mode 100644 index 0000000..00f6b7f --- /dev/null +++ b/src/lib/server/legal.ts @@ -0,0 +1,77 @@ +import type { AppSettings } from '$lib/settings'; +import { formatDate, today } from '$lib/dates'; + +/** + * Vorlagen für Impressum und Datenschutzerklärung – beschreiben genau das, + * was diese App verarbeitet. Sie ersetzen keine Rechtsberatung und sollten + * vor der Veröffentlichung geprüft werden. + */ + +const esc = (v: string) => v.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!); +const lines = (...parts: string[]) => parts.filter(Boolean).map(esc).join('
    '); +const todo = (label: string) => `[${esc(label)} ergänzen]`; +const val = (v: string, label: string) => (v.trim() ? esc(v.trim()) : todo(label)); + +export function imprintTemplate(s: AppSettings): string { + const l = s.legal; + return [ + '

    Angaben gemäß § 5 DDG

    ', + `

    ${val(l.name, 'Name der Einrichtung / des Trägers')}
    ${l.street || l.city ? lines(l.street, l.city) : todo('Anschrift')}

    `, + `

    Vertreten durch:
    ${val(l.representatives, 'Geschäftsführung / Vorstand')}

    `, + '

    Kontakt

    ', + `

    ${l.phone ? `Telefon: ${esc(l.phone)}
    ` : ''}E-Mail: ${val(l.email, 'E-Mail-Adresse')}

    `, + l.register ? `

    Registereintrag

    ${esc(l.register)}

    ` : '', + l.vatId ? `

    Umsatzsteuer-ID

    Umsatzsteuer-Identifikationsnummer gemäß § 27a UStG: ${esc(l.vatId)}

    ` : '', + `

    Verantwortlich für den Inhalt nach § 18 Abs. 2 MStV

    ${val(l.contentResponsible, 'Name und Anschrift der verantwortlichen Person')}

    `, + '

    Verbraucherstreitbeilegung

    ', + '

    Wir sind nicht bereit oder verpflichtet, an Streitbeilegungsverfahren vor einer Verbraucherschlichtungsstelle teilzunehmen.

    ', + '

    Haftung für Links

    ', + '

    Diese App enthält Links zu externen Websites Dritter, auf deren Inhalte wir keinen Einfluss haben. Für diese Inhalte ist der jeweilige Anbieter verantwortlich. Bei Bekanntwerden von Rechtsverletzungen entfernen wir solche Links umgehend.

    ' + ] + .filter(Boolean) + .join('\n'); +} + +export function privacyTemplate(s: AppSettings): string { + const l = s.legal; + const days = Math.max(1, l.logRetentionDays || 7); + return [ + '

    Kurz gesagt: Diese App kommt ohne Werbung, ohne Tracking und ohne Analyse-Werkzeuge aus. Wir verarbeiten nur die Daten, die für den Betrieb nötig sind oder die du uns selbst gibst.

    ', + + '

    1. Verantwortlich

    ', + `

    ${val(l.name, 'Name der Einrichtung')}
    ${l.street || l.city ? lines(l.street, l.city) : todo('Anschrift')}
    E-Mail: ${val(l.email, 'E-Mail-Adresse')}${l.phone ? `
    Telefon: ${esc(l.phone)}` : ''}

    `, + l.dpo ? `

    Datenschutzbeauftragte/r:
    ${esc(l.dpo)}

    ` : '', + + '

    2. Betrieb der App

    ', + '

    Die App wird auf einem eigenen Server des Verantwortlichen betrieben. Es werden keine Daten an Dritte weitergegeben, außer in den unten beschriebenen Fällen, die du selbst auslöst.

    ', + `

    Beim Aufruf verarbeitet der Server technisch notwendige Daten: IP-Adresse, Datum und Uhrzeit, aufgerufene Adresse sowie Angaben zu Browser und Betriebssystem. Das ist nötig, um die Seiten auszuliefern und den Betrieb abzusichern (Art. 6 Abs. 1 lit. f DSGVO). Protokolldateien werden nach spätestens ${days} Tagen gelöscht.

    `, + + '

    3. Cookies und Speicher auf deinem Gerät

    ', + '
      ', + '
    • Anzeige-Einstellungen (Schriftgröße, Farbschema, Leichte Sprache) speichern wir in einem Cookie auf deinem Gerät, damit die App so aussieht, wie du es eingestellt hast.
    • ', + '
    • Merkliste, gewähltes Vorlese-Tempo und die Themen für Benachrichtigungen liegen nur im Speicher deines Browsers und werden nicht an uns übertragen.
    • ', + '
    • Für die Redaktion setzen wir nach der Anmeldung ein Sitzungs-Cookie.
    • ', + '
    ', + '

    Diese Speicherungen sind für die von dir gewünschten Funktionen unbedingt erforderlich (§ 25 Abs. 2 Nr. 2 TDDDG). Eine Einwilligung ist dafür nicht nötig, deshalb gibt es auch kein Cookie-Banner.

    ', + + '

    4. Kontaktformular und Meldung von Barrieren

    ', + '

    Wenn du uns schreibst, speichern wir deinen Namen, deine Nachricht und – falls angegeben – deine E-Mail-Adresse, um dein Anliegen zu bearbeiten (Art. 6 Abs. 1 lit. f DSGVO). Die Nachricht wird gelöscht, sobald sie erledigt ist und keine Aufbewahrungspflicht besteht.

    ', + + '

    5. Benachrichtigungen (Push)

    ', + '

    Benachrichtigungen erhältst du nur, wenn du sie selbst einschaltest (Einwilligung, Art. 6 Abs. 1 lit. a DSGVO). Dann speichern wir die Push-Adresse deines Browsers, die zugehörigen Schlüssel und die gewählten Themen. Zugestellt werden die Nachrichten über den Push-Dienst des Browser-Herstellers (z. B. Google, Apple, Mozilla oder Microsoft); dabei kann eine Übermittlung in Länder außerhalb der EU stattfinden. Der Inhalt der Nachricht ist verschlüsselt. Du kannst die Einwilligung jederzeit unter „Einstellungen → Benachrichtigungen“ widerrufen; die Daten werden dann gelöscht.

    ', + + '

    6. Vorlesen

    ', + '

    Die Vorlesefunktion nutzt die Sprachausgabe deines Geräts. Wir bevorzugen Stimmen, die direkt auf dem Gerät arbeiten. Steht nur eine Online-Stimme des Browsers zur Verfügung, kann der vorgelesene Text vom Browser-Anbieter verarbeitet werden. Wir selbst erhalten dabei keine Daten.

    ', + + '

    7. Eingebettete Videos

    ', + '

    Videos von YouTube (im erweiterten Datenschutzmodus, youtube-nocookie.com) oder Vimeo werden erst geladen, wenn du auf „Video abspielen“ tippst. Erst dann wird eine Verbindung zum jeweiligen Anbieter hergestellt, der dabei u. a. deine IP-Adresse erhält und Daten auch in den USA verarbeiten kann (Einwilligung, Art. 6 Abs. 1 lit. a DSGVO).

    ', + + '

    8. Deine Rechte

    ', + '

    Du hast das Recht auf Auskunft, Berichtigung, Löschung und Einschränkung der Verarbeitung, auf Datenübertragbarkeit sowie auf Widerspruch gegen Verarbeitungen, die auf berechtigtem Interesse beruhen. Eine Einwilligung kannst du jederzeit mit Wirkung für die Zukunft widerrufen. Schreib uns dazu einfach über die oben genannten Kontaktdaten.

    ', + `

    Außerdem kannst du dich bei einer Datenschutz-Aufsichtsbehörde beschweren${l.supervisory ? `, zum Beispiel bei der für uns zuständigen: ${esc(l.supervisory)}` : ''}.

    `, + + `

    Stand: ${formatDate(today())}

    ` + ] + .filter(Boolean) + .join('\n'); +} diff --git a/src/lib/server/push.ts b/src/lib/server/push.ts new file mode 100644 index 0000000..0d2aada --- /dev/null +++ b/src/lib/server/push.ts @@ -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; + 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(); +} diff --git a/src/lib/server/settings.ts b/src/lib/server/settings.ts index 25fb4b0..d2dc6ca 100644 --- a/src/lib/server/settings.ts +++ b/src/lib/server/settings.ts @@ -8,7 +8,14 @@ let cache: AppSettings | null = null; export function getSettings(): AppSettings { if (cache) return cache; const row = db.select().from(settings).all().find((r) => r.key === KEY); - cache = { ...DEFAULT_SETTINGS, ...((row?.value as Partial) ?? {}) }; + const stored = (row?.value as Partial) ?? {}; + // verschachtelte Angaben einzeln ergänzen, damit neue Felder Standardwerte bekommen + cache = { + ...DEFAULT_SETTINGS, + ...stored, + legal: { ...DEFAULT_SETTINGS.legal, ...(stored.legal ?? {}) }, + a11y: { ...DEFAULT_SETTINGS.a11y, ...(stored.a11y ?? {}) } + }; return cache; } diff --git a/src/lib/settings.ts b/src/lib/settings.ts index b2f682c..c258cde 100644 --- a/src/lib/settings.ts +++ b/src/lib/settings.ts @@ -1,3 +1,28 @@ +/** Angaben zur Einrichtung – daraus entstehen Impressum und Datenschutzerklärung */ +export type LegalInfo = { + name: string; + street: string; + city: string; + phone: string; + email: string; + representatives: string; + register: string; + vatId: string; + contentResponsible: string; + dpo: string; + supervisory: string; + logRetentionDays: number; +}; + +/** Erklärung zur Barrierefreiheit */ +export type A11yInfo = { + status: 'full' | 'partial' | 'none'; + issues: string; + date: string; + contact: string; + enforcement: string; +}; + /** Einstellungen, die im Admin unter „Einstellungen“ gepflegt werden. */ export type AppSettings = { /** Name der App (Kopfzeile, Homescreen-Symbol) */ @@ -23,6 +48,8 @@ export type AppSettings = { contactIntro: string; imprint: string; privacy: string; + legal: LegalInfo; + a11y: A11yInfo; /** Wie viele Meldungen/Termine die Startseite zeigt */ /** Administratoren müssen die Zwei-Faktor-Anmeldung einrichten */ require2faAdmins: boolean; @@ -46,6 +73,27 @@ export const DEFAULT_SETTINGS: AppSettings = { contactIntro: 'Du hast Fragen oder Ideen für die App? Schreib uns gerne!', imprint: '

    Bitte im Admin-Bereich unter „Einstellungen“ ausfüllen.

    ', privacy: '

    Bitte im Admin-Bereich unter „Einstellungen“ ausfüllen.

    ', + legal: { + name: '', + street: '', + city: '', + phone: '', + email: '', + representatives: '', + register: '', + vatId: '', + contentResponsible: '', + dpo: '', + supervisory: '', + logRetentionDays: 7 + }, + a11y: { + status: 'partial', + issues: '', + date: '', + contact: '', + enforcement: '' + }, require2faAdmins: false, homeNewsCount: 4, homeEventsCount: 4 diff --git a/src/lib/speech.svelte.ts b/src/lib/speech.svelte.ts index 4ea61ba..7ed8b2d 100644 --- a/src/lib/speech.svelte.ts +++ b/src/lib/speech.svelte.ts @@ -118,7 +118,9 @@ class Speech { #speakFrom(i: number) { const run = ++this.#run; speechSynthesis.cancel(); - const voice = speechSynthesis.getVoices().find((v) => v.lang.startsWith('de')); + // Stimmen bevorzugen, die auf dem Gerät arbeiten – Online-Stimmen schicken den Text an den Browser-Anbieter + const german = speechSynthesis.getVoices().filter((v) => v.lang.startsWith('de')); + const voice = german.find((v) => v.localService) ?? german[0]; for (let k = i; k < this.#sentences.length; k++) { const u = new SpeechSynthesisUtterance(this.#sentences[k].text); u.lang = 'de-DE'; diff --git a/src/routes/(app)/+layout.svelte b/src/routes/(app)/+layout.svelte index ad5316c..bfb5feb 100644 --- a/src/routes/(app)/+layout.svelte +++ b/src/routes/(app)/+layout.svelte @@ -100,6 +100,8 @@
    Kontakt Impressum Datenschutz + Barrierefreiheit + Barriere melden Redaktion diff --git a/src/routes/(app)/barrierefreiheit/+page.server.ts b/src/routes/(app)/barrierefreiheit/+page.server.ts new file mode 100644 index 0000000..728b25a --- /dev/null +++ b/src/routes/(app)/barrierefreiheit/+page.server.ts @@ -0,0 +1,38 @@ +import { fail } from '@sveltejs/kit'; +import { db } from '$lib/server/db'; +import { messages } from '$lib/server/db/schema'; +import { getSettings } from '$lib/server/settings'; +import { allow } from '$lib/server/ratelimit'; +import { formatDate } from '$lib/dates'; + +export const load = ({ url }) => { + const s = getSettings(); + return { + orgName: s.legal.name || s.orgName, + status: s.a11y.status, + issues: s.a11y.issues.split('\n').map((l) => l.trim()).filter(Boolean), + date: s.a11y.date ? formatDate(s.a11y.date) : '', + contact: s.a11y.contact, + enforcement: s.a11y.enforcement, + // Von welcher Seite kommt die Meldung? (Link „Barriere melden“) + page: (url.searchParams.get('seite') ?? '').slice(0, 300) + }; +}; + +export const actions = { + default: async ({ request, getClientAddress }) => { + const form = await request.formData(); + const get = (k: string, max: number) => String(form.get(k) ?? '').trim().slice(0, max); + const values = { name: get('name', 200), email: get('email', 200), message: get('message', 5000), page: get('page', 300) }; + if (form.get('website')) return { sent: true }; // Honeypot + if (!values.message) return fail(400, { ...values, error: 'Bitte beschreibe kurz, was nicht funktioniert.' }); + if (values.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) + return fail(400, { ...values, error: 'Die E-Mail-Adresse sieht nicht richtig aus.' }); + if (!allow(`barriere:${getClientAddress()}`, 5, 3600e3)) + return fail(429, { ...values, error: 'Zu viele Meldungen. Bitte versuche es später noch einmal.' }); + db.insert(messages) + .values({ kind: 'barrier', name: values.name || 'Ohne Namen', email: values.email, message: values.message, pageUrl: values.page }) + .run(); + return { sent: true }; + } +}; diff --git a/src/routes/(app)/barrierefreiheit/+page.svelte b/src/routes/(app)/barrierefreiheit/+page.svelte new file mode 100644 index 0000000..f5c3441 --- /dev/null +++ b/src/routes/(app)/barrierefreiheit/+page.svelte @@ -0,0 +1,103 @@ + + +Barrierefreiheit · {data.brand.appName} + +
    + + +
    +

    + {data.orgName} möchte, dass alle Menschen diese App gut nutzen können. Diese Erklärung beschreibt, wie weit uns das + gelingt{data.date ? ` (Stand: ${data.date})` : ''}. +

    + +

    Wie barrierefrei ist die App?

    +

    Die App „{data.brand.appName}“ ist {statusText[data.status]}.

    +

    + Wir prüfen App und Redaktionsbereich regelmäßig mit dem Prüfwerkzeug axe gegen die Web-Richtlinien WCAG 2.2 (Stufe AA), + in hellem und dunklem Farbschema, am Handy und am Computer. Dazu gibt es: große Schrift, dunkles Farbschema, + Vorlesen, Leichte Sprache, Bedienung mit Tastatur und Unterstützung für Bildschirmleser. +

    + + {#if data.issues.length} +

    Was ist noch nicht barrierefrei?

    +
      + {#each data.issues as issue (issue)}
    • {issue}
    • {/each} +
    + {/if} + +

    Barriere gefunden?

    +

    + Wenn dir etwas auffällt, das du nicht gut nutzen kannst, sag uns bitte Bescheid. Wir kümmern uns darum und melden uns + bei dir, wenn du uns eine E-Mail-Adresse gibst. + {#if data.contact}Du erreichst uns auch per E-Mail: {data.contact}.{/if} +

    +
    + +
    + {#if form?.sent} +
    + +
    +

    Danke für deine Meldung!

    +

    Wir schauen uns das an.

    +
    +
    + {:else} +
    { + sending = true; + return async ({ update }) => { + await update({ reset: false }); + sending = false; + }; + }} + > + {#if form?.error}{/if} +
    + + +
    +
    + + +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    + {/if} +
    + + {#if data.enforcement} +
    +

    Durchsetzungsverfahren

    +

    {data.enforcement}

    +
    + {/if} +
    diff --git a/src/routes/(app)/einstellungen/+page.svelte b/src/routes/(app)/einstellungen/+page.svelte index 932d564..b794b76 100644 --- a/src/routes/(app)/einstellungen/+page.svelte +++ b/src/routes/(app)/einstellungen/+page.svelte @@ -1,6 +1,7 @@ @@ -12,6 +13,9 @@
    +
    + +
    diff --git a/src/routes/admin/(panel)/+layout.svelte b/src/routes/admin/(panel)/+layout.svelte index 4d62a1d..16f5362 100644 --- a/src/routes/admin/(panel)/+layout.svelte +++ b/src/routes/admin/(panel)/+layout.svelte @@ -9,6 +9,7 @@ import Users from '@lucide/svelte/icons/users'; import Image from '@lucide/svelte/icons/image'; import Inbox from '@lucide/svelte/icons/inbox'; + import BellRing from '@lucide/svelte/icons/bell-ring'; import UserCog from '@lucide/svelte/icons/user-cog'; import Settings from '@lucide/svelte/icons/settings'; import LogOut from '@lucide/svelte/icons/log-out'; @@ -45,6 +46,7 @@ title: 'Verwaltung', items: [ { href: '/admin/postfach', label: 'Postfach', icon: Inbox, badge: data.unread }, + { href: '/admin/benachrichtigungen', label: 'Benachrichtigungen', icon: BellRing }, ...(data.user.role === 'admin' ? [ { href: '/admin/benutzer', label: 'Benutzer', icon: UserCog }, diff --git a/src/routes/admin/(panel)/benachrichtigungen/+page.server.ts b/src/routes/admin/(panel)/benachrichtigungen/+page.server.ts new file mode 100644 index 0000000..8bf2efc --- /dev/null +++ b/src/routes/admin/(panel)/benachrichtigungen/+page.server.ts @@ -0,0 +1,36 @@ +import { fail } from '@sveltejs/kit'; +import { desc, eq } from 'drizzle-orm'; +import { db } from '$lib/server/db'; +import { pushMessages, users } from '$lib/server/db/schema'; +import { sendToTopic, subscriberCounts } from '$lib/server/push'; +import { fields } from '$lib/server/forms'; +import { allow } from '$lib/server/ratelimit'; +import { PUSH_TOPICS, type PushTopic } from '$lib/push'; + +export const load = () => ({ + counts: subscriberCounts(), + history: db + .select({ m: pushMessages, by: users.name }) + .from(pushMessages) + .leftJoin(users, eq(pushMessages.sentBy, users.id)) + .orderBy(desc(pushMessages.id)) + .limit(50) + .all() + .map(({ m, by }) => ({ ...m, by, createdAt: m.createdAt.toISOString() })) +}); + +export const actions = { + send: async ({ request, locals }) => { + const f = fields(await request.formData()); + const topic = f.str('topic'); + const title = f.str('title', 80); + const body = f.str('body', 200); + const url = f.str('url', 300) || '/'; + if (topic !== 'all' && !(topic in PUSH_TOPICS)) return fail(400, { error: 'Bitte wähle, wer die Nachricht bekommt.' }); + if (!title) return fail(400, { error: 'Bitte gib einen Titel ein.' }); + if (!url.startsWith('/')) return fail(400, { error: 'Der Link muss auf eine Seite der App zeigen (beginnt mit /).' }); + if (!allow(`push-send:${locals.user!.id}`, 10, 3600e3)) return fail(429, { error: 'Zu viele Nachrichten in kurzer Zeit.' }); + const res = await sendToTopic(topic as PushTopic | 'all', { title, body, url }, { sentBy: locals.user!.id }); + return { sent: res?.recipients ?? 0 }; + } +}; diff --git a/src/routes/admin/(panel)/benachrichtigungen/+page.svelte b/src/routes/admin/(panel)/benachrichtigungen/+page.svelte new file mode 100644 index 0000000..d733c1c --- /dev/null +++ b/src/routes/admin/(panel)/benachrichtigungen/+page.svelte @@ -0,0 +1,129 @@ + + + + +
    +
    +

    {data.counts.total}

    +

    Geräte mit Benachrichtigungen

    +
    + {#each pushTopicKeys as t (t)} +
    +

    {data.counts.byTopic[t]}

    +

    {PUSH_TOPICS[t].label}

    +
    + {/each} +
    + +
    +
    +

    Nachricht senden

    +
    { + busy = true; + return async ({ result, update }) => { + busy = false; + if (result.type === 'failure') toasts.show(String(result.data?.error), 'error'); + else if (result.type === 'success') { + toasts.show(`An ${result.data?.sent ?? 0} Geräte gesendet`); + title = body = ''; + } + await update({ reset: false }); + }; + }} + > +
    + An wen? +
    + {#each [...pushTopicKeys, 'all'] as t (t)} + + {/each} +
    +
    +
    + + +

    {title.length} / 80 Zeichen – kurz halten, auf dem Sperrbildschirm ist wenig Platz.

    +
    +
    + + +
    +
    + + +

    Pfad innerhalb der App, z. B. /termine oder /s/speiseplaene.

    +
    + + {#if form?.error}{/if} +
    +
    + + +
    + +
    +

    Verlauf

    +
    + + + + + + + + + + + + {#each data.history as m (m.id)} + + + + + + + + {:else} + + {/each} + +
    ZeitpunktNachrichtAnZugestelltVon
    {when(m.createdAt)}{m.title}{#if m.body}{m.body}{/if}{topicLabel(m.topic)}{m.recipients}{#if m.failures} ({m.failures} fehlgeschlagen){/if} + {#if m.automatic}{:else}{m.by ?? '–'}{/if} +
    Noch keine Benachrichtigungen gesendet.
    +
    +
    diff --git a/src/routes/admin/(panel)/einstellungen/+page.server.ts b/src/routes/admin/(panel)/einstellungen/+page.server.ts index 3cc6661..e15f0b2 100644 --- a/src/routes/admin/(panel)/einstellungen/+page.server.ts +++ b/src/routes/admin/(panel)/einstellungen/+page.server.ts @@ -3,6 +3,8 @@ import { getSettings, saveSettings } from '$lib/server/settings'; import { getMedia } from '$lib/server/content'; import { fields, requireAdmin } from '$lib/server/forms'; import { cleanHtml } from '$lib/server/sanitize'; +import { imprintTemplate, privacyTemplate } from '$lib/server/legal'; +import type { AppSettings } from '$lib/settings'; export const load = ({ locals }) => { requireAdmin(locals.user); @@ -10,38 +12,78 @@ export const load = ({ locals }) => { return { settings: s, logo: getMedia(s.logoId), hero: getMedia(s.heroImageId) }; }; +/** Liest alle Felder des Formulars – oder gibt eine Fehlermeldung zurück */ +function read(form: FormData): Partial | string { + const f = fields(form); + const appName = f.str('appName', 40); + const brandColor = f.str('brandColor', 7); + const accentColor = f.str('accentColor', 7); + if (!appName) return 'Die App braucht einen Namen.'; + if (![brandColor, accentColor].every((c) => /^#[0-9a-f]{6}$/i.test(c))) return 'Eine der Farben ist ungültig.'; + const website = f.str('website', 300); + if (website && !/^https?:\/\//.test(website)) return 'Die Website muss mit https:// beginnen.'; + const a11yStatus = f.str('a11yStatus'); + const a11yDate = f.str('a11yDate'); + + return { + appName, + orgName: f.str('orgName', 120), + greeting: f.str('greeting', 120), + intro: f.str('intro', 400), + brandColor, + accentColor, + logoId: f.int('logoId'), + heroEnabled: f.bool('heroEnabled'), + heroImageId: f.int('heroImageId'), + heroTagline: f.str('heroTagline', 40), + website, + contactEmail: f.str('contactEmail', 200), + contactIntro: f.str('contactIntro', 400), + imprint: cleanHtml(f.html('imprint')), + privacy: cleanHtml(f.html('privacy')), + require2faAdmins: f.bool('require2faAdmins'), + homeNewsCount: Math.min(12, Math.max(0, f.int('homeNewsCount') ?? 4)), + homeEventsCount: Math.min(12, Math.max(0, f.int('homeEventsCount') ?? 4)), + legal: { + name: f.str('legalName', 200), + street: f.str('legalStreet', 200), + city: f.str('legalCity', 200), + phone: f.str('legalPhone', 60), + email: f.str('legalEmail', 200), + representatives: f.str('legalRepresentatives', 300), + register: f.str('legalRegister', 200), + vatId: f.str('legalVatId', 40), + contentResponsible: f.str('legalContentResponsible', 300), + dpo: f.str('legalDpo', 300), + supervisory: f.str('legalSupervisory', 300), + logRetentionDays: Math.min(90, Math.max(1, f.int('legalLogDays') ?? 7)) + }, + a11y: { + status: a11yStatus === 'full' || a11yStatus === 'none' ? a11yStatus : 'partial', + issues: f.str('a11yIssues', 4000), + date: /^\d{4}-\d{2}-\d{2}$/.test(a11yDate) ? a11yDate : '', + contact: f.str('a11yContact', 200), + enforcement: f.str('a11yEnforcement', 2000) + } + }; +} + export const actions = { save: async ({ request, locals }) => { requireAdmin(locals.user); - const f = fields(await request.formData()); - const appName = f.str('appName', 40); - const brandColor = f.str('brandColor', 7); - const accentColor = f.str('accentColor', 7); - if (!appName) return fail(400, { error: 'Die App braucht einen Namen.' }); - if (![brandColor, accentColor].every((c) => /^#[0-9a-f]{6}$/i.test(c))) return fail(400, { error: 'Eine der Farben ist ungültig.' }); - const website = f.str('website', 300); - if (website && !/^https?:\/\//.test(website)) return fail(400, { error: 'Die Website muss mit https:// beginnen.' }); - - saveSettings({ - appName, - orgName: f.str('orgName', 120), - greeting: f.str('greeting', 120), - intro: f.str('intro', 400), - brandColor, - accentColor, - logoId: f.int('logoId'), - heroEnabled: f.bool('heroEnabled'), - heroImageId: f.int('heroImageId'), - heroTagline: f.str('heroTagline', 40), - website, - contactEmail: f.str('contactEmail', 200), - contactIntro: f.str('contactIntro', 400), - imprint: cleanHtml(f.html('imprint')), - privacy: cleanHtml(f.html('privacy')), - require2faAdmins: f.bool('require2faAdmins'), - homeNewsCount: Math.min(12, Math.max(0, f.int('homeNewsCount') ?? 4)), - homeEventsCount: Math.min(12, Math.max(0, f.int('homeEventsCount') ?? 4)) - }); + const patch = read(await request.formData()); + if (typeof patch === 'string') return fail(400, { error: patch }); + saveSettings(patch); return { saved: true }; + }, + + /** Speichert und erzeugt Impressum und Datenschutzerklärung neu aus den Angaben */ + generateLegal: async ({ request, locals }) => { + requireAdmin(locals.user); + const patch = read(await request.formData()); + if (typeof patch === 'string') return fail(400, { error: patch }); + const next = saveSettings(patch); + saveSettings({ imprint: imprintTemplate(next), privacy: privacyTemplate(next) }); + return { saved: true, generated: true }; } }; diff --git a/src/routes/admin/(panel)/einstellungen/+page.svelte b/src/routes/admin/(panel)/einstellungen/+page.svelte index fd7cab6..5a24673 100644 --- a/src/routes/admin/(panel)/einstellungen/+page.svelte +++ b/src/routes/admin/(panel)/einstellungen/+page.svelte @@ -102,9 +102,102 @@ /> - - - + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +

    So einstellen, wie es der Webserver (z. B. Caddy) tatsächlich tut.

    +
    +
    + +
    + + + {#key `${s.imprint}|${s.privacy}`} + + + {/key} + + + +
    + Die App ist … +
    + {#each [['full', 'vollständig barrierefrei'], ['partial', 'teilweise barrierefrei'], ['none', 'nicht barrierefrei']] as [v, l] (v)} + + {/each} +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + +
    +
    +
    + + +

    Für öffentliche Stellen vorgeschrieben (BITV 2.0 bzw. Landesrecht) – bitte die zuständige Stelle eintragen. Sonst leer lassen.

    +
    {#snippet aside()} diff --git a/src/routes/admin/(panel)/meldungen/[id]/+page.server.ts b/src/routes/admin/(panel)/meldungen/[id]/+page.server.ts index e459728..e12e43b 100644 --- a/src/routes/admin/(panel)/meldungen/[id]/+page.server.ts +++ b/src/routes/admin/(panel)/meldungen/[id]/+page.server.ts @@ -6,6 +6,7 @@ import { attachmentsOf, contactOptions as listContactOptions, getMedia, mediaByI import { fields, parseId, uniqueSlug } from '$lib/server/forms'; import { cleanHtml } from '$lib/server/sanitize'; import { fromLocalInput, toLocalInput } from '$lib/dates'; +import { sendDuePosts, subscriberCounts } from '$lib/server/push'; import type { MediaItem } from '$lib/types'; export const load = ({ params }) => { @@ -15,9 +16,10 @@ export const load = ({ params }) => { if (id === 'new') { return { isNew: true, + subscribers: subscriberCounts().byTopic.news, contactOptions, post: { - id: 0, title: '', slug: '', teaser: '', content: '', contentEasy: '', videoUrl: '', pinned: false, published: true, + id: 0, title: '', slug: '', teaser: '', content: '', contentEasy: '', videoUrl: '', pinned: false, published: true, notify: false, notifiedAt: null as string | null, publishedAt: toLocalInput(new Date()), cover: null as MediaItem | null, gallery: [] as MediaItem[], attachments: [] as ReturnType, contactIds: [] as number[] } @@ -29,10 +31,12 @@ export const load = ({ params }) => { const gallery = mediaByIds(p.gallery); return { isNew: false, + subscribers: subscriberCounts().byTopic.news, contactOptions, post: { id: p.id, title: p.title, slug: p.slug, teaser: p.teaser, content: p.content, contentEasy: p.contentEasy, videoUrl: p.videoUrl, pinned: p.pinned, published: p.published, publishedAt: toLocalInput(p.publishedAt), + notify: p.notify, notifiedAt: p.notifiedAt?.toISOString() ?? null, cover: getMedia(p.coverId), gallery: p.gallery.map((g) => gallery.get(g)).filter((m): m is MediaItem => !!m), attachments: attachmentsOf(p.attachments), @@ -60,15 +64,19 @@ export const actions = { attachments: f.attachments('attachments'), contactIds: f.ids('contactIds'), pinned: f.bool('pinned'), + notify: f.bool('notify'), published: f.bool('published'), publishedAt: fromLocalInput(f.str('publishedAt')) ?? new Date() }; if (id === 'new') { const created = db.insert(posts).values(values).returning({ id: posts.id }).get(); + await sendDuePosts(); redirect(303, `/admin/meldungen/${created.id}`); } db.update(posts).set(values).where(eq(posts.id, id)).run(); + // Ist die Meldung jetzt erschienen und soll benachrichtigen? Dann sofort senden. + await sendDuePosts(); return { saved: true }; }, delete: ({ params }) => { diff --git a/src/routes/admin/(panel)/meldungen/[id]/+page.svelte b/src/routes/admin/(panel)/meldungen/[id]/+page.svelte index 16eb764..848dbbc 100644 --- a/src/routes/admin/(panel)/meldungen/[id]/+page.svelte +++ b/src/routes/admin/(panel)/meldungen/[id]/+page.svelte @@ -53,6 +53,17 @@ + {#if p.notifiedAt} +

    Benachrichtigung gesendet am {new Date(p.notifiedAt).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' })}.

    + + {:else} + + {/if}
    diff --git a/src/routes/admin/(panel)/postfach/+page.server.ts b/src/routes/admin/(panel)/postfach/+page.server.ts index 8e008b5..b7030c5 100644 --- a/src/routes/admin/(panel)/postfach/+page.server.ts +++ b/src/routes/admin/(panel)/postfach/+page.server.ts @@ -3,15 +3,20 @@ import { db } from '$lib/server/db'; import { messages } from '$lib/server/db/schema'; import { fields } from '$lib/server/forms'; -export const load = () => ({ +export const load = ({ url }) => { + const kind = url.searchParams.get('art'); + return { + kind: kind === 'barrier' || kind === 'contact' ? kind : null, messages: db .select() .from(messages) + .where(kind === 'barrier' || kind === 'contact' ? eq(messages.kind, kind) : undefined) .orderBy(desc(messages.id)) .limit(500) .all() .map((m) => ({ ...m, createdAt: m.createdAt.toISOString() })) -}); + }; +}; export const actions = { read: async ({ request }) => { diff --git a/src/routes/admin/(panel)/postfach/+page.svelte b/src/routes/admin/(panel)/postfach/+page.svelte index 3c6ae67..924b158 100644 --- a/src/routes/admin/(panel)/postfach/+page.svelte +++ b/src/routes/admin/(panel)/postfach/+page.svelte @@ -12,7 +12,13 @@ let openId = $state(null); - + + + {#if data.messages.length}
      @@ -34,7 +40,10 @@ {#if m.read}{:else}{/if} - {m.name} + + {m.name} + {#if m.kind === 'barrier'}Barriere{/if} + {m.message} {formatShort(m.createdAt)} @@ -42,6 +51,7 @@ {#if open}
      + {#if m.pageUrl}

      Seite: {m.pageUrl}

      {/if}

      {m.message}

      {#if m.email}Antworten ({m.email}){/if} diff --git a/src/routes/api/push/+server.ts b/src/routes/api/push/+server.ts new file mode 100644 index 0000000..b686b69 --- /dev/null +++ b/src/routes/api/push/+server.ts @@ -0,0 +1,33 @@ +import { error, json } from '@sveltejs/kit'; +import { publicKey, removeSubscription, saveSubscription, type BrowserSubscription } from '$lib/server/push'; +import { allow } from '$lib/server/ratelimit'; + +/** Öffentlicher Schlüssel für das Abonnieren im Browser */ +export const GET = () => json({ publicKey: publicKey() }); + +const isSub = (s: unknown): s is BrowserSubscription => { + const x = s as BrowserSubscription; + return ( + !!x && + typeof x.endpoint === 'string' && + /^https:\/\//.test(x.endpoint) && + x.endpoint.length < 1000 && + typeof x.keys?.p256dh === 'string' && + typeof x.keys?.auth === 'string' + ); +}; + +/** Abo anlegen oder Themen ändern */ +export const POST = async ({ request, getClientAddress }) => { + if (!allow(`push:${getClientAddress()}`, 30, 3600e3)) error(429, 'Zu viele Anfragen.'); + const body = await request.json().catch(() => null); + if (!isSub(body?.subscription)) error(400, 'Ungültiges Abo.'); + return json({ topics: saveSubscription(body.subscription, body.topics) }); +}; + +/** Abo beenden */ +export const DELETE = async ({ request }) => { + const body = await request.json().catch(() => null); + if (typeof body?.endpoint === 'string') removeSubscription(body.endpoint); + return json({ ok: true }); +}; diff --git a/src/service-worker.ts b/src/service-worker.ts index 1a54fd7..53891f8 100644 --- a/src/service-worker.ts +++ b/src/service-worker.ts @@ -51,3 +51,39 @@ sw.addEventListener('fetch', (event) => { })() ); }); + +// ─── Push-Benachrichtigungen ──────────────────────────────────────────────── + +sw.addEventListener('push', (event) => { + let data: { title?: string; body?: string; url?: string } = {}; + try { + data = event.data?.json() ?? {}; + } catch { + data = { title: event.data?.text() }; + } + event.waitUntil( + sw.registration.showNotification(data.title ?? 'Neuigkeit', { + body: data.body ?? '', + icon: '/app-icon/192', + badge: '/app-icon/64', + lang: 'de', + data: { url: data.url ?? '/' } + }) + ); +}); + +sw.addEventListener('notificationclick', (event) => { + event.notification.close(); + const url = new URL(event.notification.data?.url ?? '/', location.origin).href; + event.waitUntil( + (async () => { + const windows = await sw.clients.matchAll({ type: 'window', includeUncontrolled: true }); + const open = windows.find((w) => new URL(w.url).origin === location.origin); + if (open) { + await open.focus(); + return open.navigate(url); + } + return sw.clients.openWindow(url); + })() + ); +});