Vote-time presence scan, rescue codes, websocket heartbeat

Each vote can require N fresh codes read off the projector (default 3,
off for rooms without a projector); voters enrolled with a paper or
rescue code are exempt. Rescue codes enroll a phone without camera.
Projector keeps the QR up while such a vote is open. Server pings every
socket every 25s so proxies keep them open. Composer no longer closes on
enter. Schema migrates existing databases.
This commit is contained in:
2026-08-16 13:48:53 +01:00
parent fca4a1194e
commit 4650db4b40
15 changed files with 427 additions and 91 deletions
+31 -9
View File
@@ -52,21 +52,43 @@
<option value="2000">2 s</option>
</select>
</div>
<div><label for="s-scans">Codes à scanner</label><input id="s-scans" type="number" min="2" max="20"></div>
<div><label for="s-scans">Codes à scanner pour s'inscrire</label><input id="s-scans" type="number" min="2" max="20"></div>
</div>
<div class="row">
<div><label for="s-expected">Personnes attendues</label><input id="s-expected" type="number" min="0" placeholder="non précisé"></div>
<div><label for="s-max">Plafond</label><input id="s-max" type="number" min="0" placeholder="aucun"></div>
</div>
</div>
<div class="card">
<label class="inline"><input id="s-code" type="checkbox"> Exiger un code papier</label>
<div id="codes-box" hidden>
<p id="codes-summary" class="muted codes-summary"></p>
<div class="linkbox">
<input id="codes-count" type="number" min="1" max="5000" value="20" aria-label="Nombre de codes à générer">
<button id="codes-gen" class="small" type="button">Générer</button>
<button id="codes-print" class="small" type="button">Imprimer</button>
<h2>Sécurité</h2>
<label for="s-vote-scans">Scan pour confirmer chaque vote</label>
<select id="s-vote-scans">
<option value="0">Désactivé (pas de vidéoprojecteur)</option>
<option value="1">1 code</option>
<option value="2">2 codes</option>
<option value="3">3 codes</option>
<option value="4">4 codes</option>
<option value="5">5 codes</option>
</select>
<label class="inline"><input id="s-code" type="checkbox"> Code papier obligatoire à l'inscription</label>
</div>
<div class="card share-list">
<div class="share-row" id="access-row">
<div><b>Codes papier</b><span class="muted" id="access-summary"></span></div>
<div class="code-actions">
<input id="access-count" type="number" min="1" max="5000" value="20" aria-label="Nombre de codes papier">
<button class="small" type="button" data-gen="access">Générer</button>
<button class="small" type="button" data-print="access">Imprimer</button>
</div>
</div>
<div class="share-row">
<div><b>Codes de secours</b><span class="muted" id="rescue-summary"></span></div>
<div class="code-actions">
<input id="rescue-count" type="number" min="1" max="5000" value="5" aria-label="Nombre de codes de secours">
<button class="small" type="button" data-gen="rescue">Générer</button>
<button class="small" type="button" data-print="rescue">Imprimer</button>
</div>
</div>
</div>
@@ -117,7 +139,7 @@
</div>
<label class="inline"><input id="q-blank" type="checkbox"> Autoriser le vote blanc</label>
<div class="actions">
<button value="cancel" type="submit" formnovalidate>Annuler</button>
<button id="q-cancel" type="button">Annuler</button>
<span class="spacer"></span>
<button id="q-draft" type="button">Garder en brouillon</button>
<button id="q-push" class="go" type="button">Lancer le vote</button>
+4 -2
View File
@@ -42,12 +42,14 @@
.q .progress { margin-top: 12px; }
.q .actions { margin-top: 14px; }
.codes-summary { margin: 10px 0; }
.code-actions { display: flex; gap: 6px; align-items: center; flex: none; }
.code-actions input { width: 76px; padding: 7px 10px; }
.card > h2 { margin-bottom: 4px; }
.share-list { padding: 6px 20px; }
.share-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 0; }
.share-row + .share-row { border-top: 1.5px solid var(--bg); }
.share-row div { display: grid; }
.share-row > div:first-child { display: grid; }
.share-row .muted { font-size: .85rem; }
#composer { border: none; border-radius: 24px; padding: 24px; width: min(94vw, 560px); background: var(--surface); color: var(--ink); }
+5 -1
View File
@@ -12,7 +12,11 @@ body.voter h1 { font-size: 1.6rem; margin-bottom: 18px; }
.scan-msg.bad { color: var(--bad); }
.scan-msg.ok { color: var(--ok); }
#code { font: 700 1.5rem var(--round); text-align: center; letter-spacing: .12em; text-transform: uppercase; }
#code, #rescue-code { font: 700 1.5rem var(--round); text-align: center; letter-spacing: .12em; text-transform: uppercase; }
button.link { display: block; margin: 12px auto 0; border: none; background: none; color: var(--ink-3); font-weight: 500; text-decoration: underline; padding: 6px; }
#presence { text-align: center; }
#presence .cam { margin-top: 0; }
#presence .actions button { flex: 1; }
.enrolled-chip { margin: -8px 0 8px; }
+1
View File
@@ -46,6 +46,7 @@
</div>
</div>
<label class="inline"><input id="vote-scans-on" type="checkbox" checked> Confirmer chaque vote par 3 scans</label>
<label class="inline"><input id="codes-on" type="checkbox"> Exiger un code papier à usage unique</label>
<div id="codes-box" hidden>
<label for="codes">Nombre de codes à générer</label>
+30 -17
View File
@@ -74,11 +74,12 @@ function renderSettings(p) {
if (active !== $("#s-scans")) $("#s-scans").value = p.scans_required;
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);
$("#s-code").checked = p.require_code;
$("#codes-box").hidden = !p.require_code;
$("#codes-summary").textContent = state.codes.total
? `${state.codes.used} utilisé${state.codes.used > 1 ? "s" : ""} sur ${state.codes.total}`
: "Aucun code généré";
$("#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);
$("#access-summary").textContent = sum(state.codes.access, "Un code par personne, avec le scan");
$("#rescue-summary").textContent = sum(state.codes.rescue, "Inscription sans caméra");
}
function renderQuestions() {
@@ -156,6 +157,9 @@ for (const t of TEMPLATES) {
onclick: () => { applyTemplate(t); $("#q-text").focus(); },
}, t.label));
}
$("#q-cancel").addEventListener("click", () => composer.close());
// enter in a field must not submit (and close) the dialog
$("#q-form").addEventListener("submit", (e) => e.preventDefault());
$("#q-kind").addEventListener("change", () => { $("#q-max-box").hidden = $("#q-kind").value !== "multi"; });
async function submitQuestion(open) {
@@ -197,6 +201,7 @@ const SETTINGS = {
"#s-expected": (el) => ({ expected: intOrNull(el.value) }),
"#s-max": (el) => ({ max_voters: intOrNull(el.value) }),
"#s-code": (el) => ({ require_code: el.checked }),
"#s-vote-scans": (el) => ({ vote_scans: +el.value }),
};
for (const [sel, build] of Object.entries(SETTINGS)) {
$(sel).addEventListener("change", async (e) => {
@@ -205,19 +210,27 @@ for (const [sel, build] of Object.entries(SETTINGS)) {
});
}
$("#codes-gen").addEventListener("click", async () => {
try {
await call("POST", "/codes", { count: +$("#codes-count").value });
toast("Codes générés");
} catch (e) { toast(errMsg(e), "bad"); }
});
$("#codes-print").addEventListener("click", async () => {
const { codes } = await call("GET", "/codes");
$("#codes-title").textContent = `Codes d'accès, ${state.poll.title}`;
$("#codes-grid").replaceChildren(...codes.map((c) => h("div", { class: "code-cell" + (c.used ? " used" : "") }, c.code)));
$("#codes-sheet").hidden = false;
$("#codes-sheet").scrollIntoView({ behavior: "smooth" });
});
const CODE_LABEL = { access: "Codes papier", rescue: "Codes de secours" };
for (const b of document.querySelectorAll("[data-gen]")) {
b.addEventListener("click", async () => {
const kind = b.dataset.gen;
try {
await call("POST", "/codes", { count: +$(`#${kind}-count`).value, rescue: kind === "rescue" });
toast(`${CODE_LABEL[kind]} générés`);
} catch (e) { toast(errMsg(e), "bad"); }
});
}
for (const b of document.querySelectorAll("[data-print]")) {
b.addEventListener("click", async () => {
const kind = b.dataset.print;
const { codes } = await call("GET", "/codes");
const list = codes.filter((c) => Boolean(c.rescue) === (kind === "rescue"));
$("#codes-title").textContent = `${CODE_LABEL[kind]}, ${state.poll.title}`;
$("#codes-grid").replaceChildren(...list.map((c) => h("div", { class: "code-cell" + (c.used ? " used" : "") }, c.code)));
$("#codes-sheet").hidden = false;
$("#codes-sheet").scrollIntoView({ behavior: "smooth" });
});
}
$("#codes-close").addEventListener("click", () => { $("#codes-sheet").hidden = true; });
$("#codes-do-print").addEventListener("click", () => window.print());
+1
View File
@@ -25,6 +25,7 @@ $("#form").addEventListener("submit", async (e) => {
expected: $("#expected").value ? +$("#expected").value : null,
max_voters: $("#maxv").value ? +$("#maxv").value : null,
require_code: $("#codes-on").checked,
vote_scans: $("#vote-scans-on").checked ? 3 : 0,
codes: $("#codes-on").checked ? +$("#codes").value : 0,
password: $("#pw").value || undefined,
});
+8 -5
View File
@@ -8,12 +8,15 @@ let raf = 0;
function layout() {
if (!st) return;
const enroll = st.enrollment_open;
// qr stays up while enrolling, and during a vote that needs a presence scan
const qrOn = st.enrollment_open || st.presence;
const focus = st.focus;
$("#enroll").hidden = !enroll;
$("#enroll").hidden = !qrOn;
$("#focus").hidden = !focus;
$("#idle").hidden = enroll || !!focus;
$(".s-main").classList.toggle("split", enroll && !!focus);
$("#idle").hidden = qrOn || !!focus;
$(".s-main").classList.toggle("split", qrOn && !!focus);
$("#qr-title").textContent = st.enrollment_open ? "Inscription" : "Scannez pour voter";
$("#qr-steps").hidden = !st.enrollment_open;
}
function render() {
@@ -75,7 +78,7 @@ liveSocket(`/ws/${pid}/screen`, {
onMessage(msg) {
if (msg.type === "state") {
st = msg;
if (!st.enrollment_open) qr = null;
if (!st.enrollment_open && !st.presence) qr = null;
render();
} else if (msg.type === "qr") {
// server clock drives validity, estimate offset so the countdown bar is right
+86 -21
View File
@@ -18,7 +18,7 @@ let lastState = null;
let lastJson = "";
function show(id) {
for (const s of ["#v-loading", "#v-enroll", "#v-code", "#v-blocked", "#v-vote"]) $(s).hidden = s !== id;
for (const s of ["#v-loading", "#v-enroll", "#v-code", "#v-rescue", "#v-blocked", "#v-vote"]) $(s).hidden = s !== id;
}
function block(msg) {
@@ -50,17 +50,7 @@ async function startScanner() {
return;
}
$("#cam-box").hidden = false;
scanner = new window.QrScanner($("#video"), (r) => onScan(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) };
},
});
scanner = makeScanner($("#video"), onScan);
try {
await scanner.start();
$("#start-cam").hidden = true;
@@ -76,6 +66,29 @@ 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) };
},
});
}
// token of a code shown for this poll, null for anything else
function tokenOf(data) {
let u;
try { u = new URL(data); } catch { return null; }
const parts = u.pathname.split("/").filter(Boolean);
if (parts[0] !== "v" || parts[1] !== pid) return null;
return decodeURIComponent(u.hash.slice(1)) || null;
}
function stopScanner() {
if (!scanner) return;
scanner.stop();
@@ -85,15 +98,12 @@ function stopScanner() {
}
function onScan(data) {
let u;
try { u = new URL(data); } catch { return; }
const parts = u.pathname.split("/").filter(Boolean);
if (parts[0] !== "v" || parts[1] !== pid) {
const token = tokenOf(data);
if (!token) {
scanMsg("QR d'un autre scrutin.", "bad");
return;
}
const token = decodeURIComponent(u.hash.slice(1));
if (!token || sent.has(token)) return;
if (sent.has(token)) return;
sent.add(token);
submitToken(token);
}
@@ -142,6 +152,22 @@ function enrolled() {
$("#start-cam").addEventListener("click", startScanner);
$("#no-cam").addEventListener("click", () => { stopScanner(); show("#v-rescue"); $("#rescue-code").focus(); });
$("#rescue-back").addEventListener("click", () => startEnroll(0));
$("#rescue-form").addEventListener("submit", async (e) => {
e.preventDefault();
const msg = $("#rescue-msg");
try {
const r = await api("POST", `${apiBase}/rescue`, { code: $("#rescue-code").value });
if (r.status === "enrolled") return enrolled();
msg.className = "scan-msg bad";
msg.textContent = { bad_code: "Code invalide ou déjà utilisé.", closed: "Inscriptions closes.", full: "Nombre maximal d'inscriptions atteint." }[r.status] || r.status;
} catch (err) {
msg.className = "scan-msg bad";
msg.textContent = `Erreur : ${err.message}`;
}
});
$("#code-form").addEventListener("submit", async (e) => {
e.preventDefault();
const msg = $("#code-msg");
@@ -241,20 +267,59 @@ async function confirmVote(q) {
dlg.showModal();
await new Promise((res) => dlg.addEventListener("close", res, { once: true }));
if (dlg.returnValue !== "ok") return;
let presence;
if (lastState.vote_scans > 0) {
presence = await collectPresence(lastState.vote_scans);
if (!presence) return;
}
try {
await api("POST", `${apiBase}/vote`, { question_id: q.id, choices: s.blank ? [] : choices });
await api("POST", `${apiBase}/vote`, { question_id: q.id, choices: s.blank ? [] : choices, presence });
selections.delete(q.id);
toast("Vote enregistré", "ok");
navigator.vibrate?.(60);
} catch (e) {
const m = { already_voted: "Déjà voté.", not_open: "Vote clos.", not_enrolled: "Appareil non inscrit." };
const m = { already_voted: "Déjà voté.", not_open: "Vote clos.", not_enrolled: "Appareil non inscrit.",
presence_required: "Scan expiré, revotez en visant l'écran." };
toast(m[e.code] || `Erreur : ${e.message}`, "bad");
}
}
// proof of presence at vote time: read n distinct codes off the projector, resolve with them
// (or null if cancelled). the server checks freshness
function collectPresence(n) {
const dlg = $("#presence");
const got = [];
const paint = () => $("#p-ring").replaceChildren(ring(got.length, n, 120));
paint();
$("#p-msg").textContent = "";
dlg.showModal();
const sc = makeScanner($("#p-video"), (data) => {
const t = tokenOf(data);
if (!t || got.includes(t)) return;
got.push(t);
paint();
navigator.vibrate?.(15);
if (got.length >= n) finish(got);
});
let done, finished = false;
const result = new Promise((res) => { done = res; });
function finish(value) {
if (finished) return;
finished = true;
sc.stop();
sc.destroy();
if (dlg.open) dlg.close();
done(value);
}
dlg.addEventListener("close", () => finish(null), { once: true });
sc.start().catch(() => { $("#p-msg").textContent = "Autorisez la caméra puis réessayez."; });
return result;
}
$("#p-cancel").addEventListener("click", () => $("#presence").close());
function connect() {
if (socket) return;
$("#conn").hidden = false;
socket = liveSocket(`/ws/${pid}/voter`, {
onMessage(msg) {
if (msg.type === "state") {
+2 -2
View File
@@ -30,8 +30,8 @@
<div class="tick"><div id="tick-bar"></div></div>
</div>
<div class="s-steps">
<h2>Inscription</h2>
<ol>
<h2 id="qr-title">Inscription</h2>
<ol id="qr-steps">
<li><span>Scannez ce code</span></li>
<li><span>Visez l'écran <b id="secs">5</b>&nbsp;s</span></li>
</ol>
+23 -1
View File
@@ -29,6 +29,7 @@
</div>
<p id="scan-msg" class="scan-msg muted"></p>
<button id="start-cam" class="primary block" type="button">Activer la caméra</button>
<button id="no-cam" class="link" type="button">Caméra indisponible ?</button>
</div>
<p class="hint center">Vote anonyme</p>
</section>
@@ -37,7 +38,7 @@
<div class="card">
<p>Saisissez votre code papier.</p>
<form id="code-form">
<input id="code" type="text" inputmode="text" autocomplete="one-time-code" autocapitalize="characters"
<input id="code" type="text" autocomplete="one-time-code" autocapitalize="characters"
maxlength="12" placeholder="XXXX-XXXX" aria-label="Code d'accès">
<div class="actions"><button class="primary block" type="submit">Valider</button></div>
</form>
@@ -45,6 +46,19 @@
</div>
</section>
<section id="v-rescue" hidden>
<div class="card">
<p>Saisissez le code de secours remis par l'équipe organisatrice.</p>
<form id="rescue-form">
<input id="rescue-code" type="text" autocomplete="one-time-code" autocapitalize="characters"
maxlength="12" placeholder="XXXX-XXXX" aria-label="Code de secours">
<div class="actions"><button class="primary block" type="submit">Valider</button></div>
</form>
<p id="rescue-msg" class="scan-msg"></p>
<button id="rescue-back" class="link" type="button">Revenir au scan</button>
</div>
</section>
<section id="v-blocked" hidden>
<div class="notice bad" id="blocked-msg"></div>
</section>
@@ -68,5 +82,13 @@
</div>
</form>
</dialog>
<dialog id="presence">
<h2>Visez l'écran</h2>
<div id="p-ring" class="dots"></div>
<div class="cam"><video id="p-video" playsinline muted></video></div>
<p id="p-msg" class="scan-msg bad"></p>
<div class="actions"><button id="p-cancel" type="button">Annuler</button></div>
</dialog>
</body>
</html>