Problem
In online classes the material is usually separate from the whiteboard: the teacher shares the screen, but students can't interact with the content or take notes on it together.
technical case study
Web App • Live class / Real time
A platform for teaching on top of HTML documents: the teacher opens a lesson from the library, everyone draws on it at the same time, and scrolling, opened answers and fields stay the same on every device.
Drawing mode: the teacher circles the formula and highlights the key points; the green check came from the student's phone.
On her phone, the student joins through the link: the page follows the teacher and strokes arrive in real time.
Live class panel: a 5-character code, a link to join and who is in the room.
Document library: each lesson is an HTML file the teacher imports with the password.
Create a lesson with Claude: subject, topic, audience and lesson type become a ready prompt to generate the lesson's HTML.
In online classes the material is usually separate from the whiteboard: the teacher shares the screen, but students can't interact with the content or take notes on it together.
An app where the lesson document itself becomes the whiteboard: everyone draws on it, the teacher leads the scrolling, and the document's answers, fields and buttons stay in sync.
Live classes with up to 30 people per room, joining by link or code, drawings kept per document and a library that survives server updates.
Public version on GitHub, ready to run on a VPS with Docker and Traefik.
The idea is to teach on top of single-file HTML pages, written by hand or generated with AI from a standard prompt. The server is written in plain PHP with no libraries: it serves the app, stores the library and relays, in real time over WebSocket, the strokes, clicks and scrolling of everyone in the same room.
An app in HTML, CSS and JavaScript with no framework: a canvas over the document for strokes (pen, highlighter and eraser), other people's cursors and a bridge (ponte.js) that runs inside each document and talks to the app through postMessage.
server.php implements HTTP and WebSocket from scratch with stream_select: it serves the files, the library API and the login, and relays live messages to everyone in the same room. It runs in Docker behind Traefik, which handles HTTPS.
No database: the library is a JSON index, written atomically, with the HTML files in a Docker volume that survives git pull, restarts and new versions of the app.
Each lesson is served with a sandbox Content-Security-Policy: the imported HTML runs isolated and can't see the login or the app's data.
The password is compared with hash_equals, the token is signed with HMAC and lasts 30 days, and there is a 15-minute wait after 10 wrong attempts.
The WebSocket only accepts connections from its own origin and limits message size, messages per person and people per room.
HTTP and WebSocket implemented on top of sockets, without any library.
A canvas over the document, strokes sent in 50 ms batches and a bridge to sync fields and answers.
Importing, editing and deleting documents with a password, keeping everything in a Docker volume.
A standard prompt and lesson template to create new documents with Claude.
An open repository with Docker, Traefik and a guide to installing it on a VPS.
private function login(int $k, array $h, string $corpo): void
{
if ($this->senha === '') {
$this->responderJson($k, 503, ['erro' => 'A importação está desligada. Defina SENHA_PROFESSOR no arquivo .env da VPS e reinicie.']);
return;
}
$ip = $this->ipDe($k, $h);
$agora = time();
$this->falhas[$ip] = array_values(array_filter($this->falhas[$ip] ?? [], fn($t) => $agora - $t < JANELA_FALHAS));
if (count($this->falhas[$ip]) >= MAX_FALHAS) {
$this->responderJson($k, 429, ['erro' => 'Muitas tentativas erradas. Espere 15 minutos e tente de novo.']);
return;
}
$d = json_decode($corpo, true);
$senha = is_array($d) && is_string($d['senha'] ?? null) ? $d['senha'] : '';
if (!hash_equals($this->senha, $senha)) {
$this->falhas[$ip][] = $agora;
$this->log("Senha de professor errada ($ip)");
$this->responderJson($k, 401, ['erro' => 'Senha incorreta.']);
return;
}
unset($this->falhas[$ip]);
$exp = $agora + TOKEN_DIAS * 86400;
$this->responderJson($k, 200, ['token' => $exp . '.' . hash_hmac('sha256', 'aula:' . $exp, $this->senha)]);
}
/** @param array<string, string> $h */
private function autorizado(array $h): bool
{
if ($this->senha === '') {
return false;
}
if (!preg_match('/^Bearer\s+(\d{9,12})\.([a-f0-9]{64})$/', $h['authorization'] ?? '', $m)) {
return false;
}
return (int) $m[1] >= time() && hash_equals(hash_hmac('sha256', 'aula:' . $m[1], $this->senha), $m[2]);
}
private function servirDoc(int $k, string $id, bool $soCab): void
{
$html = @file_get_contents($this->arquivoDoc($id));
$codigo = 200;
if ($html === false) {
$codigo = 404;
$html = '<!doctype html><html lang="pt-BR"><head><meta charset="utf-8"><title>Documento não encontrado</title></head>'
. '<body style="font:16px/1.5 system-ui,sans-serif;padding:2rem;margin:0">'
. '<h1 style="font-size:1.4rem">Esse documento não existe mais.</h1>'
. '<p>Ele pode ter sido apagado da biblioteca. Escolha outro em Documentos.</p></body></html>';
}
$temCharset = (bool) preg_match('/<meta[^>]+charset/i', substr($html, 0, 4096));
$this->responder($k, $codigo, 'text/html' . ($temCharset ? '' : '; charset=utf-8'), $this->injetarPonte($html), $soCab, [
/* O documento roda isolado: não enxerga o login nem os dados do aplicativo. */
'Content-Security-Policy' => 'sandbox allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals',
]);
}
private function injetarPonte(string $html): string
{
$tag = '<script src="/ponte.js"></script>';
foreach (['/<head\b[^>]*>/i', '/<html\b[^>]*>/i'] as $re) {
if (preg_match($re, $html, $m, PREG_OFFSET_CAPTURE)) {
$pos = $m[0][1] + strlen($m[0][0]);
return substr($html, 0, $pos) . $tag . substr($html, $pos);
}
}
if (preg_match('/^\s*<!doctype[^>]*>/i', $html, $m)) {
return $m[0] . $tag . substr($html, strlen($m[0]));
}
return $tag . $html;
}
private function texto(int $k, string $txt): void
{
$d = json_decode($txt, false, 64);
if (!($d instanceof stdClass) || !isset($d->tipo) || !is_string($d->tipo)) {
return;
}
switch ($d->tipo) {
case 'pulso':
$this->enviarJson($k, ['tipo' => 'pulso']);
return;
case 'entrar':
$this->entrar($k, $d);
return;
case 'msg':
$sala = $this->c[$k]['sala'];
if ($sala === null || !isset($d->m) || !($d->m instanceof stdClass) || !$this->dentroDoLimite($k)) {
return;
}
$json = json_encode(['tipo' => 'msg', 'm' => $d->m], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($json !== false) {
$this->paraSala($sala, $json, $k);
}
return;
}
}
var enviados = 0, timerPts = null;
cv.addEventListener('pointerdown', function(e){
if (!ativo || !doc) return;
if (e.pointerType === 'mouse' && e.button !== 0) return;
e.preventDefault();
pointers.set(e.pointerId, e.clientY);
try { cv.setPointerCapture(e.pointerId); } catch(_){}
if (pointers.size >= 2){
if (atual) enviar({t:'del', d:atual.d, id:atual.id});
atual = null; panning = true; lastPanY = media(); pararDeSeguir(); pedir();
return;
}
if (panning) return;
var w = ferramenta.tool === 'marca' ? 20 : ferramenta.tool === 'borracha' ? 28 : 3.5;
var pt = paraPagina(e.clientX, e.clientY);
atual = {id:meuId + '-' + (++seq), d:doc.id, tool:ferramenta.tool, color:ferramenta.color, w:w, pts:[pt], minY:pt[1], maxY:pt[1]};
enviados = 1;
enviar({t:'s0', d:doc.id, id:atual.id, tool:atual.tool, color:atual.color, w:w, p:[r1(pt[0]), r1(pt[1])]});
pedir();
});
cv.addEventListener('pointermove', function(e){
if (!ativo || !pointers.has(e.pointerId)) return;
pointers.set(e.pointerId, e.clientY);
if (panning){ var m = media(); window.scrollBy(0, lastPanY - m); lastPanY = m; return; }
if (!atual) return;
var evs = (e.getCoalescedEvents && e.getCoalescedEvents()) || [];
if (!evs.length) evs = [e];
evs.forEach(function(ev){
var pt = paraPagina(ev.clientX, ev.clientY), last = atual.pts[atual.pts.length - 1];
if (Math.abs(pt[0] - last[0]) + Math.abs(pt[1] - last[1]) < 1.5) return;
atual.pts.push(pt);
if (pt[1] < atual.minY) atual.minY = pt[1];
if (pt[1] > atual.maxY) atual.maxY = pt[1];
});
agendarPontos();
pedir();
});
function agendarPontos(){
if (timerPts || !conectado) return;
timerPts = setTimeout(function(){
timerPts = null;
if (atual && atual.pts.length > enviados){
enviar({t:'sp', d:atual.d, id:atual.id, pts:atual.pts.slice(enviados).map(function(p){ return [r1(p[0]), r1(p[1])]; })});
enviados = atual.pts.length;
}
}, 50);
}
/* ---------------- o que acontece aqui vai para os outros ---------------- */
var aplicando = false;
function aoCampo(e){
if (aplicando) return;
var el = e.target;
if (!el || !/^(INPUT|SELECT|TEXTAREA)$/.test(el.tagName) || ignorarCampo(el)) return;
var k = chave(el, 'campo');
if (k) postar({tipo:'evento', e:{k:'campo', id:k, v:valor(el), ev:e.type === 'change' ? 'change' : 'input'}});
}
document.addEventListener('input', aoCampo, true);
document.addEventListener('change', aoCampo, true);
document.addEventListener('toggle', function(e){
var d = e.target;
if (!d || d.tagName !== 'DETAILS') return;
agendarMedida();
if (d._aulaRemoto){ d._aulaRemoto = false; return; }
var k = chave(d, 'det');
if (k) postar({tipo:'evento', e:{k:'det', id:k, o:d.open}});
}, true);
A complete live-class app, with a dependency-free server of under a thousand lines that starts with a single Docker command.
Implementing WebSocket by hand showed what libraries hide: the handshake, frames, masking, pings and limits. Isolating content with a sandbox is what made it possible to accept any HTML into the library.