Files
dogfather-universe/server/pruef-laufnummer-blick.mjs
T

253 lines
13 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.
/* =====================================================================
JÜNGER GEWINNT – LAUFNUMMER JE LAGE (05.11.2026, Perfektionsplan 2.1)
Ein Abruf wird absichtlich verspätet: Er geht vor einer Änderung los und
kommt danach an. Er darf den neueren Stand nicht zurückdrehen. Gegenprobe:
dieselbe Antwort ohne Laufnummer dreht ihn zurück (die Prüfung sieht es).
DREI AUSGÄNGE: 0 in Ordnung · 1 Befund · 3 konnte nicht nachsehen.
Aufruf: node server/pruef-laufnummer-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-laufnummer-"));
process.env.WORKSPACE_DB = join(ordner, "workspace.db");
const PORT = await eigenerPort(import.meta);
const HTTPS_PORT = await eigenerPort(import.meta, "pruef-laufnummer-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-laufnummer-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",
};
/* 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);
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"),
};
/* ---------- 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 */ } });
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 warte = (ms) => new Promise((r) => setTimeout(r, ms));
const konsole = [];
const kx = await browser.newContext({ viewport: { width: 1440, height: 900 }, ignoreHTTPSErrors: true, serviceWorkers: "block" });
await kx.addCookies(k.gast.split("; ").filter(Boolean).map((z) => { const [n, ...r] = z.split("="); return { name: n, value: r.join("="), domain: CREW, path: "/" }; }));
const s = await kx.newPage();
await s.addInitScript(() => window.addEventListener("saal:lage", (e) => { window.__lage = e.detail; }));
s.on("pageerror", (f) => konsole.push(String(f?.message || f)));
const anfragen = []; s.on("request", (r) => { if (/\/api\/reaktion/.test(r.url())) anfragen.push(r.method() + " " + new URL(r.url()).pathname); });
await s.goto(`${BASIS}/workspace/reaktion.html`, { waitUntil: "domcontentloaded" });
await s.waitForSelector("body[data-stand]", { timeout: 20000 });
await s.waitForTimeout(1500);
const titel = () => s.evaluate(() => window.__lage?.titel);
const { DatabaseSync: DBx } = await import("node:sqlite");
const dbx = new DBx(process.env.WORKSPACE_DB); const gastId = dbx.prepare("SELECT id FROM personen WHERE name = 'Nachtfalter'").get().id; dbx.close();
const setze = (t) => roh("/workspace/api/reaktion", { method: "PUT", keks: k.admin, rumpf: { titel: t } });
/* Ein Abruf, der VOR einer Änderung losgeht und erst DANACH ankommt. */
async function lauf(ohneNummer) {
await setze("Stand A");
await roh("/workspace/api/reaktion/massnahme", { method: "POST", keks: k.admin, rumpf: { art: "stumm", person_id: gastId, minuten: 5 } });
await warte(1200);
let gehalten = 0;
await s.route("**/workspace/api/reaktion", async (route) => {
if (route.request().method() !== "GET") return route.continue();
gehalten++;
/* Der Stand JETZT (A) – direkt beim Prüfserver geholt (route.fetch kennt
die Umleitung des Prüfbrowsers auf 127.0.0.1 nicht). */
let body = (await roh("/workspace/api/reaktion", { keks: k.gast })).text;
if (ohneNummer) { const j = JSON.parse(body); delete j.nummer; body = JSON.stringify(j); }
await warte(2500); /* … und kommt erst nach der Änderung an */
await route.fulfill({ status: 200, contentType: "application/json", body }).catch(() => {});
});
const vorher = await s.evaluate(() => window.__lageVerworfen || 0);
/* Einen Abruf auslösen: Das Aufheben der Maßnahme lässt die Seite des Zuschauers neu holen. */
await roh(`/workspace/api/reaktion/massnahme/${gastId}`, { method: "DELETE", keks: k.admin });
for (let i = 0; i < 40 && !gehalten; i++) await warte(150); /* bis der Abruf unterwegs ist */
await warte(300);
await setze("Stand B"); /* Rundruf mit neuerer Nummer */
await warte(3500);
await s.unrouteAll({ behavior: "ignoreErrors" });
await warte(800);
return { gehalten, titel: await titel(), verworfen: (await s.evaluate(() => window.__lageVerworfen || 0)) - vorher };
}
const mit = await lauf(false);
console.log(" mit Nummer:", JSON.stringify(mit));
ok(mit.gehalten >= 1, `Voraussetzung: ein Abruf wurde absichtlich verspätet (${mit.gehalten})`);
ok(mit.titel === "Stand B" && mit.verworfen >= 1, `die verspätete ältere Antwort überschreibt den neueren Stand nicht (${mit.titel}, ${mit.verworfen} verworfen)`);
const ohne = await lauf(true);
console.log(" ohne Nummer:", JSON.stringify(ohne));
ok(ohne.gehalten >= 1 && ohne.titel === "Stand A", `Gegenprobe: ohne Laufnummer hätte genau diese Antwort den Stand zurückgedreht (${ohne.titel}) – die Prüfung sieht den Fehler`);
ok(!konsole.length, `keine Fehler (${konsole.slice(0, 3).join(" | ")})`);
await s.unrouteAll({ behavior: "ignoreErrors" }).catch(() => {});
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);