#!/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") parser.add_argument( "--key-prefix", default="VAPID", help="Präfix der Keys, z. B. VAPID_LIVE für das netcup-Ziel (Default: %(default)s)", ) args = parser.parse_args() public, private = generate() values = { "%s_PUBLIC_KEY" % args.key_prefix: public, "%s_PRIVATE_KEY" % args.key_prefix: private, "%s_SUBJECT" % args.key_prefix: args.subject, } public_key = "%s_PUBLIC_KEY" % args.key_prefix private_key = "%s_PRIVATE_KEY" % args.key_prefix if args.write: existing = read_env(args.file) if (existing.get(public_key) or existing.get(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()