added ed webhook to it

This commit is contained in:
rainyy21
2026-11-11 09:50:38 -05:00
parent 27e1c0047f
commit 218d1a1366
4 changed files with 51 additions and 10 deletions
View File
+1
View File
@@ -38,6 +38,7 @@ services:
REQUESTS_DIR: /data/requests REQUESTS_DIR: /data/requests
TOKEN_ENVS: GITEA_TOKEN,GITHUB_TOKEN # names only, for the add-repo dropdown TOKEN_ENVS: GITEA_TOKEN,GITHUB_TOKEN # names only, for the add-repo dropdown
SECRET_KEY: ${WEB_SECRET_KEY} SECRET_KEY: ${WEB_SECRET_KEY}
WEBHOOK_SECRET: ${WEBHOOK_SECRET} # same value goes in the GitHub/Gitea webhook settings
volumes: volumes:
# NO docker socket: the website can't run containers, only ask the watcher # NO docker socket: the website can't run containers, only ask the watcher
- ./config:/config:ro - ./config:/config:ro
+8 -7
View File
@@ -181,13 +181,14 @@ def process_requests(state: dict) -> None:
# if repo["paused"]: # if repo["paused"]:
# continue # continue
# #
# c) so the website reacts fast: wait in short steps and wake up early # c) so the website and webhooks react fast: wait_for_next_round() already
# when a request file shows up. Replace the end-of-round wait with: # wakes up early via has_requests(), but only for the CLI's REQUEST_DIR.
# Make it look at the website's folder too:
# #
# deadline = time.monotonic() + max(0, CHECK_INTERVAL - elapsed) # def has_requests() -> bool:
# while not STOP.is_set() and time.monotonic() < deadline: # return any(d.is_dir() and any(d.glob("*.json"))
# if any(REQUESTS_DIR.glob("*.json")): # for d in (REQUEST_DIR, REQUESTS_DIR))
# break
# STOP.wait(2)
# #
# Only do this together with (a): if nothing deletes the files in
# REQUESTS_DIR, the watcher would wake up every second forever.
# (a full round then runs: requests first, then the normal checks) # (a full round then runs: requests first, then the normal checks)
+42 -3
View File
@@ -8,6 +8,8 @@ Runs as its own container. It never touches Docker: it only
- WRITES local files (data/local/<repo>) -> .env, overrides, etc. - WRITES local files (data/local/<repo>) -> .env, overrides, etc.
""" """
import hashlib
import hmac
import json import json
import os import os
import re import re
@@ -29,6 +31,7 @@ LOCAL_DIR = Path(os.environ.get("LOCAL_DIR", "data/local"))
REQUESTS_DIR = Path(os.environ.get("REQUESTS_DIR", "data/requests")) REQUESTS_DIR = Path(os.environ.get("REQUESTS_DIR", "data/requests"))
CHECK_INTERVAL = int(os.environ.get("CHECK_INTERVAL", "300")) CHECK_INTERVAL = int(os.environ.get("CHECK_INTERVAL", "300"))
TOKEN_ENVS = [t for t in os.environ.get("TOKEN_ENVS", "GITEA_TOKEN,GITHUB_TOKEN").split(",") if t] TOKEN_ENVS = [t for t in os.environ.get("TOKEN_ENVS", "GITEA_TOKEN,GITHUB_TOKEN").split(",") if t]
WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "") # empty = webhooks turned off
MAX_FILE = 256 * 1024 # biggest file the editor will open/save MAX_FILE = 256 * 1024 # biggest file the editor will open/save
SAFE_REPO = re.compile(r"^[a-z0-9][a-z0-9_-]{0,62}$") # compose project names are lowercase SAFE_REPO = re.compile(r"^[a-z0-9][a-z0-9_-]{0,62}$") # compose project names are lowercase
@@ -194,18 +197,21 @@ app.jinja_env.globals["csrf_token"] = csrf_token
@app.before_request @app.before_request
def check_csrf(): def check_csrf():
if request.method == "POST": # webhooks can't send our token; they're checked by their HMAC signature instead
if request.method == "POST" and not request.path.startswith("/webhook/"):
sent = request.form.get("csrf") or request.headers.get("X-CSRF-Token") or "" sent = request.form.get("csrf") or request.headers.get("X-CSRF-Token") or ""
if not secrets.compare_digest(sent, session.get("csrf", "")): expected = session.get("csrf", "")
if not expected or not secrets.compare_digest(sent, expected): # no session = no token = reject
abort(400, "invalid or missing CSRF token: reload the page and try again") abort(400, "invalid or missing CSRF token: reload the page and try again")
@app.errorhandler(400) @app.errorhandler(400)
@app.errorhandler(403)
@app.errorhandler(404) @app.errorhandler(404)
@app.errorhandler(413) @app.errorhandler(413)
@app.errorhandler(415) @app.errorhandler(415)
def api_errors(e): def api_errors(e):
if request.path.startswith("/api/"): if request.path.startswith(("/api/", "/webhook/")):
return jsonify(error=e.description), e.code return jsonify(error=e.description), e.code
return e return e
@@ -407,5 +413,38 @@ def save_file(name: str, filename: str):
return jsonify(ok=True, missing_env=missing_env(name), shadows_git=shadows) return jsonify(ok=True, missing_env=missing_env(name), shadows_git=shadows)
# ---------- webhooks (GitHub / Gitea call this on every push) ----------
def valid_signature(body: bytes) -> bool:
"""GitHub sends X-Hub-Signature-256: sha256=<hex>, Gitea sends X-Gitea-Signature: <hex>."""
if not WEBHOOK_SECRET:
return False
expected = hmac.new(WEBHOOK_SECRET.encode(), body, hashlib.sha256).hexdigest()
sent = (request.headers.get("X-Hub-Signature-256", "").removeprefix("sha256=")
or request.headers.get("X-Gitea-Signature", ""))
return bool(sent) and hmac.compare_digest(sent, expected)
@app.post("/webhook/<name>")
def webhook(name: str):
if not valid_signature(request.get_data()): # before get_repo, so strangers can't probe repo names
abort(403, "bad or missing signature")
repo = get_repo(name)
event = request.headers.get("X-GitHub-Event") or request.headers.get("X-Gitea-Event")
if event == "ping":
return jsonify(ok=True, msg="pong")
if event != "push":
return jsonify(ok=True, ignored=f"event {event}")
ref = (request.get_json(silent=True) or {}).get("ref", "")
if ref != f"refs/heads/{repo['branch']}":
return jsonify(ok=True, ignored=f"push to {ref}")
if repo["paused"]:
return jsonify(ok=True, ignored="paused")
if name not in pending_requests(): # 5 quick pushes = 1 deploy
queue_request("deploy", name)
return jsonify(ok=True, queued="deploy"), 202
if __name__ == "__main__": if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000"))) app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))