Skip to content

Commit 1e56dfa

Browse files
committed
feat(proctoring): add anti-cheating protections and proctoring violation tracking
1 parent c10c9b9 commit 1e56dfa

9 files changed

Lines changed: 1573 additions & 385 deletions

File tree

‎frontend/src/components/ProctoringMonitor.vue‎

Lines changed: 163 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,9 @@ let stream = null
149149
let setupInterval = null
150150
let monitorInterval = null
151151
let focusBlurTimer = null
152+
let tabHiddenAt = 0
153+
let monitoredTrack = null
154+
let isDestroyed = false
152155
let noFaceStreak = 0
153156
let multiFaceStreak = 0
154157
// When each condition was first warned about, so the violation can be held back
@@ -160,8 +163,8 @@ const STREAK_THRESHOLD = 3
160163
const ESCALATION_GAP = 10_000
161164
// Wide enough to recognise a face and read a room, small enough that forty of them
162165
// still make a reasonable request.
163-
const FRAME_WIDTH = 320
164-
const FRAME_QUALITY = 0.6
166+
const FRAME_WIDTH = 240
167+
const FRAME_QUALITY = 0.5
165168
let cameraReadyEmitted = false
166169
167170
const setupStatusLabel = computed(() => {
@@ -188,31 +191,62 @@ const setMinimized = async (value) => {
188191
189192
onMounted(async () => {
190193
await startCamera()
194+
// Unmount during getUserMedia used to fall through and attach the clipboard
195+
// listeners anyway. Nothing removes them after onUnmounted.
196+
if (isDestroyed || !props.active) return
191197
// Monitoring instance mounts with active=true — skip setup, go straight to monitoring
192-
if (props.active) {
193-
clearInterval(setupInterval)
194-
phase.value = 'monitoring'
195-
// Wait for the monitoring <video> element to mount, then re-attach the stream
196-
await nextTick()
197-
if (videoEl.value && stream) videoEl.value.srcObject = stream
198-
startMonitoring()
199-
}
198+
clearInterval(setupInterval)
199+
setupInterval = null
200+
phase.value = 'monitoring'
201+
// Wait for the monitoring <video> element to mount, then re-attach the stream
202+
await nextTick()
203+
if (isDestroyed || !props.active) return
204+
if (videoEl.value && stream) videoEl.value.srcObject = stream
205+
startMonitoring()
200206
})
201207
202208
onUnmounted(() => {
209+
isDestroyed = true
203210
stopAll()
204211
})
205212
206213
// ─── Setup phase ─────────────────────────────────────────────────────────────
207214
208-
const startCamera = async () => {
215+
// Acquire the camera stream without touching the setup UI. Called on mount and
216+
// again when monitoring resumes after stopCamera() released the stream.
217+
const acquireStream = async () => {
218+
if (stream) return true
209219
try {
210-
stream = await navigator.mediaDevices.getUserMedia({ video: true })
220+
let mediaStream
221+
try {
222+
// On mobile, request front-facing (selfie) camera for face proctoring
223+
mediaStream = await navigator.mediaDevices.getUserMedia({
224+
video: { facingMode: 'user' },
225+
})
226+
} catch {
227+
mediaStream = await navigator.mediaDevices.getUserMedia({ video: true })
228+
}
229+
if (isDestroyed) {
230+
mediaStream.getTracks?.().forEach((t) => t.stop())
231+
return false
232+
}
233+
stream = mediaStream
234+
return true
211235
} catch {
236+
if (isDestroyed) return false
212237
cameraError.value = __(
213238
'Camera access was denied. Please allow camera access and reload.'
214239
)
215240
emit('camera-denied')
241+
return false
242+
}
243+
}
244+
245+
const startCamera = async () => {
246+
if (!(await acquireStream())) return
247+
248+
if (isDestroyed) {
249+
stopCamera()
216250
return
217251
}
218252
@@ -225,12 +259,18 @@ const startCamera = async () => {
225259
'/assets/lms/frontend/models'
226260
)
227261
} catch {
262+
if (isDestroyed) return
228263
cameraError.value = __(
229264
'Failed to load face detection models. Please reload.'
230265
)
231266
return
232267
}
233268
269+
if (isDestroyed) {
270+
stopCamera()
271+
return
272+
}
273+
234274
setupStatus.value = 'detecting'
235275
setupInterval = setInterval(runSetupDetection, 800)
236276
}
@@ -268,23 +308,72 @@ watch(
268308
async (active) => {
269309
if (active) {
270310
clearInterval(setupInterval)
311+
setupInterval = null
271312
phase.value = 'monitoring'
313+
// stopCamera() releases the stream when monitoring stops, so resuming
314+
// (a failed submit put the attempt back in progress) has to reacquire
315+
// it, not just reattach the old, stopped tracks.
316+
await acquireStream()
317+
// The attempt can end, or this instance can unmount, while getUserMedia
318+
// is still pending. Starting the listeners then leaves copy, paste and
319+
// the keyboard blocked on a page that is no longer an exam.
320+
if (isDestroyed || !props.active) {
321+
stopCamera()
322+
return
323+
}
272324
await nextTick()
325+
if (isDestroyed || !props.active) {
326+
stopCamera()
327+
return
328+
}
273329
if (videoEl.value && stream) videoEl.value.srcObject = stream
274330
startMonitoring()
331+
} else {
332+
stopMonitoring()
333+
stopCamera()
275334
}
276335
}
277336
)
278337
279338
// ─── Monitoring phase ─────────────────────────────────────────────────────────
280339
281340
const startMonitoring = () => {
341+
stopMonitoring()
342+
tabHiddenAt = 0
282343
monitorInterval = setInterval(runMonitorDetection, 2000)
283344
document.addEventListener('visibilitychange', onVisibilityChange)
345+
// Capture so a child that stops the event (the answer editor, for one)
346+
// cannot let a copy or a devtools shortcut through.
347+
document.addEventListener('copy', onCopy, true)
348+
document.addEventListener('paste', onPaste, true)
349+
document.addEventListener('cut', onCut, true)
350+
document.addEventListener('contextmenu', onContextMenu, true)
351+
window.addEventListener('keydown', onKeyDown, true)
284352
window.addEventListener('blur', onWindowBlur)
285353
window.addEventListener('focus', onWindowFocus)
286-
const videoTrack = stream?.getVideoTracks?.()?.[0]
287-
if (videoTrack) videoTrack.addEventListener('ended', onCameraDisconnect)
354+
monitoredTrack = stream?.getVideoTracks?.()?.[0] ?? null
355+
monitoredTrack?.addEventListener('ended', onCameraDisconnect)
356+
}
357+
358+
const stopMonitoring = () => {
359+
if (monitorInterval) {
360+
clearInterval(monitorInterval)
361+
monitorInterval = null
362+
}
363+
if (focusBlurTimer) {
364+
clearTimeout(focusBlurTimer)
365+
focusBlurTimer = null
366+
}
367+
monitoredTrack?.removeEventListener?.('ended', onCameraDisconnect)
368+
monitoredTrack = null
369+
document.removeEventListener('visibilitychange', onVisibilityChange)
370+
document.removeEventListener('copy', onCopy, true)
371+
document.removeEventListener('paste', onPaste, true)
372+
document.removeEventListener('cut', onCut, true)
373+
document.removeEventListener('contextmenu', onContextMenu, true)
374+
window.removeEventListener('keydown', onKeyDown, true)
375+
window.removeEventListener('blur', onWindowBlur)
376+
window.removeEventListener('focus', onWindowFocus)
288377
}
289378
290379
const runMonitorDetection = async () => {
@@ -365,19 +454,56 @@ const captureFrame = () => {
365454
}
366455
367456
const onVisibilityChange = () => {
457+
if (document.visibilityState !== 'hidden') return
458+
tabHiddenAt = Date.now()
459+
// blur often fires while the tab is still visible, and the timer would
460+
// otherwise count focus_loss on top of the tab switch.
461+
if (focusBlurTimer) {
462+
clearTimeout(focusBlurTimer)
463+
focusBlurTimer = null
464+
}
368465
// The element keeps its frames while the tab is hidden, so the still shows
369466
// what the camera saw at the moment they switched away.
370-
if (document.visibilityState === 'hidden')
371-
emit('violation', 'tab_switch', captureFrame())
467+
if (props.active) emit('violation', 'tab_switch', captureFrame())
468+
}
469+
470+
// Silently prevent copying, cutting, pasting, right-click, and devtools/inspection shortcuts
471+
const onCopy = (e) => e.preventDefault()
472+
const onCut = (e) => e.preventDefault()
473+
const onPaste = (e) => e.preventDefault()
474+
const onContextMenu = (e) => e.preventDefault()
475+
476+
const matchesShortcut = (e, letters) => {
477+
const key = e.key?.toLowerCase()
478+
if (letters.includes(key)) return true
479+
// Option on macOS rewrites e.key (Cmd+Option+I reports a dead key), so the
480+
// physical key is what identifies the devtools shortcuts.
481+
return letters.some((letter) => e.code === `Key${letter.toUpperCase()}`)
482+
}
483+
484+
const onKeyDown = (e) => {
485+
const ctrlOrCmd = e.ctrlKey || e.metaKey
486+
const devtools =
487+
e.key === 'F12' ||
488+
e.code === 'F12' ||
489+
(ctrlOrCmd &&
490+
(e.shiftKey || e.altKey) &&
491+
matchesShortcut(e, ['i', 'j', 'c', 'k', 'u']))
492+
const clipboard =
493+
ctrlOrCmd && !e.altKey && matchesShortcut(e, ['c', 'v', 'x', 'u', 'p', 's'])
494+
495+
if (devtools || clipboard) e.preventDefault()
372496
}
373497
374498
const onWindowBlur = () => {
375499
// Tab switch is already handled by visibilitychange — skip to avoid duplicate events
376-
if (document.visibilityState === 'hidden') return
377-
focusBlurTimer = setTimeout(
378-
() => emit('violation', 'focus_loss', captureFrame()),
379-
10_000
380-
)
500+
if (!props.active || document.visibilityState === 'hidden') return
501+
if (focusBlurTimer) clearTimeout(focusBlurTimer)
502+
focusBlurTimer = setTimeout(() => {
503+
focusBlurTimer = null
504+
if (!props.active || document.visibilityState === 'hidden') return
505+
emit('violation', 'focus_loss', captureFrame())
506+
}, 1500)
381507
}
382508
383509
const onWindowFocus = () => {
@@ -392,13 +518,22 @@ const onCameraDisconnect = () =>
392518
393519
// ─── Cleanup ──────────────────────────────────────────────────────────────────
394520
521+
const stopCamera = () => {
522+
if (stream) {
523+
stream.getTracks?.().forEach((t) => t.stop())
524+
stream = null
525+
}
526+
if (videoEl.value) {
527+
videoEl.value.srcObject = null
528+
}
529+
}
530+
395531
const stopAll = () => {
396-
clearInterval(setupInterval)
397-
clearInterval(monitorInterval)
398-
clearTimeout(focusBlurTimer)
399-
document.removeEventListener('visibilitychange', onVisibilityChange)
400-
window.removeEventListener('blur', onWindowBlur)
401-
window.removeEventListener('focus', onWindowFocus)
402-
stream?.getTracks?.().forEach((t) => t.stop())
532+
if (setupInterval) {
533+
clearInterval(setupInterval)
534+
setupInterval = null
535+
}
536+
stopMonitoring()
537+
stopCamera()
403538
}
404539
</script>

0 commit comments

Comments
 (0)