Files
dogfather-universe/server/pruef-dogtag-seite.mjs
T

271 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.
/* =====================================================================
DOGTAGS — Schritte 8 und 9: die Seite „Dein DogTag“ und die Zeile in
der Reaction-Kachel (28.10.2026). Echter Browser, Wegwerf-Datenbank.
Aufrufen mit: node server/pruef-dogtag-seite.mjs
===================================================================== */
import { mkdtempSync, rmSync } 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 { readFileSync } from "node:fs";
import { createServer as httpsServer } from "node:https";
import { zertifikatBauen } from "./helfer-openssl.mjs";
const HIER = dirname(fileURLToPath(import.meta.url));
const ordner = mkdtempSync(join(tmpdir(), "ws-dogtag-seite-"));
process.env.WORKSPACE_DB = join(ordner, "workspace.db");
import { notbremse } from "./helfer-notbremse.mjs";
const { eigenerPort } = await import("./helfer-port.mjs");
const PORT = await eigenerPort(import.meta, "die DogTag-Seiten-Pruefung");
const HTTPS_PORT = await eigenerPort(import.meta, "die DogTag-Seiten-Pruefung (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;
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-dogtag-seite");
await new Promise((r) => setTimeout(r, 900));
let fehler = 0, geprueft = 0;
const ok = (b, t) => { geprueft++; console.log((b ? " ok " : " FEHL ") + t); if (!b) fehler++; };
const melde = (t) => console.log(t);
process.on("exit", () => { try { rmSync(ordner, { recursive: true, force: true }); } catch { /* egal */ } });
const { DatabaseSync } = await import("node:sqlite");
const { scryptSync, randomBytes, createHmac } = await import("node:crypto");
const d = new DatabaseSync(process.env.WORKSPACE_DB);
const nun = new Date().toISOString();
const kennSchluessel = randomBytes(32).toString("hex");
d.prepare("INSERT INTO einstellungen (schluessel, wert, geaendert, von) VALUES (?,?,?,NULL)"
+ " ON CONFLICT(schluessel) DO NOTHING").run("code_kennung_schluessel", kennSchluessel, nun);
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", kennSchluessel).update(code).digest("hex"), ALT);
}
const ROLLEN = [["admin", "Filipe"], ["g1", "Luna"], ["g2", "Kai"], ["g3", "Mo"]];
const CODES = {};
for (const [i, [rolle, name]] of ROLLEN.entries()) {
CODES[rolle] = `CODE-P${String(i).padStart(2, "0")}-000001`;
anlegen(name, rolle.startsWith("g") ? "gast" : rolle, CODES[rolle]);
}
const CREW = "crew.dogfather-universe.com";
function anmelden(rolle) {
return new Promise((fertig, schief) => {
const daten = Buffer.from(JSON.stringify({ rolle: rolle.startsWith("g") ? "gast" : rolle, code: CODES[rolle], alter_ok: true }));
const q = request({ host: "127.0.0.1", port: PORT, path: "/workspace/api/anmelden", method: "POST",
headers: { Host: CREW, Origin: `https://${CREW}`, "Content-Type": "application/json", "Content-Length": daten.length } },
(antw) => {
antw.resume();
antw.on("end", () => fertig([].concat(antw.headers["set-cookie"] || []).map((z) => z.split(";")[0]).join("; ")));
});
q.on("error", schief); q.write(daten); q.end();
});
}
const k = {};
for (const [rolle] of ROLLEN) k[rolle] = await anmelden(rolle);
ok(Object.values(k).every(Boolean), `alle ${Object.keys(k).length} Zugänge melden sich an`);
/* HTTPS, WEIL DIE SEITE ES VERLANGT: Sie laedt ihre Skripte mit
`upgrade-insecure-requests` -- ueber blankes http bleiben sie still
aus (gemessen: Status 0 fuer jedes Skript). Derselbe Vorbau wie in
mess-serverziele. */
const sd = join(ordner, "p.key"), zd = join(ordner, "p.crt");
zertifikatBauen(sd, zd, CREW);
const vorbau = httpsServer({ key: readFileSync(sd), cert: readFileSync(zd) }, (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 */ } });
von.pipe(weiter);
});
await new Promise((r) => vorbau.listen(HTTPS_PORT, "127.0.0.1", r));
const { chromium } = await import("playwright");
const browser = await chromium.launch({ args: [`--host-resolver-rules=MAP ${CREW} 127.0.0.1`, "--ignore-certificate-errors"] });
const BASIS = `https://${CREW}:${HTTPS_PORT}`;
async function seiteAls(rolle, breite = 1400, hoehe = 900) {
const kontext = await browser.newContext({ viewport: { width: breite, height: hoehe }, hasTouch: breite <= 860 });
await kontext.addCookies(k[rolle].split("; ").filter(Boolean).map((z) => {
const [n, ...r] = z.split("=");
return { name: n, value: r.join("="), domain: CREW, path: "/" };
}));
const seite = await kontext.newPage();
const konsole = [];
seite.on("pageerror", (f) => konsole.push(String(f?.message || f)));
/* Auch fehlgeschlagene Abrufe zaehlen -- ein 403 im Hintergrund ist
genau die Sorte Fehler, die man im Browser nicht sieht. */
seite.on("response", (a) => { if (a.status() >= 400) konsole.push(`${a.status()} ${a.url().replace(/^https?:\/\/[^/]+/, "")}`); });
await seite.goto(`${BASIS}/workspace/reaktion.html`, { waitUntil: "domcontentloaded" });
return { kontext, seite, konsole };
}
const hoeheVon = (seite, sel) => seite.evaluate((s) => {
const e = document.querySelector(s); return e ? Math.round(e.getBoundingClientRect().height) : -1;
}, sel);
const R = await import("./dogtag-tabellen.js");
const IDS = Object.fromEntries(d.prepare("SELECT id, name FROM personen").all().map((z) => [z.name, z.id]));
d.prepare("UPDATE dogtag_einstellung SET sichtbar = 'alle' WHERE id = 1").run();
const tag = (n) => R.tagBerlin(Date.now() - n * 86400000);
/* Kai: 25 Tage am Stück bis gestern, eine Spende → Jungwolf */
for (let i = 1; i <= 25; i++) d.prepare("INSERT INTO dogtag_heulen (person_id, tag, erstellt) VALUES (?,?,?)").run(IDS.Kai, tag(i), nun);
d.prepare("INSERT INTO spenden (betrag_cent, name, person_id, herkunft, stand, erstellt, bestaetigt_am) VALUES (100,'x',?,'gemeldet','bestaetigt',?,?)").run(IDS.Kai, nun, nun);
melde("\n=== Die Kachel auf der Startseite ===");
for (const [lagename, b, h] of [["Rechner", 1400, 900], ["Breit", 1920, 1000], ["Handy", 360, 780]]) {
const s = await seiteAls("g2", b, h);
await s.seite.goto(`${BASIS}/workspace/start.html`, { waitUntil: "domcontentloaded" });
const da = await s.seite.waitForFunction(() => document.querySelector(".kachel__dogtag")?.getBoundingClientRect().height > 20, null, { timeout: 12000 })
.then(() => true, () => false);
const m = await s.seite.evaluate(() => {
const z = document.querySelector(".kachel__dogtag");
if (!z) return null;
const r = z.getBoundingClientRect();
const kachel = z.closest(".kachel").getBoundingClientRect();
/* GEMESSEN WIRD DER TEXT, NICHT SEIN KASTEN: Der Kasten des Namens
reicht über die ganze Kachel, die Schrift nur über ihre Zeichen. */
const zeichen = (e) => { const rg = document.createRange(); rg.selectNodeContents(e); return rg.getBoundingClientRect(); };
const stoert = [...z.closest(".kachel").querySelectorAll(".kachel__name, .kachel__unter, .kachel__titel, h2, h3")]
.map((e) => [e, zeichen(e)]).concat([...z.closest(".kachel").querySelectorAll(".kachel__leute")].map((e) => [e, e.getBoundingClientRect()]))
.filter(([, q]) => q.width > 2 && !(r.right <= q.left || r.left >= q.right || r.bottom <= q.top || r.top >= q.bottom))
.map(([e]) => e.className);
const ring = z.querySelector(".kdt-ring__fuell");
return { text: z.textContent, href: z.getAttribute("href"), drin: r.left >= kachel.left && r.right <= kachel.right && r.top >= kachel.top && r.bottom <= kachel.bottom, stoert,
h: Math.round(r.height), w: Math.round(r.width), ring: !!ring && getComputedStyle(ring).strokeDashoffset === "0px",
marke: !!z.querySelector(".kdt-marke svg.dogtag-marke"), titel: z.querySelector(".kdt-titel")?.textContent || "" };
});
ok(da && !!m && /DogTag liegt bereit/.test(m.text) && /Jetzt heulen · 25 Nächte halten/.test(m.text) && m.href === "dogtags.html", `${lagename}: „${m?.text}“ in der Reaction-Kachel, führt zur Seite`);
ok(!!m && m.drin && m.stoert.length === 0, `${lagename}: ganz in der Kachel, über keinem Text (${m?.stoert.join(",") || "frei"})`);
if (lagename === "Breit") {
const haengt = await s.seite.evaluate(() => {
const z = document.querySelector(".kachel__dogtag");
const k = z.closest(".kachel").getBoundingClientRect();
const kette = z.querySelector(".kdt-kette").getBoundingClientRect();
return { abKante: Math.round(kette.top - k.top), rechts: Math.round(k.right - z.getBoundingClientRect().right), kachelH: Math.round(k.height) };
});
ok(haengt.abKante <= 2 && haengt.kachelH < 200, `Breit: der DogTag hängt an der oberen Kachelkante (Kette ab ${haengt.abKante} px, Kachel ${haengt.kachelH} hoch)`);
}
ok(!!m && m.h >= 56 && m.marke && m.ring && m.titel === "Dein DogTag liegt bereit",
`${lagename}: die Marke zum Anfassen — ${m?.w}×${m?.h} Punkte, Marke im vollen Ring, „${m?.titel}“`);
await s.seite.waitForTimeout(3200);
/* Den Willkommensdialog der Testperson wegklicken, damit das Foto die
Kachel zeigt und nicht ihn. */
await s.seite.evaluate(() => [...document.querySelectorAll("button")].find((b) => b.textContent.trim() === "Später")?.click());
await s.seite.waitForTimeout(600);
await s.seite.locator(".kachel[data-sendung='ja']").screenshot({ path: join(HIER, `pruef-dogtag-seite-kachel-${lagename}.png`) }).catch(() => {});
ok(s.konsole.length === 0, `${lagename}: keine Fehler in der Konsole (${s.konsole.join(" | ") || "keine"})`);
await s.kontext.close();
}
melde("\n=== Die Seite „Dein DogTag“ ===");
const s = await seiteAls("g2", 1400, 900);
await s.seite.goto(`${BASIS}/workspace/dogtags.html`, { waitUntil: "domcontentloaded" });
await s.seite.waitForFunction(() => !document.getElementById("dtp-held")?.hidden && document.querySelectorAll("#dtp-raenge .dtp-rang").length === 7, null, { timeout: 12000 }).catch(() => {});
let m = await s.seite.evaluate(() => ({
sammlung: document.getElementById("dtp-sammlung")?.textContent,
knopf: document.getElementById("dtp-heulen")?.textContent,
bis: document.getElementById("dtp-bis")?.textContent,
du: document.querySelector("#dtp-raenge .dtp-rang[data-du='ja'] .dtp-rang__name")?.textContent,
woche: document.querySelectorAll("#dtp-woche .dtp-tag").length,
geheult: document.querySelectorAll("#dtp-woche .dtp-tag[data-geheult='ja']").length,
seit: document.getElementById("dtp-seit")?.textContent,
marke: document.querySelector("#dtp-marke svg textPath")?.textContent || "",
}));
/* 25 Nächte am Stück bis gestern = 25 + 3 Bonus (je 7. Nacht) = 28. */
ok(m.sammlung === "28" && m.knopf === "Heute heulen", `Kai: 25 Nächte + 3 Bonus = 28 DogTags, „Heute heulen“ (${m.sammlung}, ${m.knopf})`);
ok(m.du === "Jungwolf" && /Bis Späher: 32 DogTags und 1 Spende/.test(m.bis), `Rang „Du“: Jungwolf, „${m.bis}“`);
ok(m.woche === 7, `die Woche Mo–So (${m.woche} Tage, ${m.geheult} geheult)`);
ok(/Monats-Siegel .* aktiv/.test(m.seit) && /KAI · JUNGWOLF · DOGFATHER/.test(m.marke), `Siegel aktiv, Gravur „${m.marke}“`);
await s.seite.click("#dtp-heulen");
await s.seite.waitForFunction(() => document.getElementById("dtp-heulen")?.textContent === "Heute geheult", null, { timeout: 8000 }).catch(() => {});
m = await s.seite.evaluate(() => ({ knopf: document.getElementById("dtp-heulen")?.textContent, sammlung: document.getElementById("dtp-sammlung")?.textContent,
status: document.getElementById("dtp-status")?.textContent }));
ok(m.knopf === "Heute geheult" && m.sammlung === "29", `ohne Stream geheult: 29, „Heute geheult“ (${m.status})`);
const h = d.prepare("SELECT sendung_id, topf_fuer FROM dogtag_heulen WHERE person_id = ? AND tag = ?").get(IDS.Kai, R.tagBerlin());
ok(!!h && h.sendung_id === null && h.topf_fuer === null, "es liegt im Rudel-Topf (ohne Sendung)");
/* Der zweite Zustand der Kachel: schon geheult. Der Ring ist dann nur
teilweise gefüllt, der Titel kürzer und die Zeile zählt herunter —
ein anderes Bild, also eigens gemessen und fotografiert. */
for (const [lagename, b, h2] of [["Breit", 1920, 1000], ["Handy", 360, 780]]) {
const g = await seiteAls("g2", b, h2);
await g.seite.goto(`${BASIS}/workspace/start.html`, { waitUntil: "domcontentloaded" });
await g.seite.waitForFunction(() => document.querySelector(".kachel__dogtag")?.getBoundingClientRect().height > 20, null, { timeout: 12000 }).catch(() => {});
await g.seite.waitForTimeout(3200);
await g.seite.evaluate(() => [...document.querySelectorAll("button")].find((x) => x.textContent.trim() === "Später")?.click());
await g.seite.waitForTimeout(600);
const gm = await g.seite.evaluate(() => {
const z = document.querySelector(".kachel__dogtag");
if (!z) return null;
const r = z.getBoundingClientRect();
const kachel = z.closest(".kachel").getBoundingClientRect();
const zeichen = (e) => { const rg = document.createRange(); rg.selectNodeContents(e); return rg.getBoundingClientRect(); };
const stoert = [...z.closest(".kachel").querySelectorAll(".kachel__name, .kachel__unter, .kachel__titel, h2, h3")]
.map((e) => [e, zeichen(e)]).filter(([, q]) => q.width > 2 && !(r.right <= q.left || r.left >= q.right || r.bottom <= q.top || r.top >= q.bottom))
.map(([e]) => e.className);
const ring = z.querySelector(".kdt-ring__fuell");
return { bereit: z.dataset.bereit, titel: z.querySelector(".kdt-titel")?.textContent || "", zustand: z.querySelector(".kdt-zustand")?.textContent || "",
punkt: !!z.querySelector(".kdt-punkt"), voll: !!ring && getComputedStyle(ring).strokeDashoffset === "0px",
drin: r.left >= kachel.left && r.right <= kachel.right && r.top >= kachel.top && r.bottom <= kachel.bottom, stoert };
});
ok(!!gm && gm.bereit === "nein" && gm.titel === "Dein DogTag" && /^Nächster in \d\d:\d\d:\d\d$/.test(gm.zustand) && !gm.punkt && !gm.voll,
`${lagename}, geheult: „${gm?.titel}“ · „${gm?.zustand}“, Ring nicht voll, kein Leuchtpunkt`);
ok(!!gm && gm.drin && gm.stoert.length === 0, `${lagename}, geheult: ganz in der Kachel, über keinem Text (${gm?.stoert.join(",") || "frei"})`);
await g.seite.locator(".kachel[data-sendung='ja']").screenshot({ path: join(HIER, `pruef-dogtag-seite-kachel-${lagename}-geheult.png`) }).catch(() => {});
ok(g.konsole.length === 0, `${lagename}, geheult: keine Fehler in der Konsole (${g.konsole.join(" | ") || "keine"})`);
await g.kontext.close();
}
await s.seite.click("#dtp-anrede button:nth-of-type(2)");
await s.seite.waitForFunction(() => document.querySelector("#dtp-raenge .dtp-rang[data-du='ja'] .dtp-rang__name")?.textContent === "Jungwölfin", null, { timeout: 6000 }).catch(() => {});
m = await s.seite.evaluate(() => ({ du: document.querySelector("#dtp-raenge .dtp-rang[data-du='ja'] .dtp-rang__name")?.textContent,
rl: [...document.querySelectorAll("#dtp-rangliste .dtp-rl__name")].map((x) => x.textContent) }));
ok(m.du === "Jungwölfin", `Anrede Wölfin: „${m.du}“`);
ok(m.rl.includes("Kai"), `Kai steht auf der Rangliste des Monats (${m.rl.join(", ")})`);
const ueber = await s.seite.evaluate(() => document.documentElement.scrollWidth <= innerWidth);
ok(ueber, "nichts läuft seitlich hinaus");
await s.seite.screenshot({ path: join(HIER, "pruef-dogtag-seite.png"), fullPage: true });
ok(s.konsole.length === 0, `keine Fehler in der Konsole (${s.konsole.join(" | ") || "keine"})`);
await s.kontext.close();
const hy = await seiteAls("g1", 390, 844);
await hy.seite.goto(`${BASIS}/workspace/dogtags.html`, { waitUntil: "domcontentloaded" });
await hy.seite.waitForFunction(() => !document.getElementById("dtp-held")?.hidden, null, { timeout: 12000 }).catch(() => {});
await hy.seite.waitForTimeout(800);
m = await hy.seite.evaluate(() => {
const k = document.getElementById("dtp-heulen").getBoundingClientRect();
const figuren = [...document.querySelectorAll(".dtp-figur")].map((f) => f.getBoundingClientRect());
const ueberKnopf = figuren.some((f) => !(f.right <= k.left || f.left >= k.right || f.bottom <= k.top || f.top >= k.bottom));
return { breit: document.documentElement.scrollWidth <= innerWidth, knopfH: Math.round(k.height), ueberKnopf };
});
ok(m.breit && m.knopfH >= 44 && !m.ueberKnopf, `Handy: nichts seitlich hinaus, Knopf ${m.knopfH} px, Figuren nicht über dem Knopf`);
await hy.seite.screenshot({ path: join(HIER, "pruef-dogtag-seite-handy.png"), fullPage: true });
await hy.kontext.close();
melde("\n=== Wer sie nicht sieht ===");
d.prepare("UPDATE dogtag_einstellung SET sichtbar = 'leitung' WHERE id = 1").run();
const zu = await seiteAls("g1", 1200, 800);
await zu.seite.goto(`${BASIS}/workspace/dogtags.html`, { waitUntil: "domcontentloaded" });
const bald = await zu.seite.waitForFunction(() => !document.getElementById("dtp-bald")?.hidden, null, { timeout: 8000 }).then(() => true, () => false);
const heldWeg = await zu.seite.evaluate(() => document.getElementById("dtp-held").getBoundingClientRect().height === 0);
ok(bald && heldWeg, "bei „Nur Leitung“: „Die DogTags kommen bald“, nichts weiter");
ok(zu.konsole.length === 0, `und kein Fehlabruf in der Konsole (${zu.konsole.join(" | ") || "keiner"})`);
await zu.seite.goto(`${BASIS}/workspace/start.html`, { waitUntil: "domcontentloaded" });
await zu.seite.waitForTimeout(2500);
ok(await zu.seite.evaluate(() => !document.querySelector(".kachel__dogtag")), "und keine DogTag-Zeile in der Kachel");
await zu.kontext.close();
await browser.close();
vorbau.close();
melde(`\n${geprueft} Prüfungen, ${fehler} Fehler`);
console.log(fehler ? "NICHT IN ORDNUNG" : "ALLES IN ORDNUNG");
process.exit(fehler ? 1 : 0);