tippspiel2027/tools/generate_vapid_keys.py

125 lines
4.3 KiB
Python

#!/usr/bin/env python3
"""Erzeugt die VAPID-Schlüssel für App-Erinnerungen (Web-Push).
Die Schlüssel gehören in docs/live_credentials.txt (gitignored). Von dort
schreibt tools/deploy_live.py sie als SetEnv in public/.htaccess.
python3 tools/generate_vapid_keys.py # nur ausgeben
python3 tools/generate_vapid_keys.py --write # in live_credentials.txt eintragen
Format (kompatibel zu gängigen Web-Push-Bibliotheken):
VAPID_PUBLIC_KEY base64url, unkomprimierter P-256-Punkt (65 Byte)
VAPID_PRIVATE_KEY base64url, privater Schlüssel (32 Byte)
VAPID_SUBJECT Kontakt-URI, z. B. mailto:admin@example.org
"""
import argparse
import base64
import os
import sys
try:
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
except ImportError: # pragma: no cover - Hinweis statt Traceback
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", "live_credentials.txt")
DEFAULT_SUBJECT = "mailto:volker.geissler@kstamedien.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):
"""Ersetzt vorhandene VAPID_*-Zeilen, hängt neue an."""
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="Werte in docs/live_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 (Default: docs/live_credentials.txt)")
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"):
if 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)
print("Hinweis: Achtung, die Datei enthält Geheimnisse und ist gitignored.")
return
print("In docs/live_credentials.txt eintragen:\n")
for key, value in values.items():
print("%s=%s" % (key, value))
print("\nDanach: python3 tools/deploy_live.py")
print("Achtung: Danach müssen sich alle Geräte neu anmelden (alter Schlüssel ungültig).")
if __name__ == "__main__":
main()