Trial page: throwaway ring poll to test a screen with a phone, swept after 2 h

This commit is contained in:
2026-11-16 22:11:33 +01:00
parent 0dbb3f08bd
commit c93d1595a9
9 changed files with 98 additions and 3 deletions
+3
View File
@@ -57,6 +57,7 @@ location / {
| `DB_PATH` | `rotatyvote.db` | base SQLite | | `DB_PATH` | `rotatyvote.db` | base SQLite |
| `CREATE_PASSWORD` | vide | mot de passe pour créer un scrutin | | `CREATE_PASSWORD` | vide | mot de passe pour créer un scrutin |
| `TOKEN_GRACE_MS` | `2500` | tolérance réseau sur un code | | `TOKEN_GRACE_MS` | `2500` | tolérance réseau sur un code |
| `MAX_TRIALS` | `50` | essais `/essai` ouverts en même temps |
## Déroulé ## Déroulé
@@ -66,6 +67,8 @@ location / {
4. Lancer les questions préparées ou en créer en direct. Les téléphones les reçoivent instantanément. 4. Lancer les questions préparées ou en créer en direct. Les téléphones les reçoivent instantanément.
5. Clore, publier les résultats à l'écran, exporter en JSON. 5. Clore, publier les résultats à l'écran, exporter en JSON.
Avant l'AG, `/essai` lance un scrutin jetable sur l'écran à tester : code circulaire à 0,5 s, 5 scans, inscriptions ouvertes. On vise l'écran avec son téléphone depuis le fond de la salle et le compteur d'inscriptions confirme la lecture. Personne ne reçoit le lien d'administration, et l'essai est effacé au bout de 2 h, même sans mot de passe de création.
## Code circulaire ## Code circulaire
Par défaut, le projecteur affiche un code circulaire : un disque sombre avec le logo au centre, entouré de 4 anneaux de segments qui tournent. Le QR classique reste disponible par scrutin (Inscriptions > Code projeté). Par défaut, le projecteur affiche un code circulaire : un disque sombre avec le logo au centre, entouré de 4 anneaux de segments qui tournent. Le QR classique reste disponible par scrutin (Inscriptions > Code projeté).
+12
View File
@@ -415,6 +415,16 @@ async def create_poll(request: Request):
return JSONResponse({"id": pid, "admin_key": admin_key, "screen_key": screen_key}) return JSONResponse({"id": pid, "admin_key": admin_key, "screen_key": screen_key})
async def create_trial(request: Request):
# no password even when creation is locked: a trial only enrolls, nobody gets its admin key
db.purge_trials(config.TRIAL_TTL_MS)
if db.trial_count() >= config.MAX_TRIALS:
return err("too_many_trials", 429)
pid, _, screen_key = db.create_poll("Essai", 500, 5, False, None, 200, 0, "ring", trial=True)
db.update_poll(pid, enrollment_open=1)
return JSONResponse({"id": pid, "screen_key": screen_key})
async def admin_get(request: Request): async def admin_get(request: Request):
pid = request.path_params["pid"] pid = request.path_params["pid"]
require_admin(request, pid) require_admin(request, pid)
@@ -845,10 +855,12 @@ routes = [
Route("/", page("index.html")), Route("/", page("index.html")),
Route("/admin/{pid}", page("admin.html")), Route("/admin/{pid}", page("admin.html")),
Route("/screen/{pid}", page("screen.html")), Route("/screen/{pid}", page("screen.html")),
Route("/essai", page("essai.html")),
Route("/v/{pid}", page("vote.html")), Route("/v/{pid}", page("vote.html")),
Route("/V/{pid}", lambda r: RedirectResponse(f"/v/{r.path_params['pid'].lower()}", status_code=301)), Route("/V/{pid}", lambda r: RedirectResponse(f"/v/{r.path_params['pid'].lower()}", status_code=301)),
Route("/api/config", public_config, methods=["GET"]), Route("/api/config", public_config, methods=["GET"]),
Route("/api/polls", create_poll, methods=["POST"]), Route("/api/polls", create_poll, methods=["POST"]),
Route("/api/trial", create_trial, methods=["POST"]),
Route("/api/polls/{pid}", admin_get, methods=["GET"]), Route("/api/polls/{pid}", admin_get, methods=["GET"]),
Route("/api/polls/{pid}", admin_patch, methods=["PATCH"]), Route("/api/polls/{pid}", admin_patch, methods=["PATCH"]),
Route("/api/polls/{pid}/screen-key", admin_rotate_screen_key, methods=["POST"]), Route("/api/polls/{pid}/screen-key", admin_rotate_screen_key, methods=["POST"]),
+4
View File
@@ -29,6 +29,10 @@ HEARTBEAT_S = float(os.environ.get("HEARTBEAT_S", "25"))
DEFAULT_VOTE_SCANS = 3 DEFAULT_VOTE_SCANS = 3
MAX_VOTE_SCANS = 5 MAX_VOTE_SCANS = 5
# throwaway polls from /essai: deleted after this, and only so many alive at once
TRIAL_TTL_MS = 2 * 3600 * 1000
MAX_TRIALS = int(os.environ.get("MAX_TRIALS", "50"))
MIN_INTERVAL_MS = 300 MIN_INTERVAL_MS = 300
MAX_INTERVAL_MS = 5000 MAX_INTERVAL_MS = 5000
MIN_SCANS = 2 MIN_SCANS = 2
+19 -3
View File
@@ -87,6 +87,7 @@ class DB:
("voters", "via_code", "INTEGER NOT NULL DEFAULT 0"), ("voters", "via_code", "INTEGER NOT NULL DEFAULT 0"),
("access_codes", "rescue", "INTEGER NOT NULL DEFAULT 0"), ("access_codes", "rescue", "INTEGER NOT NULL DEFAULT 0"),
("polls", "code_style", "TEXT NOT NULL DEFAULT 'qr'"), ("polls", "code_style", "TEXT NOT NULL DEFAULT 'qr'"),
("polls", "trial", "INTEGER NOT NULL DEFAULT 0"),
): ):
cols = {r[1] for r in self.c.execute(f"PRAGMA table_info({table})")} cols = {r[1] for r in self.c.execute(f"PRAGMA table_info({table})")}
if col not in cols: if col not in cols:
@@ -110,19 +111,34 @@ class DB:
def create_poll(self, title, interval_ms, scans_required, require_code, expected, max_voters, vote_scans=0, def create_poll(self, title, interval_ms, scans_required, require_code, expected, max_voters, vote_scans=0,
code_style="qr"): code_style="qr", trial=False):
pid = new_id() pid = new_id()
while self.one("SELECT 1 FROM polls WHERE id=?", pid): while self.one("SELECT 1 FROM polls WHERE id=?", pid):
pid = new_id() pid = new_id()
admin_key, screen_key = new_key(), new_key() admin_key, screen_key = new_key(), new_key()
self.c.execute( self.c.execute(
"INSERT INTO polls(id,title,admin_hash,screen_hash,secret,interval_ms,scans_required," "INSERT INTO polls(id,title,admin_hash,screen_hash,secret,interval_ms,scans_required,"
"require_code,expected,max_voters,vote_scans,code_style,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)", "require_code,expected,max_voters,vote_scans,code_style,trial,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(pid, title, sha(admin_key), sha(screen_key), secrets.token_bytes(32), interval_ms, (pid, title, sha(admin_key), sha(screen_key), secrets.token_bytes(32), interval_ms,
scans_required, int(require_code), expected, max_voters, vote_scans, code_style, now_ms()), scans_required, int(require_code), expected, max_voters, vote_scans, code_style, int(trial), now_ms()),
) )
return pid, admin_key, screen_key return pid, admin_key, screen_key
def purge_trials(self, max_age_ms):
old = [r["id"] for r in self.all("SELECT id FROM polls WHERE trial=1 AND created_at<?", now_ms() - max_age_ms)]
with self.tx() as c:
for pid in old:
qids = "SELECT id FROM questions WHERE poll_id=?"
c.execute(f"DELETE FROM ballots WHERE question_id IN ({qids})", (pid,))
c.execute(f"DELETE FROM participation WHERE question_id IN ({qids})", (pid,))
for table, col in (("questions", "poll_id"), ("voters", "poll_id"), ("access_codes", "poll_id"),
("polls", "id")):
c.execute(f"DELETE FROM {table} WHERE {col}=?", (pid,))
return old
def trial_count(self):
return self.one("SELECT COUNT(*) n FROM polls WHERE trial=1")["n"]
def poll(self, pid): def poll(self, pid):
return self.one("SELECT * FROM polls WHERE id=?", pid) return self.one("SELECT * FROM polls WHERE id=?", pid)
+1
View File
@@ -154,3 +154,4 @@ button:disabled { opacity: .35; cursor: not-allowed; transform: none; }
.card { padding: 0; } .card { padding: 0; }
.code-cell { break-inside: avoid; } .code-cell { break-inside: avoid; }
} }
.center { text-align: center; }
+23
View File
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RotatyVote · Essai</title>
<link rel="icon" href="/static/img/mark.svg" type="image/svg+xml">
<link rel="stylesheet" href="/static/css/app.css">
<script type="module" src="/static/js/essai.js"></script>
</head>
<body>
<main class="wrap narrow">
<div class="topbar"><a class="brand" href="/"><img src="/static/img/mark.svg" alt=""><span>rotaty<b>vote</b></span></a></div>
<section class="card">
<h1>Tester l'écran</h1>
<p>Ouvrez cette page sur l'ordinateur relié au projecteur, puis visez l'écran avec votre téléphone depuis le fond de la salle.</p>
<div class="actions"><button id="go" class="primary block" type="button">Lancer l'essai</button></div>
<p class="hint">Scrutin jetable, effacé au bout de 2 h.</p>
</section>
</main>
</body>
</html>
+1
View File
@@ -61,6 +61,7 @@
<div class="actions"><button class="primary block" type="submit">Créer le scrutin</button></div> <div class="actions"><button class="primary block" type="submit">Créer le scrutin</button></div>
</form> </form>
</section> </section>
<p class="hint center" id="try-link"><a href="/essai">Tester l'écran et les téléphones avant l'AG</a></p>
<section id="done" class="card" hidden> <section id="done" class="card" hidden>
<h1>Scrutin créé</h1> <h1>Scrutin créé</h1>
+12
View File
@@ -0,0 +1,12 @@
import { $, api, toast } from "./common.js";
$("#go").addEventListener("click", async (e) => {
e.target.disabled = true;
try {
const r = await api("POST", "/api/trial");
location.href = `/screen/${r.id}#${r.screen_key}`;
} catch (err) {
toast(err.code === "too_many_trials" ? "Trop d'essais en cours, réessayez plus tard" : `Erreur : ${err.message}`, "bad");
e.target.disabled = false;
}
});
+23
View File
@@ -667,3 +667,26 @@ def test_entry_redirect(server):
p = create(server) p = create(server)
r = httpx.get(f"{server['base']}/V/{p['id'].upper()}", follow_redirects=False, verify=server["verify"]) r = httpx.get(f"{server['base']}/V/{p['id'].upper()}", follow_redirects=False, verify=server["verify"])
assert r.status_code == 301 and r.headers["location"] == f"/v/{p['id']}" assert r.status_code == 301 and r.headers["location"] == f"/v/{p['id']}"
def test_trial_enrolls_then_expires(server):
r = httpx.post(server["base"] + "/api/trial", verify=server["verify"])
assert r.status_code == 200
p = r.json()
assert "admin_key" not in p
async def run():
async with projector(server, p) as next_token:
c = await enroll(server, p, next_token)
await c.aclose()
asyncio.run(run())
# age it past the ttl, the next trial sweeps it away with everything it held
con = sqlite3.connect(server["db"])
con.execute("UPDATE polls SET created_at=created_at-? WHERE id=?", (3 * 3600 * 1000, p["id"]))
con.commit()
assert httpx.post(server["base"] + "/api/trial", verify=server["verify"]).status_code == 200
assert con.execute("SELECT COUNT(*) FROM polls WHERE id=?", (p["id"],)).fetchone()[0] == 0
assert con.execute("SELECT COUNT(*) FROM voters WHERE poll_id=?", (p["id"],)).fetchone()[0] == 0
con.close()
assert httpx.get(f"{server['base']}/screen/{p['id']}", verify=server["verify"]).status_code == 404