Files
urutau/scripts/check-ui-i18n.mjs
Lucas RayanandClaude Opus 5.5 b7462c14fa
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
feat: 1.2.0 attack intelligence, replay, 30-day history and new interface
Intelligence: attack families mapped to MITRE ATT&CK, network type from
ASN/rDNS without external APIs, request cadence, sessions with
recon/probe/exploit/access/banned stages, campaigns across IPs, verdict
with reasons, recommended actions, exposure detection (2xx with a body
on sensitive paths), STIX 2.1 export, FCrDNS for search engine bots,
optional Tor exit list.

Data: 30-day retention, twelve ranges plus custom from/to, an on-disk
event log (daily files, hourly gzip members, size cap, corruption and
disk-full tolerant), /events, /period, /metrics with stable per-hour
metrics, an extended /ip/{ip}, and peer /period merged on the hub.

Interface: layout system with fixed card sizes, range picker in the
URL, IP analysis page, Replay page, Geography down to state and city
(Natural Earth admin-1), Live page redesigned with stable metrics and a
reusable attack map. Demo data and documentation screenshots.

Security: bounded and deadline-limited period computations, linear
campaign clustering, singleflight caches, sanitized peer studies, event
query budgets, gzip bomb guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:45:59 -03:00

148 lines
7.5 KiB
JavaScript
Executable File

