164 lignes
5.5 KiB
Python
164 lignes
5.5 KiB
Python
"""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
|
|
ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" # sans I, L, O, 0, 1
|
|
|
|
|
|
def dossier_data():
|
|
return Path(os.environ.get("BETA_DATA", ICI / "data"))
|
|
|
|
|
|
def dossier_prive():
|
|
"""Dossier de données en 0700 (sous Windows, chmod est sans effet : voir README)."""
|
|
d = dossier_data()
|
|
d.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
try:
|
|
os.chmod(d, 0o700)
|
|
except OSError:
|
|
pass
|
|
return d
|
|
|
|
|
|
class _DataProxy:
|
|
def __truediv__(self, other):
|
|
return dossier_data() / other
|
|
|
|
def __getattr__(self, name):
|
|
return getattr(dossier_data(), name)
|
|
|
|
def __fspath__(self):
|
|
return str(dossier_data())
|
|
|
|
def __str__(self):
|
|
return str(dossier_data())
|
|
|
|
|
|
DATA = _DataProxy()
|
|
|
|
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 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 dossier_prive() / "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 = dossier_prive() / "sel.bin"
|
|
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
|