// Zweite Prüfung aller Websites, die der erste Abruf nicht eindeutig als Gemeindeseite bestätigt hat.
// Lädt die Startseite des Zielhosts und höchstens eine Impressum- oder Kontaktseite. Beachtet robots.txt.
// Es wird kein Seiteninhalt gespeichert. Ergebnis: daten/nachpruefung.jsonl
import dnsCb from 'node:dns';
import { appendFileSync, existsSync, readFileSync } from 'node:fs';
import http from 'node:http';
import https from 'node:https';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import zlib from 'node:zlib';
const hier = dirname(fileURLToPath(import.meta.url));
const pfad = (d) => join(hier, 'daten', d);
const jsonl = (d) => (existsSync(pfad(d)) ? readFileSync(pfad(d), 'utf8').trim().split('\n').filter(Boolean).map((z) => JSON.parse(z)) : []);
const UA = 'Mozilla/5.0 (compatible; municipal-hosting-study/1.0)';
const MAX = 512 * 1024;
setTimeout(() => process.exit(3), 60 * 60 * 1000).unref();
function privat(ip) {
const a = ip.toLowerCase().replace(/^::ffff:/, '');
if (a.includes(':')) return a === '::1' || a === '::' || /^f[cd]/.test(a) || /^fe[89ab]/.test(a);
const [x, y] = a.split('.').map(Number);
return x === 0 || x === 10 || x === 127 || (x === 169 && y === 254) || (x === 172 && y >= 16 && y <= 31) || (x === 192 && y === 168) || (x === 100 && y >= 64 && y <= 127) || x >= 224;
}
function suche(host, o, cb) {
dnsCb.lookup(host, { all: true }, (e, l) => {
if (e) return cb(e);
const gut = l.filter((a) => !privat(a.address));
if (!gut.length) return cb(Object.assign(new Error('PRIVATE_IP'), { code: 'PRIVATE_IP' }));
return o?.all ? cb(null, gut) : cb(null, gut[0].address, gut[0].family);
});
}
function hole(url, grenze = MAX) {
return new Promise((fertig) => {
let u;
try { u = new URL(url); } catch { return fertig({ fehler: 'URL' }); }
if (!/^https?:$/.test(u.protocol)) return fertig({ fehler: 'PROTOKOLL' });
let ende = false;
const schluss = (w) => { if (!ende) { ende = true; clearTimeout(uhr); fertig(w); } };
const a = (u.protocol === 'https:' ? https : http).request(u, {
method: 'GET', lookup: suche, rejectUnauthorized: false, agent: false,
headers: { 'User-Agent': UA, Accept: 'text/html,*/*;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'de', Connection: 'close' },
}, (r) => {
if (r.statusCode >= 300 && r.statusCode < 400) { r.destroy(); return schluss({ status: r.statusCode, kopf: r.headers, koerper: Buffer.alloc(0) }); }
const art = String(r.headers['content-encoding'] ?? '').toLowerCase();
const s = art.includes('br') ? r.pipe(zlib.createBrotliDecompress()) : art.includes('gzip') ? r.pipe(zlib.createGunzip()) : art.includes('deflate') ? r.pipe(zlib.createInflate()) : r;
const teile = [];
let n = 0;
const ab = () => schluss({ status: r.statusCode, kopf: r.headers, koerper: Buffer.concat(teile) });
s.on('data', (t) => { teile.push(t); n += t.length; if (n >= grenze) { ab(); r.destroy(); } });
s.on('end', ab); s.on('error', ab); r.on('error', ab);
});
const uhr = setTimeout(() => { a.destroy(); schluss({ fehler: 'ZEITLIMIT' }); }, 15000);
a.on('error', (e) => schluss({ fehler: e.code ?? e.message }));
a.end();
});
}
function text(k, kopf) {
const roh = k.subarray(0, 4096).toString('latin1');
const c = /charset=["']?([\w-]+)/i.exec(String(kopf?.['content-type'] ?? ''))?.[1] ?? /charset=["']?([\w-]+)/i.exec(roh)?.[1] ?? 'utf-8';
try { return new TextDecoder(c.toLowerCase()).decode(k); } catch { return new TextDecoder().decode(k); }
}
const robotsCache = new Map();
function robots(o) {
if (!robotsCache.has(o)) robotsCache.set(o, (async () => {
const r = await hole(`${o}/robots.txt`, 128 * 1024);
if (r.fehler || r.status !== 200) return [];
const regeln = [];
let aktiv = false;
let warAgent = false;
for (const zeile of text(r.koerper, r.kopf).split(/\r?\n/)) {
const z = zeile.replace(/#.*/, '').trim();
const p = z.indexOf(':');
if (p < 0) continue;
const k = z.slice(0, p).trim().toLowerCase();
const w = z.slice(p + 1).trim();
if (k === 'user-agent') { const passt = w === '*' || 'municipal-hosting-study'.includes(w.toLowerCase()); aktiv = warAgent ? aktiv || passt : passt; warAgent = true; } else {
warAgent = false;
if (aktiv && w && (k === 'allow' || k === 'disallow')) regeln.push({ erlaubt: k === 'allow', pfad: w });
}
}
return regeln;
})());
return robotsCache.get(o);
}
async function darf(url) {
const u = new URL(url);
const p = u.pathname + u.search;
let best = null;
for (const r of await robots(u.origin)) {
const m = r.pfad.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\\\$$/, '$');
if (new RegExp(`^${m}`).test(p) && (!best || r.pfad.length > best.pfad.length || (r.pfad.length === best.pfad.length && r.erlaubt))) best = r;
}
return !best || best.erlaubt;
}
async function seite(start) {
let url = start;
for (let i = 0; i < 6; i++) {
if (!(await darf(url))) return { url, robots: true };
const r = await hole(url);
if (r.fehler) return { url, fehler: r.fehler };
let ziel = r.status >= 300 && r.status < 400 ? r.kopf.location : null;
const html = r.koerper.length ? text(r.koerper, r.kopf) : '';
if (!ziel && r.status === 200) ziel = /]+http-equiv=["']?refresh["']?[^>]+content=["']?\s*\d+\s*;\s*url=['"]?([^"'>\s]+)/i.exec(html.slice(0, 8192))?.[1] ?? null;
if (!ziel) return { url, status: r.status, html };
try { url = new URL(ziel, url).href; } catch { return { url, status: r.status, html }; }
}
return { url, fehler: 'ZU_VIELE_WEITERLEITUNGEN' };
}
const norm = (s) => String(s ?? '').toLowerCase().replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss').replace(/[^a-z0-9]/g, '');
const kern = (n) => norm(String(n ?? '').split(',')[0].split('(')[0].split('/')[0].replace(/\b(Stadt|Gemeinde|Flecken|Markt)\b/gi, ''));
const reinerText = (h) => h.replace(/