116 lines
3.7 KiB
Python
116 lines
3.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Erzeugt VAPID-Schlüssel für PWA-Benachrichtigungen (Web-Push).
|
|
|
|
Die Schlüssel werden in die .env-Datei von motorradig/ geschrieben (nicht im Git).
|
|
Auf dem Live-Server müssen sie ebenfalls in /motorradig/.env stehen.
|
|
|
|
python3 tools/generate_vapid_keys.py # nur ausgeben
|
|
python3 tools/generate_vapid_keys.py --write # in motorradig/.env eintragen
|
|
"""
|
|
|
|
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__)))
|
|
ENV_FILE = os.path.join(REPO_ROOT, "motorradig", ".env")
|
|
DEFAULT_SUBJECT = "mailto:ig@fischergruppe.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 motorradig/.env 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)")
|
|
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(ENV_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)." % ENV_FILE)
|
|
|
|
write_env(ENV_FILE, values)
|
|
print("Schlüssel in %s eingetragen." % ENV_FILE)
|
|
print("Hinweis: Die Datei enthält Geheimnisse und ist gitignored.")
|
|
return
|
|
|
|
print("In motorradig/.env eintragen:\n")
|
|
for key, value in values.items():
|
|
print("%s=%s" % (key, value))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|