Native Apps für iOS und Android (Capacitor) mit Push über Firebase

Apps (mobile/):
- Capacitor-8-Hülle, lädt die Web-App von APP_URL – Inhalte ohne App-Update
- Android- und iOS-Projekt (Swift Package Manager) mit Firebase Messaging,
  nativer Sprachausgabe, Teilen, App, Statusleiste, Startbildschirm
- `npm run sync` überträgt APP_ID, Name, Adresse und Farbe aus mobile/.env
  in beide Projekte und richtet ein: App-Links (Android intent-filter,
  iOS Associated Domains), Push (Entitlements, Background Mode,
  AppDelegate, Benachrichtigungssymbol/-farbe), Offline-Seite;
  idempotent, prüft Eingaben, warnt bei fehlenden Firebase-Dateien
- `npm run assets` erzeugt Symbole und Startbildschirme aus Logo und
  Markenfarbe der Redaktion, dazu das Android-Benachrichtigungssymbol
- Schritt-für-Schritt-Anleitung für den Mac (mobile/README.md)

Server:
- Versand an App-Geräte über FCM HTTP v1 (signiertes JWT, ohne
  firebase-admin), eingebunden in alle Benachrichtigungen; abgemeldete
  Geräte werden entfernt (nur bei UNREGISTERED, nicht bei anderen Fehlern)
- Firebase-Dienstkonto in den Einstellungen hochladen (verschlüsselt),
  App-ID, Team-ID, SHA-256, Store-Links; /.well-known/apple-app-site-
  association und assetlinks.json; Smart-App-Banner, Store-Hinweis
- Server erkennt die App am User-Agent (kein Aufblitzen von
  „Als App installieren“); Datenschutz-Vorlage um Firebase ergänzt

Web-App in der App: Push über Firebase statt Web-Push, Vorlesen nativ,
Teilen nativ, Zurück-Taste (schließt erst Dialoge), Antippen einer
Benachrichtigung und App-Links öffnen die Seite (nur eigene Adressen).

Getestet mit nachgebauter Capacitor-Brücke und nachgebautem Firebase-Dienst.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-10-03 07:03:26 +00:00
parent 02171e4cfe
commit 856559f830
152 changed files with 7537 additions and 32 deletions

View file

