Web-Push mit VAPID und Erinnerungs-Endpoint
This commit is contained in:
parent
67a1614081
commit
b50267e4f0
24 changed files with 1703 additions and 50 deletions
|
|
@ -44,6 +44,10 @@ FTP_URL="$(cred FTP_URL)"
|
|||
FTP_USER="$(cred FTP_USER)"
|
||||
FTP_PASSWORD="$(cred FTP_PASSWORD)"
|
||||
DB_HOST="$(cred DB_HOST)"
|
||||
VAPID_PUBLIC_KEY="$(cred VAPID_PUBLIC_KEY)"
|
||||
VAPID_PRIVATE_KEY="$(cred VAPID_PRIVATE_KEY)"
|
||||
VAPID_SUBJECT="$(cred VAPID_SUBJECT)"
|
||||
CRON_TOKEN="$(cred DIC_CRON_TOKEN)"
|
||||
DB_NAME="$(cred DB_NAME)"
|
||||
DB_USER="$(cred DB_USER)"
|
||||
DB_PASSWORD="$(cred DB_PASSWORD)"
|
||||
|
|
@ -87,6 +91,7 @@ make_config() {
|
|||
DIC_INSTALL_TOKEN="$token" DIC_CRON_TOKEN="$cron_token" DIC_PUBLIC_URL="$PUBLIC_URL" \
|
||||
DIC_MAIL_ENABLED="${DIC_MAIL_ENABLED:-false}" \
|
||||
DIC_MAIL_FROM="${DIC_MAIL_FROM:-Drink it cold <noreply@drink-it-cold.programmschmiede.de>}" \
|
||||
VAPID_PUBLIC_KEY="$VAPID_PUBLIC_KEY" VAPID_PRIVATE_KEY="$VAPID_PRIVATE_KEY" VAPID_SUBJECT="$VAPID_SUBJECT" \
|
||||
DB_HOST="${DB_HOST:-localhost}" DB_NAME="$DB_NAME" DB_USER="$DB_USER" DB_PASSWORD="$DB_PASSWORD" \
|
||||
python3 - "$TMP_DIR/config.local.php" <<'PY'
|
||||
import os
|
||||
|
|
@ -101,6 +106,11 @@ config = f"""<?php
|
|||
declare(strict_types=1);
|
||||
|
||||
return [
|
||||
'push' => [
|
||||
'public_key' => {php(os.environ.get('VAPID_PUBLIC_KEY', ''))},
|
||||
'private_key' => {php(os.environ.get('VAPID_PRIVATE_KEY', ''))},
|
||||
'subject' => {php(os.environ.get('VAPID_SUBJECT') or 'mailto:drinkitcold@web.de')},
|
||||
],
|
||||
'db' => [
|
||||
'host' => {php(os.environ.get('DB_HOST') or 'localhost')},
|
||||
'port' => 3306,
|
||||
|
|
@ -148,7 +158,7 @@ upload_tree() {
|
|||
do_sync() {
|
||||
local token cron_token
|
||||
token="$(openssl rand -hex 24)"
|
||||
cron_token="$(openssl rand -hex 24)"
|
||||
cron_token="${CRON_TOKEN:-$(openssl rand -hex 24)}"
|
||||
make_config "$token" "$cron_token"
|
||||
|
||||
echo "Lade Anwendung hoch …"
|
||||
|
|
@ -158,6 +168,7 @@ do_sync() {
|
|||
upload_tree "$REPO_ROOT/web" ""
|
||||
echo "Lade Cron-Skript und Konfiguration hoch …"
|
||||
ftp_put "$REPO_ROOT/tools/send_reminders.php" "tools/send_reminders.php"
|
||||
ftp_put "$REPO_ROOT/tools/migrate.php" "tools/migrate.php"
|
||||
ftp_put "$REPO_ROOT/tools/.htaccess" "tools/.htaccess"
|
||||
ftp_put "$TMP_DIR/config.local.php" "app/config.local.php"
|
||||
ftp_chmod 600 "app/config.local.php"
|
||||
|
|
@ -166,6 +177,9 @@ do_sync() {
|
|||
printf '' > "$TMP_DIR/.gitkeep"
|
||||
ftp_put "$TMP_DIR/.gitkeep" "storage/logs/.gitkeep"
|
||||
ftp_put "$REPO_ROOT/storage/.htaccess" "storage/.htaccess"
|
||||
if [[ -z "$VAPID_PUBLIC_KEY" || -z "$VAPID_PRIVATE_KEY" ]]; then
|
||||
echo "WARNUNG: VAPID-Schlüssel fehlen in docs/credentials.txt – Push bleibt deaktiviert." >&2
|
||||
fi
|
||||
echo "Sync fertig. Install-Token liegt nur auf dem Server."
|
||||
}
|
||||
|
||||
|
|
|
|||
110
tools/generate_vapid_keys.py
Executable file
110
tools/generate_vapid_keys.py
Executable file
|
|
@ -0,0 +1,110 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Erzeugt VAPID-Schlüssel für Web-Push und schreibt sie in docs/credentials.txt.
|
||||
|
||||
python3 tools/generate_vapid_keys.py --write
|
||||
python3 tools/generate_vapid_keys.py --write --force --subject mailto:name@example.de
|
||||
|
||||
Vorhandene Schlüssel nur mit --force ersetzen: Ein Wechsel macht alle
|
||||
bestehenden Push-Abos ungültig.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import os
|
||||
import sys
|
||||
|
||||
try:
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
except ImportError:
|
||||
sys.exit("Fehlt: python3-cryptography (apt install python3-cryptography)")
|
||||
|
||||
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
CRED_FILE = os.path.join(REPO_ROOT, "docs", "credentials.txt")
|
||||
DEFAULT_SUBJECT = "mailto:drinkitcold@web.de"
|
||||
|
||||
|
||||
def b64url(data):
|
||||
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
||||
|
||||
|
||||
def generate():
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
scalar = key.private_numbers().private_value.to_bytes(32, "big")
|
||||
point = key.public_key().public_bytes(
|
||||
encoding=serialization.Encoding.X962,
|
||||
format=serialization.PublicFormat.UncompressedPoint,
|
||||
)
|
||||
return b64url(point), b64url(scalar)
|
||||
|
||||
|
||||
def read_env(path):
|
||||
values = {}
|
||||
if not os.path.exists(path):
|
||||
return values
|
||||
with open(path, "r", encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, value = line.partition("=")
|
||||
values[key.strip()] = value.strip()
|
||||
return values
|
||||
|
||||
|
||||
def write_env(path, values):
|
||||
lines = []
|
||||
if os.path.exists(path):
|
||||
with open(path, "r", encoding="utf-8") as handle:
|
||||
lines = handle.read().splitlines()
|
||||
|
||||
replaced = set()
|
||||
out = []
|
||||
for line in lines:
|
||||
key = line.split("=", 1)[0].strip() if "=" in line else ""
|
||||
if key in values:
|
||||
out.append("%s=%s" % (key, values[key]))
|
||||
replaced.add(key)
|
||||
else:
|
||||
out.append(line)
|
||||
|
||||
if out and out[-1].strip():
|
||||
out.append("")
|
||||
for key, value in values.items():
|
||||
if key not in replaced:
|
||||
out.append("%s=%s" % (key, value))
|
||||
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
handle.write("\n".join(out).rstrip("\n") + "\n")
|
||||
os.chmod(path, 0o600)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--write", action="store_true", help="in docs/credentials.txt eintragen")
|
||||
parser.add_argument("--force", action="store_true", help="vorhandene VAPID-Schlüssel überschreiben")
|
||||
parser.add_argument("--subject", default=DEFAULT_SUBJECT, help="VAPID_SUBJECT (Default: %(default)s)")
|
||||
parser.add_argument("--file", default=CRED_FILE, help="Zieldatei für --write")
|
||||
args = parser.parse_args()
|
||||
|
||||
public, private = generate()
|
||||
values = {
|
||||
"VAPID_PUBLIC_KEY": public,
|
||||
"VAPID_PRIVATE_KEY": private,
|
||||
"VAPID_SUBJECT": args.subject,
|
||||
}
|
||||
|
||||
if args.write:
|
||||
existing = read_env(args.file)
|
||||
if (existing.get("VAPID_PUBLIC_KEY") or existing.get("VAPID_PRIVATE_KEY")) and not args.force:
|
||||
sys.exit("VAPID-Schlüssel sind in %s schon vorhanden (--force zum Ersetzen)." % args.file)
|
||||
write_env(args.file, values)
|
||||
print("Schlüssel in %s eingetragen." % args.file)
|
||||
return
|
||||
|
||||
for key, value in values.items():
|
||||
print("%s=%s" % (key, value))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
57
tools/migrate.php
Normal file
57
tools/migrate.php
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Führt ausstehende SQL-Migrationen aus (CLI).
|
||||
*
|
||||
* php tools/migrate.php
|
||||
*
|
||||
* Frische Installationen bekommen das komplette Schema über install.php.
|
||||
* Bestehende Installationen ziehen mit diesem Skript neue Tabellen nach.
|
||||
*/
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
http_response_code(403);
|
||||
exit("Nur per CLI.\n");
|
||||
}
|
||||
|
||||
require __DIR__ . '/../app/bootstrap.php';
|
||||
|
||||
$pdo = db();
|
||||
$pdo->exec(
|
||||
'CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INT UNSIGNED NOT NULL,
|
||||
applied_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (version)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'
|
||||
);
|
||||
|
||||
$applied = array_map('intval', $pdo->query('SELECT version FROM schema_migrations')->fetchAll(PDO::FETCH_COLUMN));
|
||||
$files = glob(__DIR__ . '/../sql/migrations/*.sql') ?: [];
|
||||
sort($files, SORT_STRING);
|
||||
|
||||
$count = 0;
|
||||
foreach ($files as $file) {
|
||||
$name = basename($file);
|
||||
if (!preg_match('/^(\d+)_/', $name, $match)) {
|
||||
fwrite(STDERR, "Überspringe Datei ohne Versionsnummer: $name\n");
|
||||
continue;
|
||||
}
|
||||
$version = (int) $match[1];
|
||||
if (in_array($version, $applied, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
echo "Migration $version: $name\n";
|
||||
$sql = preg_replace('/^\s*--.*$/m', '', (string) file_get_contents($file)) ?? '';
|
||||
foreach (array_filter(array_map('trim', explode(';', $sql))) as $statement) {
|
||||
if ($statement !== '') {
|
||||
$pdo->exec($statement);
|
||||
}
|
||||
}
|
||||
$pdo->prepare('INSERT IGNORE INTO schema_migrations (version, applied_at) VALUES (?, ?)')
|
||||
->execute([$version, utc_now()]);
|
||||
$count++;
|
||||
}
|
||||
|
||||
echo $count === 0 ? "Keine ausstehenden Migrationen.\n" : "$count Migration(en) angewendet.\n";
|
||||
|
|
@ -2,14 +2,13 @@
|
|||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Täglicher Erinnerungs-Digest per E-Mail.
|
||||
* Täglicher Erinnerungslauf (Push + optional E-Mail).
|
||||
*
|
||||
* Cron-Beispiel (täglich 07:00):
|
||||
* 0 7 * * * /usr/bin/php /pfad/zu/drink-it-cold/tools/send_reminders.php
|
||||
*
|
||||
* Voraussetzung: app.mail_enabled = true und Benutzer mit E-Mail-Adresse,
|
||||
* die mit einem Mitarbeiterkonto verknüpft sind. Die In-App-Erinnerungen
|
||||
* funktionieren unabhängig davon.
|
||||
* Alternativ von außen über den token-geschützten Endpoint:
|
||||
* https://…/cron/reminders?token=<cron_token>
|
||||
*/
|
||||
|
||||
require __DIR__ . '/../app/bootstrap.php';
|
||||
|
|
@ -21,22 +20,28 @@ foreach ($argv ?? [] as $arg) {
|
|||
}
|
||||
}
|
||||
|
||||
$result = reminder_send_due($lookback);
|
||||
$push = push_dispatch_due($lookback);
|
||||
$mail = reminder_send_due($lookback);
|
||||
|
||||
if (!$result['enabled']) {
|
||||
fwrite(STDOUT, "E-Mail-Versand ist deaktiviert (app.mail_enabled = false).\n");
|
||||
exit(0);
|
||||
if (!push_is_configured()) {
|
||||
fwrite(STDOUT, "Push: nicht konfiguriert (VAPID-Schlüssel fehlen).\n");
|
||||
} else {
|
||||
fwrite(STDOUT, sprintf(
|
||||
"Push: %d gesendet, %d fehlgeschlagen, %d abgelaufene Abos entfernt, %d ohne Abo.\n",
|
||||
$push['sent'], $push['failed'], $push['removed'], $push['skipped_no_subscription']
|
||||
));
|
||||
}
|
||||
|
||||
fwrite(STDOUT, sprintf(
|
||||
"Erinnerungen: %d versendet, %d übersprungen.\n",
|
||||
$result['sent'],
|
||||
$result['skipped']
|
||||
));
|
||||
foreach ($result['details'] as $detail) {
|
||||
fwrite(STDOUT, ' ' . $detail . "\n");
|
||||
if (!$mail['enabled']) {
|
||||
fwrite(STDOUT, "E-Mail: deaktiviert.\n");
|
||||
} else {
|
||||
fwrite(STDOUT, sprintf("E-Mail: %d versendet, %d übersprungen.\n", $mail['sent'], $mail['skipped']));
|
||||
foreach ($mail['details'] as $detail) {
|
||||
fwrite(STDOUT, ' ' . $detail . "\n");
|
||||
}
|
||||
foreach ($mail['errors'] as $error) {
|
||||
fwrite(STDERR, ' Fehler: ' . $error . "\n");
|
||||
}
|
||||
}
|
||||
foreach ($result['errors'] as $error) {
|
||||
fwrite(STDERR, ' Fehler: ' . $error . "\n");
|
||||
}
|
||||
exit($result['errors'] ? 1 : 0);
|
||||
|
||||
exit(($mail['errors'] || $push['failed'] > 0) ? 1 : 0);
|
||||
|
|
|
|||
55
tools/test_webpush_rfc8291.php
Normal file
55
tools/test_webpush_rfc8291.php
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Regressionstest für die Web-Push-Verschlüsselung (RFC 8291, Anhang A).
|
||||
*
|
||||
* php tools/test_webpush_rfc8291.php
|
||||
*
|
||||
* Prüft insbesondere die leere AAD nach RFC 8188. Wird der Header als AAD
|
||||
* verwendet, akzeptiert der Push-Dienst die Nachricht, der Browser verwirft
|
||||
* sie aber still.
|
||||
*/
|
||||
|
||||
require __DIR__ . '/../app/bootstrap.php';
|
||||
|
||||
function test_b64u_decode(string $value): string
|
||||
{
|
||||
$value = preg_replace('/\s+/', '', $value) ?? '';
|
||||
$value = strtr($value, '-_', '+/');
|
||||
$value .= str_repeat('=', (4 - strlen($value) % 4) % 4);
|
||||
return base64_decode($value, true);
|
||||
}
|
||||
|
||||
function test_b64u_encode(string $value): string
|
||||
{
|
||||
return rtrim(strtr(base64_encode($value), '+/', '-_'), '=');
|
||||
}
|
||||
|
||||
$plaintext = base64_decode('V2hlbiBJIGdyb3cgdXAsIEkgd2FudCB0byBiZSBhIHdhdGVybWVsb24=');
|
||||
$asPublic = test_b64u_decode('BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8');
|
||||
$asPrivate = test_b64u_decode('yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw');
|
||||
$uaPublic = test_b64u_decode('BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4');
|
||||
$salt = test_b64u_decode('DGv6ra1nlYgDCS1FRnbzlw');
|
||||
$auth = test_b64u_decode('BTBZMqHH6r4Tts7J_aSIgg');
|
||||
|
||||
$expected = 'DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27ml'
|
||||
. 'mlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A_yl95bQpu6cVPT'
|
||||
. 'pK4Mqgkf1CXztLVBSt2Ks3oZwbuwXPXLWyouBWLVWGNWQexSgSxsj_Qulcy4a-fN';
|
||||
|
||||
$method = new ReflectionMethod(WebPush::class, 'privateKeyPem');
|
||||
$method->setAccessible(true);
|
||||
$ephemeral = openssl_pkey_get_private($method->invoke(null, $asPrivate, $asPublic));
|
||||
if (!$ephemeral) {
|
||||
fwrite(STDERR, "Der Server-Schlüssel aus dem RFC ließ sich nicht laden.\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$body = WebPush::encrypt($plaintext, test_b64u_encode($uaPublic), test_b64u_encode($auth), $salt, $ephemeral);
|
||||
if (test_b64u_encode($body) === $expected) {
|
||||
echo "OK: RFC-8291-Testvektor stimmt.\n";
|
||||
exit(0);
|
||||
}
|
||||
|
||||
fwrite(STDERR, "FEHLER: Der verschlüsselte Body weicht vom RFC-8291-Testvektor ab.\n");
|
||||
exit(1);
|
||||
Loading…
Add table
Add a link
Reference in a new issue