Files
dogfather-universe/server/pruef-chat-kopf-blick.mjs
T
DogFatherGitandClaude Opus 5.5 2c7106c0ef Runde 9: Chat-Kopf (Name ganz, zwei Abzeichen + „+N“, Zeichen-Knöpfe rechts) und Befunde der Saal-Prüfreihe
- Trusted Types: <form method=dialog> erlaubt, nur Formularziele verboten
  (vorher war jede Rückfrage im Saal leer); Prüfung mit Gegenprobe
- Regie am Handy: „↗ ganz“ lässt die eingeklappte Regie zurücktreten
  (lag über Liste und Feld); niedrige Bildschirme: Streifen im Fluss
- Freistellen zeigt die Auslesezeit der Maske (für den Probeabend)
- mess-einlauf misst nur seinen Abschnitt; Wache Bündel je Rolle 420 KB
- neue Prüfung pruef-chat-kopf-blick (37, Gegenprobe alter Kopf)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 18:07:16 +01:00

312 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* =====================================================================
DER KOPF EINES CHAT-BEITRAGS (05.11.2026, Perfektionsplan Runde 9)
Filipes Bild: Bei drei Abzeichen brachen „Funny“, „antworten“ und „weg“
Buchstabe für Buchstabe um. Gemessen wird Funnys Beitrag mit VIER
Abzeichen in sieben Breiten (Handy 360–412, Rechner 1280–1920, Gast und
Regie): kein Teil der Kopfzeile höher als 1,6 Zeilen, Name ganz, zwei
Abzeichen + „+2“, Knöpfe als Zeichen mit Namen. Gegenprobe: der alte Kopf.
DREI AUSGÄNGE: 0 in Ordnung · 1 Befund · 3 konnte nicht nachsehen.
Bilder: CK_BILDER=<ordner> node server/pruef-chat-kopf-blick.mjs
===================================================================== */
import { mkdtempSync, rmSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { request } from "node:http";
import { createServer as httpsServer } from "node:https";
import { zertifikatBauen } from "./helfer-openssl.mjs";
import { notbremse } from "./helfer-notbremse.mjs";
import { eigenerPort } from "./helfer-port.mjs";
const HIER = dirname(fileURLToPath(import.meta.url));
const ordner = mkdtempSync(join(tmpdir(), "pruef-chat-kopf-"));
process.env.WORKSPACE_DB = join(ordner, "workspace.db");
const PORT = await eigenerPort(import.meta);
const HTTPS_PORT = await eigenerPort(import.meta, "pruef-chat-kopf-blick (HTTPS)", 1);
process.env.PORT = `${PORT}`;
process.env.SITE_ACCESS_SECRET = "lokaler-test";
process.env.SITE_PUBLIC_LAUNCH_AT = "2020-01-01T00:00:00+01:00";
const express = (await import("express")).default;
/* Der Sitzungskeks ist `secure`. Der Vorbau unten spricht https, der
Server dahinter nicht -- ohne diesen Griff setzt er den Keks und
der Browser verwirft ihn. */
const ec = express.response.cookie;
express.response.cookie = function (n, w, o) { return ec.call(this, n, w, { ...(o || {}), secure: false }); };
await import("./index.js");
notbremse(300_000, "pruef-chat-kopf-blick");
await new Promise((r) => setTimeout(r, 1000));
const CREW = "crew.dogfather-universe.com";
/* ---------- Leute ------------------------------------------------------- */
const { DatabaseSync } = await import("node:sqlite");
const { scryptSync, randomBytes, createHmac } = await import("node:crypto");
const d = new DatabaseSync(process.env.WORKSPACE_DB);
const kenn = randomBytes(32).toString("hex");
d.prepare("INSERT INTO einstellungen (schluessel, wert, geaendert, von)"
+ " VALUES (?,?,?,NULL) ON CONFLICT(schluessel) DO NOTHING")
.run("code_kennung_schluessel", kenn, new Date().toISOString());
const ALT = new Date(Date.now() - 200 * 86400000).toISOString();
function anlegen(name, rolle, code) {
const salt = randomBytes(16).toString("hex");
const hash = scryptSync(code, salt, 64,
{ N: 32768, r: 8, p: 1, maxmem: 96 * 1024 * 1024 }).toString("hex");
d.prepare("INSERT INTO personen (name, rolle, code_hash, code_salt, code_n,"
+ " code_kennung, aktiv, erstellt) VALUES (?,?,?,?,?,?,1,?)")
.run(name, rolle, hash, salt, 32768,
createHmac("sha256", kenn).update(code).digest("hex"), ALT);
}
const CODES = {
admin: "CODE-M00-000001", hand: "CODE-M01-000001",
gast: "CODE-M02-000001", gast2: "CODE-M03-000001", linke: "CODE-M04-000001",
};
/* VANVAN IST DIE RECHTE HAND und wird mitgemessen, nicht nur
DogFather: Filipe hat "nur ich und vanvan" gesagt, und ob die
zweite Haelfte davon stimmt, sieht man nur, wenn sie dabei ist. */
anlegen("DogFather", "admin", CODES.admin);
anlegen("VanVan", "hand", CODES.hand);
anlegen("Nachtfalter", "gast", CODES.gast);
anlegen("Lenny", "gast", CODES.gast2);
anlegen("Funny", "linke", CODES.linke);
d.close();
function roh(pfad, { method = "GET", keks = "", rumpf = null } = {}) {
return new Promise((fertig, schief) => {
const daten = rumpf === null ? null : Buffer.from(JSON.stringify(rumpf));
const a = request({
host: "127.0.0.1", port: PORT, path: pfad, method,
headers: {
Host: CREW, Origin: `https://${CREW}`,
...(keks ? { Cookie: keks } : {}),
...(daten ? { "Content-Type": "application/json", "Content-Length": daten.length } : {}),
},
}, (antwort) => {
const teile = [];
antwort.on("data", (s) => teile.push(s));
antwort.on("end", () => {
const text = Buffer.concat(teile).toString("utf8");
let j = null; try { j = JSON.parse(text); } catch { /* kein JSON */ }
fertig({ code: antwort.statusCode, text, j, kopf: antwort.headers });
});
});
a.on("error", schief);
if (daten) a.write(daten);
a.end();
});
}
async function anmelden(wer) {
const a = await roh("/workspace/api/anmelden", {
method: "POST",
rumpf: { rolle: wer === "gast2" ? "gast" : wer, code: CODES[wer], alter_ok: true },
});
return [].concat(a.kopf["set-cookie"] || []).map((z) => z.split(";")[0]).join("; ");
}
const k = {
admin: await anmelden("admin"),
hand: await anmelden("hand"),
gast: await anmelden("gast"),
gast2: await anmelden("gast2"),
linke: await anmelden("linke"),
};
/* ---------- Zaehlwerk --------------------------------------------------- */
let fehler = 0;
let geprueft = 0;
const ok = (b, t) => {
geprueft++;
console.log((b ? " ok " : " FEHL ") + t);
if (!b) fehler++;
};
function nichtNachsehbar(grund) {
console.log("\n -- NICHT NACHSEHBAR");
console.log(` ${grund}`);
console.log(" Das ist KEIN Befund am Code -- es heisst nur, dass");
console.log(" gerade niemand nachsehen konnte.\n");
try { rmSync(ordner, { recursive: true, force: true }); } catch { /* egal */ }
process.exit(3);
}
/* ---------- Die Buehne fuellen ------------------------------------------ */
/* ZWEI STUECKE IN DER WARTESCHLANGE, EINES MIT TERMIN UND EINES OHNE.
Genau das ist die Aussage der linken Reihe ("was keinen hat, steht
unten"), und mit nur einem Eintrag liesse sie sich nicht messen. */
for (const adresse of ["https://youtu.be/9bZkp7q19f0",
"https://www.youtube.com/watch?v=kJQP7kiw5Fk"]) {
const a = await roh("/workspace/api/reaktion/liste", {
method: "POST", keks: k.admin, rumpf: { video: adresse },
});
if (a.code >= 400) nichtNachsehbar(`Die Warteschlange nimmt nichts an (HTTP ${a.code}).`);
}
const liste0 = (await roh("/workspace/api/reaktion", { keks: k.admin })).j?.liste || [];
if (liste0.length !== 2) {
nichtNachsehbar(`In der Warteschlange stehen ${liste0.length} Stuecke statt 2.`);
}
/* Der Termin liegt in der ZUKUNFT und wird relativ gerechnet. Ein
festes Datum waere eine Zeitbombe: Es ist richtig, bis der Kalender
es einholt -- und dann schlaegt "ueberfaellig" an, ohne dass etwas
kaputt ist. */
{
const a = await roh(`/workspace/api/reaktion/liste/${liste0[0].id}/wann`, {
method: "PUT", keks: k.admin,
rumpf: { wann: new Date(Date.now() + 3 * 86400000).toISOString() },
});
if (a.code >= 400) nichtNachsehbar(`Der Termin laesst sich nicht setzen (HTTP ${a.code}).`);
}
await roh("/workspace/api/reaktion", {
method: "PUT", keks: k.admin,
rumpf: {
titel: "Wir schauen den neuen Trailer",
video: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
beginnt_am: new Date(Date.now() + 7 * 60_000).toISOString(),
},
});
/* ---------- Der Vorbau -------------------------------------------------- */
const schluesselDatei = join(ordner, "p.key");
const zertDatei = join(ordner, "p.crt");
try {
zertifikatBauen(schluesselDatei, zertDatei, CREW);
} catch (f) {
nichtNachsehbar(`Kein Zertifikat zu bauen: ${f?.message}\n`
+ " openssl liegt bei Git in mingw64/bin -- im System-PATH\n"
+ " steht oft nur Git/cmd.");
}
const vorbau = httpsServer({
key: readFileSync(schluesselDatei), cert: readFileSync(zertDatei),
}, (von, nach) => {
const weiter = request({
host: "127.0.0.1", port: PORT, path: von.url, method: von.method,
headers: { ...von.headers, host: `${CREW}:${HTTPS_PORT}` },
}, (antwort) => {
nach.writeHead(antwort.statusCode || 502, antwort.headers);
antwort.pipe(nach);
});
weiter.on("error", () => { try { nach.writeHead(502); nach.end(); } catch { /* egal */ } });
/* Geschlossene Prüf-Fenster reißen offene Ströme ab – das ist kein Befund. */
von.on("error", () => {}); nach.on("error", () => {});
von.pipe(weiter);
});
await new Promise((r) => vorbau.listen(HTTPS_PORT, "127.0.0.1", r));
const BASIS = `https://${CREW}:${HTTPS_PORT}`;
for (const st of ["vorbereitung", "live"]) await roh("/workspace/api/reaktion/stand", { method: "POST", keks: k.admin, rumpf: { stand: st } });
const standNun = (await roh("/workspace/api/reaktion", { keks: k.admin })).j?.stand;
if (standNun !== "live") nichtNachsehbar(`Die Sendung geht nicht live (${standNun}).`);
for (const [w, t] of [["gast", "Erster im Saal"], ["gast2", "Zweite Nachricht"]]) await roh("/workspace/api/reaktion/chat", { method: "POST", keks: k[w], rumpf: { text: t } });
let pw = null;
try { pw = await import("file:///C:/Users/qciga/Documents/Obelix/Analyse/node_modules/playwright/index.mjs"); } catch (f) { nichtNachsehbar(`Playwright fehlt: ${f?.message}`); }
const browser = await pw.chromium.launch({ args: [`--host-resolver-rules=MAP ${CREW} 127.0.0.1`, "--ignore-certificate-errors", "--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", "--autoplay-policy=no-user-gesture-required"] });
const BILDER = process.env.CK_BILDER || "";
const warte = (ms) => new Promise((r) => setTimeout(r, ms));
const konsole = [];
async function als(rolle, breite, hoehe, handy = true) {
const kx = await browser.newContext({ viewport: { width: breite, height: hoehe }, ignoreHTTPSErrors: true, hasTouch: handy, isMobile: handy, deviceScaleFactor: handy ? 2 : 1 });
await kx.addCookies(k[rolle].split("; ").filter(Boolean).map((z) => { const [n, ...r] = z.split("="); return { name: n, value: r.join("="), domain: CREW, path: "/" }; }));
const s = await kx.newPage();
s.on("pageerror", (f) => konsole.push(`${rolle}@${breite}: ${String(f?.message || f)}`));
await s.goto(`${BASIS}/workspace/reaktion.html`, { waitUntil: "domcontentloaded" });
await s.waitForSelector("body[data-stand]", { timeout: 20000 });
await s.waitForFunction(() => window.RegieLaden?.fertig?.() || !document.getElementById("pult") || true, null, { timeout: 15000 });
await s.waitForTimeout(2500);
return s;
}
/* ---------- Beiträge: Funny (linke Hand, TEAM) und zwei Gäste ---------- */
for (const [w, t] of [["linke", "Gleich kommt die Stelle, passt auf!"], ["gast", "Wie lange noch?"], ["gast2", "Wahnsinn"]]) {
await roh("/workspace/api/reaktion/chat", { method: "POST", keks: k[w], rumpf: { text: t } });
}
/* Die drei Abzeichen, die später aus anderen Dateien kommen (DogTag-Marke aus
dogtag-saal.js, Spende, Pfote aus tipprunde.js), werden mit genau deren
Klassen angehängt – so wie diese Dateien es tun, nach dem Bauen. */
const anhaengen = (s) => s.evaluate(() => {
const li = [...document.querySelectorAll("#chat-liste > .beitrag")].find((x) => x.dataset.name === "Funny");
const wer = li?.querySelector(".beitrag__wer");
if (!wer) return false;
/* Hat dogtag-saal.js schon eine echte Marke angehängt, bleibt es bei der. */
if (!wer.querySelector(":scope > .dts-chatmarke")) {
const marke = document.createElement("span"); marke.className = "dts-chatmarke";
const zahl = document.createElement("span"); zahl.className = "dts-chatmarke__zahl"; zahl.textContent = "🐺 3"; marke.append(zahl);
wer.firstElementChild.after(marke);
}
const sp = document.createElement("span"); sp.className = "beitrag__spende"; sp.textContent = "Starke Runde"; wer.append(sp);
const p = document.createElement("span"); p.className = "tr-pfote"; p.textContent = "🐾"; wer.append(p);
return true;
});
/* Jedes sichtbare Teil der Kopfzeile: höher als 1,6 Zeilen = Befund. */
const messen = (s) => s.evaluate(() => {
const li = [...document.querySelectorAll("#chat-liste > .beitrag")].find((x) => x.dataset.name === "Funny");
const wer = li.querySelector(".beitrag__wer");
const teile = [...wer.children].filter((n) => n.getBoundingClientRect().height > 0 && getComputedStyle(n).display !== "none");
const zuHoch = teile.map((n) => {
const cs = getComputedStyle(n);
const zeile = parseFloat(cs.lineHeight) || parseFloat(cs.fontSize) * 1.25;
/* Inhaltshöhe: das Tipp-Polster am Finger (12 px oben/unten) ist keine Zeile. */
const h = n.getBoundingClientRect().height - (parseFloat(cs.paddingTop) || 0) - (parseFloat(cs.paddingBottom) || 0);
return { k: n.className || n.tagName, h: Math.round(h), z: Math.round(zeile) };
}).filter((x) => x.h > Math.max(x.z, 16) * 1.6 + 6);
const name = wer.firstElementChild;
const knoepfe = [...wer.querySelectorAll(".beitrag__antworten, .beitrag__weg, .beitrag__melden")];
/* Die Knöpfe stehen rechts: ihre Gruppe endet am rechten Rand der Kopfzeile. */
const gruppe = wer.querySelector(":scope > .beitrag__knoepfe");
const rechtsBuendig = !!gruppe && Math.abs(gruppe.getBoundingClientRect().right - (wer.getBoundingClientRect().right - (parseFloat(getComputedStyle(wer).paddingRight) || 0))) <= 2;
return {
teile: teile.length, zuHoch,
nameGanz: name.scrollWidth <= name.clientWidth + 1, nameText: name.textContent,
knoepfe: knoepfe.length, rechtsBuendig, benannt: knoepfe.every((b) => (b.getAttribute("aria-label") || "").length > 3),
zeichen: knoepfe.every((b) => b.querySelector("svg.beitrag__zeichen")),
zu: wer.querySelectorAll(':scope > [data-zu="ja"]').length,
mehr: wer.querySelector(":scope > .beitrag__mehr")?.textContent || "",
ueber: Math.round(li.scrollWidth - li.clientWidth),
breit: document.documentElement.scrollWidth <= innerWidth + 1,
seite: document.documentElement.scrollWidth,
name: [name.scrollWidth, name.clientWidth],
/* Überstand am ECHTEN Element – `scrollWidth` zählt auch die unsichtbaren
Tippflächen (::after) mit, die über den Rand reichen dürfen. */
rechts: [...li.querySelectorAll("*")].map((n) => [n.className?.baseVal ?? n.className, Math.round(n.getBoundingClientRect().right - li.getBoundingClientRect().right)]).filter((x) => x[1] > 0).slice(0, 5),
klassen: [...wer.children].map((n) => n.className.baseVal ?? n.className).join(" | "),
};
});
const ZIELE = [["gast", 360, 740, true], ["gast", 390, 844, true], ["gast", 412, 915, true], ["admin", 390, 844, true],
["gast", 1280, 800, false], ["gast", 1440, 900, false], ["admin", 1920, 1080, false]];
for (const [rolle, b, hh, handy] of ZIELE) {
const s = await als(rolle, b, hh, handy);
/* Die Regie liest am Handy über „↗ ganz“ (Runde 1) – sonst liegt der Chat unter dem Pult. */
if (rolle === "admin" && handy) { await s.evaluate(() => window.RegieChat?.ganz?.()); await s.waitForTimeout(600); }
ok(await anhaengen(s), `${rolle}@${b}: Funnys Beitrag mit vier Abzeichen steht da (Voraussetzung)`);
await s.waitForTimeout(150);
const m = await messen(s);
ok(m.teile >= 5 && m.zu === 2 && m.mehr === "+2", `${rolle}@${b}: zwei Abzeichen sichtbar, der Rest als „+2“ (${m.teile} Teile sichtbar, ${m.zu} zu, „${m.mehr}“; ${m.klassen})`);
ok(m.zuHoch.length === 0 && m.nameGanz && m.nameText === "Funny", `${rolle}@${b}: kein Name und kein Knopf höher als eine Zeile, der Name steht ganz (${JSON.stringify(m.zuHoch)}, Name ${m.name})`);
if (BILDER && b === 390 && rolle === "gast") await s.locator('#chat-liste .beitrag[data-name="Funny"]').screenshot({ path: `${BILDER}/chat-kopf-nachher-390.png` });
ok(m.knoepfe >= 2 && m.benannt && m.zeichen && m.rechtsBuendig && m.rechts.length === 0 && m.breit, `${rolle}@${b}: ${m.knoepfe} Knöpfe als Zeichen mit Namen für Vorleser, nichts läuft über (benannt ${m.benannt}, Zeichen ${m.zeichen}, Beitrag über ${m.ueber}, Seite ${m.seite}/${b}; rechts ${JSON.stringify(m.rechts)})`);
/* Alle zeigen: auch dann bricht nichts senkrecht um. */
await s.evaluate(() => document.querySelector('#chat-liste .beitrag[data-name="Funny"]').scrollIntoView({ block: 'center' }));
await s.waitForTimeout(300);
{ const z = s.locator('#chat-liste .beitrag[data-name="Funny"] .beitrag__mehr');
try { if (handy) await z.tap({ timeout: 8000 }); else await z.click({ timeout: 8000 }); }
catch (f) { ok(false, `${rolle}@${b}: „+2“ lässt sich antippen (${String(f.message).split('\n').slice(0, 12).join(' / ')})`); } }
await s.waitForTimeout(150);
const alle = await messen(s);
ok(alle.zu === 2 && alle.mehr === "−" && alle.zuHoch.length === 0 && alle.rechtsBuendig && alle.teile >= m.teile + 2, `${rolle}@${b}: „+2“ zeigt alle vier – weiter nichts senkrecht (${alle.teile} Teile, ${JSON.stringify(alle.zuHoch)})`);
if (b === 390 && rolle === "gast") {
if (BILDER) await s.locator('#chat-liste .beitrag[data-name="Funny"]').screenshot({ path: `${BILDER}/chat-kopf-nachher-alle-390.png` });
/* GEGENPROBE: der alte Kopf (eine Zeile, Teile dürfen schrumpfen). */
await s.evaluate(() => { const st = document.createElement("style"); st.id = "sabotage"; st.textContent = ".beitrag__wer{flex-wrap:nowrap!important}.beitrag__wer>*{white-space:normal!important;overflow-wrap:anywhere!important;min-width:0!important;flex:0 1 auto!important}"; document.head.append(st); });
await s.waitForTimeout(150);
const alt = await messen(s);
if (BILDER) await s.locator('#chat-liste .beitrag[data-name="Funny"]').screenshot({ path: `${BILDER}/chat-kopf-vorher-390.png` });
await s.evaluate(() => document.getElementById("sabotage")?.remove());
ok(alt.zuHoch.length > 0, `Gegenprobe: der alte Kopf (eine Zeile, schrumpfende Teile) würde erkannt (${alt.zuHoch.length} zu hohe Teile)`);
}
await s.context().close();
}
ok(!konsole.length, `keine Fehler auf den Seiten (${konsole.slice(0, 3).join(" | ")})`);
await browser.close();
vorbau.close();
console.log(`\n${geprueft} Pruefungen, ${fehler} Fehler`);
try { rmSync(ordner, { recursive: true, force: true }); } catch { /* egal */ }
process.exit(fehler ? 1 : 0);