#!/usr/bin/env node
// Verifies the dashboard translations. The core dictionary (i18n.js) and every
// registerI18n({...}) block found in web/*.js must define the same keys in en
// and pt-BR; every key used by the HTML and by the scripts (t('...'),
// data-i18n*, titleKey) must exist; the HTML must not carry visible text
// outside a data-i18n element.
//
// Usage: node scripts/check-ui-i18n.mjs
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import vm from 'node:vm';
const root = join(fileURLToPath(new URL('.', import.meta.url)), '..');
const web = join(root, 'internal/server/web');
const read = (f) => readFileSync(join(web, f), 'utf8');
const errors = [];
const LANGS = ['en', 'pt-BR'];
// dictionaries: name -> {source file, en: {}, pt-BR: {}}
const dicts = [];
// the core dictionary
const sandbox = { window: {}, document: { documentElement: { setAttribute() {} } }, localStorage: { getItem: () => null }, navigator: { language: 'en' } };
vm.runInNewContext(read('i18n.js'), sandbox);
dicts.push({ file: 'i18n.js', core: true, data: sandbox.window.URUTAU_I18N });
// registerI18n({...}) blocks: find the balanced object literal, skipping strings
function balanced(src, start) {
let depth = 0, q = null;
for (let i = start; i < src.length; i++) {
const c = src[i];
if (q) { if (c === '\\') i++; else if (c === q) q = null; continue; }
if (c === "'" || c === '"' || c === '`') { q = c; continue; }
if (c === '/' && src[i + 1] === '/') { while (i < src.length && src[i] !== '\n') i++; continue; }
if (c === '/' && src[i + 1] === '*') { i = src.indexOf('*/', i + 2) + 1; continue; }
if (c === '{') depth++;
else if (c === '}' && --depth === 0) return src.slice(start, i + 1);
}
return null;
}
const jsFiles = readdirSync(web).filter((f) => f.endsWith('.js') && f !== 'world.js');
// comments may mention registerI18n({...}) or t('...') as documentation
const stripComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/^\s*\/\/.*$/gm, '');
for (const f of jsFiles) {
const src = stripComments(read(f));
if (f === 'i18n.js') continue;
for (const m of src.matchAll(/registerI18n\s*\(\s*(?=\{)/g)) {
const lit = balanced(src, m.index + m[0].length);
if (!lit) { errors.push(`${f}: unbalanced registerI18n literal`); continue; }
try {
const data = vm.runInNewContext('(' + lit + ')', {});
dicts.push({ file: f, core: false, data, literal: lit });
} catch (e) { errors.push(`${f}: registerI18n literal is not static data (${e.message})`); }
}
}
const defined = new Map(); // key -> files
const ph = (s) => [...new Set((s.match(/\{(\w+)\}/g) ?? []))].sort().join(',');
for (const d of dicts) {
for (const lang of LANGS) if (!d.data[lang]) errors.push(`${d.file}: missing language ${lang}`);
const keys = new Set(LANGS.flatMap((l) => Object.keys(d.data[l] ?? {})));
for (const k of keys) {
if (!defined.has(k)) defined.set(k, []);
defined.get(k).push(d.file);
for (const lang of LANGS) {
const v = d.data[lang]?.[k];
if (v === undefined) errors.push(`${d.file}: missing in ${lang}: ${k}`);
else if (typeof v !== 'string' || !v.trim()) errors.push(`${d.file}: empty in ${lang}: ${k}`);
}
if (new Set(LANGS.map((l) => ph(d.data[l]?.[k] ?? ''))).size > 1) errors.push(`${d.file}: placeholder mismatch: ${k}`);
}
// duplicate keys silently collapse in an object literal: look at the source
const text = d.core ? read(d.file) : d.literal;
for (const lang of LANGS) {
const block = text.split(new RegExp(`\\n\\s*['"]?${lang}['"]?:\\s*\\{`))[1] ?? '';
const seen = new Set();
for (const m of block.split(/\n\s*\},?\s*(?:\n|$)/)[0].matchAll(/^\s*['"]([^'"]+)['"]:/gm)) {
if (seen.has(m[1])) errors.push(`${d.file}: duplicate key in ${lang}: ${m[1]}`);
seen.add(m[1]);
}
}
}
for (const [k, files] of defined) if (files.length > 1) errors.push(`key defined in more than one file: ${k} (${files.join(', ')})`);
// keys used
const used = new Map(); // key -> file
const literals = new Set();
const use = (k, f) => { if (!used.has(k)) used.set(k, f); };
const htmlFiles = readdirSync(web).filter((f) => f.endsWith('.html'));
for (const f of htmlFiles) for (const m of read(f).matchAll(/data-i18n(?:-ph|-aria|-title)?="([^"]+)"/g)) use(m[1], f);
for (const f of jsFiles) {
if (f === 'i18n.js') continue;
let src = stripComments(read(f));
// do not treat the dictionaries themselves as usage
for (const d of dicts) if (d.file === f && d.literal) src = src.replace(d.literal, '');
for (const m of src.matchAll(/\bt\(\s*'([^']+)'/g)) use(m[1], f);
for (const m of src.matchAll(/\bpl\(\s*'([^']+)'/g)) { use(m[1] + '.one', f); use(m[1] + '.other', f); }
for (const m of src.matchAll(/\b(?:titleKey|labelKey)\s*:\s*'([^']+)'/g)) use(m[1], f);
for (const m of src.matchAll(/'([A-Za-z][A-Za-z0-9-]*(?:\.[A-Za-z0-9-]+)*\.?)'/g)) literals.add(m[1]);
}
// keys built at runtime
const families = {
'cat.': ['ok', 'notfound', 'scanner', 'exploit', 'bruteforce', 'ssh-fail', 'ssh-probe', 'ssh-ok', 'ban'],
'level.': ['all', 'hostile', 'suspicious', 'low'],
'device.': ['desktop', 'mobile', 'tablet', 'bot', 'tool', 'unknown'],
'state.': ['following', 'waiting', 'backfill', 'error', 'disabled'],
'blocklist.family.': ['all', '4', '6'],
};
for (const [p, names] of Object.entries(families)) for (const n of names) use(p + n, 'runtime');
for (const [k, f] of used) if (!k.endsWith('.') && !defined.has(k)) errors.push(`${f}: used but not defined: ${k}`);
const exempt = ['live.on', 'live.off', 'feed.unban', 'yes', 'never', 'blocklist.copied', 'blocklist.failed', 'pager.count', 'ov.lead.hostile.one', 'ov.lead.hostile'];
for (const [k, files] of defined) {
// keys a script registers itself may be built dynamically, so only the core dictionary is checked for dead keys
if (!files.includes('i18n.js')) continue;
const byLiteral = literals.has(k) || [...literals].some((l) => l.endsWith('.') && k.startsWith(l));
if (!used.has(k) && !byLiteral && !k.startsWith('ago.') && !exempt.includes(k)) errors.push(`defined but unused: ${k}`);
}
// no visible text outside data-i18n in the HTML
for (const f of htmlFiles) {
const html = read(f).replace(/<script[\s\S]*?<\/script>/g, '').replace(/<!--[\s\S]*?-->/g, '').replace(/<title>[\s\S]*?<\/title>/g, '');
for (const m of html.matchAll(/<([a-z0-9]+)([^>]*)>([^<]+)</gi)) {
const text = m[3].replace(/&[a-z#0-9]+;/g, '').trim();
if (!/[A-Za-zÀ-ÿ]{2,}/.test(text)) continue;
if (/data-i18n="/.test(m[2])) continue;
if (/^(Urutau|EN|PT)$/.test(text)) continue; // brand name and the language toggle label
if (m[1] === 'span' && /id="(ver|live-text)"/.test(m[2])) continue;
errors.push(`${f}: hard-coded text <${m[1]}>${text}`);
}
// CSP: no inline style or event handler attributes
if (/\sstyle\s*=/.test(html)) errors.push(`${f}: inline style attribute (blocked by the CSP)`);
if (/\son[a-z]+\s*=/.test(html)) errors.push(`${f}: inline event handler (blocked by the CSP)`);
}
// scripts must never write markup
for (const f of jsFiles) {
if (f === 'world.js') continue;
if (/\.(innerHTML|outerHTML)\s*=|insertAdjacentHTML|document\.write/.test(read(f))) errors.push(`${f}: writes markup (innerHTML/outerHTML/insertAdjacentHTML/document.write)`);
}
if (errors.length) {
console.error('UI i18n problems:\n ' + errors.join('\n '));
process.exit(1);
}
const total = defined.size;
console.log(`ui i18n ok: ${total} keys in ${LANGS.join(', ')} (${dicts.length} dictionar${dicts.length === 1 ? 'y' : 'ies'}, ${jsFiles.length} scripts)`);