diff --git a/rotatyvote/app.py b/rotatyvote/app.py
index 41884aa..8bc0d0f 100644
--- a/rotatyvote/app.py
+++ b/rotatyvote/app.py
@@ -52,7 +52,7 @@ def clear_attempts(pid):
# camera app scans, in memory like attempts: (pid, voter id) -> pass end, claim nonce -> (pid, minted at)
passes: dict[tuple[str, str], int] = {}
-claims: dict[str, tuple[str, int]] = {}
+claims: dict[str, tuple[str, int, int]] = {} # nonce -> (pid, minted at, ms the code was off screen)
def grant_pass(pid, vid):
@@ -67,16 +67,27 @@ def has_pass(pid, vid):
return passes.get((pid, vid), 0) >= now_ms()
-def mint_claim(pid):
+def mint_claim(pid, late):
now = now_ms()
if len(claims) > 20000:
- for k in [k for k, (_, t) in claims.items() if now - t > config.PASS_CLAIM_TTL_MS]:
+ for k in [k for k, (_, t, _) in claims.items() if now - t > config.PASS_CLAIM_TTL_MS]:
del claims[k]
nonce = new_key()
- claims[nonce] = (pid, now)
+ claims[nonce] = (pid, now, late)
return nonce
+def pass_on(p):
+ # the classic qr is the camera app code itself, it can't be turned off there
+ return bool(p["camera_pass"]) or p["code_style"] == "qr"
+
+
+def pass_late(p, tok):
+ """ms since the camera app code left the screen (<= 0 still shown), None if forged or past PASS_GRACE_MS"""
+ slot = verify_pass(p["secret"], p["id"], tok[:40], config.PASS_ROTATE_MS, config.PASS_GRACE_MS)
+ return None if slot is None else now_ms() - (slot + 1) * config.PASS_ROTATE_MS
+
+
def q_public(q, with_results: bool):
d = {
"id": q["id"], "text": q["text"], "kind": q["kind"], "options": json.loads(q["options"]),
@@ -101,6 +112,7 @@ def admin_state(pid):
"max_voters": p["max_voters"], "expected": p["expected"],
"require_code": bool(p["require_code"]), "focus_qid": p["focus_qid"],
"vote_scans": p["vote_scans"], "code_style": p["code_style"], "entry_big": bool(p["entry_big"]),
+ "camera_pass": bool(p["camera_pass"]),
},
"voters": db.voter_count(pid),
"codes": codes_summary(pid),
@@ -146,7 +158,7 @@ def screen_state(pid):
"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"], "code_style": p["code_style"],
- "entry_big": bool(p["entry_big"]),
+ "entry_big": bool(p["entry_big"]), "camera_pass": pass_on(p),
}
@@ -161,7 +173,7 @@ def voter_state(pid, voter):
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,
- "code_style": p["code_style"]}
+ "code_style": p["code_style"], "camera_pass": pass_on(p)}
def qr_modules(url: str, error="m"):
@@ -177,6 +189,9 @@ def entry_qr(base: str, p, slot: int):
"""qr for the phone's camera app: opens the voting page and proves presence (/V/pid/code redirects).
upper case keeps it in qr alphanumeric mode, a smaller symbol"""
pid, rot = p["id"], config.PASS_ROTATE_MS
+ if not pass_on(p):
+ # camera app scans turned off: a plain link to the page, it never changes
+ return {"type": "entry", "modules": qr_modules(f"{base}/V/{pid}".upper(), error="q"), "url": f"{base}/v/{pid}"}
url = f"{base}/V/{pid}/{make_pass(p['secret'], pid, slot)}".upper()
# level q survives a glare patch or a smudge on a quarter of the symbol. 33 modules w/ the code
return {"type": "entry", "modules": qr_modules(url, error="q"), "url": f"{base}/v/{pid}",
@@ -283,7 +298,7 @@ class Hub:
await self.send_entry(p, screens, ps, "qr")
await asyncio.sleep(max(0.01, ((ps + 1) * config.PASS_ROTATE_MS - now_ms()) / 1000))
continue
- if ps != last_pass:
+ if ps != last_pass and pass_on(p):
last_pass = ps
await self.send_entry(p, screens, ps)
iv = p["interval_ms"]
@@ -452,7 +467,8 @@ async def create_poll(request: Request):
pid, admin_key, screen_key = db.create_poll(title, interval, scans, bool(d.get("require_code")),
expected, max_voters, vote_scans, code_style)
# the giant entry qr beside the ring is the default: people open the page from the back rows
- db.update_poll(pid, entry_big=int(d.get("entry_big", True) is not False))
+ db.update_poll(pid, entry_big=int(d.get("entry_big", True) is not False),
+ camera_pass=int(d.get("camera_pass", True) is not False))
for q in questions:
db.add_question(pid, *q)
codes = int(d.get("codes") or 0)
@@ -507,6 +523,8 @@ async def admin_patch(request: Request):
upd["code_style"] = d["code_style"]
if "entry_big" in d:
upd["entry_big"] = int(bool(d["entry_big"]))
+ if "camera_pass" in d:
+ upd["camera_pass"] = int(bool(d["camera_pass"]))
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:
@@ -518,6 +536,9 @@ async def admin_patch(request: Request):
if any(k in upd for k in ("interval_ms", "scans_required", "require_code")) or upd.get("enrollment_open") == 0:
# rules changed mid-way: half-done attempts start over
clear_attempts(pid)
+ if ("camera_pass" in upd or "code_style" in upd) and hub.screens.get(pid):
+ # switched off: the rotating qr on screen must turn back into the plain link now, not at the next tick
+ await hub.send_entry(db.poll(pid), hub.screens[pid], pass_slot())
hub.refresh(pid, voters=True)
return JSONResponse({"ok": True})
@@ -647,7 +668,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"],
+ "code_style": p["code_style"], "camera_pass": pass_on(p),
"count": len(a.slots) if a else 0,
})
@@ -738,10 +759,12 @@ async def camera_pass(request: Request):
from another app, so check the code now and hand the page a one-time claim it redeems with its cookies"""
pid = request.path_params["pid"].lower()
p = db.poll(pid)
- ok = p and verify_pass(p["secret"], pid, request.path_params["tok"][:40], config.PASS_ROTATE_MS,
- config.PASS_GRACE_MS) is not None
+ if p and not pass_on(p):
+ return RedirectResponse(f"/v/{pid}", status_code=303)
+ late = pass_late(p, request.path_params["tok"]) if p else None
# 303 + the no-store every response gets: the camera app never reuses an old redirect
- return RedirectResponse(f"/v/{pid}#" + (f"c={mint_claim(pid)}" if ok else "cam=expired"), status_code=303)
+ return RedirectResponse(f"/v/{pid}#" + (f"c={mint_claim(pid, late)}" if late is not None else "cam=expired"),
+ status_code=303)
async def voter_pass(request: Request):
@@ -750,14 +773,15 @@ async def voter_pass(request: Request):
pid = request.path_params["pid"]
p = get_poll(pid)
d = await body(request)
+ if not pass_on(p):
+ return JSONResponse({"status": "off"})
now = now_ms()
if d.get("claim"):
c = claims.pop(str(d["claim"])[:64], None)
- ok = bool(c) and c[0] == pid and now - c[1] <= config.PASS_CLAIM_TTL_MS
+ late = c[2] if c and c[0] == pid and now - c[1] <= config.PASS_CLAIM_TTL_MS else None
else:
- ok = verify_pass(p["secret"], pid, str(d.get("token", ""))[:40], config.PASS_ROTATE_MS,
- config.PASS_GRACE_MS) is not None
- if not ok:
+ late = pass_late(p, str(d.get("token", "")))
+ if late is None:
return JSONResponse({"status": "expired"})
v = current_voter(request, pid)
if v:
@@ -765,6 +789,9 @@ async def voter_pass(request: Request):
return JSONResponse({"status": "pass", "hold_ms": config.PASS_HOLD_MS})
if not p["enrollment_open"]:
return JSONResponse({"status": "closed"})
+ # joining is where a forwarded link hurts most: the code must be read almost live
+ if late > config.PASS_ENROLL_GRACE_MS:
+ return JSONResponse({"status": "late"})
att_id, a, fresh_cookie = _attempt(request, pid)
a.last_ms = a.presence_ms = now
if p["require_code"]:
diff --git a/rotatyvote/config.py b/rotatyvote/config.py
index 0c58fbd..92bef9f 100644
--- a/rotatyvote/config.py
+++ b/rotatyvote/config.py
@@ -26,9 +26,11 @@ CODE_ENTRY_TTL_S = 180
HEARTBEAT_S = float(os.environ.get("HEARTBEAT_S", "25"))
# entry qr read by the phone's own camera app: one scan proves presence (browsers with the camera blocked).
-# a new code every 3 s, each one opens the page for 3 + 12 s, and a scan covers votes for 10 s
+# a new code every 3 s. once off the screen it still validates a vote for 12 s, an enrollment for 4 s only,
+# and a scan covers votes for 10 s
PASS_ROTATE_MS = 3000
PASS_GRACE_MS = 12000
+PASS_ENROLL_GRACE_MS = 4000
PASS_HOLD_MS = int(os.environ.get("PASS_HOLD_MS", "10000"))
# the redirect hands the page a one-time claim: slow page loads on a crowded network don't eat the window
PASS_CLAIM_TTL_MS = 20000
diff --git a/rotatyvote/db.py b/rotatyvote/db.py
index d14ffa2..61a8bfd 100644
--- a/rotatyvote/db.py
+++ b/rotatyvote/db.py
@@ -91,6 +91,7 @@ class DB:
("questions", "shown", "INTEGER NOT NULL DEFAULT 0"),
("polls", "entry_big", "INTEGER NOT NULL DEFAULT 0"),
("questions", "extra", "TEXT"),
+ ("polls", "camera_pass", "INTEGER NOT NULL DEFAULT 1"),
):
cols = {r[1] for r in self.c.execute(f"PRAGMA table_info({table})")}
if col not in cols:
@@ -147,7 +148,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", "code_style", "entry_big"}
+ "expected", "require_code", "focus_qid", "vote_scans", "code_style", "entry_big", "camera_pass"}
fields = {k: v for k, v in fields.items() if k in allowed}
if not fields:
return
diff --git a/static/admin.html b/static/admin.html
index f82f726..bb97022 100644
--- a/static/admin.html
+++ b/static/admin.html
@@ -47,6 +47,11 @@
+
+
+
+
diff --git a/static/js/admin.js b/static/js/admin.js
index 3685ab0..ce8f764 100644
--- a/static/js/admin.js
+++ b/static/js/admin.js
@@ -80,6 +80,9 @@ function renderSettings(p) {
if (active !== $("#s-code-style")) $("#s-code-style").value = p.code_style;
if (active !== $("#s-entry-big")) $("#s-entry-big").value = p.entry_big ? "1" : "0";
$("#s-entry-big").disabled = p.code_style !== "ring";
+ if (active !== $("#s-camera")) $("#s-camera").value = p.camera_pass ? "1" : "0";
+ // the classic qr is the camera app code itself
+ $("#s-camera").disabled = p.code_style !== "ring";
$("#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);
@@ -239,6 +242,7 @@ const SETTINGS = {
"#s-vote-scans": (el) => ({ vote_scans: +el.value }),
"#s-code-style": (el) => ({ code_style: el.value }),
"#s-entry-big": (el) => ({ entry_big: el.value === "1" }),
+ "#s-camera": (el) => ({ camera_pass: el.value === "1" }),
};
for (const [sel, build] of Object.entries(SETTINGS)) {
$(sel).addEventListener("change", async (e) => {
diff --git a/static/js/index.js b/static/js/index.js
index 595e08e..1614fe4 100644
--- a/static/js/index.js
+++ b/static/js/index.js
@@ -4,6 +4,8 @@ const cfg = await api("GET", "/api/config").catch(() => ({}));
$("#pw-box").hidden = !cfg.create_password;
$("#codes-on").addEventListener("change", (e) => { $("#codes-box").hidden = !e.target.checked; });
+// the classic qr is the camera app code itself
+$("#code-style").addEventListener("change", (e) => { $("#camera").disabled = e.target.value !== "ring"; });
$("#form").addEventListener("submit", async (e) => {
e.preventDefault();
@@ -15,6 +17,7 @@ $("#form").addEventListener("submit", async (e) => {
interval_ms: +$("#interval").value,
scans_required: +$("#scans").value,
code_style: $("#code-style").value,
+ camera_pass: $("#camera").value === "1",
expected: $("#expected").value ? +$("#expected").value : null,
max_voters: $("#maxv").value ? +$("#maxv").value : null,
require_code: $("#codes-on").checked,
diff --git a/static/js/screen.js b/static/js/screen.js
index c09b77e..aa60977 100644
--- a/static/js/screen.js
+++ b/static/js/screen.js
@@ -53,11 +53,12 @@ function layout() {
const qrOn = st.enrollment_open || st.presence;
const ring = st.code_style === "ring";
// the camera app code: enrolls, and proves presence for a vote, so it stays up whenever the ring does
- const entryOn = !!(ring && qrOn && entry);
+ const cam = st.camera_pass !== false;
+ const entryOn = !!(ring && entry && (st.enrollment_open || (cam && st.presence)));
// with the big qr on, a vote waiting for scans (or closed with nothing to show) moves above it
const f = st.focus, idleVote = f && f.state === "closed" && !f.results;
// an upright screen has no room for the question above the qr (.entry-q hidden): it keeps its own block
- const openVote = f && f.state === "open" && st.presence && !matchMedia("(max-aspect-ratio: 1/1)").matches;
+ const openVote = cam && f && f.state === "open" && st.presence && !matchMedia("(max-aspect-ratio: 1/1)").matches;
const big = entryOn && st.entry_big && (!f || idleVote || openVote);
const focus = big ? null : f;
reveal($("#enroll"), qrOn);
@@ -68,7 +69,7 @@ function layout() {
// a vote waiting for presence scans takes the title, even while late arrivals can still enroll
$("#qr-title").textContent = st.presence || !st.enrollment_open ? (ring ? "Visez le cercle pour voter" : "Scannez pour voter") : "Inscription";
$("#qr-steps").hidden = !st.enrollment_open;
- $("#step1").textContent = ring ? "Scannez le QR avec l'appareil photo" : "Scannez avec l'appareil photo";
+ $("#step1").textContent = ring ? (cam ? "Scannez le QR avec l'appareil photo" : "Ouvrez la page de vote") : "Scannez avec l'appareil photo";
$("#step2").hidden = !ring;
reveal($("#entry"), entryOn);
document.body.classList.toggle("has-entry", entryOn);
@@ -76,16 +77,23 @@ function layout() {
const showQ = big && !!f;
document.body.classList.toggle("entry-q-on", showQ);
$("#entry-q").hidden = !showQ;
+ // an open vote keeps its options and turnout bar on screen, just above the qr
+ const opts = showQ && !!openVote;
+ document.body.classList.toggle("entry-opts-on", opts);
+ $("#entry-q-opts").hidden = !opts;
+ $("#entry-q-turnout").hidden = !opts;
+ $("#entry-q-count").hidden = opts;
if (showQ) {
$("#entry-q-text").textContent = f.text;
- if (openVote) {
- const all = f.participants + (f.extra_ballots || 0);
- $("#entry-q-count").textContent = `${all} vote${all > 1 ? "s" : ""} sur ${st.voters + (f.extra_ballots || 0)}`;
+ if (opts) {
+ const ul = $("#entry-q-opts"), key = JSON.stringify(f.options);
+ if (ul.dataset.key !== key) { ul.dataset.key = key; ul.replaceChildren(...f.options.map((o) => h("li", {}, o))); }
+ paintTurnout($("#entry-q-turnout"), f);
} else {
$("#entry-q-count").textContent = `Vote clos, ${f.participants} bulletin${f.participants > 1 ? "s" : ""}`;
}
}
- $("#entry-hint").textContent = "Scannez avec l'appareil photo";
+ $("#entry-hint").textContent = cam ? "Scannez avec l'appareil photo" : big ? "Scannez ici, puis visez le cercle" : "Pas encore sur la page ?";
$(".qr-wrap").classList.toggle("ring", ring);
flip(entryEl, before);
}
diff --git a/static/js/vote.js b/static/js/vote.js
index 490e7c9..a9e1c86 100644
--- a/static/js/vote.js
+++ b/static/js/vote.js
@@ -6,6 +6,8 @@ const DONE_KEY = `rv_done_${pid}`;
const apiBase = `/api/v/${pid}`;
const PENDING_KEY = `rv_pending_${pid}`;
+const ARRIVED_KEY = `rv_arrived_${pid}`;
+const VIA_QR = "Avec la caméra native, via le QR";
// the camera app redirect leaves a one-time claim (or why there is none) in the hash. off the url bar at once
const hash = new URLSearchParams(location.hash.slice(1));
@@ -14,6 +16,7 @@ if (location.hash) history.replaceState(null, "", location.pathname);
// a camera app scan covers votes for a few seconds (server PASS_HOLD_MS, minus the round trip)
let passUntil = 0;
let presenceFor = null;
+let camPass = true; // organizers can turn the camera app way off
let scanner = null;
let required = 5;
@@ -59,17 +62,20 @@ function scanMsg(text, kind = "") {
// the camera app way: a quiet line under a working scanner, step by step without one.
// people are already on the page, so it has to say why they leave it and what happens after
function camAlt(el, solo, vote = false) {
+ el.hidden = !camPass;
el.classList.toggle("solo", solo);
if (!solo) {
- el.replaceChildren(icon("camera", 18), h("span", {}, "Ça ne marche pas ? Scannez le grand QR de l'écran avec l'appareil photo."));
+ el.replaceChildren(icon("camera", 18), h("span", {}, "Ça ne marche pas ? Rouvrez votre scanneur de code QR et scannez le grand QR."));
return;
}
+ // "re-open": the same scanner that brought them here, not something new to find
// the vote dialog has the heading in its own title
- el.replaceChildren(icon("camera", 36), vote ? "" : h("b", {}, "Inscrivez-vous avec l'appareil photo"),
+ el.replaceChildren(icon("camera", 36), vote ? "" : h("b", {}, "Confirmez avec votre scanneur de code QR"),
h("ol", {},
- h("li", {}, "Quittez cette page et ouvrez l'appareil photo du téléphone."),
+ h("li", {}, "Rouvrez votre scanneur de code QR, celui qui vous a amené·e ici."),
h("li", {}, "Scannez le grand QR de l'écran."),
- h("li", {}, vote ? "Touchez le lien qui s'affiche. Votre vote part tout seul." : "Touchez le lien qui s'affiche. Vous êtes inscrit·e.")));
+ // joining only takes a code that left the screen less than 4 s ago
+ h("li", {}, vote ? "Touchez le lien qui s'affiche. Votre vote part tout seul." : "Touchez tout de suite le lien qui s'affiche. Vous êtes inscrit·e.")));
}
async function startScanner() {
@@ -302,7 +308,7 @@ async function afterPass(r) {
switch (r.status) {
case "enrolled":
passUntil = Date.now() + 8000;
- enrolled();
+ enrolled(true);
break;
case "pass": {
passUntil = Date.now() + (r.hold_ms || 10000) - 1500;
@@ -325,6 +331,9 @@ async function afterPass(r) {
case "expired":
toast("QR expiré, scannez-le à nouveau.", "bad");
break;
+ case "late":
+ toast("Lien ouvert trop tard. Rescannez et touchez le lien tout de suite.", "bad");
+ break;
}
}
@@ -367,17 +376,17 @@ function handleScan(r) {
}
}
-function enrolled() {
+function enrolled(viaCam = false) {
stopScanner();
lsSet(DONE_KEY, "1");
navigator.vibrate?.([40, 60, 40]);
- celebrate("Inscription validée");
+ celebrate("Inscription validée", viaCam ? VIA_QR : "");
boot();
}
// the projector's center mark with its check, drawn in, held a moment, then gone
const MARK_NS = "http://www.w3.org/2000/svg";
-function celebrate(text) {
+function celebrate(text, sub = "") {
const svg = document.createElementNS(MARK_NS, "svg");
svg.setAttribute("viewBox", "0 0 32 32");
svg.setAttribute("aria-hidden", "true");
@@ -393,10 +402,12 @@ function celebrate(text) {
for (const [k, v] of Object.entries({ d: "M12.8 16.15l2.3 2.3 4.25-4.75", fill: "none", stroke: "currentColor", "stroke-width": 2.4,
"stroke-linecap": "round", "stroke-linejoin": "round", pathLength: 1, class: "tick" })) tick.setAttribute(k, v);
svg.append(g, tick);
- const el = h("div", { class: "celebrate", role: "status" }, svg, h("p", {}, text));
+ const el = h("div", { class: "celebrate", role: "status" }, svg, h("p", {}, text), sub ? h("small", {}, sub) : "");
document.body.append(el);
- setTimeout(() => el.classList.add("out"), 1300);
- setTimeout(() => el.remove(), 1700);
+ // a second line takes longer to read
+ const hold = sub ? 2000 : 1300;
+ setTimeout(() => el.classList.add("out"), hold);
+ setTimeout(() => el.remove(), hold + 400);
}
$("#start-cam").addEventListener("click", startScanner);
@@ -526,7 +537,7 @@ async function castVote(q, choices, retried = false) {
let presence;
if (lastState.vote_scans > 0 && Date.now() > passUntil) {
// kept for the tab the camera app opens, which sends it on its own
- lsSet(PENDING_KEY, JSON.stringify({ qid: q.id, choices, at: Date.now() }));
+ if (camPass) lsSet(PENDING_KEY, JSON.stringify({ qid: q.id, choices, at: Date.now() }));
presence = await collectPresence(lastState.vote_scans, q.id);
// cancelled (or voted from the other tab): a later scan must not cast a choice left behind
if (!presence) {
@@ -538,7 +549,8 @@ async function castVote(q, choices, retried = false) {
await api("POST", `${apiBase}/vote`, { question_id: q.id, choices, presence });
try { localStorage.removeItem(PENDING_KEY); } catch { /* private mode */ }
selections.delete(q.id);
- celebrate("Vote enregistré");
+ // no codes sent while some were due: the camera app scan covered it
+ celebrate("Vote enregistré", !presence && lastState.vote_scans > 0 ? VIA_QR : "");
navigator.vibrate?.(60);
} catch (e) {
// the camera app scan ran out on the server side: scan again
@@ -600,9 +612,14 @@ function collectPresence(n, qid) {
dlg.addEventListener("close", () => finish(null), { once: true });
// no camera here: the camera app opens a new tab that sends the kept choice
sc.start().catch((e) => {
- $("#p-title").textContent = "Validez avec l'appareil photo";
- $("#p-msg").textContent = camError(e);
$("#p-scan").hidden = true;
+ if (!camPass) {
+ // no camera and no camera app way: the desk can still count this vote by hand (votes en plus)
+ $("#p-msg").textContent = `${camError(e)} Sinon, signalez-vous à la tribune.`;
+ return;
+ }
+ $("#p-title").textContent = "Validez avec votre scanneur de code QR";
+ $("#p-msg").textContent = camError(e);
camAlt($("#p-alt"), true, true);
});
return result;
@@ -621,6 +638,7 @@ function connect() {
lastJson = j;
show("#v-vote");
$("#title").textContent = msg.title;
+ camPass = msg.camera_pass !== false;
renderVote(msg);
}
else if (msg.type === "not_enrolled") { socket?.close(); socket = null; boot(); }
@@ -645,6 +663,8 @@ async function boot() {
}
$("#title").textContent = me.title;
document.title = me.title;
+ camPass = me.camera_pass !== false;
+ camAlt($("#enroll-alt"), $("#enroll-alt").classList.contains("solo"));
if (me.enrolled) {
lsSet(DONE_KEY, "1");
show("#v-vote");
@@ -665,12 +685,12 @@ async function boot() {
}
async function start() {
- // the claim goes first: it may enroll this phone before the page asks who it is
- const r = claim ? await redeem({ claim }) : null;
- if (r?.status === "enrolled") { lsSet(DONE_KEY, "1"); celebrate("Inscription validée"); passUntil = Date.now() + 8000; }
await boot();
- if (r && r.status !== "enrolled") afterPass(r);
+ // the scan that brings someone here only opens the page: joining takes the ring, or a second scan
+ const arrived = +lsGet(ARRIVED_KEY) > Date.now() - 3 * 3600e3;
+ if (claim && (lastState || arrived)) afterPass(await redeem({ claim }));
else if (camExpired) afterPass({ status: "expired" });
+ if (!lastState) lsSet(ARRIVED_KEY, String(Date.now()));
}
camAlt($("#enroll-alt"), false);
diff --git a/static/screen.html b/static/screen.html
index 5821723..0cf6853 100644
--- a/static/screen.html
+++ b/static/screen.html
@@ -33,7 +33,7 @@
Inscription
Scannez ce code
-
Ou visez le cercle 5 s
+
Visez le cercle 5 s
@@ -48,7 +48,15 @@
diff --git a/tests/test_e2e.py b/tests/test_e2e.py
index 7fcf9a6..ce03a68 100644
--- a/tests/test_e2e.py
+++ b/tests/test_e2e.py
@@ -790,6 +790,10 @@ def test_camera_app_scan_enrolls_and_covers_votes(server):
con.close()
stale = tk.make_pass(secret, p["id"], e["slot"] - 6)
assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": stale})).json()["status"] == "expired"
+ # gone from the screen 6 s ago: too late to join (4 s), still fine for a vote (12 s)
+ recent = tk.make_pass(secret, p["id"], tk.current_slot(3000) - 3)
+ assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": recent})).json()["status"] == "late"
+ assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": recent})).json()["status"] == "pass"
# late arrival after enrollment closed: nothing to do here
admin(server, p, "PATCH", "", json={"enrollment_open": False})
e = await camera_code(server, p)
@@ -828,3 +832,23 @@ def test_classic_qr_is_the_camera_code(server):
await a.aclose()
asyncio.run(run())
+
+
+def test_camera_app_scan_can_be_turned_off(server):
+ p = create(server, camera_pass=False)
+ admin(server, p, "PATCH", "", json={"enrollment_open": True})
+ assert admin(server, p, "GET", "").json()["poll"]["camera_pass"] is False
+
+ async def run():
+ e = await camera_code(server, p)
+ assert "token" not in e and len(e["modules"]) == 29
+ a = device(server)
+ r = await a.get(f"/V/{p['id']}/1-AAAAAAAAAA", follow_redirects=False)
+ assert r.headers["location"] == f"/v/{p['id']}"
+ assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": "1-AAAAAAAAAA"})).json()["status"] == "off"
+ admin(server, p, "PATCH", "", json={"camera_pass": True})
+ e = await camera_code(server, p)
+ assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "enrolled"
+ await a.aclose()
+
+ asyncio.run(run())