@ -286,6 +286,12 @@
}
}
/* Nur im Browser bzw. nur in der nativen App anzeigen */
:root[data-client='app'] .web-only,
:root:not([data-client='app']) .app-only {
display: none !important;
}
/* Satz, der gerade vorgelesen wird */
::highlight(vorlesen) {
background-color: var(--accent-soft);

View file

@ -1,5 +1,5 @@
<!doctype html>
<html lang="de" data-theme="%wa.theme%" data-size="%wa.size%">
<html lang="de" data-theme="%wa.theme%" data-size="%wa.size%" data-client="%wa.client%">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />

View file

@ -17,8 +17,43 @@ export const init: ServerInit = async () => {
startPushScheduler();
};
/** Nachweis für App-Links: Links zur Website öffnen direkt die App (iOS „Universal Links“, Android „App Links“) */
function wellKnown(pathname: string): Response | null {
const apps = getSettings().apps;
if (pathname === '/.well-known/apple-app-site-association' && apps.appId && apps.appleTeamId) {
return Response.json({
applinks: {
details: [
{
appIDs: [`${apps.appleTeamId}.${apps.appId}`],
// Redaktion bleibt im Browser, alles andere öffnet die App
components: [{ '/': '/admin/*', exclude: true }, { '/': '/*' }]
}
]
}
});
}
if (pathname === '/.well-known/assetlinks.json' && apps.appId && apps.androidSha256.trim()) {
return Response.json([
{
relation: ['delegate_permission/common.handle_all_urls'],
target: {
namespace: 'android_app',
package_name: apps.appId,
sha256_cert_fingerprints: apps.androidSha256.split(/\s+/).filter(Boolean)
}
}
]);
}
return null;
}
export const handle: Handle = async ({ event, resolve }) => {
const { cookies, url } = event;
if (url.pathname.startsWith('/.well-known/')) {
const res = wellKnown(url.pathname);
if (res) return res;
}
event.locals.prefs = parsePrefs(cookies.get(PREFS_COOKIE));
event.locals.user = url.pathname.startsWith('/admin') ? validateSession(cookies.get(SESSION_COOKIE)) : null;
@ -35,9 +70,11 @@ export const handle: Handle = async ({ event, resolve }) => {
}
const { theme, size } = event.locals.prefs;
// Die nativen Apps melden sich mit „WerkstattApp/…“ im User-Agent (siehe mobile/capacitor.config.ts)
const client = event.request.headers.get('user-agent')?.includes('WerkstattApp/') ? 'app' : 'web';
const response = await resolve(event, {
transformPageChunk: ({ html }) =>
html.replace('%wa.theme%', theme).replace('%wa.size%', size)
html.replace('%wa.theme%', theme).replace('%wa.size%', size).replace('%wa.client%', client)
});
response.headers.set('X-Content-Type-Options', 'nosniff');

View file

@ -0,0 +1,70 @@
<script lang="ts">
import FileJson from '@lucide/svelte/icons/file-json';
import type { AppsInfo } from '$lib/settings';
let { apps, fcm }: { apps: AppsInfo; fcm: { projectId: string; clientEmail: string } | null } = $props();
let account = $state('');
let fileName = $state('');
async function pick(e: Event) {
const file = (e.currentTarget as HTMLInputElement).files?.[0];
if (!file) return;
account = await file.text();
fileName = file.name;
}
</script>
<div class="space-y-5">
<div>
<span class="label">Push für die Apps (Firebase)</span>
{#if fcm}
<p class="text-sm rounded-xl bg-surface-2 px-4 py-3" role="status">
Eingerichtet: Projekt <strong>{fcm.projectId}</strong>, Dienstkonto {fcm.clientEmail}.
</p>
{:else}
<p class="text-sm rounded-xl bg-accent-soft text-accent-ink px-4 py-3">
Noch nicht eingerichtet. In der Firebase-Konsole: Projekteinstellungen → Dienstkonten → „Neuen privaten Schlüssel generieren“.
Die heruntergeladene JSON-Datei hier auswählen.
</p>
{/if}
<div class="mt-3 flex flex-wrap items-center gap-3">
<label class="btn btn-soft btn-sm cursor-pointer">
<FileJson class="size-4" />{fcm ? 'Andere Datei wählen' : 'JSON-Datei wählen'}
<input type="file" accept=".json,application/json" class="sr-only" onchange={pick} />
</label>
{#if fileName}<span class="text-sm text-ink-2">{fileName} – wird beim Speichern übernommen</span>{/if}
</div>
<input type="hidden" name="fcmServiceAccount" value={account} />
{#if fcm}
<label class="inline-flex items-center gap-2 text-sm mt-3 cursor-pointer min-h-8"><input type="checkbox" name="fcmDelete" class="accent-[var(--brand)]" />Dienstkonto löschen</label>
{/if}
<p class="hint">Wird verschlüsselt gespeichert. Ohne Dienstkonto bekommen nur Browser Benachrichtigungen, nicht die Apps.</p>
</div>
<div class="grid sm:grid-cols-2 gap-4">
<div>
<label class="label" for="appsAppId">App-ID (Bundle-ID / Paketname)</label>
<input id="appsAppId" name="appsAppId" class="field font-mono text-sm" value={apps.appId} placeholder="org.lindenhof.app" />
<p class="hint">Dieselbe wie in der App (mobile/.env → APP_ID).</p>
</div>
<div>
<label class="label" for="appsTeamId">Apple Team-ID</label>
<input id="appsTeamId" name="appsTeamId" class="field font-mono text-sm" value={apps.appleTeamId} placeholder="ABCDE12345" />
<p class="hint">Steht im Apple-Developer-Konto unter „Membership“.</p>
</div>
<div class="sm:col-span-2">
<label class="label" for="appsSha">Android: SHA-256-Fingerabdrücke der Signatur</label>
<textarea id="appsSha" name="appsSha" rows="2" class="field font-mono text-sm" placeholder="AB:CD:… (einer pro Zeile)">{apps.androidSha256}</textarea>
<p class="hint">Play Console → Einrichten → App-Integrität → „App-Signaturschlüsselzertifikat“. Nötig, damit Links direkt die App öffnen.</p>
</div>
<div>
<label class="label" for="appsAppStore">Link zum App Store</label>
<input id="appsAppStore" name="appsAppStore" class="field" value={apps.appStoreUrl} placeholder="https://apps.apple.com/…" />
</div>
<div>
<label class="label" for="appsPlayStore">Link zum Play Store</label>
<input id="appsPlayStore" name="appsPlayStore" class="field" value={apps.playStoreUrl} placeholder="https://play.google.com/store/apps/details?id=…" />
</div>
</div>
<p class="hint !mt-0">Sind die Store-Links gesetzt, weist die Website unter „Einstellungen“ auf die Apps hin.</p>
</div>

View file

@ -6,6 +6,7 @@
import Share2 from '@lucide/svelte/icons/share-2';
import { favorites } from '$lib/favorites.svelte';
import { speech } from '$lib/speech.svelte';
import { isNative, nativeShare } from '$lib/native';
import type { Favorite } from '$lib/types';
let { target, favorite }: { target: string; favorite?: Favorite } = $props();
@ -20,6 +21,10 @@
async function share() {
const data = { title: document.title, url: location.href };
if (isNative()) {
await nativeShare(data.title, data.url).catch(() => {});
return;
}
if (navigator.share) {
try {
await navigator.share(data);

106
src/lib/native.ts Normal file
View file

@ -0,0 +1,106 @@
import { Capacitor, registerPlugin, type PluginListenerHandle } from '@capacitor/core';
/**
* Brücke zu den nativen Apps (Capacitor). Im Browser passiert hier nichts.
* Die Plugins werden nur über ihren Namen angesprochen – ihr Code steckt in
* der nativen App, nicht im Web-Bundle (spart u. a. das ganze Firebase-SDK).
*/
export const isNative = () => typeof window !== 'undefined' && Capacitor.isNativePlatform();
export const platform = () => Capacitor.getPlatform() as 'ios' | 'android' | 'web';
// ─── Minimale Schnittstellen der verwendeten Plugins ──────────────────────────
type Permission = 'granted' | 'denied' | 'prompt' | 'prompt-with-rationale';
export interface FirebaseMessagingPlugin {
checkPermissions(): Promise<{ receive: Permission }>;
requestPermissions(): Promise<{ receive: Permission }>;
getToken(): Promise<{ token: string }>;
deleteToken(): Promise<void>;
addListener(event: 'tokenReceived', fn: (e: { token: string }) => void): Promise<PluginListenerHandle>;
addListener(
event: 'notificationActionPerformed',
fn: (e: { notification: { data?: Record<string, unknown> } }) => void
): Promise<PluginListenerHandle>;
}
export interface TextToSpeechPlugin {
speak(o: { text: string; lang?: string; rate?: number; pitch?: number; volume?: number; category?: string }): Promise<void>;
stop(): Promise<void>;
}
interface AppPlugin {
addListener(event: 'backButton', fn: (e: { canGoBack: boolean }) => void): Promise<PluginListenerHandle>;
addListener(event: 'appUrlOpen', fn: (e: { url: string }) => void): Promise<PluginListenerHandle>;
exitApp(): Promise<void>;
}
interface SharePlugin {
share(o: { title?: string; text?: string; url?: string; dialogTitle?: string }): Promise<unknown>;
}
interface StatusBarPlugin {
setStyle(o: { style: 'DARK' | 'LIGHT' | 'DEFAULT' }): Promise<void>;
}
interface SplashScreenPlugin {
hide(): Promise<void>;
}
export const FirebaseMessaging = registerPlugin<FirebaseMessagingPlugin>('FirebaseMessaging');
export const TextToSpeech = registerPlugin<TextToSpeechPlugin>('TextToSpeech');
const App = registerPlugin<AppPlugin>('App');
const Share = registerPlugin<SharePlugin>('Share');
const StatusBar = registerPlugin<StatusBarPlugin>('StatusBar');
const SplashScreen = registerPlugin<SplashScreenPlugin>('SplashScreen');
/** Teilen: in der App über das native Teilen-Menü */
export async function nativeShare(title: string, url: string) {
await Share.share({ title, url, dialogTitle: 'Teilen' });
}
/** Statusleiste passend zum Farbschema (helle Schrift auf dunklem Grund und umgekehrt) */
export function syncStatusBar() {
if (!isNative()) return;
const dark = getComputedStyle(document.documentElement).colorScheme.includes('dark');
StatusBar.setStyle({ style: dark ? 'DARK' : 'LIGHT' }).catch(() => {});
}
/**
* Einmal beim Start der App: Startbildschirm ausblenden, Zurück-Taste (Android),
* Links und angetippte Benachrichtigungen öffnen die passende Seite.
*/
export function initNative(navigate: (path: string) => void) {
if (!isNative()) return;
document.documentElement.classList.add('native-app');
SplashScreen.hide().catch(() => {});
syncStatusBar();
// Pfad innerhalb der App aus einer URL holen (nur eigene Seiten)
const toPath = (raw: string) => {
try {
const u = new URL(raw, location.origin);
return u.origin === location.origin ? u.pathname + u.search + u.hash : null;
} catch {
return null;
}
};
App.addListener('backButton', ({ canGoBack }) => {
const open = document.querySelector('dialog[open]') as HTMLDialogElement | null;
if (open) open.close();
else if (canGoBack) history.back();
else App.exitApp();
}).catch(() => {});
App.addListener('appUrlOpen', ({ url }) => {
const path = toPath(url);
if (path) navigate(path);
}).catch(() => {});
FirebaseMessaging.addListener('notificationActionPerformed', ({ notification }) => {
const path = toPath(String(notification?.data?.url ?? '/'));
if (path) navigate(path);
}).catch(() => {});
}

View file

@ -1,4 +1,5 @@
import { PREFS_COOKIE, type Prefs } from './prefs';
import { syncStatusBar } from './native';
/** Reaktive Anzeige-Einstellungen im Browser. */
class PrefsState {
@ -13,6 +14,7 @@ class PrefsState {
document.cookie = `${PREFS_COOKIE}=${encodeURIComponent(JSON.stringify(this.current))}; path=/; max-age=31536000; samesite=lax`;
document.documentElement.dataset.theme = this.current.theme;
document.documentElement.dataset.size = this.current.size;
syncStatusBar();
}
}

View file

@ -1,6 +1,9 @@
import type { PushTopic } from './push';
import { FirebaseMessaging, isNative, platform } from './native';
const TOPICS_KEY = 'wa_push_topics';
/** In der App: Benachrichtigungen ein (1) oder aus (0) */
const NATIVE_ON_KEY = 'wa_push_app';
function urlBase64ToUint8Array(base64: string) {
const padding = '='.repeat((4 - (base64.length % 4)) % 4);
@ -17,7 +20,34 @@ class PushState {
busy = $state(false);
error = $state('');
/** In der nativen App: Push über Firebase statt Web-Push */
#native = false;
#token = '';
async init() {
this.#native = isNative();
try {
const saved = JSON.parse(localStorage.getItem(TOPICS_KEY) ?? 'null');
if (Array.isArray(saved)) this.topics = saved;
} catch {
/* ohne Speicher */
}
if (this.#native) {
const { receive } = await FirebaseMessaging.checkPermissions().catch(() => ({ receive: 'denied' as const }));
this.status = receive === 'granted' ? 'granted' : receive === 'denied' ? 'denied' : 'default';
let on = false;
try {
on = localStorage.getItem(NATIVE_ON_KEY) === '1';
} catch {
/* ohne Speicher */
}
this.subscribed = receive === 'granted' && on && this.topics.length > 0;
// Firebase kann das Token erneuern – dann neu anmelden
FirebaseMessaging.addListener('tokenReceived', ({ token }) => {
if (this.subscribed && token !== this.#token) void this.#registerNative(token, this.topics);
}).catch(() => {});
return;
}
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)) {
@ -25,20 +55,51 @@ class PushState {
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 #registerNative(token: string, topics: PushTopic[]) {
const res = await fetch('/api/push/native', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ token, platform: platform(), topics })
});
if (!res.ok) throw new Error();
this.#token = token;
return (await res.json()).topics as PushTopic[];
}
#remember() {
try {
localStorage.setItem(TOPICS_KEY, JSON.stringify(this.topics));
if (this.#native) localStorage.setItem(NATIVE_ON_KEY, this.subscribed ? '1' : '0');
} catch {
/* ohne Speicher */
}
}
async subscribe(topics: PushTopic[] = this.topics) {
this.busy = true;
this.error = '';
if (this.#native) {
try {
const { receive } = await FirebaseMessaging.requestPermissions();
this.status = receive === 'granted' ? 'granted' : 'denied';
if (receive !== 'granted') return false;
const { token } = await FirebaseMessaging.getToken();
this.topics = await this.#registerNative(token, topics);
this.subscribed = true;
this.#remember();
return true;
} catch {
this.error = 'Das Einschalten hat nicht geklappt. Bitte später noch einmal versuchen.';
return false;
} finally {
this.busy = false;
}
}
try {
const permission = await Notification.requestPermission();
this.status = permission;
@ -79,6 +140,17 @@ class PushState {
async unsubscribe() {
this.busy = true;
if (this.#native) {
try {
const token = this.#token || (await FirebaseMessaging.getToken()).token;
await fetch('/api/push/native', { method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ token }) });
this.subscribed = false;
this.#remember();
} finally {
this.busy = false;
}
return;
}
try {
const reg = await navigator.serviceWorker.getRegistration();
const sub = await reg?.pushManager.getSubscription();

View file

@ -234,6 +234,15 @@ export const pushSubscriptions = sqliteTable('push_subscriptions', {
...timestamps
});
/** Geräte mit der nativen App (iOS/Android) – Zustellung über Firebase Cloud Messaging */
export const nativePushTokens = sqliteTable('native_push_tokens', {
id: integer('id').primaryKey({ autoIncrement: true }),
token: text('token').notNull().unique(),
platform: text('platform', { enum: ['ios', 'android'] }).notNull(),
topics: text('topics', { mode: 'json' }).$type<string[]>().notNull().default([]),
...timestamps
});
export const pushMessages = sqliteTable('push_messages', {
id: integer('id').primaryKey({ autoIncrement: true }),
topic: text('topic').notNull(),

154
src/lib/server/fcm.ts Normal file
View file

@ -0,0 +1,154 @@
import { createSign } from 'node:crypto';
import { eq } from 'drizzle-orm';
import { db } from './db';
import { nativePushTokens, settings } from './db/schema';
import { decrypt, encrypt } from './secret';
/**
* Push an die nativen Apps über Firebase Cloud Messaging (HTTP v1 API).
* Bewusst ohne firebase-admin: ein signiertes JWT für das OAuth-Token und
* ein einfacher HTTP-Aufruf je Gerät genügen – spart viel Speicher.
*/
const ROW = 'fcm-service-account';
// Für Tests überschreibbar
const TOKEN_URL = process.env.GOOGLE_TOKEN_URL ?? 'https://oauth2.googleapis.com/token';
const FCM_URL = process.env.FCM_API_URL ?? 'https://fcm.googleapis.com';
type ServiceAccount = { project_id: string; client_email: string; private_key: string };
export class FcmConfigError extends Error {}
/** Prüft und speichert das Firebase-Dienstkonto (JSON) verschlüsselt */
export function saveServiceAccount(json: string | null) {
if (!json) {
db.delete(settings).where(eq(settings.key, ROW)).run();
accessToken = null;
return null;
}
let sa: ServiceAccount;
try {
sa = JSON.parse(json);
} catch {
throw new FcmConfigError('Das ist keine gültige JSON-Datei.');
}
if (!sa.project_id || !sa.client_email || !sa.private_key?.includes('PRIVATE KEY'))
throw new FcmConfigError('Die Datei ist kein Firebase-Dienstkonto (project_id, client_email oder private_key fehlt).');
const value = encrypt(JSON.stringify({ project_id: sa.project_id, client_email: sa.client_email, private_key: sa.private_key }));
db.insert(settings).values({ key: ROW, value }).onConflictDoUpdate({ target: settings.key, set: { value } }).run();
accessToken = null;
return { projectId: sa.project_id, clientEmail: sa.client_email };
}
function serviceAccount(): ServiceAccount | null {
const row = db.select().from(settings).where(eq(settings.key, ROW)).get();
const plain = row ? decrypt(String(row.value)) : null;
return plain ? JSON.parse(plain) : null;
}
/** Für die Anzeige in den Einstellungen (ohne Schlüssel) */
export function serviceAccountInfo() {
const sa = serviceAccount();
return sa ? { projectId: sa.project_id, clientEmail: sa.client_email } : null;
}
export const fcmReady = () => !!serviceAccount();
// ─── OAuth-Token (1 Stunde gültig, wird zwischengespeichert) ─────────────────
let accessToken: { token: string; until: number } | null = null;
async function getAccessToken(sa: ServiceAccount): Promise<string> {
if (accessToken && accessToken.until > Date.now() + 60e3) return accessToken.token;
const now = Math.floor(Date.now() / 1000);
const b64 = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64url');
const unsigned = `${b64({ alg: 'RS256', typ: 'JWT' })}.${b64({
iss: sa.client_email,
scope: 'https://www.googleapis.com/auth/firebase.messaging',
aud: TOKEN_URL,
iat: now,
exp: now + 3600
})}`;
const signature = createSign('RSA-SHA256').update(unsigned).sign(sa.private_key).toString('base64url');
const res = await fetch(TOKEN_URL, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion: `${unsigned}.${signature}` })
});
if (!res.ok) throw new FcmConfigError(`Anmeldung bei Firebase fehlgeschlagen (${res.status}). Ist das Dienstkonto noch gültig?`);
const data = (await res.json()) as { access_token: string; expires_in: number };
accessToken = { token: data.access_token, until: Date.now() + data.expires_in * 1000 };
return accessToken.token;
}
// ─── Versand ─────────────────────────────────────────────────────────────────
type Payload = { title: string; body: string; url: string };
/**
* Sendet an alle App-Geräte mit dem Thema. Abgemeldete Geräte (App gelöscht,
* Token abgelaufen) werden dabei entfernt.
*/
export async function sendNative(topic: string | 'all', payload: Payload): Promise<{ ok: number; failed: number }> {
const sa = serviceAccount();
const devices = db
.select()
.from(nativePushTokens)
.all()
.filter((d) => (topic === 'all' ? d.topics.length > 0 : d.topics.includes(topic)));
if (!sa || !devices.length) return { ok: 0, failed: 0 };
let token: string;
try {
token = await getAccessToken(sa);
} catch (e) {
console.error('[fcm]', (e as Error).message);
return { ok: 0, failed: devices.length };
}
let ok = 0,
failed = 0;
for (let i = 0; i < devices.length; i += 10) {
await Promise.all(
devices.slice(i, i + 10).map(async (d) => {
const res = await fetch(`${FCM_URL}/v1/projects/${sa.project_id}/messages:send`, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({
message: {
token: d.token,
notification: { title: payload.title, body: payload.body || undefined },
data: { url: payload.url },
android: { priority: 'HIGH', notification: { default_sound: true } },
apns: { payload: { aps: { sound: 'default' } } }
}
})
}).catch(() => null);
if (res?.ok) {
ok++;
return;
}
failed++;
const body = res ? await res.text().catch(() => '') : '';
// Gerät gibt es nicht mehr → abmelden. Nicht bei anderen Fehlern (z. B. in der Nachricht),
// sonst würden bei einem einzigen Fehler alle Geräte abgemeldet.
if (res && (res.status === 404 || /UNREGISTERED|not a valid FCM registration token/i.test(body)))
db.delete(nativePushTokens).where(eq(nativePushTokens.id, d.id)).run();
})
);
}
return { ok, failed };
}
// ─── Geräte verwalten ────────────────────────────────────────────────────────
export function saveNativeToken(token: string, platform: 'ios' | 'android', topics: string[]) {
db.insert(nativePushTokens)
.values({ token, platform, topics })
.onConflictDoUpdate({ target: nativePushTokens.token, set: { platform, topics } })
.run();
}
export function removeNativeToken(token: string) {
db.delete(nativePushTokens).where(eq(nativePushTokens.token, token)).run();
}

View file

@ -58,7 +58,7 @@ export function privacyTemplate(s: AppSettings): string {
'<p>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.</p>',
'<h2>5. Benachrichtigungen (Push)</h2>',
'<p>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.</p>',
'<p>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. In den Apps für iPhone und Android werden die Nachrichten über Firebase Cloud Messaging von Google zugestellt (auf dem iPhone zusätzlich über den Push-Dienst von Apple); gespeichert wird dafür eine Gerätekennung der App. Du kannst die Einwilligung jederzeit unter „Einstellungen → Benachrichtigungen“ widerrufen; die Daten werden dann gelöscht.</p>',
'<h2>6. Vorlesen</h2>',
'<p>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.</p>',

View file

@ -1,7 +1,8 @@
import webpush from 'web-push';
import { and, asc, eq, isNull, lte } from 'drizzle-orm';
import { db } from './db';
import { events, posts, pushMessages, pushSubscriptions, settings } from './db/schema';
import { events, nativePushTokens, posts, pushMessages, pushSubscriptions, settings } from './db/schema';
import { sendNative } from './fcm';
import { getSettings } from './settings';
import { addDays, formatLong, TZ, today } from '$lib/dates';
import { PUSH_TOPICS, type PushTopic } from '$lib/push';
@ -52,11 +53,13 @@ export function removeSubscription(endpoint: string) {
db.delete(pushSubscriptions).where(eq(pushSubscriptions.endpoint, endpoint)).run();
}
/** Empfänger je Thema – Browser (Web-Push) und App-Geräte zusammen */
export function subscriberCounts() {
const rows = db.select({ topics: pushSubscriptions.topics }).from(pushSubscriptions).all();
const web = db.select({ topics: pushSubscriptions.topics }).from(pushSubscriptions).all();
const app = db.select({ topics: nativePushTokens.topics }).from(nativePushTokens).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 };
for (const r of [...web, ...app]) for (const t of r.topics) if (t in counts) counts[t as PushTopic]++;
return { total: web.length + app.length, web: web.length, app: app.length, byTopic: counts };
}
// ─── Versand ──────────────────────────────────────────────────────────────────
@ -79,9 +82,15 @@ export async function sendToTopic(
.all()
.filter((s) => (topic === 'all' ? s.topics.length > 0 : s.topics.includes(topic)));
const appDevices = db
.select({ topics: nativePushTokens.topics })
.from(nativePushTokens)
.all()
.filter((d) => (topic === 'all' ? d.topics.length > 0 : d.topics.includes(topic))).length;
// 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;
if (opts.automatic && subs.length === 0 && appDevices === 0) return null;
let messageId: number;
try {
@ -124,6 +133,10 @@ export async function sendToTopic(
})
);
}
// Native Apps (iOS/Android) über Firebase
const native = await sendNative(topic, { title: payload.title, body: payload.body ?? '', url: payload.url ?? '/' });
ok += native.ok;
failed += native.failed;
db.update(pushMessages).set({ recipients: ok, failures: failed }).where(eq(pushMessages.id, messageId)).run();
return { recipients: ok, failures: failed };
}

View file

@ -14,7 +14,8 @@ export function getSettings(): AppSettings {
...DEFAULT_SETTINGS,
...stored,
legal: { ...DEFAULT_SETTINGS.legal, ...(stored.legal ?? {}) },
a11y: { ...DEFAULT_SETTINGS.a11y, ...(stored.a11y ?? {}) }
a11y: { ...DEFAULT_SETTINGS.a11y, ...(stored.a11y ?? {}) },
apps: { ...DEFAULT_SETTINGS.apps, ...(stored.apps ?? {}) }
};
return cache;
}

View file

@ -33,6 +33,17 @@ export type A11yInfo = {
};
/** Einstellungen, die im Admin unter „Einstellungen“ gepflegt werden. */
/** Native Apps (iOS/Android) */
export type AppsInfo = {
/** Bundle-ID bzw. Paketname, z. B. org.lindenhof.app */
appId: string;
appleTeamId: string;
/** SHA-256-Fingerabdrücke der Android-Signatur (einer pro Zeile) */
androidSha256: string;
appStoreUrl: string;
playStoreUrl: string;
};
export type AppSettings = {
/** Name der App (Kopfzeile, Homescreen-Symbol) */
appName: string;
@ -58,6 +69,7 @@ export type AppSettings = {
imprint: string;
privacy: string;
legal: LegalInfo;
apps: AppsInfo;
a11y: A11yInfo;
/** Wie viele Meldungen/Termine die Startseite zeigt */
/** Administratoren müssen die Zwei-Faktor-Anmeldung einrichten */
@ -108,6 +120,7 @@ export const DEFAULT_SETTINGS: AppSettings = {
supervisory: '',
logRetentionDays: 7
},
apps: { appId: '', appleTeamId: '', androidSha256: '', appStoreUrl: '', playStoreUrl: '' },
a11y: {
status: 'partial',
issues: '',

View file

@ -1,5 +1,7 @@
import { isNative, TextToSpeech } from './native';
/**
* Vorlesen mit der Sprachausgabe des Geräts (Web Speech API).
* Vorlesen mit der Sprachausgabe des Geräts (Web Speech API, in der App nativ).
* Liest einen Bereich satzweise vor und markiert den aktuellen Satz
* (CSS Custom Highlight API), damit man mitlesen kann.
*/
@ -90,10 +92,13 @@ class Speech {
slow = $state(false);
label = $state('');
#sentences: Sentence[] = [];
#native = false;
#run = 0;
init() {
this.supported = typeof window !== 'undefined' && 'speechSynthesis' in window;
this.#native = isNative();
// In der App die native Sprachausgabe – Android-WebViews haben keine Web Speech API
this.supported = this.#native || (typeof window !== 'undefined' && 'speechSynthesis' in window);
try {
this.slow = localStorage.getItem(RATE_KEY) === 'slow';
} catch {
@ -115,8 +120,29 @@ class Speech {
this.#speakFrom(0);
}
/** Nativ: Satz für Satz nacheinander sprechen */
async #speakNative(i: number, run: number) {
await TextToSpeech.stop().catch(() => {});
for (let k = i; k < this.#sentences.length; k++) {
if (run !== this.#run) return;
this.index = k;
this.#highlight(k);
try {
await TextToSpeech.speak({ text: this.#sentences[k].text, lang: 'de-DE', rate: this.slow ? 0.8 : 1.0, category: 'playback' });
} catch {
if (run === this.#run) this.stop();
return;
}
}
if (run === this.#run) this.stop();
}
#speakFrom(i: number) {
const run = ++this.#run;
if (this.#native) {
void this.#speakNative(i, run);
return;
}
speechSynthesis.cancel();
// 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'));
@ -155,7 +181,8 @@ class Speech {
} else {
this.paused = true;
this.#run++;
speechSynthesis.cancel();
if (this.#native) TextToSpeech.stop().catch(() => {});
else speechSynthesis.cancel();
}
}
@ -179,7 +206,8 @@ class Speech {
stop() {
this.#run++;
if (this.supported) speechSynthesis.cancel();
if (this.#native) TextToSpeech.stop().catch(() => {});
else if (this.supported) speechSynthesis.cancel();
if (typeof CSS !== 'undefined' && 'highlights' in CSS) CSS.highlights.delete(HIGHLIGHT);
this.active = false;
this.paused = false;

View file

@ -12,11 +12,16 @@
import { speech } from '$lib/speech.svelte';
import MenuSheet from '$lib/components/MenuSheet.svelte';
import { favorites } from '$lib/favorites.svelte';
import { goto } from '$app/navigation';
import { initNative } from '$lib/native';
let { data, children } = $props();
let menuOpen = $state(false);
onMount(() => favorites.load());
onMount(() => {
favorites.load();
initNative((path) => goto(path));
});
const nav = [
{ href: '/', label: 'Start', icon: House },

View file

@ -16,14 +16,22 @@
<div class="card p-5">
<PushSettings />
</div>
<div class="card p-5 flex gap-4">
<div class="card p-5 flex gap-4 web-only">
<span class="grid place-items-center size-10 rounded-xl bg-brand-soft text-brand-ink shrink-0"><Smartphone class="size-5" /></span>
<div>
<p class="font-semibold">Als App installieren</p>
<p class="text-sm text-ink-2 mt-1">
Auf dem iPhone: Teilen-Symbol antippen → „Zum Home-Bildschirm“. Auf Android: Menü (⋮) → „App installieren“.
Dann startet {data.brand.appName} wie eine richtige App.
</p>
<p class="font-semibold">{data.brand.appStoreUrl || data.brand.playStoreUrl ? 'Als App aufs Handy' : 'Als App installieren'}</p>
{#if data.brand.appStoreUrl || data.brand.playStoreUrl}
<p class="text-sm text-ink-2 mt-1">{data.brand.appName} gibt es auch als App – mit Benachrichtigungen und Vorlesen.</p>
<div class="flex flex-wrap gap-2 mt-3">
{#if data.brand.appStoreUrl}<a href={data.brand.appStoreUrl} class="btn btn-primary btn-sm" target="_blank" rel="noopener">App Store (iPhone)</a>{/if}
{#if data.brand.playStoreUrl}<a href={data.brand.playStoreUrl} class="btn btn-primary btn-sm" target="_blank" rel="noopener">Google Play (Android)</a>{/if}
</div>
{:else}
<p class="text-sm text-ink-2 mt-1">
Auf dem iPhone: Teilen-Symbol antippen → „Zum Home-Bildschirm“. Auf Android: Menü (⋮) → „App installieren“.
Dann startet {data.brand.appName} wie eine richtige App.
</p>
{/if}
</div>
</div>
</div>

View file

@ -12,7 +12,11 @@ export const load = ({ locals }) => {
orgName: s.orgName,
color: hex(s.brandColor, '#2e2672'),
accent: hex(s.accentColor, '#85357c'),
logo: getMedia(s.logoId)
logo: getMedia(s.logoId),
// numerische App-Store-ID für das Smart-App-Banner in Safari
appStoreId: s.apps.appStoreUrl.match(/\/id(\d+)/)?.[1] ?? '',
appStoreUrl: s.apps.appStoreUrl,
playStoreUrl: s.apps.playStoreUrl
}
};
};

View file

@ -11,6 +11,7 @@
<svelte:head>
<meta name="theme-color" content={data.brand.color} />
{#if data.brand.appStoreId}<meta name="apple-itunes-app" content="app-id={data.brand.appStoreId}" />{/if}
{@html `<style>:root{--brand:${data.brand.color};--accent:${data.brand.accent}}</style>`}
</svelte:head>

View file

@ -22,6 +22,7 @@
<div class="card p-4">
<p class="text-3xl font-bold tabular-nums">{data.counts.total}</p>
<p class="text-sm text-ink-2">Geräte mit Benachrichtigungen</p>
<p class="text-xs text-ink-3 mt-1">{data.counts.web} Browser · {data.counts.app} App</p>
</div>
{#each pushTopicKeys as t (t)}
<div class="card p-4">

View file

@ -7,12 +7,13 @@ import { imprintTemplate, privacyTemplate } from '$lib/server/legal';
import type { AppSettings } from '$lib/settings';
import { aiReady, keyHint, saveKey } from '$lib/server/ai';
import { dailyUsage } from '$lib/server/easy-auto';
import { FcmConfigError, saveServiceAccount, serviceAccountInfo } from '$lib/server/fcm';
import { AI_PROVIDERS, type AiProvider } from '$lib/settings';
export const load = ({ locals }) => {
requireAdmin(locals.user);
const s = getSettings();
return { settings: s, logo: getMedia(s.logoId), hero: getMedia(s.heroImageId), ai: { ready: aiReady(), keyHint: keyHint(), usedToday: dailyUsage() } };
return { settings: s, logo: getMedia(s.logoId), hero: getMedia(s.heroImageId), ai: { ready: aiReady(), keyHint: keyHint(), usedToday: dailyUsage() }, fcm: serviceAccountInfo() };
};
/** Liest alle Felder des Formulars – oder gibt eine Fehlermeldung zurück */
@ -68,6 +69,13 @@ function read(form: FormData): Partial<AppSettings> | string {
supervisory: f.str('legalSupervisory', 300),
logRetentionDays: Math.min(90, Math.max(1, f.int('legalLogDays') ?? 7))
},
apps: {
appId: f.str('appsAppId', 150).replace(/\s/g, ''),
appleTeamId: f.str('appsTeamId', 20).toUpperCase(),
androidSha256: f.str('appsSha', 2000),
appStoreUrl: f.str('appsAppStore', 300),
playStoreUrl: f.str('appsPlayStore', 300)
},
a11y: {
status: a11yStatus === 'full' || a11yStatus === 'none' ? a11yStatus : 'partial',
issues: f.str('a11yIssues', 4000),
@ -87,6 +95,17 @@ export const actions = {
if (patch.aiBaseUrl && !/^https?:\/\//.test(patch.aiBaseUrl)) return fail(400, { error: 'Die KI-Adresse muss mit http:// oder https:// beginnen.' });
const f = fields(form);
// Schlüssel nur ändern, wenn ein neuer eingegeben oder Löschen gewählt wurde
const storeLinks = [patch.apps?.appStoreUrl, patch.apps?.playStoreUrl].filter(Boolean) as string[];
if (storeLinks.some((l) => !/^https:\/\//.test(l))) return fail(400, { error: 'Store-Links müssen mit https:// beginnen.' });
if (patch.apps?.appId && !/^[a-zA-Z][\w]*(\.[a-zA-Z][\w]*)+$/.test(patch.apps.appId))
return fail(400, { error: 'Die App-ID sieht nicht richtig aus (z. B. org.lindenhof.app).' });
try {
if (f.bool('fcmDelete')) saveServiceAccount(null);
else if (f.html('fcmServiceAccount').trim()) saveServiceAccount(f.html('fcmServiceAccount'));
} catch (e) {
if (e instanceof FcmConfigError) return fail(400, { error: e.message });
throw e;
}
if (f.bool('aiKeyDelete')) saveKey(null);
else if (f.str('aiKey', 500)) saveKey(f.str('aiKey', 500));
saveSettings(patch);

View file

@ -6,6 +6,7 @@
import RichEditor from '$lib/admin/RichEditor.svelte';
import Switch from '$lib/admin/Switch.svelte';
import AiSettings from '$lib/admin/AiSettings.svelte';
import AppsSettings from '$lib/admin/AppsSettings.svelte';
let { data } = $props();
const s = $derived(data.settings);
@ -98,6 +99,10 @@
<AiSettings {s} ai={data.ai} />
</Panel>
<Panel title="Apps (iOS und Android)" description="Für Push-Nachrichten an die Apps, Links, die direkt die App öffnen, und Hinweise auf die Stores.">
<AppsSettings apps={s.apps} fcm={data.fcm} />
</Panel>
<Panel title="Sicherheit">
<Switch
name="require2faAdmins"

View file

@ -0,0 +1,22 @@
import { error, json } from '@sveltejs/kit';
import { removeNativeToken, saveNativeToken } from '$lib/server/fcm';
import { allow } from '$lib/server/ratelimit';
import { PUSH_TOPICS } from '$lib/push';
/** Gerät der nativen App für Push anmelden bzw. Themen ändern */
export const POST = async ({ request, getClientAddress }) => {
if (!allow(`push-app:${getClientAddress()}`, 30, 3600e3)) error(429, 'Zu viele Anfragen.');
const body = await request.json().catch(() => null);
const token = typeof body?.token === 'string' ? body.token.trim() : '';
const platform = body?.platform === 'ios' ? 'ios' : body?.platform === 'android' ? 'android' : null;
if (!token || token.length > 4096 || !platform) error(400, 'Ungültiges Gerät.');
const topics = Array.isArray(body?.topics) ? [...new Set(body.topics.filter((t: unknown) => typeof t === 'string' && t in PUSH_TOPICS))] : [];
saveNativeToken(token, platform, topics as string[]);
return json({ topics });
};
export const DELETE = async ({ request }) => {
const body = await request.json().catch(() => null);
if (typeof body?.token === 'string') removeNativeToken(body.token);
return json({ ok: true });
};

View file

@ -12,12 +12,22 @@ const cache = new Map<string, Buffer>();
/** App-Symbol: Logo auf weißem Grund, oder Anfangsbuchstabe auf Markenfarbe. */
export const GET = async ({ params, url }) => {
const size = Number(params.size);
if (![32, 64, 180, 192, 512].includes(size)) error(404);
if (![24, 32, 36, 48, 64, 72, 96, 180, 192, 512, 1024].includes(size)) error(404);
const s = getSettings();
const maskable = url.searchParams.has('maskable');
const key = `${size}|${maskable}|${s.logoId}|${s.brandColor}|${s.appName}`;
// Android-Benachrichtigungssymbol: weiß auf transparent (Android färbt es selbst ein)
const notification = url.searchParams.has('notification');
const key = `${size}|${maskable}|${notification}|${s.logoId}|${s.brandColor}|${s.appName}`;
let png = cache.get(key);
if (!png && notification) {
const letter = (s.appName.trim()[0] ?? 'W').toUpperCase().replace(/[<>&"']/g, '');
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}">
<text x="50%" y="54%" dominant-baseline="middle" text-anchor="middle" font-family="sans-serif" font-weight="700"
font-size="${size * 0.8}" fill="#ffffff">${letter}</text></svg>`;
png = await sharp(Buffer.from(svg)).png().toBuffer();
cache.set(key, png);
}
if (!png) {
const logo = s.logoId ? db.select().from(media).where(eq(media.id, s.logoId)).get() : undefined;
if (logo?.mimeType.startsWith('image/')) {