Deploy SQLite WAL SHA256 audit core, modular sources, and per-ministry Charcoal dispatcher
This commit is contained in:
parent
ea32bde3ac
commit
1e003c2f50
6 changed files with 190 additions and 0 deletions
87
core/audit_core.py
Normal file
87
core/audit_core.py
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
import os, json, socket, hashlib, sqlite3
|
||||
from datetime import datetime, timezone
|
||||
|
||||
AUDIT_DB = "/var/www/flexicraft-site/data/audit.db"
|
||||
AUDIT_SOCK = "/run/flexicraft-audit.sock"
|
||||
GENESIS_HASH = "0" * 64
|
||||
|
||||
def _get_conn():
|
||||
os.makedirs(os.path.dirname(AUDIT_DB), exist_ok=True)
|
||||
conn = sqlite3.connect(AUDIT_DB, timeout=10)
|
||||
conn.execute("PRAGMA journal_mode=WAL;")
|
||||
conn.execute("PRAGMA synchronous=NORMAL;")
|
||||
conn.execute("PRAGMA cache_size=-2000;")
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS audit_events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ts TEXT NOT NULL,
|
||||
ministry TEXT NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
actor_name TEXT NOT NULL,
|
||||
actor_discord_id TEXT,
|
||||
action TEXT NOT NULL,
|
||||
target TEXT,
|
||||
details_json TEXT,
|
||||
prev_hash TEXT NOT NULL,
|
||||
row_hash TEXT NOT NULL
|
||||
)
|
||||
""")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_audit_ts ON audit_events(ts);")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_audit_ministry ON audit_events(ministry);")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_audit_actor ON audit_events(actor_name);")
|
||||
return conn
|
||||
|
||||
def _compute_hash(prev_hash: str, ts: str, ministry: str, source: str, actor_name: str, action: str, target: str, details_str: str) -> str:
|
||||
raw = f"{prev_hash}|{ts}|{ministry}|{source}|{actor_name}|{action}|{target}|{details_str}".encode("utf-8")
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
def _notify_discord_socket(event_id: int):
|
||||
if not os.path.exists(AUDIT_SOCK):
|
||||
return
|
||||
try:
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as s:
|
||||
s.sendto(str(event_id).encode("utf-8"), AUDIT_SOCK)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def emit_audit(ministry: str, source: str, actor_name: str, action: str, target: str = "", details: dict = None, actor_discord_id: str = None) -> int:
|
||||
if not actor_name or actor_name.upper() == "CONSOLE":
|
||||
return 0
|
||||
ts = datetime.now(timezone.utc).isoformat()
|
||||
details_str = json.dumps(details or {}, ensure_ascii=False, sort_keys=True)
|
||||
ministry_clean = str(ministry or "general").lower().strip()
|
||||
|
||||
conn = _get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("BEGIN IMMEDIATE;")
|
||||
cur.execute("SELECT row_hash FROM audit_events ORDER BY id DESC LIMIT 1;")
|
||||
row = cur.fetchone()
|
||||
prev_hash = row[0] if row else GENESIS_HASH
|
||||
row_hash = _compute_hash(prev_hash, ts, ministry_clean, source, actor_name, action, target, details_str)
|
||||
cur.execute(
|
||||
"""INSERT INTO audit_events (ts, ministry, source, actor_name, actor_discord_id, action, target, details_json, prev_hash, row_hash)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(ts, ministry_clean, source, actor_name, str(actor_discord_id) if actor_discord_id else None, action, target, details_str, prev_hash, row_hash)
|
||||
)
|
||||
event_id = cur.lastrowid
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
_notify_discord_socket(event_id)
|
||||
return event_id
|
||||
|
||||
def get_event_by_id(event_id: int) -> dict:
|
||||
conn = _get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM audit_events WHERE id = ?", (event_id,))
|
||||
r = cur.fetchone()
|
||||
return dict(r) if r else None
|
||||
finally:
|
||||
conn.close()
|
||||
13
core/audit_sources/source_discord.py
Normal file
13
core/audit_sources/source_discord.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
from core.audit_core import emit_audit
|
||||
|
||||
def log_discord_human_action(ministry: str, sphere_label: str, actor_name: str, actor_discord_id: str, action: str, target: str = "", details: dict = None):
|
||||
payload = {"sphere": sphere_label, **(details or {})}
|
||||
return emit_audit(
|
||||
ministry=ministry,
|
||||
source="discord",
|
||||
actor_name=actor_name,
|
||||
actor_discord_id=actor_discord_id,
|
||||
action=action,
|
||||
target=target,
|
||||
details=payload
|
||||
)
|
||||
55
core/audit_sources/source_minecraft.py
Normal file
55
core/audit_sources/source_minecraft.py
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import os, re, json
|
||||
from core.audit_core import emit_audit
|
||||
|
||||
LINKS_DB = "/root/flexicraft-discord-setup/data/crossplay_links.json"
|
||||
|
||||
CMD_MINISTRY_RULES = [
|
||||
(re.compile(r"^/(?:lp|luckperms|ban|tempban|banip|unban|unbanip|kick|co|whitelist|op|deop)\b", re.I), "netherite", "Serveur Minecraft — Sécurité & Sanctions"),
|
||||
(re.compile(r"^/(?:mute|unmute|socialspy|broadcast)\b", re.I), "amethyst", "Serveur Minecraft — Modération Communication"),
|
||||
(re.compile(r"^/(?:invsee|enderchest|echest|teamadmin)\b", re.I), "coal", "Serveur Minecraft — Intérieur & Clans"),
|
||||
(re.compile(r"^/(?:worldedit|we|/)\b", re.I), "copper", "Serveur Minecraft — Travaux Publics"),
|
||||
(re.compile(r"^/(?:tp|tphere|tppos)\b", re.I), "gold", "Serveur Minecraft — Transports & Mobilité"),
|
||||
(re.compile(r"^/(?:spark|tps)\b", re.I), "quartz", "Serveur Minecraft — Technique & Performance"),
|
||||
(re.compile(r"^/(?:datapack|gamerule)\b", re.I), "lapis", "Serveur Minecraft — Mécaniques & Datapacks"),
|
||||
(re.compile(r"^/(?:save-all)\b", re.I), "emerald", "Serveur Minecraft — Économie & Sauvegarde"),
|
||||
(re.compile(r"^/(?:gamemode|gm|give)\b", re.I), "diamond", "Serveur Minecraft — Administration Suprême"),
|
||||
]
|
||||
|
||||
def _resolve_discord_id_for_mc_player(mc_name: str):
|
||||
if not os.path.exists(LINKS_DB):
|
||||
return None
|
||||
low = mc_name.lower().lstrip(".")
|
||||
try:
|
||||
with open(LINKS_DB, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
for did, info in data.items():
|
||||
if not isinstance(info, dict):
|
||||
continue
|
||||
jname = str(info.get("java_name") or info.get("mc_name") or "").lower()
|
||||
bname = str(info.get("bedrock_name") or "").lower().lstrip(".")
|
||||
if low and (low == jname or low == bname):
|
||||
return str(did)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
def process_mc_log_line(line: str):
|
||||
m = re.search(r":\s+([A-Za-z0-9_\.]{2,20})\s+issued server command:\s+(/.*)$", line.strip())
|
||||
if not m:
|
||||
return None
|
||||
player, cmd = m.group(1), m.group(2).strip()
|
||||
if player.upper() == "CONSOLE":
|
||||
return None
|
||||
for regex, ministry, sphere in CMD_MINISTRY_RULES:
|
||||
if regex.search(cmd):
|
||||
did = _resolve_discord_id_for_mc_player(player)
|
||||
return emit_audit(
|
||||
ministry=ministry,
|
||||
source="minecraft",
|
||||
actor_name=player,
|
||||
actor_discord_id=did,
|
||||
action="Commande exécutée en jeu",
|
||||
target=cmd,
|
||||
details={"sphere": sphere}
|
||||
)
|
||||
return None
|
||||
13
core/audit_sources/source_web.py
Normal file
13
core/audit_sources/source_web.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
from core.audit_core import emit_audit
|
||||
|
||||
def log_web_ministry_action(ministry: str, panel_label: str, actor_name: str, actor_discord_id: str, action: str, target: str = "", details: dict = None):
|
||||
payload = {"sphere": panel_label, **(details or {})}
|
||||
return emit_audit(
|
||||
ministry=ministry,
|
||||
source="web_panel",
|
||||
actor_name=actor_name,
|
||||
actor_discord_id=actor_discord_id,
|
||||
action=action,
|
||||
target=target,
|
||||
details=payload
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue