Camera app scan: the big qr rotates every 3 s and one scan with the phone's camera app enrolls or validates a vote (10 s), for browsers with the camera blocked; qr stays big beside the ring during a vote, step by step help on the phone
This commit is contained in:
+124
-35
@@ -18,7 +18,7 @@ from starlette.websockets import WebSocket, WebSocketDisconnect
|
||||
|
||||
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
|
||||
from .tokens import check_key, current_slot, make_pass, new_key, now_ms, sha, verify_pass
|
||||
|
||||
log = logging.getLogger("rotatyvote")
|
||||
STATIC = Path(__file__).resolve().parent.parent / "static"
|
||||
@@ -50,6 +50,33 @@ def clear_attempts(pid):
|
||||
del attempts[k]
|
||||
|
||||
|
||||
# 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]] = {}
|
||||
|
||||
|
||||
def grant_pass(pid, vid):
|
||||
now = now_ms()
|
||||
if len(passes) > 20000:
|
||||
for k in [k for k, t in passes.items() if t < now]:
|
||||
del passes[k]
|
||||
passes[(pid, vid)] = now + config.PASS_HOLD_MS
|
||||
|
||||
|
||||
def has_pass(pid, vid):
|
||||
return passes.get((pid, vid), 0) >= now_ms()
|
||||
|
||||
|
||||
def mint_claim(pid):
|
||||
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]:
|
||||
del claims[k]
|
||||
nonce = new_key()
|
||||
claims[nonce] = (pid, now)
|
||||
return nonce
|
||||
|
||||
|
||||
def q_public(q, with_results: bool):
|
||||
d = {
|
||||
"id": q["id"], "text": q["text"], "kind": q["kind"], "options": json.loads(q["options"]),
|
||||
@@ -142,23 +169,29 @@ def qr_modules(url: str, error="m"):
|
||||
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()
|
||||
# level q survives a glare patch or a smudge on a quarter of the symbol, and only grows 25 -> 29 modules
|
||||
return {"type": "entry", "modules": qr_modules(url, error="q"), "url": f"{base}/v/{pid}"}
|
||||
def pass_slot():
|
||||
return now_ms() // config.PASS_ROTATE_MS
|
||||
|
||||
|
||||
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
|
||||
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}",
|
||||
"token": make_pass(p["secret"], pid, slot), "slot": slot, "interval_ms": rot, "valid_until": (slot + 1) * rot}
|
||||
|
||||
|
||||
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)
|
||||
"""full slot for a fresh, authentic ring token 'r<s16>.<mac>', else None"""
|
||||
if not tok.startswith("r"):
|
||||
return None
|
||||
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
|
||||
|
||||
|
||||
class Hub:
|
||||
@@ -219,6 +252,13 @@ class Hub:
|
||||
return
|
||||
await self.send_all(conns, voter_state(pid, v))
|
||||
|
||||
async def send_entry(self, p, screens, slot, kind="entry"):
|
||||
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():
|
||||
await self.send_all(conns, {**entry_qr(base, p, slot), "type": kind})
|
||||
|
||||
def ensure_ticker(self, pid):
|
||||
t = self.tickers.get(pid)
|
||||
if t and not t.done():
|
||||
@@ -228,31 +268,31 @@ class Hub:
|
||||
self.tickers[pid] = asyncio.get_running_loop().create_task(self._tick(pid))
|
||||
|
||||
async def _tick(self, pid):
|
||||
last_pass = -1
|
||||
try:
|
||||
while True:
|
||||
p = db.poll(pid)
|
||||
screens = self.screens.get(pid)
|
||||
if not p or not needs_qr(p) or not screens:
|
||||
return
|
||||
ps = pass_slot()
|
||||
if p["code_style"] == "qr":
|
||||
# the classic qr is the camera app code itself, in the middle of the screen
|
||||
if ps != last_pass:
|
||||
last_pass = ps
|
||||
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:
|
||||
last_pass = ps
|
||||
await self.send_entry(p, screens, ps)
|
||||
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, "token": token, "modules": qr_modules(url), "slot": slot,
|
||||
"interval_ms": iv, "valid_until": (slot + 1) * iv}
|
||||
await self.send_all(conns, msg)
|
||||
# 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))
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
@@ -612,11 +652,13 @@ async def voter_me(request: Request):
|
||||
})
|
||||
|
||||
|
||||
def _finish_enroll(pid, att_id, code=None):
|
||||
def _finish_enroll(pid, att_id, code=None, with_pass=False):
|
||||
cred, e = db.enroll(pid, code)
|
||||
if e:
|
||||
return None, e
|
||||
attempts.pop((pid, att_id), None)
|
||||
if with_pass:
|
||||
grant_pass(pid, db.voter_by_cred(pid, cred)["id"])
|
||||
resp = JSONResponse({"status": "enrolled"})
|
||||
set_cookie(resp, voter_cookie(pid), cred, 7 * 24 * 3600)
|
||||
resp.delete_cookie(attempt_cookie(pid), path="/")
|
||||
@@ -691,6 +733,51 @@ async def voter_scan(request: Request):
|
||||
return resp
|
||||
|
||||
|
||||
async def camera_pass(request: Request):
|
||||
"""the entry qr read by the camera app lands here. strict cookies may not come along on a navigation
|
||||
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
|
||||
# 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)
|
||||
|
||||
|
||||
async def voter_pass(request: Request):
|
||||
"""one camera app scan = presence: enrolls this phone, or covers its votes for PASS_HOLD_MS.
|
||||
takes the claim from camera_pass, or the code itself when the page's own camera read the qr"""
|
||||
pid = request.path_params["pid"]
|
||||
p = get_poll(pid)
|
||||
d = await body(request)
|
||||
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
|
||||
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:
|
||||
return JSONResponse({"status": "expired"})
|
||||
v = current_voter(request, pid)
|
||||
if v:
|
||||
grant_pass(pid, v["id"])
|
||||
return JSONResponse({"status": "pass", "hold_ms": config.PASS_HOLD_MS})
|
||||
if not p["enrollment_open"]:
|
||||
return JSONResponse({"status": "closed"})
|
||||
att_id, a, fresh_cookie = _attempt(request, pid)
|
||||
a.last_ms = a.presence_ms = now
|
||||
if p["require_code"]:
|
||||
resp = JSONResponse({"status": "need_code"})
|
||||
else:
|
||||
resp, e = _finish_enroll(pid, att_id, with_pass=True)
|
||||
if not resp:
|
||||
return JSONResponse({"status": e})
|
||||
if fresh_cookie and p["require_code"]:
|
||||
set_cookie(resp, attempt_cookie(pid), fresh_cookie, 900)
|
||||
return resp
|
||||
|
||||
|
||||
async def voter_rescue(request: Request):
|
||||
"""enrollment with a one-time rescue code, for phones whose camera can't scan"""
|
||||
pid = request.path_params["pid"]
|
||||
@@ -752,7 +839,7 @@ async def voter_vote(request: Request):
|
||||
if len(choices) > q["max_choices"]:
|
||||
return err("too_many_choices")
|
||||
p = db.poll(pid)
|
||||
need = 0 if v["via_code"] else p["vote_scans"]
|
||||
need = 0 if v["via_code"] or has_pass(pid, v["id"]) else p["vote_scans"]
|
||||
if need:
|
||||
# proof of presence at vote time: fresh distinct codes read off the projector.
|
||||
# checked then dropped, nothing about them is stored next to the ballot
|
||||
@@ -805,7 +892,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, entry_qr(config.PUBLIC_URL or origin, p, pass_slot()))
|
||||
await hub.send(ws, screen_state(pid))
|
||||
hub.ensure_ticker(pid)
|
||||
hub.refresh(pid)
|
||||
@@ -917,6 +1004,7 @@ routes = [
|
||||
Route("/present/{pid}", page("screen.html")),
|
||||
Route("/essai", page("essai.html")),
|
||||
Route("/v/{pid}", page("vote.html")),
|
||||
Route("/V/{pid}/{tok}", camera_pass),
|
||||
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"]),
|
||||
@@ -933,6 +1021,7 @@ routes = [
|
||||
Route("/api/v/{pid}/code", voter_code, methods=["POST"]),
|
||||
Route("/api/v/{pid}/vote", voter_vote, methods=["POST"]),
|
||||
Route("/api/v/{pid}/rescue", voter_rescue, methods=["POST"]),
|
||||
Route("/api/v/{pid}/pass", voter_pass, methods=["POST"]),
|
||||
WebSocketRoute("/ws/{pid}/screen", ws_screen),
|
||||
WebSocketRoute("/ws/{pid}/admin", ws_admin),
|
||||
WebSocketRoute("/ws/{pid}/voter", ws_voter),
|
||||
|
||||
@@ -25,6 +25,14 @@ CODE_ENTRY_TTL_S = 180
|
||||
# keepalive for websockets, proxies drop idle ones (cloudflare ~100s)
|
||||
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
|
||||
PASS_ROTATE_MS = 3000
|
||||
PASS_GRACE_MS = 12000
|
||||
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
|
||||
|
||||
# codes needed to confirm each vote, 0 turns the check off
|
||||
DEFAULT_VOTE_SCANS = 3
|
||||
MAX_VOTE_SCANS = 5
|
||||
|
||||
+16
-15
@@ -29,30 +29,31 @@ def check_key(given: str | None, stored_hash: str) -> bool:
|
||||
return hmac.compare_digest(sha(given), stored_hash)
|
||||
|
||||
|
||||
def _mac(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> str:
|
||||
msg = f"{poll_id}:{interval_ms}:{slot}".encode()
|
||||
# 72 bits is plenty for a code that lives ~3s, keeps the QR small
|
||||
return base64.urlsafe_b64encode(hmac.new(secret, msg, hashlib.sha256).digest()[:9]).decode()
|
||||
|
||||
|
||||
def current_slot(interval_ms: int, at_ms: int | None = None) -> int:
|
||||
return (at_ms if at_ms is not None else now_ms()) // interval_ms
|
||||
|
||||
|
||||
def make_token(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> str:
|
||||
return f"{slot}.{_mac(secret, poll_id, interval_ms, slot)}"
|
||||
def _pass_mac(secret: bytes, poll_id: str, slot: int) -> str:
|
||||
# 50 bits in qr alphanumeric charset (base32 upper), the code lives ~15 s and is checked online only
|
||||
d = hmac.new(secret, f"pass:{poll_id}:{slot}".encode(), hashlib.sha256).digest()
|
||||
return base64.b32encode(d[:7]).decode()[:10]
|
||||
|
||||
|
||||
def verify_token(secret: bytes, poll_id: str, interval_ms: int, token: str, grace_ms: int) -> int | None:
|
||||
"""returns the slot if the token is authentic and fresh, else None"""
|
||||
def make_pass(secret: bytes, poll_id: str, slot: int) -> str:
|
||||
return f"{slot}-{_pass_mac(secret, poll_id, slot)}"
|
||||
|
||||
|
||||
def verify_pass(secret: bytes, poll_id: str, token: str, rotate_ms: int, grace_ms: int) -> int | None:
|
||||
"""camera app code from the entry qr: slot if authentic and shown less than rotate + grace ago"""
|
||||
try:
|
||||
slot_s, mac = token.split(".", 1)
|
||||
slot_s, mac = token.upper().split("-", 1)
|
||||
slot = int(slot_s)
|
||||
# compare_digest raises on non ascii str
|
||||
if not hmac.compare_digest(mac.encode(), _pass_mac(secret, poll_id, slot).encode()):
|
||||
return None
|
||||
except (ValueError, AttributeError):
|
||||
return None
|
||||
if not hmac.compare_digest(mac, _mac(secret, poll_id, interval_ms, slot)):
|
||||
return None
|
||||
age = now_ms() - slot * interval_ms
|
||||
if age < 0 or age > interval_ms + grace_ms:
|
||||
age = now_ms() - slot * rotate_ms
|
||||
if age < 0 or age > rotate_ms + grace_ms:
|
||||
return None
|
||||
return slot
|
||||
|
||||
@@ -36,7 +36,7 @@ body.entry-big { --dock-qr: clamp(180px, min(58vh, 34vw), 640px); }
|
||||
body.entry-big .entry { top: 50%; bottom: auto; right: max(4vw, calc((50vw - var(--dock-qr)) / 2 - 2vw)); translate: 0 -46%; padding: 2vh; gap: 1.2vh; }
|
||||
body.entry-big .entry div { font-size: clamp(.9rem, 1.4vw, 1.6rem); }
|
||||
body.entry-big .s-main:not(.split) .s-steps { visibility: hidden; }
|
||||
body.entry-q-on { --dock-qr: clamp(160px, min(46vh, 30vw), 520px); }
|
||||
body.entry-q-on { --dock-qr: clamp(160px, min(52vh, 32vw), 580px); }
|
||||
/* width 0 + min-width 100%: a long question wraps to the qr's width instead of widening the block */
|
||||
.entry-q { display: grid; gap: .6vh; padding-bottom: 1vh; margin-bottom: .4vh; border-bottom: 2px solid var(--bg); width: 0; min-width: 100%; }
|
||||
.entry-q b { font: 700 clamp(1rem, 1.7vw, 2rem) var(--round); color: var(--ink); line-height: 1.15; }
|
||||
|
||||
@@ -82,3 +82,13 @@ dialog .actions button { flex: 1; }
|
||||
border: 0; color: #fff; background: rgba(20, 22, 36, .55); font: 700 .95rem var(--round);
|
||||
-webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px);
|
||||
}
|
||||
|
||||
/* the phone's own camera app reads the projector qr when the browser can't use the camera */
|
||||
.cam-alt { display: flex; align-items: center; justify-content: center; gap: 8px; margin: 0 0 12px; font-size: .9rem; color: var(--ink-2); text-align: left; }
|
||||
.cam-alt .icon { flex: none; }
|
||||
.cam-alt.solo { flex-direction: column; gap: 12px; margin: 4px 0 18px; color: var(--ink); }
|
||||
.cam-alt.solo .icon { width: 64px; height: 64px; padding: 14px; border-radius: 50%; background: var(--mark); stroke-width: 1.8; }
|
||||
.cam-alt.solo b { font: 700 1.25rem/1.25 var(--round); text-align: center; }
|
||||
.cam-alt.solo ol { list-style: none; counter-reset: st; padding: 0; margin: 0; display: grid; gap: 10px; font: 600 1rem/1.35 var(--round); }
|
||||
.cam-alt.solo li { counter-increment: st; display: grid; grid-template-columns: 28px 1fr; gap: 10px; align-items: start; }
|
||||
.cam-alt.solo li::before { content: counter(st); display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: var(--ink); color: var(--surface); font-weight: 700; font-size: .9rem; }
|
||||
|
||||
@@ -165,6 +165,8 @@ const ICONS = {
|
||||
screen: ["M3 5h18v11H3z", "M8 20h8", "M12 16v4"],
|
||||
check: ["M5 12.5l4.5 4.5L19 7.5"],
|
||||
swap: ["M4 9h13l-3.5-3.5", "M20 15H7l3.5 3.5"],
|
||||
camera: ["M3 8.5A2.5 2.5 0 0 1 5.5 6h2L9 4h6l1.5 2h2A2.5 2.5 0 0 1 21 8.5v9a2.5 2.5 0 0 1-2.5 2.5h-13A2.5 2.5 0 0 1 3 17.5z",
|
||||
"M12 9.5a3.5 3.5 0 1 0 0 7a3.5 3.5 0 1 0 0-7"],
|
||||
};
|
||||
|
||||
export function icon(name, size = 16) {
|
||||
|
||||
+18
-12
@@ -52,10 +52,14 @@ function layout() {
|
||||
// qr stays up while enrolling, and during a vote that needs a presence scan
|
||||
const qrOn = st.enrollment_open || st.presence;
|
||||
const ring = st.code_style === "ring";
|
||||
const entryOn = !!(ring && st.enrollment_open && entry);
|
||||
// a closed vote whose results aren't shown has nothing to say: with the big entry qr on, it steps aside
|
||||
// the camera app code: enrolls, and proves presence for a vote, so it stays up whenever the ring does
|
||||
const entryOn = !!(ring && qrOn && entry);
|
||||
// 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;
|
||||
const focus = idleVote && entryOn && st.entry_big ? null : f;
|
||||
// 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 big = entryOn && st.entry_big && (!f || idleVote || openVote);
|
||||
const focus = big ? null : f;
|
||||
reveal($("#enroll"), qrOn);
|
||||
reveal($("#focus"), !!focus);
|
||||
reveal($("#idle"), !qrOn && !focus);
|
||||
@@ -64,22 +68,24 @@ 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;
|
||||
// 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";
|
||||
$("#step1").textContent = ring ? "Scannez le QR avec l'appareil photo" : "Scannez avec l'appareil photo";
|
||||
$("#step2").hidden = !ring;
|
||||
reveal($("#entry"), entryOn);
|
||||
document.body.classList.toggle("has-entry", entryOn);
|
||||
// big entry qr next to the ring (start of a meeting, between votes), back to the corner while a question is up
|
||||
const big = entryOn && st.entry_big && !focus;
|
||||
document.body.classList.toggle("entry-big", big);
|
||||
// the closed vote it replaced stays readable above the qr: question and ballot count
|
||||
const showQ = big && !!idleVote;
|
||||
const showQ = big && !!f;
|
||||
document.body.classList.toggle("entry-q-on", showQ);
|
||||
$("#entry-q").hidden = !showQ;
|
||||
if (showQ) {
|
||||
$("#entry-q-text").textContent = f.text;
|
||||
$("#entry-q-count").textContent = `Vote clos, ${f.participants} bulletin${f.participants > 1 ? "s" : ""}`;
|
||||
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)}`;
|
||||
} else {
|
||||
$("#entry-q-count").textContent = `Vote clos, ${f.participants} bulletin${f.participants > 1 ? "s" : ""}`;
|
||||
}
|
||||
}
|
||||
$("#entry-hint").textContent = big ? "Scannez ici, puis visez le cercle" : "Pas encore sur la page ?";
|
||||
$("#entry-hint").textContent = "Scannez avec l'appareil photo";
|
||||
$(".qr-wrap").classList.toggle("ring", ring);
|
||||
flip(entryEl, before);
|
||||
}
|
||||
@@ -178,7 +184,7 @@ function animateTick() {
|
||||
}
|
||||
|
||||
let skew = 0;
|
||||
window.addEventListener("resize", paintQR);
|
||||
window.addEventListener("resize", () => { paintQR(); layout(); });
|
||||
|
||||
$("#fs").addEventListener("click", () => document.documentElement.requestFullscreen?.());
|
||||
|
||||
|
||||
+143
-29
@@ -5,9 +5,15 @@ const pid = pollId();
|
||||
const DONE_KEY = `rv_done_${pid}`;
|
||||
const apiBase = `/api/v/${pid}`;
|
||||
|
||||
// token from the QR that opened this page, then drop it from the url bar so it isn't shared
|
||||
const firstToken = decodeURIComponent(location.hash.slice(1));
|
||||
const PENDING_KEY = `rv_pending_${pid}`;
|
||||
|
||||
// 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));
|
||||
const claim = hash.get("c"), camExpired = hash.get("cam") === "expired";
|
||||
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 scanner = null;
|
||||
let required = 5;
|
||||
@@ -50,6 +56,22 @@ function scanMsg(text, kind = "") {
|
||||
m.className = `scan-msg ${kind || "muted"}`;
|
||||
}
|
||||
|
||||
// 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.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."));
|
||||
return;
|
||||
}
|
||||
// the vote dialog has the heading in its own title
|
||||
el.replaceChildren(icon("camera", 36), vote ? "" : h("b", {}, "Inscrivez-vous avec l'appareil photo"),
|
||||
h("ol", {},
|
||||
h("li", {}, "Quittez cette page et ouvrez l'appareil photo du téléphone."),
|
||||
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.")));
|
||||
}
|
||||
|
||||
async function startScanner() {
|
||||
if (scanner) return;
|
||||
if (!window.isSecureContext) {
|
||||
@@ -61,6 +83,8 @@ async function startScanner() {
|
||||
try {
|
||||
await scanner.start();
|
||||
$("#start-cam").hidden = true;
|
||||
$("#dots").hidden = false;
|
||||
camAlt($("#enroll-alt"), false);
|
||||
scanMsg("");
|
||||
navigator.wakeLock?.request("screen").catch(() => {});
|
||||
} catch (e) {
|
||||
@@ -68,31 +92,30 @@ async function startScanner() {
|
||||
scanner.destroy();
|
||||
scanner = null;
|
||||
$("#cam-box").hidden = true;
|
||||
// the camera app is the way now: the ring and a big retry button would only compete with it
|
||||
$("#dots").hidden = true;
|
||||
$("#start-cam").hidden = false;
|
||||
$("#start-cam").className = "link";
|
||||
$("#start-cam").textContent = "Réessayer la caméra";
|
||||
scanMsg(camError(e), "bad");
|
||||
camAlt($("#enroll-alt"), true);
|
||||
}
|
||||
}
|
||||
|
||||
// what blocked the camera, and where to unblock it on this phone. the browser only tells the kind of failure
|
||||
// what blocked the camera. no settings walkthrough: the camera app path below works without them
|
||||
function camError(e) {
|
||||
const ios = /iPhone|iPad|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
|
||||
const android = /Android/.test(navigator.userAgent);
|
||||
switch (e && e.name) {
|
||||
case "NotAllowedError":
|
||||
case "SecurityError":
|
||||
return ios
|
||||
? "Accès à la caméra refusé. Touchez « aA » dans la barre d'adresse, puis Réglages du site web, Caméra, Autoriser. Si rien ne change, ouvrez Réglages, puis Safari, puis Caméra."
|
||||
: android
|
||||
? "Accès à la caméra refusé. Touchez le cadenas à gauche de l'adresse, puis Autorisations, Caméra. Vérifiez aussi l'accès à la caméra dans les réglages de confidentialité du téléphone."
|
||||
: "Accès à la caméra refusé. Autorisez-la dans les réglages du navigateur pour ce site, puis réessayez.";
|
||||
return "Ce navigateur n'a pas accès à la caméra.";
|
||||
case "NotReadableError":
|
||||
case "AbortError":
|
||||
return "La caméra est bloquée par le téléphone. Fermez les autres applis qui l'utilisent, ou réactivez l'accès à la caméra dans les réglages de confidentialité.";
|
||||
return "Caméra occupée ou bloquée par le téléphone.";
|
||||
case "NotFoundError":
|
||||
case "OverconstrainedError":
|
||||
return "Aucune caméra trouvée sur cet appareil.";
|
||||
return "Aucune caméra trouvée.";
|
||||
default:
|
||||
return "Caméra indisponible. Autorisez-la puis réessayez.";
|
||||
return "Caméra indisponible.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,12 +262,13 @@ function rankCameras(cams) {
|
||||
}
|
||||
|
||||
// token of a code shown for this poll, null for anything else
|
||||
// the classic qr is the camera app code: /V/<poll>/<code>, upper case
|
||||
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;
|
||||
const [v, id, tok] = u.pathname.split("/").filter(Boolean);
|
||||
if (v?.toLowerCase() !== "v" || id?.toLowerCase() !== pid || !tok) return null;
|
||||
return tok;
|
||||
}
|
||||
|
||||
function stopScanner() {
|
||||
@@ -258,7 +282,50 @@ function stopScanner() {
|
||||
function onScan(token) {
|
||||
if (landing || sent.has(token)) return;
|
||||
sent.add(token);
|
||||
submitToken(token);
|
||||
if (codeStyle === "qr") redeem({ token }).then(afterPass);
|
||||
else submitToken(token);
|
||||
}
|
||||
|
||||
async function redeem(body) {
|
||||
try { return await api("POST", `${apiBase}/pass`, body); }
|
||||
catch { return { status: "network" }; }
|
||||
}
|
||||
|
||||
function pendingVote() {
|
||||
let p;
|
||||
try { p = JSON.parse(lsGet(PENDING_KEY)); } catch { return null; }
|
||||
return p && Date.now() - p.at < 5 * 60e3 ? p : null;
|
||||
}
|
||||
|
||||
// what one camera app scan gave: enrolled, votes covered for a moment, or why not
|
||||
async function afterPass(r) {
|
||||
switch (r.status) {
|
||||
case "enrolled":
|
||||
passUntil = Date.now() + 8000;
|
||||
enrolled();
|
||||
break;
|
||||
case "pass": {
|
||||
passUntil = Date.now() + (r.hold_ms || 10000) - 1500;
|
||||
// the choice made before going to the camera app goes through on its own
|
||||
const p = pendingVote();
|
||||
const q = p && lastState?.questions.find((x) => x.id === p.qid && x.state === "open" && !x.voted);
|
||||
if (q) castVote(q, p.choices);
|
||||
break;
|
||||
}
|
||||
case "need_code":
|
||||
stopScanner();
|
||||
show("#v-code");
|
||||
break;
|
||||
case "closed":
|
||||
if (!lastState) block("Inscriptions closes. Inscrit·e dans un autre navigateur ? Revenez-y pour voter.");
|
||||
break;
|
||||
case "full":
|
||||
block("Nombre maximal d'inscriptions atteint.");
|
||||
break;
|
||||
case "expired":
|
||||
toast("QR expiré, scannez-le à nouveau.", "bad");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function submitToken(token) {
|
||||
@@ -384,6 +451,8 @@ function sel(qid) {
|
||||
|
||||
function renderVote(st) {
|
||||
lastState = st;
|
||||
// voted from the tab the camera app opened: nothing left to scan here
|
||||
if (presenceFor && st.questions.some((q) => q.id === presenceFor && q.voted)) $("#presence").close();
|
||||
if (st.code_style) codeStyle = st.code_style;
|
||||
const box = $("#questions");
|
||||
box.replaceChildren();
|
||||
@@ -450,17 +519,33 @@ async function confirmVote(q) {
|
||||
dlg.showModal();
|
||||
await new Promise((res) => dlg.addEventListener("close", res, { once: true }));
|
||||
if (dlg.returnValue !== "ok") return;
|
||||
castVote(q, s.blank ? [] : choices);
|
||||
}
|
||||
|
||||
async function castVote(q, choices, retried = false) {
|
||||
let presence;
|
||||
if (lastState.vote_scans > 0) {
|
||||
presence = await collectPresence(lastState.vote_scans);
|
||||
if (!presence) return;
|
||||
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() }));
|
||||
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) {
|
||||
try { localStorage.removeItem(PENDING_KEY); } catch { /* private mode */ }
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
await api("POST", `${apiBase}/vote`, { question_id: q.id, choices: s.blank ? [] : choices, presence });
|
||||
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é");
|
||||
navigator.vibrate?.(60);
|
||||
} catch (e) {
|
||||
// the camera app scan ran out on the server side: scan again
|
||||
if (e.code === "presence_required" && !presence && !retried) {
|
||||
passUntil = 0;
|
||||
return castVote(q, choices, true);
|
||||
}
|
||||
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");
|
||||
@@ -469,16 +554,29 @@ async function confirmVote(q) {
|
||||
|
||||
// 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) {
|
||||
function collectPresence(n, qid) {
|
||||
const dlg = $("#presence");
|
||||
const got = [];
|
||||
// the classic qr is the camera app code: one read is enough, the server then covers the vote
|
||||
if (codeStyle === "qr") n = 1;
|
||||
const paint = () => paintRing($("#p-ring"), got.length, n, 120);
|
||||
paint();
|
||||
$("#p-title").textContent = codeStyle === "ring" ? "Visez le cercle" : "Scannez le QR";
|
||||
$("#p-scan").hidden = false;
|
||||
$("#p-msg").textContent = "";
|
||||
camAlt($("#p-alt"), false);
|
||||
presenceFor = qid;
|
||||
dlg.showModal();
|
||||
const seenAt = new Map();
|
||||
const sc = makeScanner($("#p-video"), (t) => {
|
||||
const seenAt = new Map(), tried = new Set();
|
||||
const sc = makeScanner($("#p-video"), async (t) => {
|
||||
if (got.length >= n || got.includes(t)) return;
|
||||
if (codeStyle === "qr") {
|
||||
if (tried.has(t)) return;
|
||||
tried.add(t);
|
||||
const r = await redeem({ token: t });
|
||||
if (r.status === "pass" && !got.length) { got.push(t); paint(); setTimeout(() => finish([]), FILL_MS); }
|
||||
return;
|
||||
}
|
||||
// the server takes codes spread over ~8 s + n intervals: on a slow phone the oldest ones lapse, drop them
|
||||
const now = performance.now();
|
||||
while (got.length && now - seenAt.get(got[0]) > 9000) got.shift();
|
||||
@@ -493,14 +591,20 @@ function collectPresence(n) {
|
||||
function finish(value) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
presenceFor = null;
|
||||
sc.stop();
|
||||
sc.destroy();
|
||||
if (dlg.open) dlg.close();
|
||||
done(value);
|
||||
}
|
||||
dlg.addEventListener("close", () => finish(null), { once: true });
|
||||
// no camera at vote time: the desk can still count this vote by hand (votes en plus)
|
||||
sc.start().catch((e) => { $("#p-msg").textContent = `${camError(e)} Sinon, signalez-vous à la tribune.`; });
|
||||
// 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;
|
||||
camAlt($("#p-alt"), true, true);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -553,14 +657,24 @@ async function boot() {
|
||||
return block("Appareil déjà inscrit à ce scrutin (accès perdu). Adressez-vous à l'équipe organisatrice.");
|
||||
}
|
||||
if (!me.enrollment_open) return block("Inscriptions closes.");
|
||||
required = me.scans_required;
|
||||
codeStyle = me.code_style || "qr";
|
||||
// the classic qr is read once (camera app code), the ring several times
|
||||
required = codeStyle === "qr" ? 1 : me.scans_required;
|
||||
if (me.need_code) { show("#v-code"); return; }
|
||||
startEnroll(me.count);
|
||||
if (firstToken && !sent.has(firstToken)) { sent.add(firstToken); submitToken(firstToken); }
|
||||
}
|
||||
|
||||
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);
|
||||
else if (camExpired) afterPass({ status: "expired" });
|
||||
}
|
||||
|
||||
camAlt($("#enroll-alt"), false);
|
||||
start();
|
||||
// a socket can look open after sleep while being dead, so refetch on wake
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "visible" && lastState) boot();
|
||||
|
||||
+2
-2
@@ -33,7 +33,7 @@
|
||||
<h2 id="qr-title">Inscription</h2>
|
||||
<ol id="qr-steps">
|
||||
<li><span id="step1">Scannez ce code</span></li>
|
||||
<li><span>Visez l'écran <b id="secs">5</b> s</span></li>
|
||||
<li id="step2"><span>Ou visez le cercle <b id="secs">5</b> s</span></li>
|
||||
</ol>
|
||||
<p id="url-warn" class="notice warn" hidden></p>
|
||||
</div>
|
||||
@@ -50,7 +50,7 @@
|
||||
<aside id="entry" class="entry" hidden>
|
||||
<div id="entry-q" class="entry-q" hidden><b id="entry-q-text"></b><span id="entry-q-count"></span></div>
|
||||
<canvas id="entry-qr" aria-label="QR code de la page de vote"></canvas>
|
||||
<div><b id="entry-hint">Pas encore sur la page ?</b><span id="entry-url"></span></div>
|
||||
<div><b id="entry-hint">Scannez avec l'appareil photo</b><span id="entry-url"></span></div>
|
||||
</aside>
|
||||
|
||||
<footer class="s-foot">
|
||||
|
||||
+7
-3
@@ -28,6 +28,7 @@
|
||||
<video id="video" playsinline muted></video>
|
||||
</div>
|
||||
<p id="scan-msg" class="scan-msg muted"></p>
|
||||
<div id="enroll-alt" class="cam-alt"></div>
|
||||
<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>
|
||||
@@ -84,10 +85,13 @@
|
||||
</dialog>
|
||||
|
||||
<dialog id="presence">
|
||||
<h2 tabindex="-1" autofocus>Visez l'écran</h2>
|
||||
<div id="p-ring" class="dots"></div>
|
||||
<div class="cam"><video id="p-video" playsinline muted></video></div>
|
||||
<h2 id="p-title" tabindex="-1" autofocus>Visez le cercle</h2>
|
||||
<div id="p-scan">
|
||||
<div id="p-ring" class="dots"></div>
|
||||
<div class="cam"><video id="p-video" playsinline muted></video></div>
|
||||
</div>
|
||||
<p id="p-msg" class="scan-msg bad"></p>
|
||||
<div id="p-alt" class="cam-alt"></div>
|
||||
<div class="actions"><button id="p-cancel" type="button">Annuler</button></div>
|
||||
</dialog>
|
||||
</body>
|
||||
|
||||
+105
-28
@@ -35,7 +35,8 @@ def server(tmp_path_factory):
|
||||
port = free_port()
|
||||
tmp = tmp_path_factory.mktemp("db")
|
||||
db = tmp / "test.db"
|
||||
env = {**os.environ, "PORT": str(port), "HOST": "127.0.0.1", "DB_PATH": str(db), "PUBLIC_URL": "", "HEARTBEAT_S": "1"}
|
||||
env = {**os.environ, "PORT": str(port), "HOST": "127.0.0.1", "DB_PATH": str(db), "PUBLIC_URL": "", "HEARTBEAT_S": "1",
|
||||
"PASS_HOLD_MS": "1500"}
|
||||
scheme, wscheme, ws_kw = "http", "ws", {}
|
||||
if TLS:
|
||||
cert, key = tmp / "cert.pem", tmp / "key.pem"
|
||||
@@ -201,8 +202,8 @@ def test_full_flow_and_anonymity(server):
|
||||
assert con.execute("SELECT COUNT(*) FROM participation").fetchone()[0] >= 2
|
||||
|
||||
|
||||
def test_stale_duplicate_and_forged_tokens(server):
|
||||
p = create(server, scans_required=3, code_style="qr")
|
||||
def test_duplicate_token_counts_once(server):
|
||||
p = create(server, scans_required=3)
|
||||
admin(server, p, "PATCH", "", json={"enrollment_open": True})
|
||||
|
||||
async def run():
|
||||
@@ -211,25 +212,8 @@ def test_stale_duplicate_and_forged_tokens(server):
|
||||
tok = await next_token()
|
||||
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json()
|
||||
assert r["count"] == 1 and r["accepted"]
|
||||
# same code twice does not count twice
|
||||
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json()
|
||||
assert r["count"] == 1 and not r["accepted"]
|
||||
# forged mac
|
||||
slot = tok.split(".")[0]
|
||||
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": f"{int(slot) + 1}.AAAAAAAAAAAA"})).json()
|
||||
assert not r["valid"] and r["count"] == 1
|
||||
# replaying an old photo of the screen
|
||||
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"]
|
||||
# a token from another poll is useless here
|
||||
other = create(server)
|
||||
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"]
|
||||
await c.aclose()
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -455,8 +439,7 @@ def test_behind_proxy(proxied):
|
||||
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']}"
|
||||
assert m["url"] == 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",
|
||||
@@ -628,7 +611,7 @@ def test_heartbeat_survives_dead_client(server):
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_ring_tokens_stale_forged_and_cross_format(server):
|
||||
def test_ring_tokens_stale_and_forged(server):
|
||||
from rotatyvote import tokens as tk
|
||||
p = create(server, scans_required=3, code_style="ring")
|
||||
admin(server, p, "PATCH", "", json={"enrollment_open": True})
|
||||
@@ -643,12 +626,10 @@ def test_ring_tokens_stale_forged_and_cross_format(server):
|
||||
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
|
||||
# a camera app code is not a ring code
|
||||
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tk.make_pass(secret, p["id"], 1)})).json()
|
||||
assert not r["valid"]
|
||||
# forged mac, malformed
|
||||
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": f"r{s16}.00000000"})).json()
|
||||
assert not r["valid"]
|
||||
@@ -751,3 +732,99 @@ def test_duplicated_screen_page(server):
|
||||
assert (await next_token()) is not None
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
async def camera_code(server, p, kind="entry"):
|
||||
"""the code the camera app would read off the projector right now"""
|
||||
ws = await websockets.connect(f"{server['ws']}/ws/{p['id']}/screen", **server["ws_kw"])
|
||||
await ws.send(json.dumps({"key": p["screen_key"]}))
|
||||
while True:
|
||||
m = json.loads(await asyncio.wait_for(ws.recv(), 5))
|
||||
if m["type"] == kind:
|
||||
await ws.close()
|
||||
return m
|
||||
|
||||
|
||||
def test_camera_app_scan_enrolls_and_covers_votes(server):
|
||||
from rotatyvote import tokens as tk
|
||||
p = create(server, scans_required=5, vote_scans=3)
|
||||
admin(server, p, "PATCH", "", json={"enrollment_open": True})
|
||||
|
||||
async def run():
|
||||
e = await camera_code(server, p)
|
||||
assert len(e["modules"]) == 33
|
||||
a = device(server)
|
||||
r = await a.get(f"/V/{p['id'].upper()}/{e['token'].upper()}", follow_redirects=False)
|
||||
assert r.status_code == 303 and "no-store" in r.headers["cache-control"]
|
||||
loc = r.headers["location"]
|
||||
assert loc.startswith(f"/v/{p['id']}#c=")
|
||||
claim = loc.split("#c=")[1]
|
||||
# one scan is enough to enroll, the claim is single use
|
||||
assert (await a.post(f"/api/v/{p['id']}/pass", json={"claim": claim})).json()["status"] == "enrolled"
|
||||
b = device(server)
|
||||
assert (await b.post(f"/api/v/{p['id']}/pass", json={"claim": claim})).json()["status"] == "expired"
|
||||
url = f"/api/v/{p['id']}/vote"
|
||||
q1 = admin(server, p, "POST", "/questions", json={"text": "Q1", "options": ["A", "B"], "open": True}).json()["id"]
|
||||
# the scan that enrolled also covers a vote right after
|
||||
assert (await a.post(url, json={"question_id": q1, "choices": [0]})).status_code == 200
|
||||
await asyncio.sleep(1.6)
|
||||
admin(server, p, "POST", f"/questions/{q1}/close")
|
||||
q2 = admin(server, p, "POST", "/questions", json={"text": "Q2", "options": ["A", "B"], "open": True}).json()["id"]
|
||||
r = await a.post(url, json={"question_id": q2, "choices": [1]})
|
||||
assert r.json()["error"] == "presence_required"
|
||||
# rescan with the camera app (or the page's camera on the classic qr): the code itself
|
||||
e = await camera_code(server, p)
|
||||
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "pass"
|
||||
assert (await a.post(url, json={"question_id": q2, "choices": [1]})).status_code == 200
|
||||
# forged, malformed, other poll, stale
|
||||
bad = await a.get(f"/V/{p['id']}/{e['slot']}-AAAAAAAAAA", follow_redirects=False)
|
||||
assert bad.headers["location"] == f"/v/{p['id']}#cam=expired"
|
||||
bad = await a.get(f"/V/{p['id']}/%C3%A9-%C3%A9", follow_redirects=False)
|
||||
assert bad.headers["location"] == f"/v/{p['id']}#cam=expired"
|
||||
other = create(server)
|
||||
admin(server, other, "PATCH", "", json={"enrollment_open": True})
|
||||
oe = await camera_code(server, other)
|
||||
assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": oe["token"]})).json()["status"] == "expired"
|
||||
con = sqlite3.connect(server["db"])
|
||||
secret = con.execute("SELECT secret FROM polls WHERE id=?", (p["id"],)).fetchone()[0]
|
||||
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"
|
||||
# late arrival after enrollment closed: nothing to do here
|
||||
admin(server, p, "PATCH", "", json={"enrollment_open": False})
|
||||
e = await camera_code(server, p)
|
||||
assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "closed"
|
||||
for x in (a, b):
|
||||
await x.aclose()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_camera_app_scan_then_paper_code(server):
|
||||
p = create(server, require_code=True, codes=2)
|
||||
admin(server, p, "PATCH", "", json={"enrollment_open": True})
|
||||
code = admin(server, p, "GET", "/codes").json()["codes"][0]["code"]
|
||||
|
||||
async def run():
|
||||
e = await camera_code(server, p)
|
||||
a = device(server)
|
||||
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "need_code"
|
||||
assert (await a.get(f"/api/v/{p['id']}/me")).json()["need_code"]
|
||||
assert (await a.post(f"/api/v/{p['id']}/code", json={"code": code})).json()["status"] == "enrolled"
|
||||
await a.aclose()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_classic_qr_is_the_camera_code(server):
|
||||
p = create(server, code_style="qr", vote_scans=2)
|
||||
admin(server, p, "PATCH", "", json={"enrollment_open": True})
|
||||
|
||||
async def run():
|
||||
m = await camera_code(server, p, "qr")
|
||||
assert m["interval_ms"] == 3000 and len(m["modules"]) == 33
|
||||
a = device(server)
|
||||
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": m["token"]})).json()["status"] == "enrolled"
|
||||
await a.aclose()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
Reference in New Issue
Block a user