"""Python 3.10+, Linux/macOS. Expose application through a WSGI server + HTTPS. Configure PUSH2HOOK_DEVICE_ID, PUSH2HOOK_SECRET (32+ UTF-8 bytes), PUSH2HOOK_INBOX. The inbox must be an existing private directory, outside your web root. python3 receiver.py starts a loopback-only DEVELOPMENT server, port 8000. """ import base64 import binascii import fcntl import hashlib import hmac import json import os from pathlib import Path import re import tempfile import time from http import HTTPStatus MAX_BODY = 1048576 def application(environ, start_response): def reply(status, message=""): body = json.dumps({"error": message}).encode() if message else b"" headers = [("Content-Type", "application/json; charset=utf-8"), ("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff"), ("Content-Length", str(len(body)))] if status == 405: headers.append(("Allow", "POST")) start_response(f"{status} {HTTPStatus(status).phrase}", headers) return [body] if environ.get("REQUEST_METHOD") != "POST": return reply(405, "POST required") if environ.get("CONTENT_TYPE", "").split(";", 1)[0].strip().lower() != "application/json": return reply(415, "application/json required") device = os.environ.get("PUSH2HOOK_DEVICE_ID", "") secret = os.environ.get("PUSH2HOOK_SECRET", "").encode("utf-8") inbox = Path(os.environ.get("PUSH2HOOK_INBOX", ".")) if not device or len(secret) < 32 or not inbox.is_absolute() or not inbox.is_dir(): return reply(503, "Receiver not configured") device_header = environ.get("HTTP_X_DEVICE_ID", "") timestamp = environ.get("HTTP_X_TIMESTAMP", "") signature = environ.get("HTTP_X_SIGNATURE", "") now = int(time.time()) if (not hmac.compare_digest(device.encode("utf-8"), device_header.encode("utf-8")) or not re.fullmatch(r"[0-9]{1,12}", timestamp) or abs(now - int(timestamp)) > 300 or len(signature) > 128): return reply(401, "Authentication failed") length = environ.get("CONTENT_LENGTH", "") if not re.fullmatch(r"[0-9]{1,10}", length): return reply(411, "Content-Length required") length = int(length) if length > MAX_BODY: return reply(413, "Body too large") raw = environ["wsgi.input"].read(length) if len(raw) != length: return reply(400, "Incomplete body") # Verify ORIGINAL bytes; do not decode/re-encode JSON before checking HMAC. expected = hmac.digest(secret, timestamp.encode("ascii") + b"." + raw, "sha256") try: supplied = base64.b64decode(signature, validate=True) except (ValueError, binascii.Error): return reply(401, "Authentication failed") if len(supplied) != 32 or not hmac.compare_digest(expected, supplied): return reply(401, "Authentication failed") try: data = json.loads(raw.decode("utf-8")) except (ValueError, UnicodeError, RecursionError): return reply(400, "Invalid JSON") if (not isinstance(data, dict) or type(data.get("schemaVersion")) is not int or data["schemaVersion"] != 1 or data.get("deviceId") != device or data.get("demo") is not False or not isinstance(data.get("eventId"), str) or not re.fullmatch(r"[A-Za-z0-9._:-]{1,200}", data["eventId"]) or not isinstance(data.get("source"), dict) or not isinstance(data["source"].get("packageName"), str) or not 1 <= len(data["source"]["packageName"].encode("utf-8")) <= 255 or not isinstance(data.get("notification"), dict) or not data["notification"]): return reply(400, "Invalid notification or device mismatch") # Stable inbox key: acknowledge retries, but never store a second copy. key = hashlib.sha256((device + "\0" + data["eventId"]).encode("utf-8")).hexdigest() target = inbox / f"{key}.json" temporary = None try: descriptor = os.open(inbox / ".lock", os.O_CREAT | os.O_WRONLY, 0o600) with os.fdopen(descriptor, "wb") as lock: fcntl.flock(lock, fcntl.LOCK_EX) duplicate = target.is_file() if not duplicate: descriptor, temporary = tempfile.mkstemp(prefix=".pending-", dir=inbox) with os.fdopen(descriptor, "wb") as output: output.write(raw) output.flush() os.fsync(output.fileno()) os.replace(temporary, target) temporary = None except OSError: # 5xx asks push2hook to retry. A failed write must never return success. return reply(503, "Storage unavailable") finally: if temporary is not None: Path(temporary).unlink(missing_ok=True) return reply(204 if duplicate else 202) if __name__ == "__main__": from wsgiref.simple_server import make_server with make_server("127.0.0.1", int(os.environ.get("PORT", "8000")), application) as server: server.serve_forever()