Context
Quizzes now come in two delivery modes (Quiz.deliveryMode): ONLINE (single/multi choice, true/false, CODE for algorithm and SQL, graded on submit) and SUBMISSION (project work graded by engines). Only ONLINE quizzes are taken live in the browser, so only they need proctoring. Nothing exists today: no event logging, no camera, no consent. A browser cannot stop a student from using remote-desktop software, a second device or the operating system's screenshot keys, and the "black screen" effect only blocks software capture (DRM), not a phone pointed at the monitor.
Decision
- Signals, not locks. Every suspicious action is logged and warned, never blocked: copy, cut, paste, right click, print, PrintScreen, tab switch, window blur, leaving full screen, going offline, camera loss. The student sees a warning; the server stores an event. Nothing auto-submits or auto-fails an attempt on its own. A quiz may opt in to "auto-submit after N severe events" later.
- Per-quiz level, chosen by the instructor:
Quiz.proctoringLevel=OFF(default) |BASIC(browser signals) |STRICT(BASIC + camera + full screen). Applies only whendeliveryMode = ONLINE. - Data. New table
QuizAttemptEvent(attemptId,type,severity,occurredAt,meta, optionalevidenceRef, a private image id; the API hands out a short-lived signed link asevidenceUrl, see Evidence snapshots). OnQuizAttempt:riskScore(computed on the server when events arrive),reviewVerdict(UNREVIEWED|CLEAN|SUSPECTED) andreviewNote.AuditLogis not used: it is global and append-only, and a test pins its action list. - Risk score weights are constants in
packages/shared, not configurable per quiz, so scores stay comparable. An instructor reviews and marks the attempt. No automatic grade penalty. - Transport. The browser batches events about every 5 s and flushes on submit and page hide (
sendBeacon), through/bff/assessmenttoPOST /student/quiz-attempts/:attemptId/events. The server stamps the time, rate-limits, and ignores events after submission. Offline spells are kept in memory, sent on reconnect, and logged asOFFLINE. Not merged with the draft autosave. - Camera (STRICT). Analysis runs in the browser with MediaPipe Tasks Vision (face detector, face landmarker for head pose, object detector for
cell phone), loaded only for STRICT quizzes and self-hosted underapps/web/public. Sampling every 1–2 s; an event needs the condition to hold for several seconds, to avoid false alarms. Gesture recognition is out of scope for the first version. No continuous video is recorded. - Camera failures. A STRICT attempt cannot start without a working camera. Losing it mid-attempt logs a severe
CAMERA_LOST, shows an overlay asking to turn it back on, and the clock keeps running (the deadline is server-side). An instructor can move one student to BASIC. - Evidence and privacy. An explicit consent screen precedes every proctored attempt. Snapshots are taken on camera violations (max 20 per attempt) plus one baseline at the start, stored privately in Cloudinary under
smartlearn/proctoring, visible only to the course instructor and admins, and deleted by a worker job 90 days after the quiz closes. Text events live longer; they hold no images. - Code editor. BASIC and up log and warn on paste (including inside the editor) and on copying the question text. Copy, cut, undo and redo inside the editor stay free. Each quiz can allow pasting in the editor.
- Devices. STRICT only on desktop Chrome, Edge and Firefox; other devices see "this quiz needs a computer". BASIC works everywhere and skips signals that do not apply on phones.
- Review. The instructor attempt result page (
.../quizzes/[quizId]/results/[attemptId]) gets a timeline of events with evidence, the risk score, and verdict + note. The attempts list can be sorted and filtered by risk. - Stated limits. Remote-desktop software (UltraViewer and similar) and a phone photographing the screen cannot be detected or prevented from a web page. They are covered only indirectly by signals: a phone or a second person in camera, repeated looking away, odd focus patterns. We do not promise to stop them. A desktop lockdown app is out of scope.
Alternatives considered
- Hard blocking and auto-submit on violations — false positives would ruin honest students' attempts, and most actions cannot be blocked from a browser anyway.
- Recording and storing continuous video — storage and bandwidth cost, plus personal-data risk under Decree 13/2023; snapshots on violation are enough for a reviewer.
- Server-side face analysis — moves expensive work to the worker and uploads video; the browser can do it for free.
- Reusing
AuditLogfor events — wrong shape and volume, and it is pinned by a test. - Desktop lockdown app — the only real answer to remote tools; too large for this semester.
Consequences
Instructors get a reviewable signal instead of a verdict, and honest students are not locked out by mistakes. We must be honest with students and mentors that this deters but does not guarantee. New things to maintain: one table, a worker retention job, a Cloudinary image path, a self-hosted model bundle (a few MB, STRICT only), and a consent text that legal-minded readers should review.
Browser capture (#207)
- Consent comes before the attempt exists, because the attempt clock starts at creation. Resuming an attempt already in progress does not ask again. Declining is a link back to the quiz list.
- Copy and cut inside the code editor and inside answer fields are the student's own text and are not logged. Copying the question text is logged and warned. Paste is logged everywhere, except inside the code editor when the quiz sets
allowEditorPaste. Nothing is everpreventDefaulted. - A tab switch also fires
blur; a blur is logged only if the page is still visible 150 ms later, so one action is one event. Same-type repeats inside 1.5 s are one action (PrintScreen fires both keydown and keyup). - Events are queued in memory, sent about every 5 seconds in batches of at most 50, flushed before submit and when the tab is hidden (
fetchwithkeepalive), and sent withsendBeacononpagehide. While offline they stay queued and go out on theonlineevent. A 4xx answer drops the batch; 5xx and network errors keep it. A page closed while offline loses its queue.
Instructor review (#208)
GETandPATCH /courses/:courseId/quizzes/:quizId/attempts/:attemptId/proctoringreturn the timeline (oldest first), the risk score and the verdict, and set the verdict. Only the owner of the course and admins reach them; any other caller, a student included, gets 404 (ADR-0028).- A verdict is
CLEAN,SUSPECTEDorUNREVIEWED, with a note of up to 1000 characters, stored withreviewedByIdandreviewedAt.UNREVIEWEDtakes a verdict back and clears all four fields. It never touches the grade, the pass mark or the attempt status. The audit row (quiz_attempt.proctoring_reviewed) records the change of verdict and whether a note existed, not the note's text. - The attempt list adds
riskScoreandreviewVerdictper row and takessort(recent,risk_desc,risk_asc),verdictandminRisk. These fields exist only on the instructor list schema. The student result and history mappers never read them, and a test pins that. - Events carry an
evidenceUrl: a fresh signed link per event with a snapshot,nullotherwise (see Evidence snapshots below). pnpm --filter @smartlearn/database db:seed:proctoring -- --attempt <uuid> [--profile calm|mixed|heavy] [--reset]adds tagged sample events to an existing attempt on a local database, to check the page before the student side ships. It is not part ofdb:seed.
Strict gate: desktop, full screen, camera (#209)
- A Strict quiz starts only on a desktop Chrome, Edge or Firefox (version 100 or newer) whose page can reach
getUserMedia. Phones and tablets are recognised by UA Client Hints, the user agent, an iPad asking for the desktop site (a "Macintosh" with touch points) and, as the fallback for Android's "desktop site", a coarse primary pointer with no fine pointer. They read "Bài này chỉ làm được trên máy tính". The rule islib/proctoring/capability.ts. A forged user agent gets through, which is accepted: the gate is a courtesy and every signal is still logged. Basic and Off quizzes never run this check. - The consent click requests full screen and the camera in the same gesture. The attempt, and its clock, are created only after the camera is on, so a denied permission, a missing camera or a camera held by another app leaves nothing to undo. A refused full screen does not stop the start. A blocked permission lists the Chrome, Edge and Firefox steps to allow it again.
- The
MediaStreamlives inProctoringCameraProvider(useProctoringCamera():status,stream,lostReason,failure,request(),release()), above both the consent screen and the attempt. Snapshots (#210) and detection (#211) readstreamfrom there and never open the camera themselves. - A video track that ends (unplugged, permission revoked) or mutes (lens covered) reports one
CAMERA_LOST(severe, weight 10) withmeta.reasonofended,mutedornot_started(an attempt resumed in a new page has no stream yet), and shows an overlay with a retry button. It is not a lock: the clock, the server deadline and autosave are untouched, and "Tiếp tục làm bài" folds it into a banner so a student with a broken camera can still submit. QuizAttempt.proctoringLevelOverride(nullable) lets an instructor of the course, or an admin, lower ONE attempt:PATCH .../attempts/:attemptId/proctoring-levelwith{ "level": "BASIC" }. It is allowed only on a Strict quiz and only to BASIC; any other level is a 400, and a caller who may not see the attempt gets 404 first (ADR-0028). The level that applies iseffectiveProctoringLevel(quiz, override), the lower of the two, so an override never raises a quiz that was lowered later.ProctoringServicefilters events with it and the attempt paper sends it asquiz.proctoringLevel; the student never sees that an override exists. Events already logged, the risk score and the grade are untouched. Audit:quiz_attempt.proctoring_level_overridden.
Evidence snapshots (#210)
- Storage:
DocumentStorageServicekeeps snapshots as Cloudinaryimageassets of typeauthenticatedundersmartlearn/proctoring, so a read always needs a signature. The read link isprivate_download_urlwith a 5 minute expiry, made on every timeline request; nothing stores a URL. Without Cloudinary (development) the file goes tostorage/proctoring(PROCTORING_STORAGE_PATH), outside the documents directory, andGET .../proctoring/evidence/:eventIdserves it to the course instructor and admins only. A failed Cloudinary upload is a 503, never a silent copy on the API disk. - Upload:
POST student/quiz-attempts/:id/evidencetakes JSON{ type, image, occurredAt, meta? }, whereimageis a base64 JPEG. The server checks the attempt is the caller's (404 otherwise), in progress, before its deadline and effectively Strict (409 / 400), then the size (300 KB decoded, 413) and the JPEG signature (start FF D8 FF, end FF D9, 400). Types that may carry a photo areBASELINE_PHOTO(new, INFO, weight 0) and the four camera signals; any other type is a 400. Limits are 20 evidence photos plus one baseline per attempt: the 21st is a 409. Severity, weight and the atomic risk-score increment use the same table asreportEvents. BASELINE_PHOTOonly exists with a photo: the plain events route drops it.- The caps are checked before the upload (to refuse early) and again inside the write transaction, which first updates the attempt's score and so holds its row lock: two racing snapshots cannot both take the last slot. The loser's photo is deleted.
- The browser takes the baseline once the camera is on (
captureSnapshotdownscales to 640 px wide, JPEG quality 0.7 down to 0.3, then half width, until it fits). It is best effort and retries only network trouble. #211 reusescaptureSnapshotanduploadEvidencefor violation photos. - A student can send photos and can never read one: the read route lives on the instructor controller, and no student response schema has an evidence field.
Camera detection in the browser (#211)
- Bundle.
@mediapipe/tasks-visionis pinned to 1.2.3 and loaded by a dynamicimport()insidelib/proctoring/detector.ts, the only file that names the package (a test pins that). The wasm runtime and two models live inapps/web/public/proctoringwith their source URL, version, licence (Apache-2.0) and sha256 in its README, so nothing comes from a CDN. A Strict attempt starts the load when the camera is on after consent; Off and Basic attempts, and an attempt an instructor lowered to Basic, never request it. The Next build puts the package in its own lazy chunk (about 155 KB) outside the quiz page's chunk list. - Models. BlazeFace short range (230 KB) gives faces and six keypoints. A rough head angle comes from those keypoints, so the 3.7 MB face landmarker is not shipped. EfficientDet-Lite0 int8 (4.6 MB, the smallest official object detector) finds
cell phone; it runs on every second sample because it costs about ten times the face pass. - Decision rules are a pure module (
detection-rules.ts) fed frames of `{ faceCount, yaw,
pitch, phoneVisible, timestamp }. A condition fires one event after its hold time (no face 4 s, several faces 3 s, looking away 8 s, phone 3 s), tolerates one missed frame per run, then is silent for a cooldown (60 s, 120 s for no face and looking away) so a student who stays out of view does not use up the 20 photos. Every number is in detection-config.ts`. A pause of more than 10 s between frames, such as a hidden tab, restarts every hold.
- Sending. An event takes one still photo (
captureSnapshot) and goes through the evidence route, one request per event, which also creates the event row. When no photo can be taken, or the server answers with anything but success, the event goes through the normal events batch instead, so the signal is not lost. The student gets the same warning either way. - Degrading. Sampling pauses while the tab is hidden. A slow frame lengthens the gap up to 4 s; three frames in a row over 1.5 s, a failed load, or a frame that throws turn detection off for the attempt with one
console.infoline. The attempt, the clock and the #209 camera-loss overlay are unaffected. - Not calibrated. The head-angle limits and the phone score are starting values, and the CPU cost on a mid-range laptop has not been measured. The README of the bundle says how to measure it.
- Permissions-Policy.
next.config.tssentcamera=(), which blocksgetUserMediaon the site's own pages; it is nowcamera=(self).
Evidence retention (#212)
- When. An image is deleted once
Quiz.closedAt(elseQuiz.closesAt) plusPROCTORING_EVIDENCE_RETENTION_DAYS(90, inpackages/shared) is at or before now. A quiz with neither date never expires its evidence. Text events, weights andriskScoreare never touched; onlyQuizAttemptEvent.evidenceRefgoes back to null. - How it runs. An in-process timer in the worker (
workers/proctoring-retention-sweep.ts): once at boot, then every 24 hours. Not a BullMQ repeatable job: a scheduler keeps a delayed job in the queue and holds the worker to 10 s polling of the metered Redis (ADR-0059), for work that happens once a day. The payload is still a Zod schema (proctoringRetentionJobDataSchema) and is parsed before the work starts. The sweep needs no Redis and is idempotent, so two processes running it is harmless. - Order. The image is deleted first; only after that succeeded is the reference cleared. A Cloudinary error, a timeout or a missing
CLOUDINARY_*configuration leaves the reference, and the next day's run tries again. Cloudinary's "not found", or a local file already gone, counts as deleted. A reference that is not exactly the shape the api writes (smartlearn/proctoring/<uuid>orlocal/proctoring/<uuid>.jpg) is skipped and never passed to Cloudinary or the file system. - Bounded. Rows are read in id order with a cursor, 100 per round, at most 50 rounds a run, five deletions in flight. A row that keeps failing cannot hide the rows after it; what a run leaves over is picked up by the next.
- Storage. The worker destroys
imageassets of typeauthenticatedwith the sameCLOUDINARY_*names as the api (proctoring-storage.ts), and removes local-fallback files fromPROCTORING_STORAGE_PATH(defaultstorage/proctoring), which must match the api's setting. - Logs. One line with counts (deleted, failed, skipped). Never a reference, URL or id.
- Not verified. There was no Cloudinary account or database in the build environment: the Cloudinary call is unit-tested against a stand-in, and the query's
whereagainst a fake table. Run once against staging data before relying on it.