Add ComboCoal client-only Fabric mod for Minecraft 1.21.4
Mobile-game style coal grinding: combo counter and ranks, HUD with popups and confetti, XP/coins/daily quest, dancing client-side pets, Coal Maniac mode, coal ESP and guide arrow (off on multiplayer by default), tool durability warnings and an English lang file. Opt-in online features backed by the Flask server in backend/: leaderboard, shared team combo per server, Help pings and a Help servers list, protected by a one-time captcha token and a proof of work. Includes Docker/Caddy deployment files and Fabric client game tests (single player, team combo and a two-client scenario). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
324e6f75c8
53 changed files with 4495 additions and 0 deletions
3
backend/.dockerignore
Normal file
3
backend/.dockerignore
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
*.db
|
||||
secret.key
|
||||
__pycache__
|
||||
4
backend/Caddyfile
Normal file
4
backend/Caddyfile
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
# Caddy obtains and renews the HTTPS certificate for this domain automatically.
|
||||
master.combocoal.wihuk.pro {
|
||||
reverse_proxy api:8000
|
||||
}
|
||||
12
backend/Dockerfile
Normal file
12
backend/Dockerfile
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
FROM python:3.12-slim
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY app.py .
|
||||
ENV COMBOCOAL_DB=/data/combocoal.db \
|
||||
COMBOCOAL_SECRET_FILE=/data/secret.key \
|
||||
COMBOCOAL_BEHIND_PROXY=1
|
||||
VOLUME /data
|
||||
EXPOSE 8000
|
||||
# All shared state (team combo, used proof-of-work challenges) lives in SQLite, so more workers are fine.
|
||||
CMD ["gunicorn", "--workers", "2", "--threads", "8", "--bind", "0.0.0.0:8000", "app:app"]
|
||||
316
backend/app.py
Normal file
316
backend/app.py
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
"""Example backend for the optional ComboCoal stats, leaderboard and "Help!" modules.
|
||||
|
||||
Public endpoints:
|
||||
GET /leaderboard top 10 players
|
||||
GET /help servers where players recently asked for help
|
||||
GET /captcha a small human challenge {"id", "question"}
|
||||
POST /captcha {"id", "answer"} -> {"token"} (valid for 30 days)
|
||||
GET /pow a proof-of-work challenge {"challenge", "difficulty"}; ?scope=team gives an easier one
|
||||
|
||||
Protected endpoints (headers X-Token, X-Pow-Challenge, X-Pow-Nonce):
|
||||
POST /stats {"player", "coal", "bestCombo", "server"}
|
||||
POST /help {"player", "server", "combo"}
|
||||
POST /team/sync {"player", "server", "hits"} (team scope proof of work) -> {"combo", "players"}
|
||||
|
||||
Team combo: players on the same server address who opted in share one combo. Every sync reports the
|
||||
coal they broke since the last sync; the combo resets after 5 seconds without a hit from anyone.
|
||||
|
||||
Proof of work: find a nonce so that sha256(challenge + ":" + nonce) starts with `difficulty`
|
||||
zero bits. The captcha stops casual scripts from getting a token, the proof of work makes mass
|
||||
submissions expensive. Both are simple on purpose; stats stay self-reported. Run behind HTTPS.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import closing
|
||||
|
||||
from flask import Flask, jsonify, request
|
||||
|
||||
app = Flask(__name__)
|
||||
# Behind a reverse proxy (Caddy) the real client address comes from X-Forwarded-For.
|
||||
if os.environ.get("COMBOCOAL_BEHIND_PROXY"):
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)
|
||||
DB_PATH = os.environ.get("COMBOCOAL_DB", "combocoal.db")
|
||||
SECRET_PATH = os.environ.get("COMBOCOAL_SECRET_FILE", "secret.key")
|
||||
POW_DIFFICULTY = 18
|
||||
TEAM_POW_DIFFICULTY = 12
|
||||
TEAM_WINDOW = 5.0
|
||||
TEAM_PLAYER_TTL = 10.0
|
||||
MAX_TEAM_HITS = 20
|
||||
POW_TTL = 120
|
||||
TOKEN_TTL = 30 * 24 * 3600
|
||||
CAPTCHA_TTL = 300
|
||||
HELP_WINDOW = 600
|
||||
MAX_NAME = 16
|
||||
MAX_SERVER = 255
|
||||
MAX_VALUE = 10_000_000
|
||||
|
||||
CAPTCHA_ATTEMPTS = {}
|
||||
|
||||
|
||||
def load_secret():
|
||||
env = os.environ.get("COMBOCOAL_SECRET")
|
||||
if env:
|
||||
return env.encode()
|
||||
if not os.path.exists(SECRET_PATH):
|
||||
# Several worker processes may start at once: write a temp file and link it into place
|
||||
# atomically so exactly one key wins and nobody reads a half-written file.
|
||||
tmp = f"{SECRET_PATH}.{os.getpid()}.tmp"
|
||||
with open(tmp, "wb") as f:
|
||||
f.write(secrets.token_bytes(32))
|
||||
try:
|
||||
os.link(tmp, SECRET_PATH)
|
||||
except FileExistsError:
|
||||
pass
|
||||
finally:
|
||||
os.remove(tmp)
|
||||
with open(SECRET_PATH, "rb") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
SECRET = load_secret()
|
||||
|
||||
|
||||
def sign(data):
|
||||
body = base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
mac = hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()
|
||||
return body + "." + mac
|
||||
|
||||
|
||||
def unsign(value):
|
||||
"""Returns the signed payload, or None if it is malformed, forged or expired."""
|
||||
try:
|
||||
body, mac = value.rsplit(".", 1)
|
||||
expected = hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()
|
||||
if not hmac.compare_digest(mac, expected):
|
||||
return None
|
||||
data = json.loads(base64.urlsafe_b64decode(body.encode()))
|
||||
return data if data["exp"] > time.time() else None
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def db():
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
|
||||
def init_db():
|
||||
with closing(db()) as conn, conn:
|
||||
conn.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS stats (
|
||||
player TEXT PRIMARY KEY, coal INTEGER NOT NULL, best_combo INTEGER NOT NULL,
|
||||
server TEXT NOT NULL, updated TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)"""
|
||||
)
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS used_pow (challenge TEXT PRIMARY KEY, exp REAL NOT NULL)")
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS team (server TEXT PRIMARY KEY, combo INTEGER NOT NULL, last REAL NOT NULL)")
|
||||
conn.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS team_players (
|
||||
server TEXT NOT NULL, player TEXT NOT NULL, ts REAL NOT NULL, PRIMARY KEY (server, player))"""
|
||||
)
|
||||
conn.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS help (
|
||||
player TEXT NOT NULL, server TEXT NOT NULL, combo INTEGER NOT NULL, ts INTEGER NOT NULL)"""
|
||||
)
|
||||
|
||||
|
||||
def clamp_int(value):
|
||||
return max(0, min(MAX_VALUE, int(value)))
|
||||
|
||||
|
||||
def leading_zero_bits(digest):
|
||||
bits = 0
|
||||
for byte in digest:
|
||||
if byte == 0:
|
||||
bits += 8
|
||||
continue
|
||||
bits += 8 - byte.bit_length()
|
||||
break
|
||||
return bits
|
||||
|
||||
|
||||
def require_pow(scope="default"):
|
||||
"""Checks token and proof of work. Returns an error response, or None if everything is valid."""
|
||||
token = unsign(request.headers.get("X-Token", ""))
|
||||
if not token or token.get("kind") != "token":
|
||||
return jsonify(error="captcha token missing or expired"), 401
|
||||
challenge = request.headers.get("X-Pow-Challenge", "")
|
||||
nonce = request.headers.get("X-Pow-Nonce", "")
|
||||
data = unsign(challenge)
|
||||
if not data or data.get("kind") != "pow" or data.get("scope") != scope:
|
||||
return jsonify(error="invalid proof of work challenge"), 400
|
||||
digest = hashlib.sha256(f"{challenge}:{nonce}".encode()).digest()
|
||||
if leading_zero_bits(digest) < data["d"]:
|
||||
return jsonify(error="proof of work too weak"), 400
|
||||
# Single use, tracked in the database so every worker process sees the same set.
|
||||
with closing(db()) as conn, conn:
|
||||
conn.execute("DELETE FROM used_pow WHERE exp < ?", (time.time(),))
|
||||
try:
|
||||
conn.execute("INSERT INTO used_pow (challenge, exp) VALUES (?, ?)", (challenge, data["exp"]))
|
||||
except sqlite3.IntegrityError:
|
||||
return jsonify(error="invalid proof of work challenge"), 400
|
||||
return None
|
||||
|
||||
|
||||
@app.get("/pow")
|
||||
def get_pow():
|
||||
scope = "team" if request.args.get("scope") == "team" else "default"
|
||||
difficulty = TEAM_POW_DIFFICULTY if scope == "team" else POW_DIFFICULTY
|
||||
challenge = sign({"kind": "pow", "scope": scope, "d": difficulty, "r": secrets.token_hex(8),
|
||||
"exp": time.time() + POW_TTL})
|
||||
return jsonify(challenge=challenge, difficulty=difficulty)
|
||||
|
||||
|
||||
@app.get("/captcha")
|
||||
def get_captcha():
|
||||
a, b = secrets.randbelow(20) + 1, secrets.randbelow(20) + 1
|
||||
ident = sign({"kind": "captcha", "sum": a + b, "r": secrets.token_hex(4), "exp": time.time() + CAPTCHA_TTL})
|
||||
return jsonify(id=ident, question=f"{a} + {b}")
|
||||
|
||||
|
||||
@app.post("/captcha")
|
||||
def post_captcha():
|
||||
# Crude per-address limit so the captcha cannot be brute forced.
|
||||
now = time.time()
|
||||
recent = [t for t in CAPTCHA_ATTEMPTS.get(request.remote_addr, []) if t > now - 60]
|
||||
if len(recent) >= 10:
|
||||
return jsonify(error="too many attempts"), 429
|
||||
CAPTCHA_ATTEMPTS[request.remote_addr] = recent + [now]
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
data = unsign(str(body.get("id", "")))
|
||||
try:
|
||||
correct = data and data.get("kind") == "captcha" and int(body.get("answer")) == data["sum"]
|
||||
except (TypeError, ValueError):
|
||||
correct = False
|
||||
if not correct:
|
||||
return jsonify(error="wrong answer"), 400
|
||||
return jsonify(token=sign({"kind": "token", "n": secrets.token_hex(8), "exp": now + TOKEN_TTL}))
|
||||
|
||||
|
||||
@app.post("/stats")
|
||||
def post_stats():
|
||||
error = require_pow()
|
||||
if error:
|
||||
return error
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
player = str(data["player"]).strip()[:MAX_NAME]
|
||||
coal = clamp_int(data["coal"])
|
||||
best_combo = clamp_int(data["bestCombo"])
|
||||
server = str(data.get("server", ""))[:MAX_SERVER]
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return jsonify(error="bad request"), 400
|
||||
if not player:
|
||||
return jsonify(error="bad request"), 400
|
||||
|
||||
# The mod reports one session, so keep the best values instead of adding them up.
|
||||
with closing(db()) as conn, conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO stats (player, coal, best_combo, server) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(player) DO UPDATE SET
|
||||
coal = MAX(coal, excluded.coal), best_combo = MAX(best_combo, excluded.best_combo),
|
||||
server = excluded.server, updated = CURRENT_TIMESTAMP""",
|
||||
(player, coal, best_combo, server),
|
||||
)
|
||||
return jsonify(ok=True)
|
||||
|
||||
|
||||
@app.get("/leaderboard")
|
||||
def get_leaderboard():
|
||||
with closing(db()) as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT player, coal, best_combo FROM stats ORDER BY coal DESC, best_combo DESC LIMIT 10"
|
||||
).fetchall()
|
||||
return jsonify([{"player": r["player"], "coal": r["coal"], "bestCombo": r["best_combo"]} for r in rows])
|
||||
|
||||
|
||||
@app.post("/help")
|
||||
def post_help():
|
||||
error = require_pow()
|
||||
if error:
|
||||
return error
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
player = str(data["player"]).strip()[:MAX_NAME]
|
||||
server = str(data["server"]).strip()[:MAX_SERVER]
|
||||
combo = clamp_int(data["combo"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return jsonify(error="bad request"), 400
|
||||
if not player or not server or server == "singleplayer":
|
||||
return jsonify(error="bad request"), 400
|
||||
with closing(db()) as conn, conn:
|
||||
conn.execute("INSERT INTO help (player, server, combo, ts) VALUES (?, ?, ?, ?)",
|
||||
(player, server, combo, int(time.time())))
|
||||
return jsonify(ok=True)
|
||||
|
||||
|
||||
@app.get("/help")
|
||||
def get_help():
|
||||
since = int(time.time()) - HELP_WINDOW
|
||||
with closing(db()) as conn:
|
||||
rows = conn.execute(
|
||||
"""SELECT server, COUNT(DISTINCT player) AS helpers, MAX(combo) AS combo
|
||||
FROM help WHERE ts > ? GROUP BY server ORDER BY helpers DESC, combo DESC LIMIT 20""",
|
||||
(since,),
|
||||
).fetchall()
|
||||
return jsonify([{"server": r["server"], "helpers": r["helpers"], "combo": r["combo"]} for r in rows])
|
||||
|
||||
|
||||
@app.post("/team/sync")
|
||||
def team_sync():
|
||||
error = require_pow("team")
|
||||
if error:
|
||||
return error
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
player = str(data["player"]).strip()[:MAX_NAME]
|
||||
server = str(data["server"]).strip().lower()[:MAX_SERVER]
|
||||
hits = max(0, min(MAX_TEAM_HITS, int(data["hits"])))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return jsonify(error="bad request"), 400
|
||||
if not player or not server or server == "singleplayer":
|
||||
return jsonify(error="bad request"), 400
|
||||
|
||||
now = time.time()
|
||||
conn = db()
|
||||
conn.isolation_level = None # explicit transaction so concurrent workers cannot interleave
|
||||
try:
|
||||
conn.execute("BEGIN IMMEDIATE")
|
||||
conn.execute("DELETE FROM team WHERE last < ?", (now - 3600,))
|
||||
row = conn.execute("SELECT combo, last FROM team WHERE server = ?", (server,)).fetchone()
|
||||
combo, last = (row["combo"], row["last"]) if row else (0, 0.0)
|
||||
if now - last > TEAM_WINDOW:
|
||||
combo = 0
|
||||
if hits:
|
||||
combo += hits
|
||||
last = now
|
||||
conn.execute("INSERT INTO team (server, combo, last) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT(server) DO UPDATE SET combo = excluded.combo, last = excluded.last",
|
||||
(server, combo, last))
|
||||
conn.execute("INSERT INTO team_players (server, player, ts) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT(server, player) DO UPDATE SET ts = excluded.ts", (server, player, now))
|
||||
conn.execute("DELETE FROM team_players WHERE ts < ?", (now - TEAM_PLAYER_TTL,))
|
||||
players = conn.execute("SELECT COUNT(*) FROM team_players WHERE server = ?", (server,)).fetchone()[0]
|
||||
conn.execute("COMMIT")
|
||||
finally:
|
||||
conn.close()
|
||||
return jsonify(combo=combo, players=players)
|
||||
|
||||
|
||||
init_db()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Local testing only; use a proper WSGI server and HTTPS in production.
|
||||
# Set COMBOCOAL_TLS_CERT and COMBOCOAL_TLS_KEY (PEM files) to serve https directly for development.
|
||||
cert, key = os.environ.get("COMBOCOAL_TLS_CERT"), os.environ.get("COMBOCOAL_TLS_KEY")
|
||||
app.run(host="127.0.0.1", port=int(os.environ.get("PORT", "5000")),
|
||||
ssl_context=(cert, key) if cert and key else None)
|
||||
25
backend/docker-compose.yml
Normal file
25
backend/docker-compose.yml
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
services:
|
||||
api:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
# Optional: set a fixed signing secret instead of the generated /data/secret.key
|
||||
- COMBOCOAL_SECRET=${COMBOCOAL_SECRET:-}
|
||||
volumes:
|
||||
- combocoal-data:/data
|
||||
|
||||
caddy:
|
||||
image: caddy:2
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
||||
- caddy-data:/data
|
||||
depends_on:
|
||||
- api
|
||||
|
||||
volumes:
|
||||
combocoal-data:
|
||||
caddy-data:
|
||||
2
backend/requirements.txt
Normal file
2
backend/requirements.txt
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
flask>=3.0
|
||||
gunicorn>=22.0
|
||||
Loading…
Add table
Add a link
Reference in a new issue