Compare commits

..
2 Commits
13 changed files with 250 additions and 51 deletions
+11
View File
@@ -66,6 +66,17 @@ location / {
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.
## 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é).
- L'anneau intérieur porte un motif fixe qui donne l'orientation. Les 3 autres portent le jeton : 16 bits de créneau et 32 bits de signature HMAC, protégés par un code Reed-Solomon (12, 6) qui corrige 3 octets illisibles.
- Le téléphone repère le disque central, corrige la perspective à partir des anneaux (deux cercles concentriques suffisent à retrouver l'horizon), lit les segments puis corrige les erreurs.
- La longueur et l'opacité des segments varient en continu, dans des bornes qui ne touchent jamais la donnée. Un segment qui change de couleur passe en fondu.
- Les anneaux ne s'ouvrent pas avec l'appareil photo natif : un petit QR fixe, dans un coin de l'écran, mène à la page de vote.
- Signature de 32 bits : un jeton ne vaut que pendant environ 3 s et le serveur doit le recevoir en ligne. Même à 1 000 essais par seconde, la probabilité de deviner un jeton valide pendant sa durée de vie est d'environ 7 × 10⁻⁷, et il en faut 5 distincts pour s'inscrire.
- Banc d'essai : `uv run python tools/ringbench.py` (Chrome sans interface, perspective, flou, contraste délavé, décor encombré, images sans code). `CPU=6` simule un téléphone lent.
## Sécurité : ce qui est garanti, ce qui ne l'est pas
**Présence à l'inscription.** Chaque code est un HMAC du créneau horaire, valable environ 3 s. Il faut N codes distincts en une fenêtre courte : une photo ou une capture partagée ne suffit pas.
Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+48 -11
View File
@@ -11,12 +11,12 @@ from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import FileResponse, JSONResponse, Response
from starlette.responses import FileResponse, JSONResponse, RedirectResponse, Response
from starlette.routing import Mount, Route, WebSocketRoute
from starlette.staticfiles import StaticFiles
from starlette.websockets import WebSocket, WebSocketDisconnect
from . import config
from . import config, ringcode
from .db import DB, open_db
from .tokens import check_key, current_slot, make_token, new_key, now_ms, sha, verify_token
@@ -71,7 +71,7 @@ def admin_state(pid):
"scans_required": p["scans_required"], "enrollment_open": bool(p["enrollment_open"]),
"max_voters": p["max_voters"], "expected": p["expected"],
"require_code": bool(p["require_code"]), "focus_qid": p["focus_qid"],
"vote_scans": p["vote_scans"],
"vote_scans": p["vote_scans"], "code_style": p["code_style"],
},
"voters": db.voter_count(pid),
"codes": codes_summary(pid),
@@ -116,7 +116,7 @@ def screen_state(pid):
"type": "state", "title": p["title"], "enrollment_open": bool(p["enrollment_open"]),
"voters": db.voter_count(pid), "expected": p["expected"], "max_voters": p["max_voters"],
"scans_required": p["scans_required"], "interval_ms": p["interval_ms"], "focus": focus,
"presence": presence_check(p), "vote_scans": p["vote_scans"],
"presence": presence_check(p), "vote_scans": p["vote_scans"], "code_style": p["code_style"],
}
@@ -130,14 +130,33 @@ def voter_state(pid, voter):
d["voted"] = q["id"] in voted
qs.append(d)
scans = 0 if voter["via_code"] else p["vote_scans"]
return {"type": "state", "title": p["title"], "enrolled": True, "questions": qs, "vote_scans": scans}
return {"type": "state", "title": p["title"], "enrolled": True, "questions": qs, "vote_scans": scans,
"code_style": p["code_style"]}
def qr_modules(url: str):
qr = segno.make(url, error="m", micro=False)
def qr_modules(url: str, error="m"):
qr = segno.make(url, error=error, micro=False)
return ["".join("1" if b else "0" for b in row) for row in qr.matrix]
def entry_qr(base: str, pid: str):
"""static qr shown in a corner of the ring-code projector: opens the voting page from the camera app.
upper case keeps it in qr alphanumeric mode, a smaller symbol (/V/ redirects to /v/)"""
url = f"{base}/V/{pid}".upper()
return {"type": "entry", "modules": qr_modules(url, error="l"), "url": f"{base}/v/{pid}"}
def resolve_token(p, tok: str, grace_ms: int):
"""full slot for a fresh, authentic token in either format (qr 'slot.mac' or ring 'r<s16>.<mac>'), else None"""
if tok.startswith("r"):
iv, now = p["interval_ms"], now_ms()
slot = ringcode.resolve(p["secret"], p["id"], iv, tok, current_slot(iv, now), (iv + grace_ms) // iv + 1)
if slot is None or not 0 <= now - slot * iv <= iv + grace_ms:
return None
return slot
return verify_token(p["secret"], p["id"], p["interval_ms"], tok, grace_ms)
class Hub:
def __init__(self):
self.screens: dict[str, dict[WebSocket, str]] = {} # ws -> origin
@@ -213,13 +232,21 @@ class Hub:
return
iv = p["interval_ms"]
slot = current_slot(iv)
if p["code_style"] == "ring":
# the screen draws the rings itself, it only needs the bits for this slot
await self.send_all(screens, {
"type": "ring", "bits": ringcode.render_bits(p["secret"], pid, iv, slot),
"token": ringcode.token(p["secret"], pid, iv, slot), "slot": slot,
"interval_ms": iv, "valid_until": (slot + 1) * iv})
await asyncio.sleep(max(0.01, ((slot + 1) * iv - now_ms()) / 1000))
continue
token = make_token(p["secret"], pid, iv, slot)
by_origin: dict[str, list[WebSocket]] = {}
for ws, origin in list(screens.items()):
by_origin.setdefault(config.PUBLIC_URL or origin, []).append(ws)
for base, conns in by_origin.items():
url = f"{base}/v/{pid}#{token}"
msg = {"type": "qr", "url": url, "modules": qr_modules(url), "slot": slot,
msg = {"type": "qr", "url": url, "token": token, "modules": qr_modules(url), "slot": slot,
"interval_ms": iv, "valid_until": (slot + 1) * iv}
await self.send_all(conns, msg)
await asyncio.sleep(max(0.01, ((slot + 1) * iv - now_ms()) / 1000))
@@ -374,9 +401,12 @@ async def create_poll(request: Request):
expected = opt_int(d.get("expected"), 1, 100000, "expected")
max_voters = opt_int(d.get("max_voters"), 1, 100000, "max_voters")
vote_scans = clamp_int(d.get("vote_scans", config.DEFAULT_VOTE_SCANS), 0, config.MAX_VOTE_SCANS, "vote_scans")
code_style = d.get("code_style", "ring")
if code_style not in ("ring", "qr"):
return err("bad_code_style")
questions = [parse_question(q) for q in (d.get("questions") or [])]
pid, admin_key, screen_key = db.create_poll(title, interval, scans, bool(d.get("require_code")),
expected, max_voters, vote_scans)
expected, max_voters, vote_scans, code_style)
for q in questions:
db.add_question(pid, *q)
codes = int(d.get("codes") or 0)
@@ -413,6 +443,10 @@ async def admin_patch(request: Request):
upd["expected"] = opt_int(d["expected"], 1, 100000, "expected")
if "require_code" in d:
upd["require_code"] = int(bool(d["require_code"]))
if "code_style" in d:
if d["code_style"] not in ("ring", "qr"):
return err("bad_code_style")
upd["code_style"] = d["code_style"]
if "vote_scans" in d:
upd["vote_scans"] = clamp_int(d["vote_scans"], 0, config.MAX_VOTE_SCANS, "vote_scans")
if "focus_qid" in d:
@@ -525,6 +559,7 @@ async def voter_me(request: Request):
"type": "state", "title": p["title"], "enrolled": False,
"enrollment_open": bool(p["enrollment_open"]), "scans_required": p["scans_required"],
"require_code": bool(p["require_code"]), "need_code": presence and bool(p["require_code"]),
"code_style": p["code_style"],
"count": len(a.slots) if a else 0,
})
@@ -569,7 +604,7 @@ async def voter_scan(request: Request):
a.slots.clear(); a.first_ms = 0
status = "progress"
slot = verify_token(p["secret"], pid, p["interval_ms"], str(d.get("token", ""))[:64], config.TOKEN_GRACE_MS)
slot = resolve_token(p, str(d.get("token", ""))[:64], config.TOKEN_GRACE_MS)
accepted = False
if slot is not None and not a.presence_ms and slot not in a.slots:
if not a.first_ms:
@@ -662,7 +697,7 @@ async def voter_vote(request: Request):
if not isinstance(tokens, list):
return err("presence_required")
window = config.TOKEN_GRACE_MS + need * p["interval_ms"]
slots = {verify_token(p["secret"], pid, p["interval_ms"], str(t)[:64], window) for t in tokens[:20]}
slots = {resolve_token(p, str(t)[:64], window) for t in tokens[:20]}
slots.discard(None)
if len(slots) < need:
return err("presence_required")
@@ -703,6 +738,7 @@ async def ws_screen(ws: WebSocket):
scheme = "https" if ws.url.scheme == "wss" or config.BEHIND_PROXY else "http"
origin = f"{scheme}://{public_host(ws)}"
hub.screens.setdefault(pid, {})[ws] = origin
await hub.send(ws, entry_qr(config.PUBLIC_URL or origin, pid))
await hub.send(ws, screen_state(pid))
hub.ensure_ticker(pid)
hub.refresh(pid)
@@ -810,6 +846,7 @@ routes = [
Route("/admin/{pid}", page("admin.html")),
Route("/screen/{pid}", page("screen.html")),
Route("/v/{pid}", page("vote.html")),
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/polls", create_poll, methods=["POST"]),
Route("/api/polls/{pid}", admin_get, methods=["GET"]),
+7 -4
View File
@@ -20,6 +20,7 @@ CREATE TABLE IF NOT EXISTS polls(
expected INTEGER,
require_code INTEGER NOT NULL DEFAULT 0,
vote_scans INTEGER NOT NULL DEFAULT 0,
code_style TEXT NOT NULL DEFAULT 'qr',
focus_qid INTEGER,
created_at INTEGER NOT NULL
);
@@ -85,6 +86,7 @@ class DB:
("polls", "vote_scans", "INTEGER NOT NULL DEFAULT 0"),
("voters", "via_code", "INTEGER NOT NULL DEFAULT 0"),
("access_codes", "rescue", "INTEGER NOT NULL DEFAULT 0"),
("polls", "code_style", "TEXT NOT NULL DEFAULT 'qr'"),
):
cols = {r[1] for r in self.c.execute(f"PRAGMA table_info({table})")}
if col not in cols:
@@ -107,16 +109,17 @@ class DB:
return self.c.execute(sql, args).fetchall()
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"):
pid = new_id()
while self.one("SELECT 1 FROM polls WHERE id=?", pid):
pid = new_id()
admin_key, screen_key = new_key(), new_key()
self.c.execute(
"INSERT INTO polls(id,title,admin_hash,screen_hash,secret,interval_ms,scans_required,"
"require_code,expected,max_voters,vote_scans,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)",
"require_code,expected,max_voters,vote_scans,code_style,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
(pid, title, sha(admin_key), sha(screen_key), secrets.token_bytes(32), interval_ms,
scans_required, int(require_code), expected, max_voters, vote_scans, now_ms()),
scans_required, int(require_code), expected, max_voters, vote_scans, code_style, now_ms()),
)
return pid, admin_key, screen_key
@@ -125,7 +128,7 @@ class DB:
def update_poll(self, pid, **fields):
allowed = {"title", "interval_ms", "scans_required", "enrollment_open", "max_voters",
"expected", "require_code", "focus_qid", "vote_scans"}
"expected", "require_code", "focus_qid", "vote_scans", "code_style"}
fields = {k: v for k, v in fields.items() if k in allowed}
if not fields:
return
+6 -1
View File
@@ -42,9 +42,14 @@
<section data-panel="enroll" class="no-print" hidden>
<div class="card">
<label for="s-code-style">Code projeté</label>
<select id="s-code-style">
<option value="ring">Code circulaire</option>
<option value="qr">QR classique</option>
</select>
<div class="row">
<div>
<label for="s-interval">Rotation du QR</label>
<label for="s-interval">Rotation du code</label>
<select id="s-interval">
<option value="500">0,5 s</option>
<option value="1000">1 s</option>
+6
View File
@@ -15,6 +15,11 @@ body.screen {
height: 100%; max-height: 74vh; aspect-ratio: 1; display: grid; grid-template-rows: 1fr auto;
background: #fff; border-radius: 28px; padding: 2vh; gap: 1.4vh;
}
.qr-wrap.ring { background: transparent; padding: 0; }
.entry { display: flex; align-items: center; gap: 1.2vw; margin-top: 3vh; background: var(--surface); border-radius: 18px; padding: 1.2vh 1.2vw; width: fit-content; }
.entry canvas { width: clamp(70px, 7vw, 130px); height: auto; aspect-ratio: 1; image-rendering: pixelated; }
.entry div { display: grid; gap: .3vh; font-size: clamp(.8rem, 1.1vw, 1.2rem); color: var(--ink-2); }
.entry b { color: var(--ink); font-weight: 700; }
#qr { width: 100%; height: 100%; min-height: 0; image-rendering: pixelated; image-rendering: crisp-edges; object-fit: contain; }
.tick { height: 6px; background: var(--bg); border-radius: 99px; overflow: hidden; margin: 0 1vh; }
#tick-bar { height: 100%; width: 0; background: var(--mark); border-radius: 99px; }
@@ -64,3 +69,4 @@ body.screen {
.s-enroll, .s-main.split { grid-template-columns: 1fr; }
.qr-wrap { max-height: 50vh; justify-self: center; }
}
.qr-wrap.ring .tick { display: none; }
+3 -3
View File
@@ -20,10 +20,10 @@
<div class="row">
<div>
<label for="interval">Rotation du QR</label>
<label for="interval">Rotation du code</label>
<select id="interval">
<option value="500">0,5 s</option>
<option value="1000" selected>1 s</option>
<option value="500" selected>0,5 s</option>
<option value="1000">1 s</option>
<option value="1500">1,5 s</option>
<option value="2000">2 s</option>
</select>
+2
View File
@@ -76,6 +76,7 @@ function renderSettings(p) {
if (active !== $("#s-expected")) $("#s-expected").value = p.expected ?? "";
if (active !== $("#s-max")) $("#s-max").value = p.max_voters ?? "";
if (active !== $("#s-vote-scans")) $("#s-vote-scans").value = String(p.vote_scans);
if (active !== $("#s-code-style")) $("#s-code-style").value = p.code_style;
$("#s-code").checked = p.require_code;
$("#access-row").hidden = !p.require_code && !state.codes.access.total;
const sum = (c, none) => (c.total ? `${c.used} utilisé${c.used > 1 ? "s" : ""} sur ${c.total}` : none);
@@ -203,6 +204,7 @@ const SETTINGS = {
"#s-max": (el) => ({ max_voters: intOrNull(el.value) }),
"#s-code": (el) => ({ require_code: el.checked }),
"#s-vote-scans": (el) => ({ vote_scans: +el.value }),
"#s-code-style": (el) => ({ code_style: el.value }),
};
for (const [sel, build] of Object.entries(SETTINGS)) {
$(sel).addEventListener("change", async (e) => {
+44 -3
View File
@@ -1,10 +1,13 @@
import { $, h, pollId, takeKey, liveSocket, drawQR, resultsView, fill, pct } from "./common.js";
import { render as drawRing, DISC } from "./ringcode.js";
const pid = pollId();
const key = takeKey(`rv_screen_${pid}`);
let st = null;
let qr = null;
let qr = null; // current code message, qr or ring
let raf = 0;
let entry = null;
let prevBits = null, switchedAt = 0;
function layout() {
if (!st) return;
@@ -15,8 +18,13 @@ function layout() {
$("#focus").hidden = !focus;
$("#idle").hidden = qrOn || !!focus;
$(".s-main").classList.toggle("split", qrOn && !!focus);
$("#qr-title").textContent = st.enrollment_open ? "Inscription" : "Scannez pour voter";
const ring = st.code_style === "ring";
$("#qr-title").textContent = st.enrollment_open ? "Inscription" : ring ? "Visez le cercle pour voter" : "Scannez pour voter";
$("#qr-steps").hidden = !st.enrollment_open;
// rings can't be opened by the camera app, so a small fixed qr leads to the page
$("#step1").textContent = ring ? "Ouvrez la page de vote" : "Scannez ce code";
$("#entry").hidden = !(ring && st.enrollment_open && entry);
$(".qr-wrap").classList.toggle("ring", ring);
}
function render() {
@@ -50,12 +58,33 @@ function render() {
}
function paintQR() {
if (!qr) return;
if (!qr || qr.type !== "qr") return;
const c = $("#qr");
const px = Math.min(c.clientWidth || 600, c.clientHeight || 600) * (window.devicePixelRatio || 1);
drawQR(c, qr.modules, px);
}
function paintEntry() {
if (!entry) return;
drawQR($("#entry-qr"), entry.modules, 220 * (window.devicePixelRatio || 1));
$("#entry-url").textContent = entry.url.replace(/^https?:\/\//, "");
}
// rings rotate continuously (one turn every 45 s); changed dashes cross-fade when the code switches
function ringLoop(t) {
if (!qr || qr.type !== "ring") return;
const c = $("#qr"), dpr = window.devicePixelRatio || 1;
const size = Math.round(Math.min(c.clientWidth || 600, c.clientHeight || 600) * dpr);
if (c.width !== size) { c.width = c.height = size; }
const ctx = c.getContext("2d");
ctx.clearRect(0, 0, size, size);
const fadeMs = Math.min(220, qr.interval_ms * 0.25);
const k = prevBits ? Math.min(1, (t - switchedAt) / fadeMs) : 1;
drawRing(ctx, size / 2, size / 2, (size / 2) / DISC * 0.98, (t / 1000) * (2 * Math.PI / 45), qr.bits, t / 1000,
prevBits ? { from: prevBits, k } : null);
requestAnimationFrame(ringLoop);
}
function animateTick() {
cancelAnimationFrame(raf);
const bar = $("#tick-bar");
@@ -80,6 +109,18 @@ liveSocket(`/ws/${pid}/screen`, {
st = msg;
if (!st.enrollment_open && !st.presence) qr = null;
render();
} else if (msg.type === "entry") {
entry = msg;
paintEntry();
if (st) layout();
} else if (msg.type === "ring") {
skew = Date.now() - msg.slot * msg.interval_ms;
const wasRing = qr && qr.type === "ring";
prevBits = wasRing ? qr.bits : null;
switchedAt = performance.now();
qr = msg;
if (!wasRing) requestAnimationFrame(ringLoop);
animateTick();
} else if (msg.type === "qr") {
// server clock drives validity, estimate offset so the countdown bar is right
skew = Date.now() - msg.slot * msg.interval_ms;
+53 -21
View File
@@ -1,4 +1,5 @@
import { $, h, api, pollId, liveSocket, resultsView, toast, ring, icon } from "./common.js";
import { decodeFrame, grayOf } from "./ringcode.js";
const pid = pollId();
const DONE_KEY = `rv_done_${pid}`;
@@ -15,6 +16,8 @@ const sent = new Set();
const selections = new Map();
let queue = Promise.resolve();
let lastState = null;
let codeStyle = "qr"; // what the projector shows: rotating qr or ring code
let qrEngine = null;
let lastJson = "";
function show(id) {
@@ -50,7 +53,7 @@ async function startScanner() {
return;
}
$("#cam-box").hidden = false;
scanner = makeScanner($("#video"), onScan);
scanner = makeScanner($("#video"), onScan, () => scanMsg("QR d'un autre scrutin.", "bad"));
try {
await scanner.start();
$("#start-cam").hidden = true;
@@ -66,18 +69,51 @@ async function startScanner() {
}
}
function makeScanner(video, onData) {
return new window.QrScanner(video, (r) => onData(r.data), {
returnDetailedScanResult: true,
preferredCamera: "environment",
maxScansPerSecond: 15,
// whole frame, the projected code is often small and off-center
calculateScanRegion: (v) => {
const w = Math.min(960, v.videoWidth);
return { x: 0, y: 0, width: v.videoWidth, height: v.videoHeight,
downScaledWidth: w, downScaledHeight: Math.round((w * v.videoHeight) / v.videoWidth) };
// own camera loop: decodes the ring code, or the classic qr through qr-scanner's engine.
// calls onToken(token) for every code of this poll it reads
function makeScanner(video, onToken, onOther) {
let stream = null, running = false;
const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true });
async function loop() {
if (!running) return;
const t0 = performance.now();
if (video.readyState >= 2 && video.videoWidth) {
// 960 px is plenty and keeps low-end phones near 7 fps
const k = Math.min(1, 960 / video.videoWidth);
canvas.width = Math.round(video.videoWidth * k);
canvas.height = Math.round(video.videoHeight * k);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
try {
if (codeStyle === "ring") {
const d = decodeFrame(grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height)));
if (d.token) onToken(d.token);
} else {
qrEngine ||= await window.QrScanner.createQrEngine();
const r = await window.QrScanner.scanImage(canvas, { qrEngine, returnDetailedScanResult: true }).catch(() => null);
if (r) { const tok = tokenOf(r.data); if (tok) onToken(tok); else onOther?.(); }
}
} catch (e) { console.warn(e); }
}
// ~15 fps cap, saves battery on fast phones
setTimeout(loop, Math.max(0, 66 - (performance.now() - t0)));
}
return {
async start() {
stream = await navigator.mediaDevices.getUserMedia({
audio: false, video: { facingMode: { ideal: "environment" }, width: { ideal: 1280 }, height: { ideal: 720 } },
});
video.srcObject = stream;
await video.play();
running = true;
loop();
},
});
stop() {
running = false;
stream?.getTracks().forEach((t) => t.stop());
video.srcObject = null;
},
destroy() {},
};
}
// token of a code shown for this poll, null for anything else
@@ -97,12 +133,7 @@ function stopScanner() {
$("#cam-box").hidden = true;
}
function onScan(data) {
const token = tokenOf(data);
if (!token) {
scanMsg("QR d'un autre scrutin.", "bad");
return;
}
function onScan(token) {
if (sent.has(token)) return;
sent.add(token);
submitToken(token);
@@ -202,6 +233,7 @@ function sel(qid) {
function renderVote(st) {
lastState = st;
if (st.code_style) codeStyle = st.code_style;
const box = $("#questions");
box.replaceChildren();
let pending = 0;
@@ -293,9 +325,8 @@ function collectPresence(n) {
paint();
$("#p-msg").textContent = "";
dlg.showModal();
const sc = makeScanner($("#p-video"), (data) => {
const t = tokenOf(data);
if (!t || got.includes(t)) return;
const sc = makeScanner($("#p-video"), (t) => {
if (got.includes(t)) return;
got.push(t);
paint();
navigator.vibrate?.(15);
@@ -366,6 +397,7 @@ async function boot() {
}
if (!me.enrollment_open) return block("Inscriptions closes.");
required = me.scans_required;
codeStyle = me.code_style || "qr";
if (me.need_code) { show("#v-code"); return; }
startEnroll(me.count);
if (firstToken && !sent.has(firstToken)) { sent.add(firstToken); submitToken(firstToken); }
+6 -2
View File
@@ -26,15 +26,19 @@
<main class="s-main">
<section id="enroll" class="s-enroll" hidden>
<div class="qr-wrap">
<canvas id="qr" aria-label="QR code d'inscription, renouvelé en continu"></canvas>
<canvas id="qr" aria-label="Code d'inscription, renouvelé en continu"></canvas>
<div class="tick"><div id="tick-bar"></div></div>
</div>
<div class="s-steps">
<h2 id="qr-title">Inscription</h2>
<ol id="qr-steps">
<li><span>Scannez ce code</span></li>
<li><span id="step1">Scannez ce code</span></li>
<li><span>Visez l'écran <b id="secs">5</b>&nbsp;s</span></li>
</ol>
<div id="entry" class="entry" hidden>
<canvas id="entry-qr" aria-label="QR code de la page de vote"></canvas>
<div><b>Pas encore sur la page ?</b><span id="entry-url"></span></div>
</div>
<p id="url-warn" class="notice warn" hidden></p>
</div>
</section>
+64 -6
View File
@@ -90,8 +90,8 @@ async def projector(server, p, key=None):
async def reader():
async for raw in ws:
m = json.loads(raw)
if m["type"] == "qr":
latest.update(tok=m["url"].split("#", 1)[1], slot=m["slot"])
if m["type"] in ("qr", "ring"):
latest.update(tok=m["token"], slot=m["slot"])
changed.set()
task = asyncio.create_task(reader())
@@ -191,7 +191,7 @@ def test_full_flow_and_anonymity(server):
def test_stale_duplicate_and_forged_tokens(server):
p = create(server, scans_required=3)
p = create(server, scans_required=3, code_style="qr")
admin(server, p, "PATCH", "", json={"enrollment_open": True})
async def run():
@@ -431,7 +431,7 @@ def proxied(tmp_path_factory):
def test_behind_proxy(proxied):
fwd = {"X-Forwarded-Host": "vote.example.org", "X-Forwarded-Proto": "https"}
p = httpx.post(proxied["base"] + "/api/polls", json={"title": "P", "interval_ms": 300, "scans_required": 3}).json()
p = httpx.post(proxied["base"] + "/api/polls", json={"title": "P", "interval_ms": 300, "scans_required": 3, "code_style": "qr"}).json()
httpx.patch(f"{proxied['base']}/api/polls/{p['id']}", json={"enrollment_open": True},
headers={"authorization": f"Bearer {p['admin_key']}"})
@@ -440,9 +440,12 @@ def test_behind_proxy(proxied):
await ws.send(json.dumps({"key": p["screen_key"]}))
while True:
m = json.loads(await asyncio.wait_for(ws.recv(), 3))
if m["type"] == "entry":
entry = m
if m["type"] == "qr":
break
assert m["url"].startswith(f"https://vote.example.org/v/{p['id']}#")
assert entry["url"] == f"https://vote.example.org/v/{p['id']}"
await ws.close()
# browser origin is the public host, not the rewritten Host: must pass the origin check
v = await websockets.connect(f"{proxied['ws']}/ws/{p['id']}/voter", origin="https://vote.example.org",
@@ -574,14 +577,16 @@ def test_no_presence_qr_when_everyone_has_a_code(server):
ws = await websockets.connect(f"{server['ws']}/ws/{p['id']}/screen", **server["ws_kw"])
await ws.send(json.dumps({"key": p["screen_key"]}))
st = json.loads(await asyncio.wait_for(ws.recv(), 3))
assert st["type"] == "state" and st["presence"] is False
while st["type"] != "state":
st = json.loads(await asyncio.wait_for(ws.recv(), 3))
assert st["presence"] is False
t0 = time.time()
while time.time() - t0 < 2:
try:
m = json.loads(await asyncio.wait_for(ws.recv(), 0.5))
except asyncio.TimeoutError:
continue
assert m["type"] != "qr"
assert m["type"] not in ("qr", "ring")
await ws.close()
await a.aclose()
@@ -609,3 +614,56 @@ def test_heartbeat_survives_dead_client(server):
await alive.close()
asyncio.run(run())
def test_ring_tokens_stale_forged_and_cross_format(server):
from rotatyvote import tokens as tk
p = create(server, scans_required=3, code_style="ring")
admin(server, p, "PATCH", "", json={"enrollment_open": True})
con = sqlite3.connect(server["db"])
secret, iv = con.execute("SELECT secret, interval_ms FROM polls WHERE id=?", (p["id"],)).fetchone()
con.close()
async def run():
async with projector(server, p) as next_token:
c = device(server)
tok = await next_token()
assert tok.startswith("r")
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json()
assert r["count"] == 1 and r["accepted"]
# the same slot in the classic format is the same code: counted once
s16 = int(tok[1:].split(".")[0])
now = tk.current_slot(iv)
full = next(s for s in range(now, now - 10, -1) if s & 0xFFFF == s16)
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tk.make_token(secret, p["id"], iv, full)})).json()
assert r["valid"] and not r["accepted"] and r["count"] == 1
# forged mac, malformed
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": f"r{s16}.00000000"})).json()
assert not r["valid"]
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": "r99999999.zz"})).json()
assert not r["valid"]
# stale ring code
old = await next_token()
await asyncio.sleep(3.2)
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": old})).json()
assert not r["valid"]
# ring code of another poll
other = create(server, code_style="ring")
admin(server, other, "PATCH", "", json={"enrollment_open": True})
async with projector(server, other) as other_next:
ot = await other_next()
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": ot})).json()
assert not r["valid"]
# and a full enrollment with ring codes only
d = device(server)
assert (await scan_until(d, server, p, next_token))["status"] == "enrolled"
for x in (c, d):
await x.aclose()
asyncio.run(run())
def test_entry_redirect(server):
p = create(server)
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']}"