technical case study

Web App • Live class / Real time

Lousa ao vivo

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.

Product, real-time server and interface Open source Public version on GitHub
PHP 8.1 WebSocket JavaScript Canvas Docker Traefik
executive summary

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.

Solution

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.

Result

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.

Current stage

Public version on GitHub, ready to run on a VPS with Docker and Traefik.

context

The document is the whiteboard

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.

goals and constraints

Goals

  • Draw on top of any HTML document, on a computer or a phone
  • Sync scrolling, opened answers, fields and buttons for everyone
  • Join a class by link or code, without creating an account
  • Keep a lesson library protected by a teacher password
  • Generate new lessons with Claude from a shared visual template

Constraints

  • Dependency-free server: just PHP 8.1 on the command line
  • Imported documents can't read the login or tamper with the app
  • Up to 30 people per room and a message limit per person
  • Each document has to be a single file, with CSS, JavaScript and images embedded
solution architecture

Front-end

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.

Back-end

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.

Database

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.

security and safeguards

Isolated documents

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.

Teacher login

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.

Real time with limits

The WebSocket only accepts connections from its own origin and limits message size, messages per person and people per room.

process
01

Plain PHP server

HTTP and WebSocket implemented on top of sockets, without any library.

02

Drawing and sync

A canvas over the document, strokes sent in 50 ms batches and a bridge to sync fields and answers.

03

Library and teacher

Importing, editing and deleting documents with a password, keeping everything in a Docker volume.

04

Lessons with AI

A standard prompt and lesson template to create new documents with Claude.

05

Public version

An open repository with Docker, Traefik and a guide to installing it on a VPS.

behind the scenes
app/server.php PHP lines 572–608
    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]);
    }
Constant-time password comparison, per-IP lockout after 10 failures and an HMAC-signed token instead of a session.
app/server.php PHP lines 295–326
    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;
    }
Each document is served with the bridge injected into the <head> and a sandbox CSP: it runs scripts, but can't access the login or the app.
app/server.php PHP lines 779–803
    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;
        }
    }
WebSocket messages: validated JSON, a per-person limit and relaying to everyone in the room except the sender.
app/public/app.js JavaScript lines 313–359
  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);
  }
Each stroke starts on pointerdown and its points follow in 50 ms batches; with two fingers, the gesture becomes scrolling.
app/public/ponte.js JavaScript lines 102–122
  /* ---------------- 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);
Inside the document, fields, opened answers and buttons become events for everyone else; password and file fields are never synced.
impact

Results

A complete live-class app, with a dependency-free server of under a thousand lines that starts with a single Docker command.

Learnings

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.