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
+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") {