feat: anti-cheat + presence panel + projector view
Refinement pass on top of the validated v1.2 base.
Hardening / quick fixes
- Caddyfile.tpl: CSP / HSTS / X-Frame / Referrer-Policy / Permissions-Policy,
1 MiB request body cap, X-Forwarded-For pass-through; stock-Caddy compatible.
- auth.py: STUDENT_MAX_AGE 1y -> 30d.
- bootstrap.sh: stage 5 prepends `git config --add safe.directory` so the
re-bootstrap path no longer 'detected dubious ownership' faults.
- admin.js: drop the misleading `closedPayload?.state || session.state`
shim; state derives from session only.
Anti-cheat
- New `student_events` audit table; new POST /api/session/{sid}/event for
blur / visibility_hidden / focus / visibility_visible. quiz.js debounces
events at 1.5s and uses sendBeacon for visibility_hidden so the event
survives a navigation. Counts surface in admin presence + CSV export.
- First-claim-wins on join: add_participant raises DuplicateStudentId on
PK violation; route returns 409 + records a duplicate_join audit event
with attempted name + IP + UA. Admin dashboard surfaces a per-row red
badge for hits on real participants and a top-of-page alert for orphan
attempts.
- DELETE /admin/api/students/{id} as the recovery hatch: clears the
participant + submissions, kicks active WS sockets so a stale cookie
cannot continue submitting. quiz.js surfaces the FastAPI detail message
in the join form so users see the 'already in use' guidance.
Presence panel
- New presence_update WS message; in-process presence map keyed on
student_id tracks ws_count + last_seen_ms. Admin dashboard renders
per-student rows: connected/idle/dropped dot, blur+hidden+duplicate
badges, 'answered current Q' tick, and a clear-student button.
Projector view (public, read-only)
- /projector/?sid=..., GET /api/session/{sid}/projector, WS
/ws/projector/{sid}. Single self-contained projector_state snapshot
pushed on every state change. Public leaderboard strips student_id;
QR rendered server-side as data: URL (CSP-compliant).
- Includes per-Q answer histogram, 8-bucket response-time distribution,
10-bucket score distribution.
- static/projector.{html,css,js}: editorial-broadside design — masthead,
registration crosses, conic-gradient countdown ring, SVG stepped-area
score distribution with median tick, leaderboard row-stagger. Inherits
light/dark tokens from style.css; honours prefers-reduced-motion. No
scroll at 1366x768 / 1920x1080 / 3440x1440.
Tests
- tests/test_anti_cheat.py: blur logging + CSV count, unknown-kind 422,
unauthenticated event 401, duplicate-join 409 + audit, admin
clear-student happy + 404, server-side submit lockout regression.
- tests/test_projector.py: snapshot shape, leaderboard student_id
redaction, WS push on state change, 404 for unknown sid, page redirect
when no sid.
- Existing tests updated for the new presence_update snapshot frame +
CSV header columns + first-claim-wins refusal of re-key.
57/57 pytest green; smoke-tested locally end-to-end.
This commit is contained in:
@@ -34,6 +34,61 @@ const RECONNECT = {
|
||||
|
||||
let countdownTimer = null;
|
||||
|
||||
/* Tab-blur audit. We POST a server event whenever the student
|
||||
* backgrounds the page (visibilitychange) or moves focus away from the
|
||||
* window (blur). Both are debounced so a rapid alt-tab roundtrip
|
||||
* doesn't spam events. The server records each event in `student_events`
|
||||
* and surfaces a count to the instructor presence panel.
|
||||
*
|
||||
* We only ping during a question_open state — switching tabs between
|
||||
* questions is fine and we don't want to noise the audit. */
|
||||
const FOCUS = {
|
||||
lastBlur: 0,
|
||||
lastHidden: 0,
|
||||
debounceMs: 1500,
|
||||
};
|
||||
|
||||
function postEvent(kind) {
|
||||
if (!sid || !store.currentQuestion || store.submitted) return;
|
||||
// Use sendBeacon when leaving the page so the event survives the
|
||||
// navigation; otherwise fetch with credentials so the cookie rides.
|
||||
const body = JSON.stringify({ kind, question_idx: store.currentQuestion.question_idx });
|
||||
const url = `/api/session/${sid}/event`;
|
||||
if (kind === "visibility_hidden" && navigator.sendBeacon) {
|
||||
const blob = new Blob([body], { type: "application/json" });
|
||||
navigator.sendBeacon(url, blob);
|
||||
return;
|
||||
}
|
||||
fetch(url, {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body,
|
||||
keepalive: true,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
function onBlur() {
|
||||
const now = Date.now();
|
||||
if (now - FOCUS.lastBlur < FOCUS.debounceMs) return;
|
||||
FOCUS.lastBlur = now;
|
||||
postEvent("blur");
|
||||
}
|
||||
|
||||
function onVisibility() {
|
||||
const now = Date.now();
|
||||
if (document.visibilityState === "hidden") {
|
||||
if (now - FOCUS.lastHidden < FOCUS.debounceMs) return;
|
||||
FOCUS.lastHidden = now;
|
||||
postEvent("visibility_hidden");
|
||||
} else if (document.visibilityState === "visible") {
|
||||
postEvent("visibility_visible");
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("blur", onBlur);
|
||||
document.addEventListener("visibilitychange", onVisibility);
|
||||
|
||||
function fmtScore(value) {
|
||||
// Scores are floats on a 0.05 grid in [0, 1]. Display as a fixed
|
||||
// two-decimal string so users see e.g. "0.85" instead of
|
||||
@@ -136,7 +191,15 @@ function renderJoin(error = null) {
|
||||
connect();
|
||||
} catch (err) {
|
||||
submit.disabled = false;
|
||||
renderJoin(err.message || "Could not join.");
|
||||
let msg = err.message || "Could not join.";
|
||||
// The /join endpoint returns the FastAPI default JSON error envelope
|
||||
// ({"detail": "..."}) — surface the human-readable detail rather
|
||||
// than the raw JSON blob in the alert.
|
||||
try {
|
||||
const parsed = JSON.parse(msg);
|
||||
if (parsed && parsed.detail) msg = parsed.detail;
|
||||
} catch {}
|
||||
renderJoin(msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user