feat(beta): stockage des codes d'acces (SQLite) avec droits restreints

Dossier de donnees en 0700, cle en 0600 (O_EXCL), CSV des codes en 0600,
umask 077 a l'ouverture de la base. Test des droits (ignore sous Windows).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Cette révision appartient à :
Théo GastineletClaude Sonnet 5.5 a révisé 2026-10-29 10:22:08 +01:00
1 Parent e2b648e36c
révision 6a7872b09b
4 fichiers modifiés
+284

Aucun fichier ne correspond à votre recherche

+4
Voir le fichier
@@ -30,3 +30,7 @@ WhatsApp Video*.mp4
*.caddy
*auth*
*.secret
# Bêta testeurs : base locale, captures, codes émis (jamais dans git)
beta/data/
beta/pdf/*.ttf
+105
Voir le fichier
@@ -0,0 +1,105 @@
"""Gestion des codes d'accès et des retours de la bêta (en ligne de commande, local).
python beta/codes.py generer --label "Prénom N." [--jours 30] [--nombre 1] [--sessions 3] [--csv]
python beta/codes.py liste
python beta/codes.py revoquer <id>
python beta/codes.py prolonger <id> --jours 14
python beta/codes.py journal [--n 30]
python beta/codes.py retours [--n 30]
python beta/codes.py testeurs
Le code en clair n'est affiché qu'une seule fois, à la génération.
"""
import argparse
import csv
import os
import sys
import time
from datetime import datetime
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import db # noqa: E402
def fmt(ts):
return datetime.fromtimestamp(ts).strftime("%d/%m/%Y %H:%M") if ts else "-"
def etat(r):
if r["revoked_at"]:
return "révoqué"
if r["expires_at"] and r["expires_at"] <= time.time():
return "expiré"
return "actif"
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sp = ap.add_subparsers(dest="cmd", required=True)
g = sp.add_parser("generer")
g.add_argument("--label", required=True)
g.add_argument("--jours", type=int, default=30, help="durée de validité (0 = sans expiration)")
g.add_argument("--nombre", type=int, default=1)
g.add_argument("--sessions", type=int, default=3)
g.add_argument("--csv", action="store_true", help="écrit aussi beta/data/codes-emis.csv (hors git)")
sp.add_parser("liste")
r = sp.add_parser("revoquer"); r.add_argument("id", type=int)
p = sp.add_parser("prolonger"); p.add_argument("id", type=int); p.add_argument("--jours", type=int, required=True)
j = sp.add_parser("journal"); j.add_argument("--n", type=int, default=30)
f = sp.add_parser("retours"); f.add_argument("--n", type=int, default=30)
sp.add_parser("testeurs")
a = ap.parse_args(argv)
c = db.connect()
if a.cmd == "generer":
lignes = []
for i in range(a.nombre):
label = a.label if a.nombre == 1 else f"{a.label} {i + 1}"
cid, code = db.creer_code(c, label, a.jours, a.sessions)
lignes.append((cid, label, code))
print(f"#{cid} {label} {code}")
if a.csv:
f_ = db.DATA / "codes-emis.csv"
neuf = not f_.exists()
fd = os.open(f_, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
with os.fdopen(fd, "a", newline="", encoding="utf-8") as fh:
w = csv.writer(fh)
if neuf:
w.writerow(["id", "label", "code"])
w.writerows(lignes)
print(f"(écrit dans {f_} : hors git, à supprimer après envoi)")
elif a.cmd == "liste":
for r_ in c.execute("SELECT * FROM codes ORDER BY id"):
print(f"#{r_['id']:<3} {etat(r_):<8} {r_['label']:<24} créé {fmt(r_['created_at'])} expire {fmt(r_['expires_at'])} "
f"usages {r_['uses']} dernier {fmt(r_['last_used_at'])}")
elif a.cmd == "revoquer":
c.execute("UPDATE codes SET revoked_at=? WHERE id=? AND revoked_at IS NULL", (time.time(), a.id))
c.execute("DELETE FROM sessions WHERE code_id=?", (a.id,))
c.commit()
db.journal(c, "code_revoque", a.id)
print(f"Code #{a.id} révoqué ; ses sessions sont coupées.")
elif a.cmd == "prolonger":
row = c.execute("SELECT * FROM codes WHERE id=?", (a.id,)).fetchone()
if not row or row["revoked_at"]:
sys.exit("Code introuvable ou révoqué.")
base = max(row["expires_at"] or time.time(), time.time())
c.execute("UPDATE codes SET expires_at=? WHERE id=?", (base + a.jours * 86400, a.id))
c.commit()
db.journal(c, "code_prolonge", a.id, None, f"+{a.jours} j")
print("Prolongé.")
elif a.cmd == "journal":
for r_ in c.execute("SELECT * FROM audit ORDER BY id DESC LIMIT ?", (a.n,)):
print(f"{fmt(r_['ts'])} {r_['event']:<16} code={r_['code_id'] or '-'} ip={r_['ip_hash'] or '-'} {r_['detail'] or ''}")
elif a.cmd == "retours":
for r_ in c.execute("SELECT f.*, c.label FROM feedback f LEFT JOIN codes c ON c.id=f.code_id ORDER BY f.id DESC LIMIT ?", (a.n,)):
print(f"#{r_['id']} {fmt(r_['ts'])} [{r_['kind']}] {r_['label']} sur {r_['page']} ({r_['viewport']})"
f"{' capture: ' + r_['shot'] if r_['shot'] else ''}\n {r_['text']}")
elif a.cmd == "testeurs":
for r_ in c.execute("SELECT * FROM testers ORDER BY id"):
print(f"#{r_['id']} {r_['prenom']} {r_['nom']} <{r_['email']}> {r_['tel']} "
f"{'MINEUR (parent: ' + str(r_['parent_nom']) + ')' if r_['mineur'] else 'majeur'} reseaux={r_['suivi_reseaux']}")
if __name__ == "__main__":
main()
+142
Voir le fichier
@@ -0,0 +1,142 @@
"""Stockage local de la bêta JobRunner (SQLite, un seul fichier hors git).
Tout ce qui est « démo » vit dans les tables demo_* : aucune vraie donnée
utilisateur n'existe dans ce dépôt, et la bêta n'a aucun lien avec une base
de production. Les codes d'accès ne sont jamais stockés en clair (hachés avec
un sel local).
"""
import hashlib
import hmac
import os
import secrets
import sqlite3
import time
from pathlib import Path
ICI = Path(__file__).resolve().parent
DATA = Path(os.environ.get("BETA_DATA", ICI / "data"))
ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" # sans I, L, O, 0, 1
SCHEMA = """
CREATE TABLE IF NOT EXISTS codes(
id INTEGER PRIMARY KEY, label TEXT NOT NULL, code_hash TEXT NOT NULL,
created_at REAL NOT NULL, expires_at REAL, revoked_at REAL,
last_used_at REAL, uses INTEGER NOT NULL DEFAULT 0, max_sessions INTEGER NOT NULL DEFAULT 3);
CREATE TABLE IF NOT EXISTS sessions(
token_hash TEXT PRIMARY KEY, code_id INTEGER NOT NULL, created_at REAL NOT NULL,
expires_at REAL NOT NULL, last_seen REAL);
CREATE TABLE IF NOT EXISTS attempts(
id INTEGER PRIMARY KEY, ts REAL NOT NULL, ip_hash TEXT NOT NULL, ok INTEGER NOT NULL, reason TEXT);
CREATE TABLE IF NOT EXISTS audit(
id INTEGER PRIMARY KEY, ts REAL NOT NULL, event TEXT NOT NULL, code_id INTEGER, ip_hash TEXT, detail TEXT);
CREATE TABLE IF NOT EXISTS feedback(
id INTEGER PRIMARY KEY, ts REAL NOT NULL, code_id INTEGER, page TEXT, text TEXT NOT NULL,
shot TEXT, viewport TEXT, ua TEXT, kind TEXT);
CREATE TABLE IF NOT EXISTS testers(
id INTEGER PRIMARY KEY, ts REAL NOT NULL, nom TEXT, prenom TEXT, email TEXT, tel TEXT,
naissance TEXT, mineur INTEGER, parent_nom TEXT, parent_email TEXT,
accord_participation INTEGER, rgpd INTEGER, confidentialite INTEGER, age_ok INTEGER,
suivi_reseaux INTEGER, source TEXT);
CREATE TABLE IF NOT EXISTS demo_profiles(
id INTEGER PRIMARY KEY, created_at REAL, first TEXT, last_initial TEXT, city TEXT, dept TEXT,
region TEXT, seed TEXT, bio TEXT);
CREATE TABLE IF NOT EXISTS demo_ads(
id INTEGER PRIMARY KEY, created_at REAL, profile_id INTEGER, category TEXT, title TEXT,
price INTEGER, unit TEXT, descr TEXT);
CREATE TABLE IF NOT EXISTS demo_convs(
id INTEGER PRIMARY KEY, created_at REAL, profile_id INTEGER, title TEXT, amount INTEGER, status TEXT);
CREATE TABLE IF NOT EXISTS demo_msgs(
id INTEGER PRIMARY KEY, created_at REAL, conv_id INTEGER, sender TEXT, text TEXT);
CREATE TABLE IF NOT EXISTS demo_activity(
id INTEGER PRIMARY KEY, created_at REAL, kind TEXT, text TEXT);
"""
def dossier_prive():
"""Dossier de données en 0700 (sous Windows, chmod est sans effet : voir README)."""
DATA.mkdir(mode=0o700, parents=True, exist_ok=True)
try:
os.chmod(DATA, 0o700)
except OSError:
pass
def connect(path=None, check_same_thread=True):
dossier_prive()
ancien = os.umask(0o077) # base, -wal et -shm créés en 0600
try:
c = _ouvrir(path, check_same_thread)
finally:
os.umask(ancien)
return c
def _ouvrir(path, check_same_thread):
c = sqlite3.connect(str(path or DATA / "beta.sqlite"), timeout=10, check_same_thread=check_same_thread)
c.row_factory = sqlite3.Row
c.execute("PRAGMA journal_mode=WAL")
c.executescript(SCHEMA)
return c
def sel():
"""Sel local (créé au premier usage, hors git, jamais affiché)."""
f = DATA / "sel.bin"
dossier_prive()
try:
fd = os.open(f, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "wb") as fh:
fh.write(secrets.token_bytes(32))
except FileExistsError:
pass
return f.read_bytes()
def normaliser(code):
return "".join(ch for ch in str(code).upper() if ch in ALPHABET)
def hacher(code):
return hmac.new(sel(), normaliser(code).encode(), hashlib.sha256).hexdigest()
def hacher_ip(ip):
return hmac.new(sel(), b"ip:" + str(ip).encode(), hashlib.sha256).hexdigest()[:16]
def nouveau_code():
g = lambda: "".join(secrets.choice(ALPHABET) for _ in range(4))
return f"JRB-{g()}-{g()}-{g()}"
def journal(c, event, code_id=None, ip_hash=None, detail=None):
c.execute("INSERT INTO audit(ts,event,code_id,ip_hash,detail) VALUES(?,?,?,?,?)",
(time.time(), event, code_id, ip_hash, detail))
c.commit()
def creer_code(c, label, jours=30, max_sessions=3):
code = nouveau_code()
exp = time.time() + jours * 86400 if jours else None
cur = c.execute("INSERT INTO codes(label,code_hash,created_at,expires_at,max_sessions) VALUES(?,?,?,?,?)",
(label, hacher(code), time.time(), exp, max_sessions))
c.commit()
journal(c, "code_cree", cur.lastrowid, None, label)
return cur.lastrowid, code
def code_actif(row, now=None):
now = now or time.time()
return row["revoked_at"] is None and (row["expires_at"] is None or row["expires_at"] > now)
def verifier_code(c, saisi):
"""Compare en temps constant avec TOUS les codes (pas de sortie anticipée).
Retourne la ligne du code valide ou None."""
h = hacher(saisi)
trouve = None
for row in c.execute("SELECT * FROM codes").fetchall():
egal = hmac.compare_digest(row["code_hash"], h)
if egal and code_actif(row):
trouve = row
return trouve
+33
Voir le fichier
@@ -0,0 +1,33 @@
"""Droits des fichiers sensibles (Linux/macOS). Sous Windows les bits POSIX
n'existent pas : le test est ignoré et la protection repose sur le profil
utilisateur (voir README, section Sécurité)."""
import os
import stat
import sys
import tempfile
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
@unittest.skipIf(os.name == "nt", "droits POSIX non applicables sous Windows")
class Droits(unittest.TestCase):
def test_droits(self):
tmp = tempfile.mkdtemp()
os.environ["BETA_DATA"] = str(Path(tmp) / "data")
import db, codes
c = db.connect()
db.creer_code(c, "t")
c.execute("INSERT INTO audit(ts,event) VALUES(1,'x')"); c.commit()
codes.main(["generer", "--label", "x", "--csv"])
mode = lambda p: stat.S_IMODE(os.stat(p).st_mode)
d = Path(os.environ["BETA_DATA"])
self.assertEqual(mode(d), 0o700)
for f in d.iterdir():
self.assertEqual(mode(f), 0o600, f.name)
self.assertTrue((d / "sel.bin").exists() and (d / "codes-emis.csv").exists())
if __name__ == "__main__":
unittest.main()