// Assessment backend for the static Space: Google Apps Script version of // server/exam.mjs. Paste this file into a new project on script.google.com, // then deploy it as a web app (see docs/exam-apps-script.md). // Script properties: EXAM_ACCESS_CODE (required), EXAM_RECIPIENT (default: // the script owner), EXAM_ID (default: exam-v1). The signing secret is // generated on first use. const EXERCISES = [1, 2, 3, 4, 5].map(n => ({ id: `exercice-${n}`, title: { fr: `Exercice ${n}`, en: `Exercise ${n}` } })); // Placeholder quiz for the public repository: the real one is in the untracked Code.exam.gs. // Quiz shown first; exercises unlock once the student clicks "Terminer le quiz". // Without choices, the answer is free text; `code` is shown as a highlighted snippet. Run reinitialiserQuiz after a test. const QUIZ = [ { id: 'q1', question: 'Question test 1 : de quelle couleur est Microduck ?', choices: ['Jaune', 'Bleu', 'Vert', 'Violet'] }, { id: 'q2', question: 'Question test 2 : combien de pattes a un canard ?', choices: ['1', '2', '3', '4'] }, { id: 'q3', question: 'Question test 3 : quel robot est à gauche dans le simulateur ?', choices: ['Reachy Mini', 'Microduck', 'Aucun'] }, { id: 'q4', question: 'Question test 4 : quel mot-clé C manque pour renvoyer la valeur ?', code: 'int carre(int x)\n{\n ??? x * x;\n}', choices: ['return', 'break', 'printf', 'main'] }, { id: 'q5', question: 'Question test 5 : écrivez une phrase de votre choix.' }, ]; const MAX_ANSWER_LENGTH = 2000; const SESSION_MS = 8 * 60 * 60 * 1000; const MAX_SOURCE_BYTES = 64 * 1024; function doPost(e) { let result; try { let body; try { body = JSON.parse(e.postData.contents); } catch (error) { throw fail('invalid_request'); } if (!body || typeof body !== 'object' || Array.isArray(body)) throw fail('invalid_request'); result = handle(body, Date.now()); } catch (error) { if (!error.code) console.error(error); result = { error: error.code || 'server_error' }; } return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType.JSON); } function doGet() { return ContentService.createTextOutput('Service d’évaluation actif.'); } // Run from the editor after a test: every student can take the quiz again. function reinitialiserQuiz() { const props = PropertiesService.getScriptProperties(); const keys = props.getKeys().filter(key => key.startsWith('quiz:')); for (const key of keys) props.deleteProperty(key); console.log(`${keys.length} quiz réinitialisé(s).`); } // Run once from the editor: it asks for the Gmail and Drive permissions. function autoriser() { folder('suivi'); folder('copies'); console.log(`Copies envoyées à ${config().recipient}. Quota email restant aujourd’hui : ${MailApp.getRemainingDailyQuota()}`); } function fail(code) { return Object.assign(new Error(code), { code }); } function config() { const props = PropertiesService.getScriptProperties(); let secret = props.getProperty('EXAM_SESSION_SECRET'); if (!secret) { secret = Utilities.getUuid() + Utilities.getUuid(); props.setProperty('EXAM_SESSION_SECRET', secret); } return { code: (props.getProperty('EXAM_ACCESS_CODE') || '').trim(), recipient: (props.getProperty('EXAM_RECIPIENT') || '').trim() || Session.getEffectiveUser().getEmail(), examId: (props.getProperty('EXAM_ID') || '').trim() || 'exam-v1', secret, }; } function hex(bytes) { return bytes.map(b => ((b + 256) % 256).toString(16).padStart(2, '0')).join(''); } function hash(value) { return hex(Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, value, Utilities.Charset.UTF_8)); } function utf8Bytes(value) { return Utilities.newBlob(value).getBytes().length; } function handle(body, now) { const settings = config(); if (!settings.code) throw fail('exam_unavailable'); const cache = CacheService.getScriptCache(); const props = PropertiesService.getScriptProperties(); const quizKey = session => `quiz:${settings.examId}:${session.studentKey}`; const sign = payload => Utilities.base64EncodeWebSafe(Utilities.computeHmacSha256Signature(payload, settings.secret)); const summary = session => { const quizDone = Boolean(props.getProperty(quizKey(session))); return { student: session.student, studentKey: session.studentKey, expiresAt: session.expiresAt, exam: { id: settings.examId, exercises: EXERCISES, quiz: quizDone ? [] : QUIZ }, quizDone, submissionAvailable: Boolean(settings.recipient), }; }; const authenticate = () => { const token = typeof body.token === 'string' ? body.token : ''; const [payload, signature, extra] = token.split('.'); if (token.length > 2048 || !payload || !signature || extra || sign(payload) !== signature) throw fail('session_expired'); let session; try { session = JSON.parse(Utilities.newBlob(Utilities.base64DecodeWebSafe(payload)).getDataAsString('UTF-8')); } catch (error) { throw fail('session_expired'); } if (session.examId !== settings.examId || !Number.isFinite(session.expiresAt) || session.expiresAt <= now) throw fail('session_expired'); return session; }; if (body.action === 'access') { const { code, student } = body; const attemptsKey = `fail:${hash(String(student || '').trim().toLocaleLowerCase('fr'))}`; const attempts = Number(cache.get(attemptsKey) || 0); if (attempts >= 12) throw fail('too_many_attempts'); if (typeof code !== 'string' || code.length > 256 || code.trim() !== settings.code) { cache.put(attemptsKey, String(attempts + 1), 15 * 60); throw fail('invalid_code'); } if (typeof student !== 'string' || student.trim().length < 2 || student.length > 100 || /[\u0000-\u001f\u007f]/.test(student)) throw fail('invalid_student'); cache.remove(attemptsKey); const name = student.trim().replace(/\s+/g, ' ').normalize('NFC'); const session = { examId: settings.examId, student: name, studentKey: hash(`${settings.examId}:${name.toLocaleLowerCase('fr')}`), expiresAt: now + SESSION_MS }; const payload = Utilities.base64EncodeWebSafe(JSON.stringify(session), Utilities.Charset.UTF_8); return { ...summary(session), token: `${payload}.${sign(payload)}` }; } if (body.action === 'session') return summary(authenticate()); if (body.action === 'activity') { const session = authenticate(); saveActivity({ examId: settings.examId, student: session.student, studentKey: session.studentKey, receivedAt: now, activity: validateActivity(body.activity, now) }); return { saved: true }; } if (body.action === 'quiz') { const session = authenticate(); const answers = body.answers; if (!answers || typeof answers !== 'object' || Array.isArray(answers) || Object.keys(answers).some(id => !QUIZ.some(item => item.id === id)) || QUIZ.some(item => answers[item.id] !== undefined && (typeof answers[item.id] !== 'string' || answers[item.id].length > MAX_ANSWER_LENGTH || (item.choices && answers[item.id] && !item.choices.includes(answers[item.id]))))) throw fail('invalid_answers'); if (!settings.recipient) throw fail('mail_unavailable'); // Once finished, the quiz is closed: a retry gets the first receipt, never a second email. const lock = LockService.getScriptLock(); lock.waitLock(30000); try { const done = props.getProperty(quizKey(session)); if (done) return JSON.parse(done); const receipt = sendQuiz({ settings, session, answers, now }); props.setProperty(quizKey(session), JSON.stringify(receipt)); return receipt; } finally { lock.releaseLock(); } } if (body.action === 'submit' || body.action === 'submit-all') { const session = authenticate(); const { exerciseId, source, requestId, copies, activity } = body; const all = body.action === 'submit-all'; const exercise = EXERCISES.find(item => item.id === exerciseId); if ((!all && !exercise) || typeof requestId !== 'string' || !/^[\da-f-]{36}$/i.test(requestId)) throw fail('invalid_request'); let entries; if (all) { if (!Array.isArray(copies) || copies.length !== EXERCISES.length || new Set(copies.map(item => item && item.exerciseId)).size !== EXERCISES.length) throw fail('invalid_request'); entries = EXERCISES.map(item => ({ exercise: item, source: (copies.find(copy => copy && copy.exerciseId === item.id) || {}).source })); } else entries = [{ exercise, source }]; if (entries.some(item => typeof item.source !== 'string')) throw fail('invalid_request'); if (!entries.some(item => item.source.trim())) throw fail('empty_source'); if (entries.some(item => utf8Bytes(item.source) > MAX_SOURCE_BYTES)) throw fail('source_too_large'); if (!settings.recipient) throw fail('mail_unavailable'); if (activity) { const record = { examId: settings.examId, student: session.student, studentKey: session.studentKey, receivedAt: now, activity: validateActivity(activity, now) }; withDrive(() => saveActivity(record)); } // Retrying the same request cannot send twice, including concurrent clicks. const key = hash(JSON.stringify([settings.examId, session.studentKey, all, entries.map(item => [item.exercise.id, item.source]), requestId])); const lock = LockService.getScriptLock(); lock.waitLock(30000); try { const sent = cache.get(`sent:${key}`); if (sent) return JSON.parse(sent); const rateKey = `rate:${session.studentKey}`, rate = Number(cache.get(rateKey) || 0); if (rate >= 6) throw fail('too_many_submissions'); cache.put(rateKey, String(rate + 1), 60); const receipt = sendCopies({ settings, session, entries, all, now, key }); cache.put(`sent:${key}`, JSON.stringify(receipt), 6 * 60 * 60); return receipt; } finally { lock.releaseLock(); } } throw fail('not_found'); } function sendCopies({ settings, session, entries, all, now, key }) { const student = session.student; const slug = student.normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^a-zA-Z0-9_-]+/g, '-').slice(0, 60) || 'student'; const title = all ? 'Tous les exercices' : entries[0].exercise.title.fr; const answered = item => Boolean(item.source.trim()); const files = entries.map(item => Utilities.newBlob(answered(item) ? item.source : '/* Non répondu */\n', 'text/plain', `${slug}-${item.exercise.id}.c`)); files.push(Utilities.newBlob(withDrive(() => activityReport(listActivity(settings.examId, session.studentKey), now), DRIVE_MISSING), 'text/plain', `${slug}-suivi.txt`)); const inventory = entries.map(item => `${item.exercise.title.fr} : ${answered(item) ? 'copie jointe' : 'non répondu'}`).join('\n'); try { MailApp.sendEmail({ to: settings.recipient, name: 'Évaluation C', subject: `[Évaluation C] ${student} — ${title}`, body: `Étudiant : ${student}\nExamen : ${settings.examId}\nDate : ${new Date(now).toISOString()}\n\n${inventory}\n\nLes copies et le journal de visibilité sont joints à cet email.`, attachments: files, }); } catch (error) { console.error(error); throw fail('mail_failed'); } // Backup in Drive, after the email has been accepted. const stamp = new Date(now).toISOString().replace(/[:.]/g, '-'); withDrive(() => { const copies = folder('copies'); for (const file of files) copies.createFile(file.copyBlob().setName(`${stamp}-${file.getName()}`)); }); return { id: `exam-${key.slice(0, 24)}`, sentAt: new Date(now).toISOString() }; } function sendQuiz({ settings, session, answers, now }) { const student = session.student; const slug = student.normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^a-zA-Z0-9_-]+/g, '-').slice(0, 60) || 'student'; const report = QUIZ.map((item, index) => `${index + 1}. ${item.question}\n→ ${(answers[item.id] || '').trim() || '(sans réponse)'}`).join('\n\n'); const file = Utilities.newBlob(`${student}\n\n${report}\n`, 'text/plain', `${slug}-quiz.txt`); try { MailApp.sendEmail({ to: settings.recipient, name: 'Évaluation C', subject: `[Évaluation C] ${student} — Quiz`, body: `Étudiant : ${student}\nExamen : ${settings.examId}\nDate : ${new Date(now).toISOString()}\n\n${report}\n`, attachments: [file], }); } catch (error) { console.error(error); throw fail('mail_failed'); } withDrive(() => folder('copies').createFile(file.copyBlob().setName(`${new Date(now).toISOString().replace(/[:.]/g, '-')}-${file.getName()}`))); return { id: `quiz-${hash(`${settings.examId}:${session.studentKey}`).slice(0, 24)}`, sentAt: new Date(now).toISOString() }; } // Storage: a Drive folder "Évaluation C" with the journals in suivi/ and a // copy of every submitted file in copies/. function folder(name) { const props = PropertiesService.getScriptProperties(); let root = null; try { root = props.getProperty('EXAM_FOLDER_ID') ? DriveApp.getFolderById(props.getProperty('EXAM_FOLDER_ID')) : null; } catch (error) { root = null; } if (!root) { root = DriveApp.createFolder('Évaluation C'); props.setProperty('EXAM_FOLDER_ID', root.getId()); } if (!name) return root; const found = root.getFoldersByName(name); return found.hasNext() ? found.next() : root.createFolder(name); } // Drive only keeps the journal and backups: without it, the emails still go out. const DRIVE_MISSING = 'Journal indisponible : Google Drive n’est pas autorisé pour ce script (exécuter autoriser).'; function withDrive(action, fallback) { try { return action(); } catch (error) { console.error(error); return fallback; } } function saveActivity(record) { const lock = LockService.getScriptLock(); lock.waitLock(30000); try { const target = folder('suivi'); const name = `${record.studentKey}-${hash(`${record.examId}:${record.activity.id}`)}.json`; const found = target.getFilesByName(name); if (!found.hasNext()) { target.createFile(name, JSON.stringify(record), 'application/json'); return; } const file = found.next(); if (JSON.parse(file.getBlob().getDataAsString('UTF-8')).activity.revision >= record.activity.revision) return; file.setContent(JSON.stringify(record)); } finally { lock.releaseLock(); } } function listActivity(examId, studentKey) { const records = [], files = folder('suivi').getFiles(); while (files.hasNext()) { const file = files.next(); if (studentKey && !file.getName().startsWith(`${studentKey}-`)) continue; const record = JSON.parse(file.getBlob().getDataAsString('UTF-8')); if (record.examId === examId) records.push(record); } return records.sort((a, b) => a.receivedAt - b.receivedAt); } // Teacher report for the whole class: run from the editor, then open the log. function rapportDeSuivi() { console.log(activityReport(listActivity(config().examId), Date.now())); } // Copied from shared/examActivity.js (test/apps-script.test.js checks they match). const ACTIVITY_LIMIT = 500; const ACTIVITY_STATES = ['active', 'hidden', 'unfocused', 'outside', 'closed', 'finished']; // Clues of outside help (AI side panels, extensions, pasted code), recorded alongside the journal. const SIGNAL_LIMIT = 200; const SIGNAL_KINDS = ['paste', 'drop', 'copy', 'insertion', 'synthetic', 'panel', 'extension']; const SIGNAL_LABELS = { paste: 'collage', drop: 'texte déposé (glisser-déposer)', copy: 'copie depuis l’évaluation', insertion: 'bloc de texte inséré sans frappe', synthetic: 'modification par un script ou une extension', panel: 'panneau latéral du navigateur ouvert / fermé', extension: 'élément ajouté à la page par une extension' }; function activitySummary(log, until = Date.now()) { const periods = []; let away; for (const event of (log && log.events) || []) { if (event.state === 'active' || event.state === 'finished') { if (away) { periods.push({ ...away, end: event.at, durationMs: Math.max(0, event.at - away.start) }); away = null; } } else if (!away) away = { start: event.at, reasons: [event.state] }; else if (!away.reasons.includes(event.state)) away.reasons.push(event.state); } if (away) periods.push({ ...away, end: null, durationMs: Math.max(0, until - away.start) }); return { periods, count: periods.length, totalMs: periods.reduce((sum, item) => sum + item.durationMs, 0) }; } function validateActivity(value, now = Date.now()) { const invalid = () => { throw fail('invalid_activity'); }; if (!value || !/^[a-f\d-]{36}$/i.test(value.id) || !Number.isSafeInteger(value.revision) || value.revision < 1 || !Number.isSafeInteger(value.dropped) || value.dropped < 0 || !Array.isArray(value.events) || !value.events.length || value.events.length > ACTIVITY_LIMIT) invalid(); let previous = 0; const events = value.events.map(event => { if (!event || !ACTIVITY_STATES.includes(event.state) || !Number.isSafeInteger(event.at) || event.at < previous || event.at < 0 || event.at > now + 300000) invalid(); previous = event.at; return { at: event.at, state: event.state }; }); const signals = value.signals ?? [], signalsDropped = value.signalsDropped ?? 0; if (!Array.isArray(signals) || signals.length > SIGNAL_LIMIT || !Number.isSafeInteger(signalsDropped) || signalsDropped < 0) invalid(); return { id: value.id, revision: value.revision, dropped: value.dropped, events, signalsDropped, signals: signals.map(signal => { if (!signal || !SIGNAL_KINDS.includes(signal.kind) || !Number.isSafeInteger(signal.at) || signal.at < 0 || signal.at > now + 300000 || typeof signal.detail !== 'string' || signal.detail.length > 120) invalid(); return { at: signal.at, kind: signal.kind, detail: signal.detail }; }) }; } function activityReport(records, until = Date.now()) { const labels = { hidden: 'onglet masqué / fenêtre réduite', unfocused: 'perte de focus', outside: 'évaluation quittée', closed: 'page quittée / rechargée' }; const lines = ['JOURNAL DE VISIBILITÉ — horodatages UTC', 'Signaux déclarés par le navigateur, non certifiés : ils ne prouvent pas une fraude.', 'Les durées en cours sont calculées jusqu’à ce rapport. Une fermeture brutale peut ne pas être signalée.', 'Les sessions / onglets sont présentés séparément ; leurs durées peuvent se chevaucher.', 'Les signaux d’aide extérieure possible (IA du navigateur, extensions, collages) sont des indices à vérifier, pas des preuves.', '']; if (!records.length) lines.push('Aucun journal disponible.'); for (const record of records) { const log = record.activity; const summary = activitySummary(log, until); lines.push(`${record.student} — examen ${record.examId} — session ${log.id}`, `Dernière réception serveur : ${new Date(record.receivedAt).toISOString()}`, `${summary.count} sortie(s), ${(summary.totalMs / 1000).toFixed(1)} s cumulées.`); if (log.dropped) lines.push(`Journal partiel : ${log.dropped} ancien(s) événement(s) non conservé(s).`); for (const period of summary.periods) lines.push( `${new Date(period.start).toISOString()} → ${period.end === null ? 'retour non observé' : new Date(period.end).toISOString()} | ${(period.durationMs / 1000).toFixed(1)} s | ${period.reasons.map(reason => labels[reason]).join(', ')}`); const signals = log.signals || []; if (signals.length || log.signalsDropped) lines.push(`${signals.length + (log.signalsDropped || 0)} signal(aux) d’aide extérieure possible :`); if (log.signalsDropped) lines.push(`Signaux partiels : ${log.signalsDropped} ancien(s) signal(aux) non conservé(s).`); for (const signal of signals) lines.push(`${new Date(signal.at).toISOString()} | ${SIGNAL_LABELS[signal.kind]} | ${signal.detail}`); lines.push(''); } return lines.join('\n'); }