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.
107 lines
3.4 KiB
Python
107 lines
3.4 KiB
Python
"""SQLite helpers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import AsyncIterator
|
|
from contextlib import asynccontextmanager
|
|
from pathlib import Path
|
|
|
|
import aiosqlite
|
|
|
|
SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS quizzes (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
title TEXT NOT NULL,
|
|
pool_json TEXT NOT NULL,
|
|
time_limit_default INTEGER NOT NULL DEFAULT 60,
|
|
score_fn_name TEXT NOT NULL DEFAULT 'linear_decay',
|
|
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS quiz_sessions (
|
|
sid TEXT PRIMARY KEY,
|
|
quiz_id INTEGER NOT NULL REFERENCES quizzes(id),
|
|
title TEXT NOT NULL,
|
|
state TEXT NOT NULL DEFAULT 'lobby',
|
|
current_question_idx INTEGER,
|
|
started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
finished_at TIMESTAMP
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS participants (
|
|
sid TEXT NOT NULL REFERENCES quiz_sessions(sid),
|
|
student_id TEXT NOT NULL,
|
|
name TEXT NOT NULL,
|
|
cookie_id TEXT NOT NULL,
|
|
joined_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
PRIMARY KEY (sid, student_id)
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS question_events (
|
|
sid TEXT NOT NULL REFERENCES quiz_sessions(sid),
|
|
question_idx INTEGER NOT NULL,
|
|
opened_at TIMESTAMP NOT NULL,
|
|
closed_at TIMESTAMP,
|
|
time_limit INTEGER NOT NULL,
|
|
PRIMARY KEY (sid, question_idx)
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS submissions (
|
|
sid TEXT NOT NULL REFERENCES quiz_sessions(sid),
|
|
student_id TEXT NOT NULL,
|
|
question_idx INTEGER NOT NULL,
|
|
answer TEXT,
|
|
submitted_at TIMESTAMP,
|
|
elapsed_ms INTEGER,
|
|
score REAL NOT NULL DEFAULT 0,
|
|
status TEXT NOT NULL DEFAULT 'submitted',
|
|
PRIMARY KEY (sid, student_id, question_idx)
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_submissions_sid_qidx ON submissions(sid, question_idx);
|
|
CREATE INDEX IF NOT EXISTS idx_participants_sid ON participants(sid);
|
|
|
|
-- Soft-anti-cheat audit + tab-blur trail. Append-only; the admin panel
|
|
-- and CSV export aggregate per-student counts. Kinds in use:
|
|
-- 'blur' — window blur during a question_open state
|
|
-- 'visibility_hidden' — page tab/window backgrounded
|
|
-- 'duplicate_join' — second-claim attempt on an already-claimed
|
|
-- student_id; student_id field holds the
|
|
-- ATTEMPTED id; detail JSON carries IP/UA/name
|
|
CREATE TABLE IF NOT EXISTS student_events (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
sid TEXT NOT NULL,
|
|
student_id TEXT,
|
|
question_idx INTEGER,
|
|
kind TEXT NOT NULL,
|
|
detail TEXT,
|
|
ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_student_events_sid_student ON student_events(sid, student_id);
|
|
CREATE INDEX IF NOT EXISTS idx_student_events_sid_kind ON student_events(sid, kind);
|
|
"""
|
|
|
|
|
|
async def init_db(db_path: str) -> None:
|
|
if db_path != ":memory:":
|
|
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
|
|
async with connect(db_path) as db:
|
|
await db.executescript(SCHEMA)
|
|
await db.commit()
|
|
|
|
|
|
@asynccontextmanager
|
|
async def connect(db_path: str) -> AsyncIterator[aiosqlite.Connection]:
|
|
db = await aiosqlite.connect(db_path)
|
|
db.row_factory = aiosqlite.Row
|
|
await db.execute("PRAGMA foreign_keys=ON")
|
|
await db.execute("PRAGMA journal_mode=WAL")
|
|
try:
|
|
yield db
|
|
finally:
|
|
await db.close()
|
|
|
|
|
|
def row_to_dict(row: aiosqlite.Row | None) -> dict | None:
|
|
return dict(row) if row is not None else None
|