"""
PATCHED version of the CVE-2026-105134-style lab.
Compare this to app.py to see the fix applied.

Fixes applied:
1. No shell=True - use a list of args, so there is no shell parsing at all.
2. Strict allowlist validation on 'random' (must look like a safe token).
3. receiver_id also validated to prevent path traversal into filenames.
4. No user input is ever concatenated into a command string.
"""

import re
import subprocess
from flask import Flask, request, jsonify

app = Flask(__name__)

RECEIVERS_DB = {}

# Only allow alphanumeric tokens, 1-64 chars - a safe "random" nonce shape
SAFE_TOKEN_RE = re.compile(r"^[A-Za-z0-9]{1,64}$")
SAFE_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")


@app.route("/rps/api/json/UpdateReceivers.do", methods=["POST"])
def update_receivers():
    data = request.get_json(force=True, silent=True) or {}
    receiver_id = data.get("receiver_id", "default")
    random_token = data.get("random", "")

    if not SAFE_ID_RE.match(receiver_id):
        return jsonify({"status": "error", "message": "invalid receiver_id"}), 400
    if not SAFE_TOKEN_RE.match(random_token):
        return jsonify({"status": "error", "message": "invalid random token"}), 400

    # No shell=True, no string interpolation into a command.
    # Write the file directly in Python instead of shelling out.
    path = f"/tmp/receiver_{receiver_id}.sync"
    try:
        with open(path, "w") as f:
            f.write(f"sync-token-{random_token}\n")
        RECEIVERS_DB[receiver_id] = random_token
        return jsonify({"status": "ok", "receiver_id": receiver_id})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5001, debug=True)
