Files
Pavlo Ratushnyi ddddfc864b recovered-partial: the blast-radius preview exists on disk with nobody's record on it
Recovered-partial, UNVERIFIED. These changes were in the working tree at session
start with no checkpoint record on any item (OPEN-75 carries no execution plan,
work result or handoff note), so they are preserved rather than built on.

Attribution: they are the OPEN-75 surface — GET /admin-api/impact, the console
panel that calls it, the write-path refusal of abbreviated v4 spellings, and the
smoke / compose / console scenes for it. The README section and endpoint-list
entry the item's definition of done asks for are not here.

Gate evidence taken against this state, not claimed for it:
  build (warnings-as-errors)  clean
  unit                        378/378
  integration                 403/405 — AlertPushQueueTests.Attempts_run_out_and_
                              the_surface_says_who_was_never_told and
                              PillarFailureVisibilityTests.The_snapshot_age_is_
                              measured_against_the_ttl_it_is_supposed_to_respect
                              fail here AND fail identically at 6f92d37 with
                              these changes absent, in a separate worktree, so
                              they are not this work's failures; their failure
                              site moves between runs (assertion vs fixture
                              StartServer), which is what an environment-sensitive
                              test looks like.
2026-10-05 18:20:42 +02:00

1366 lines
76 KiB
C#

namespace OpenWaf.Edge.Admin;
/// <summary>
/// The operator's console: one page, served by the edge itself, over the
/// endpoints in <see cref="AdminEndpoints"/>. It adds no decision logic — every
/// action on the page is one call to an endpoint that already exists.
///
/// Two properties are inherited from the admin API rather than invented here,
/// and both are load-bearing:
/// * <c>/admin</c> is on the always-pass list, so an operator who is themselves
/// blocked can still reach the page that clears it;
/// * the always-pass surface is never observed, so fumbling the page cannot
/// build a streak against the operator.
///
/// The token is never in a URL. A token in a query string survives in proxy
/// logs, browser history and Referer headers, which is exactly how an admin
/// token on a public edge leaks. It is typed into the page, kept in
/// sessionStorage for the tab, and sent as a header.
///
/// No external assets: the runtime image is distroless and the edge is often
/// the thing standing in front of a site that is under attack. A page that
/// needs a CDN is a page that fails at the moment it is wanted.
/// </summary>
internal static class AdminConsole
{
public static IEndpointRouteBuilder MapAdminConsole(this IEndpointRouteBuilder app)
{
// One endpoint, not two: "/admin" and "/admin/" are the same route to the
// matcher and registering both is an AmbiguousMatchException at request
// time (found by a test, not by reading). The catch-all is deliberate —
// this is a single page, so a mistyped subpath should show the page
// rather than be proxied to an upstream that has never heard of it.
app.MapGet("/admin/{**rest}", () => Results.Content(Page, "text/html; charset=utf-8"));
return app;
}
private const string Page = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>openwaf — operator</title>
<style>
:root { color-scheme: light dark; }
body { font: 14px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; margin: 0; padding: 1.2rem; }
h1 { font-size: 1rem; margin: 0 0 .2rem; }
h2 { font-size: .8rem; text-transform: uppercase; letter-spacing: .06em; margin: 1.4rem 0 .4rem; opacity: .7; }
.bar { display: flex; gap: .5rem; flex-wrap: wrap; align-items: center; margin-bottom: .6rem; }
input, select, button { font: inherit; padding: .3rem .5rem; }
button { cursor: pointer; }
table { border-collapse: collapse; width: 100%; }
th, td { text-align: left; padding: .25rem .5rem; border-bottom: 1px solid color-mix(in srgb, currentColor 18%, transparent); vertical-align: top; }
th { font-weight: normal; opacity: .6; }
.num { text-align: right; font-variant-numeric: tabular-nums; }
.pill { padding: .05rem .35rem; border: 1px solid currentColor; }
.warn { color: #b3261e; }
.ok { color: #186a3b; }
/* The status line is the only feedback the page gives, and on a dark canvas
these two colours measured 2.82:1 — unreadable. Measured, then fixed:
13.2:1 and 9.4:1 against the dark Canvas the browser actually paints. */
@media (prefers-color-scheme: dark) {
.warn { color: #ff9d9d; }
.ok { color: #7ee2a1; }
}
/* A seven-column table inside a 375 px phone measured 501 px wide and pushed
the whole document to 520 px of sideways scroll. The table scrolls in its
own box instead, so the token field and the summary stay on screen. */
.scroll { overflow-x: auto; }
.muted { opacity: .6 }
#status { font-weight: bold; }
.grid { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(22rem, 1fr)); }
/* The country table is the closest thing this page has to a map, and a column
of numbers does not show a distribution. One div per row, sized against the
busiest country: no tiles, no CDN, no asset file, because the runtime image
is distroless and the edge is usually the thing standing in front of a site
that is being attacked. A geographic map is deliberately NOT here — the
admin API exposes counts per ISO code, not coordinates, and a world outline
drawn from memory would be decoration that misleads. */
.sharebar { display: block; height: .55em; background: currentColor; opacity: .45; min-width: 2px; }
</style>
</head>
<body>
<h1>openwaf</h1>
<div class="bar">
<input id="token" type="password" placeholder="admin token" autocomplete="off" size="24">
<button id="save">use token</button>
<button id="refresh">refresh</button>
<select id="mode">
<option>Off</option><option>Observe</option><option>Enforce</option>
</select>
<button id="setMode">set mode</button>
<button id="clearEngine">clear engine bans</button>
<span id="status" class="muted">no token</span>
</div>
<div class="bar">
<input id="blockIp" placeholder="block address or CIDR" autocomplete="off" size="18">
<input id="blockReason" placeholder="reason" autocomplete="off" size="20">
<input id="blockTtl" placeholder="minutes" autocomplete="off" size="7" inputmode="numeric">
<button id="addBlock">block</button>
<input id="allowMatch" placeholder="allow address or CIDR" autocomplete="off" size="18">
<input id="allowNote" placeholder="note" autocomplete="off" size="14">
<input id="allowTtl" placeholder="minutes" autocomplete="off" size="7" inputmode="numeric">
<button id="addAllow">allow</button>
<input id="rulePattern" placeholder="path rule, e.g. /.env*" autocomplete="off" size="18">
<select id="ruleAction"><option value="observe">observe</option><option value="block">block</option></select>
<input id="ruleNote" placeholder="note" autocomplete="off" size="12">
<input id="ruleTtl" placeholder="minutes" autocomplete="off" size="7" inputmode="numeric">
<button id="addRule">add path rule</button>
<select id="rateMode"><option value="off">budget: off</option><option value="observe">budget: observe</option><option value="enforce">budget: enforce</option></select>
<input id="rateLimit" placeholder="requests" size="7" inputmode="numeric">
<input id="rateWindow" placeholder="window s" size="7" inputmode="numeric">
<button id="setRate">set budget</button>
<input id="rateRulePattern" placeholder="path budget, e.g. /login*" autocomplete="off" size="18">
<input id="rateRuleLimit" placeholder="requests" size="7" inputmode="numeric">
<input id="rateRuleWindow" placeholder="window s" size="7" inputmode="numeric">
<input id="rateRuleNote" placeholder="note" autocomplete="off" size="12">
<input id="rateRuleTtl" placeholder="minutes" autocomplete="off" size="7" inputmode="numeric">
<button id="addRateRule">add path budget</button>
</div>
<div id="summary" class="muted">—</div>
<h2>Bans and blocks</h2>
<div id="blocknote" class="muted"></div>
<div class="scroll"><table id="blocks"><thead><tr><th>source</th><th>provenance</th><th>reason</th><th>live until</th><th class="num">last</th><th></th></tr></thead><tbody></tbody></table></div>
<h2>Netblocks the edge noticed</h2>
<div id="netblocknote" class="muted"></div>
<div class="scroll"><table id="netblocks"><thead><tr><th>block</th><th class="num">bans inside</th><th>oldest ban</th><th>newest ban</th><th>some of those bans</th><th></th></tr></thead><tbody></tbody></table></div>
<h2>Allow entries</h2>
<div id="allownote" class="muted"></div>
<div class="scroll"><table id="allow"><thead><tr><th>match</th><th>note</th><th>expires</th><th></th></tr></thead><tbody></tbody></table></div>
<h2>Path rules</h2>
<div id="rulenote" class="muted"></div>
<div class="scroll"><table id="pathrules"><thead><tr><th>pattern</th><th>action</th><th>note</th><th class="num">matches</th><th>expires</th><th></th></tr></thead><tbody></tbody></table></div>
<h2>Request budget</h2>
<div id="ratenote" class="muted"></div>
<div class="scroll"><table id="ratetable"><thead><tr><th>source</th><th class="num">requests in window</th><th class="num">budget</th><th>window ends</th><th></th></tr></thead><tbody></tbody></table></div>
<h2>Path budgets</h2>
<div id="raterulenote" class="muted"></div>
<div class="scroll"><table id="raterules"><thead><tr><th>pattern</th><th class="num">requests</th><th class="num">window s</th><th class="num">sources counted</th><th class="num">windows running</th><th class="num">over budget now</th><th>note</th><th>expires</th><th></th></tr></thead><tbody></tbody></table></div>
<div id="budgetsources" class="muted"></div>
<h2>Ask what the edge would answer</h2>
<div class="bar">
<input id="askIp" placeholder="address" autocomplete="off" size="18">
<input id="askPath" placeholder="path, e.g. /wp-login.php" autocomplete="off" size="26">
<button id="askDecide">ask</button>
</div>
<div id="askanswer" class="muted"></div>
<h2>One address, one answer</h2>
<div class="bar">
<input id="dossierIp" placeholder="address" autocomplete="off" size="18">
<button id="askSource">what does this edge know about it?</button>
</div>
<div id="dossieranswer" class="muted"></div>
<h2>The enforcement horizon</h2>
<div class="bar">
<input id="horizonWithin" placeholder="minutes ahead" autocomplete="off" size="8" value="30">
<button id="askHorizon">what stops being enforced soon?</button>
</div>
<div id="horizonanswer" class="muted"></div>
<h2>One source through time</h2>
<div class="bar">
<input id="historyIp" placeholder="address" autocomplete="off" size="18">
<button id="askHistory">what happened to it, in order?</button>
</div>
<div id="historyanswer" class="muted"></div>
<h2>Where does this appear?</h2>
<div class="bar">
<input id="findq" placeholder="a note, a reason, a path, an address" autocomplete="off" size="30">
<button id="askFind">search every store</button>
</div>
<div id="findanswer" class="muted"></div>
<h2>What would this ban touch?</h2>
<div class="bar">
<input id="impactMatch" placeholder="address or CIDR" autocomplete="off" size="20">
<input id="impactPath" placeholder="path, e.g. /wp-login.php" autocomplete="off" size="22">
<button id="askImpact">what would it reach?</button>
</div>
<div id="impactanswer" class="muted"></div>
<h2>Sources the edge is watching</h2>
<div class="bar">
<input id="srcfilter" placeholder="filter observations and streaks by source key" autocomplete="off" size="28">
<button data-act="srcfilter">filter</button>
<button data-act="srcclear">show every source</button>
</div>
<div id="obsnote" class="muted"></div>
<div class="scroll"><table id="obs"><thead><tr><th>source</th><th class="num">consec.</th><th class="num">refusals</th><th>last status</th><th>path</th><th>geo</th></tr></thead><tbody></tbody></table></div>
<h2>Streaks standing in this edge</h2>
<div id="streaknote" class="muted"></div>
<div class="scroll"><table id="streaks"><thead><tr><th>source</th><th class="num">consecutive</th><th class="num">server errors</th><th>last status</th><th>path</th><th>geo</th><th>last seen</th></tr></thead><tbody></tbody></table></div>
<h2>Alerts — what the edge wants a human to look at</h2>
<div id="alertnote" class="muted"></div>
<div class="scroll"><table id="alerts"><thead><tr><th>kind</th><th>source</th><th class="num">count</th><th class="num">last</th><th>when</th></tr></thead><tbody></tbody></table></div>
<h2>What changed on this edge</h2>
<div id="changenote" class="muted"></div>
<div class="scroll"><table id="changes"><thead><tr><th>when</th><th>section</th><th>action</th><th>target</th><th>detail</th><th>surface</th></tr></thead><tbody></tbody></table></div>
<h2>Countries seen</h2>
<div id="countrysum" class="muted"></div>
<div class="scroll"><table id="countries"><thead><tr><th>code</th><th class="num">sources</th><th class="num">refusals</th><th>refusals vs the busiest</th><th>rule</th><th></th></tr></thead><tbody></tbody></table></div>
<p class="muted">Every action here is one call to the admin API. The page decides nothing.</p>
<script>
const el = (id) => document.getElementById(id);
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
let token = sessionStorage.getItem('openwaf.token') || '';
el('token').value = token;
// The source key the per-source tables are narrowed to. The empty string means
// "no filter at all": the parameter is left off rather than sent empty, because
// an empty value is a 400 since OPEN-23 and a console that sends one shows the
// operator an error where it meant to show a table.
let obsSource = '';
async function apiRaw(path, opts = {}) {
const headers = Object.assign({}, opts.headers || {});
if (token) headers['X-Admin-Token'] = token;
const r = await fetch(path, Object.assign({}, opts, { headers }));
if (r.status === 401) { note('token rejected', true); throw new Error('401'); }
let body = null;
if (r.status !== 204) {
try {
body = await r.json();
} catch (e) {
// An empty 4xx/5xx is still an answer, and it used to be an answer the
// page swallowed: r.json() threw, the caller's catch said "note() already
// said why", and nothing had been said. The status line went quiet
// exactly when the edge had the worst news to report.
body = r.ok ? null : { error: 'the edge answered ' + r.status + ' with no explanation' };
}
}
// A 404 used to be read here as "the admin API is switched off" — for every
// 404, including the one that means "that row is not there" (another tab
// removed it, the list on screen is stale). That sentence sent the operator to
// set a token that is already set. Whether the surface is off is not something
// this function can know from one response; the edge says it in the body when
// it is true, so the body is what gets shown.
if (r.status === 404 && body === null) body = { error: 'nothing at ' + path };
return { body, status: r.status, total: r.headers.get('X-Total-Count'), truncated: r.headers.get('X-Truncated') === 'true' };
}
async function api(path, opts = {}) { return (await apiRaw(path, opts)).body; }
// The answer carried a reason this call did not work. Every write on this page
// has to ask before it says it worked — the note in the status line is the only
// feedback a click gets, and a green note over an error answer is the page
// repeating the API's old lie: "deleted 0" when nothing could be deleted.
let holdNote = false;
// The note for the action the operator just took, held across the refresh that
// action itself triggers. Without the hold, load() — which every action calls,
// and which also runs on a 5 s interval — replaced the sentence with
// "refreshed" inside a second, which is shorter than the time it takes to read
// it. The next refresh says "refreshed" again, so nothing stays on screen
// forever.
function done(text) { note(text, false); holdNote = true; }
function failed(r) {
if (r.body && r.body.error) { note(r.body.error, true); holdNote = true; return true; }
return false;
}
function note(text, bad) {
const s = el('status');
s.textContent = text;
s.className = bad ? 'warn' : 'ok';
}
// c.v is text and goes through esc(); c.h is markup this file wrote itself (the
// country bar) and nothing else. Every value that came from the API is text.
const plural = (n, word) => (n === 1 ? word : word + 's');
// One filter, shared by the observations table and the streaks table, so the
// two per-source listings always answer about the same address. The separator
// is decided per path, not assumed: the observations call already carries
// ?limit=25 and the streaks call carries nothing, and the first version of this
// appended "&source=" to a bare path — which is not a query parameter, it is a
// different route, and the edge answered 404. The page then printed "unknown
// scope" for the streak line, which is the honest thing to print about an answer
// that never arrived and the wrong thing to print about a filter.
const withSrc = (path) => path + (obsSource
? (path.indexOf('?') === -1 ? '?' : '&') + 'source=' + encodeURIComponent(obsSource)
: '');
// Every source key printed on this page is a question the operator can ask
// back: "what else does the edge know about this address?" The key still goes
// through esc() on its way into the attribute, so the escaping invariant the
// console gate checks is unchanged by making the cell clickable. A row with no
// source at all — a durability alert — stays plain text: there is nothing to
// filter to.
const srcBtn = (k) => (!k ? '' : '<button data-act="srcfilter" data-k="' + esc(k)
+ '">' + esc(k) + '</button>');
function row(cells) {
return '<tr>' + cells.map((c) => '<td' + (c.n ? ' class="num"' : '') + '>'
+ (c.h !== undefined ? c.h : esc(c.v)) + '</td>').join('') + '</tr>';
}
async function load() {
if (!token) { note('no token', true); return; }
try {
const [stateRes, blocksRes, obsRes, streaksRes, countriesRes, rulesRes, allowRes, pathRulesRes, rateRes, pathBudgetsRes, alertsRes, geoRes, changesRes, netblocksRes] = await Promise.all([
apiRaw('/admin-api/state'), apiRaw('/admin-api/blocks?live=false'),
apiRaw(withSrc('/admin-api/observations?limit=25')),
apiRaw(withSrc('/admin-api/streaks')),
apiRaw('/admin-api/countries/summary'), apiRaw('/admin-api/countries'),
apiRaw('/admin-api/allow?live=false&limit=500'),
apiRaw('/admin-api/rules?live=false&limit=500'), apiRaw('/admin-api/rate?limit=25'),
apiRaw('/admin-api/rate-rules?live=false&limit=500'),
apiRaw('/admin-api/alerts?limit=25'),
apiRaw('/admin-api/geo'),
apiRaw('/admin-api/changes?limit=25'),
apiRaw('/admin-api/netblocks')
]);
// The core read decides whether there is anything to draw. When the admin
// surface is switched off the edge says so in the body — "admin api
// disabled: set OpenWaf__Admin__Token" — and that sentence is what the
// operator needs, not a guess this page makes about a status code.
if (stateRes.status !== 200) {
note((stateRes.body && stateRes.body.error) || ('the edge answered ' + stateRes.status + ' for /admin-api/state'), true);
return;
}
const state = stateRes.body;
// A listing that could not be read answers with an error object where an
// array belongs. The notes below say which call failed; the tables still map
// over these values, so the shape is normalised once here instead of at
// fourteen call sites, and a failed read draws the NOT READ row rather than
// throwing the whole refresh half-drawn.
const list = (r) => (Array.isArray(r.body) ? r.body : []);
const blocks = list(blocksRes);
const obs = list(obsRes);
const alerts = list(alertsRes);
const streaks = streaksRes.body && typeof streaksRes.body === 'object'
? streaksRes.body : { streaks: [] };
const countries = list(countriesRes), rules = list(rulesRes),
allow = list(allowRes), pathRules = list(pathRulesRes), rate = rateRes.body, geo = geoRes.body,
changes = list(changesRes), netblocks = netblocksRes.body,
pathBudgets = list(pathBudgetsRes);
// A listing that failed is not an empty listing. Every note under here is a
// count, and a count read off a failed answer is 0: measured on a run where
// two of these fourteen calls lost the database for a moment, the
// observation line printed "0 sources the edge has recorded" and the streak
// line "0 of 0 standing streaks listed" over a map holding twelve sources.
// The status line did say the call failed — but the table is what an
// operator reads, and it said there was nothing to see. An empty table and
// an unreadable one are different facts, and this page already has to tell
// "never seen" from "broken" for one filtered row; it has to do it for a
// whole listing too.
const readFailed = (r) => r.status !== 200 || r.body === null;
const failedRead = (r) => 'NOT READ \u2014 '
+ ((r.body && r.body.error) || ('the edge answered ' + r.status))
+ '. This is not an empty table.';
// The listing is capped server-side. Saying so is the difference between a
// console and a misleading one: the delete beside this table is not capped.
el('blocknote').textContent = readFailed(blocksRes) ? failedRead(blocksRes)
: blocksRes.truncated
? 'showing the newest ' + blocks.length + ' of ' + blocksRes.total + ' — clearing by provenance removes all ' + blocksRes.total + ', not just this page'
: blocksRes.total + (blocksRes.total === '1' ? ' entry' : ' entries');
// A row here can be a network rather than an address (OPEN-66), and the two
// are not the same claim: one refuses one source, the other refuses every
// address inside it. The line says which shape the table holds and what
// outranks it, because the alternative is an operator reading a /24 as a row
// of the same size as any other.
if (!readFailed(blocksRes))
el('blocknote').textContent += ' \u00b7 a range row refuses every address inside it, and an allow entry still outranks it';
// The observation listing is capped too, and it is the table an operator
// reads to decide which sources the edge has actually seen. Until the API
// said how many there are, "newest 25" and "the whole window" looked the
// same on this page.
// Under a filter the total is the FILTERED total — the API narrowed the
// count along with the rows — and a source with nothing recorded is named
// in words instead of drawn as an empty table. That is how an operator
// tells "this address was never seen" from "the page stopped working".
el('obsnote').textContent = readFailed(obsRes) ? failedRead(obsRes)
: obsSource
? (Number(obsRes.total) === 0
? 'no recorded observations for ' + obsSource
: 'filtered to ' + obsSource + ': ' + (obsRes.truncated
? 'newest ' + obs.length + ' of ' + obsRes.total + ' rows for this source — the rest are older'
: obsRes.total + ' ' + plural(Number(obsRes.total), 'row') + ' recorded for this source'))
: obsRes.truncated
? 'newest ' + obs.length + ' of ' + obsRes.total + ' recorded sources — the rest are older and this table is not the whole window'
: obsRes.total + ' ' + plural(Number(obsRes.total), 'source') + ' the edge has recorded';
// The window these rows age out at, printed on the table it applies to.
// Without the number, "3 sources recorded" reads the same whether the edge
// keeps them a week or a year — and the window is the answer to "how far
// back can this incident still be explained" (OPEN-19).
if (!readFailed(obsRes) && state.observationRetentionDays != null)
el('obsnote').textContent += ' · rows are pruned after ' + state.observationRetentionDays + 'd';
const allowed = new Map((rules || []).map((r) => [r.code, r.isAllowed]));
// A failed write is not a stale read: the row never existed, and the
// listing kept answering 200 with the count it already had. Measured on the
// shipped image with writes to source_observations and edge_alerts aborted:
// X-Total-Count stayed at 4 while three new sources were refused, the alert
// table stayed at 1 row through a six-request 5xx storm, and /readyz said
// "ready". Each number is escaped on its own, so the join stays raw.
const writeProblems = [];
if (Number(state.banWriteFailures) > 0)
writeProblems.push('bans not written \u00d7' + esc(state.banWriteFailures)
+ ' (' + esc(state.bansNotWritten) + ' not enforced)');
if (Number(state.observationWriteFailures) > 0)
writeProblems.push('observations not persisted \u00d7' + esc(state.observationWriteFailures)
+ ' (' + esc(state.observationsLost) + ' rows lost)');
if (Number(state.alertWriteFailures) > 0)
writeProblems.push('alerts not persisted \u00d7' + esc(state.alertWriteFailures)
+ ' (' + esc(state.alertsLost) + ' lost)');
if (Number(state.retentionPruneFailures) > 0)
writeProblems.push('retention not running \u00d7' + esc(state.retentionPruneFailures));
// The change log is the one table whose failure does not change what the
// edge enforces, so it would be invisible if it were not said here: the
// config changed, the record of it did not land (OPEN-64).
if (Number(state.changeWriteFailures) > 0)
writeProblems.push('change records not written \u00d7' + esc(state.changeWriteFailures)
+ ' (' + esc(state.changesNotWritten) + ' changes unrecorded)');
el('summary').innerHTML =
'<span class="pill">mode ' + esc(state.mode) + '</span> ' +
// The age against the bound it is measured against was half the story, and
// the number alone was the other half: a snapshot can sit at ten times the
// TTL, or a pillar can have stopped reading its table altogether and kept
// answering from memory, and either way this pill used to look normal.
// Marked on both counts, because this is the line an operator reads to
// decide whether the edge is obeying the list they are looking at.
'<span class="pill'
+ (state.snapshotStale || Number(state.snapshotRefreshFailures) > 0
|| Number(state.policyReloadFailures) > 0 ? ' warn' : '') + '">snapshot '
+ esc(state.snapshotAgeSeconds) + 's / ttl ' + esc(state.snapshotTtlSeconds) + 's'
+ (state.snapshotStale ? ' \u00b7 older than the ttl' : '')
+ (Number(state.snapshotRefreshFailures) > 0
? ' \u00b7 snapshot refresh failing \u00d7' + esc(state.snapshotRefreshFailures) : '')
+ (Number(state.policyReloadFailures) > 0
? ' \u00b7 policy not re-read from storage \u00d7' + esc(state.policyReloadFailures) : '')
+ '</span> ' +
'<span class="pill' + (writeProblems.length ? ' warn' : '') + '">durable writes '
+ (writeProblems.length ? writeProblems.join(' \u00b7 ') : 'ok') + '</span> ' +
'<span class="pill">tracked ' + esc(state.trackedSources) + '</span> ' +
'<span class="pill">engine bans ' + esc(state.engineBans) + '</span> ' +
'<span class="pill">operator blocks ' + esc(state.operatorBlocks) + '</span> ' +
// Counted apart from the blocks on purpose: one range row can be a
// thousand addresses, so a single number mixing the two answers neither
// "how many decisions did I write" nor "how wide are they".
'<span class="pill">ranges ' + esc(state.operatorRanges) + '</span> ' +
// What the watch is offering (OPEN-67), counted apart from what is in
// force: an offer bans nobody, and a number that mixed the two would make
// "the edge noticed a /24" look like "the edge banned a /24".
'<span class="pill">netblock offers '
+ esc(((netblocks && netblocks.netblocks) || []).length) + '</span> ' +
// Live exemptions, not rows: the pill used to count rows, which is how a
// page could say "allow entries 1" about an exemption the edge had
// already stopped honouring.
'<span class="pill">allow entries ' + esc(state.allowEntries)
+ (Number(state.allowEntriesExpired) > 0 ? ' live · ' + esc(state.allowEntriesExpired) + ' expired' : '')
+ '</span>' +
// Which geo database this edge is actually enforcing on, and how old it is.
// The pin ages with the image and a named volume is seeded once, so "which
// one am I running" is a question an operator can only answer from here.
// Marked when it passes the 90-day runtime alarm, the same rule /healthz
// reports as geoStale.
' ' + (readFailed(geoRes)
? '<span class="pill warn">geo not read \u2014 '
+ esc((geo && geo.error) || ('the edge answered ' + geoRes.status)) + '</span>'
: geo && geo.loaded
? '<span class="pill' + (Number(geo.ageDays) > 90 ? ' warn' : '') + '">geo '
+ esc(geo.database || 'unknown') + ' \u00b7 built ' + esc((geo.builtAt || '').slice(0, 10))
+ ' \u00b7 ' + esc(geo.ageDays) + 'd</span>'
: '<span class="pill warn">geo database not loaded</span>');
el('mode').value = state.mode;
el('blocks').tBodies[0].innerHTML = (blocks || []).map((b) => row([
// A range is not a source, so it is not offered as a filter question: the
// observations table holds addresses, and clicking a /24 would ask for a
// source that can never be there.
{ h: b.kind === 'range'
? esc(b.sourceKey) + ' <span class="muted">range</span>'
: srcBtn(b.sourceKey) },
{ v: b.source }, { v: b.reason },
{ v: b.live ? (b.expiresAt || '').replace('T', ' ').slice(0, 19) : 'expired' },
{ v: (b.lastStatusCode || '') + ' ' + (b.lastPath || ''), n: true },
{ h: '<button data-act="delblock" data-k="' + esc(b.sourceKey) + '">delete</button>' }
])).join('') || row([{ v: 'none' }]);
// The watch (OPEN-67): the edge's own live engine bans, grouped into the
// block they all sit under. Nothing in this table is in force - it is an
// offer, and the button is the same call the block form makes, so the
// decision to ban a netblock stays a decision.
el('netblocks').tBodies[0].innerHTML = ((netblocks && netblocks.netblocks) || []).map((n) => row([
{ v: n.match },
{ v: n.bans, n: true },
{ v: (n.firstBanAt || '').slice(0, 16).replace('T', ' ') },
{ v: (n.lastBanAt || '').slice(0, 16).replace('T', ' ') },
{ v: (n.sample || []).join(', ') },
n.alreadyBanned
? { h: '<span class="muted">already banned</span>' }
: { h: '<button data-act="banrange" data-k="' + esc(n.match) + '" data-n="' + esc(n.bans) + '">ban this range</button>' }
])).join('') || row([{ v: 'none' }]);
el('netblocknote').textContent = readFailed(netblocksRes) ? failedRead(netblocksRes)
: netblocks && netblocks.scanError
? 'the last scan failed: ' + netblocks.scanError + ' - nothing is offered, and the last answer was dropped rather than repeated'
: Number(netblocks.threshold) <= 0
? 'the watch is off (netblockCandidateBans = 0): the edge groups nothing and offers nothing'
: (((netblocks && netblocks.netblocks) || []).length === 0
? 'no block holds ' + netblocks.threshold + ' live engine bans yet - a candidate is an offer, not a ban'
: ((netblocks.netblocks || []).length) + ' block(s) hold ' + netblocks.threshold
+ '+ live engine bans - banning one replaces those rows with one range, and nothing here is in force until you do');
// The row is not the answer. An allow entry with an expiry stops being
// obeyed the moment it ages — measured on the shipped image: the exempted
// address went 502 (through) at 03:58:20 and back to 301 (blocked) at
// 03:59:38 — while this table kept printing the row as if it still meant
// something, and nothing prunes those rows. So the cell carries the
// engine's verdict, not just the column.
const allowExpired = (allow || []).filter((a) => a.live === false).length;
el('allow').tBodies[0].innerHTML = (allow || []).map((a) => row([
{ v: a.match }, { v: a.note },
{ v: a.live === false
? (a.expiresAt || '').replace('T', ' ').slice(0, 19) + ' — EXPIRED, the edge no longer honours it'
: (a.expiresAt || 'never').replace('T', ' ').slice(0, 19) },
{ h: '<button data-act="delallow" data-k="' + esc(a.id) + '">remove</button>' }
])).join('') || row([{ v: readFailed(allowRes)
? 'NOT READ \u2014 the edge could not answer this call'
: 'none — everything not blocked is allowed' }]);
el('allownote').textContent = readFailed(allowRes) ? failedRead(allowRes)
: (allow || []).length
? 'an allow entry outranks every ban, engine or operator — it is the "my customer is locked out" control'
+ (allowRes.truncated ? ' · showing ' + allow.length + ' of ' + allowRes.total + ' rows' : '')
+ (allowExpired ? ' · ' + allowExpired + ' EXPIRED: those rows no longer exempt anyone' : '')
: 'nothing allowlisted';
// Path rules are the one pillar about the request rather than the response,
// and the two actions mean different things to the person reading: observe
// answers "what would this have blocked", block refuses the request before
// the application sees it. The order on the page is the order the engine
// evaluates, so the first row that matches is the answer.
const expiredRules = (pathRules || []).filter((r) => r.live === false).length;
el('pathrules').tBodies[0].innerHTML = (pathRules || []).map((r) => row([
{ v: r.pattern },
{ h: r.action === 'block' ? '<span class="warn">' + esc(r.action) + '</span>' : esc(r.action) },
{ v: r.note },
{ v: r.matches, n: true },
{ v: r.live === false
? (r.expiresAt || '').replace('T', ' ').slice(0, 19) + ' — EXPIRED, the edge no longer honours it'
: (r.expiresAt || 'never').replace('T', ' ').slice(0, 19) },
{ h: '<button data-act="delrule" data-k="' + esc(r.id) + '">remove</button>' }
])).join('') || row([{ v: readFailed(pathRulesRes)
? 'NOT READ \u2014 the edge could not answer this call'
: 'none — the edge judges responses, not requests' }]);
el('rulenote').textContent = readFailed(pathRulesRes) ? failedRead(pathRulesRes)
: state.requestRulesAvailable === false
? 'NOT READ — this database has no request-rule table (' + (state.requestRulesError || 'no reason given')
+ '), so no path rule is in force. Apply the schema migration; every other pillar is enforcing.'
: (pathRules || []).length
? 'the first rule that matches is the answer, in this order · observe counts what it would have blocked, block refuses before the application sees the request'
+ (pathRulesRes.truncated ? ' · showing ' + pathRules.length + ' of ' + pathRulesRes.total + ' rules' : '')
+ (expiredRules ? ' · ' + expiredRules + ' EXPIRED: those rules enforce nothing' : '')
: 'no path rules — the edge reacts to what the upstream answered, never to the request itself';
// The per-path budgets (OPEN-68). The two counters are the reason this table
// exists: "sources counted" says the rule is seeing traffic at all, and
// "over budget now" says what an observe-mode rule would have refused. A
// budget nobody has blown and a budget nobody can blow look the same on
// paper, and only one of them is worth keeping.
const expiredBudgets = (pathBudgets || []).filter((r) => r.live === false).length;
el('raterules').tBodies[0].innerHTML = (pathBudgets || []).map((r) => row([
{ v: r.pattern },
{ v: r.limitPerWindow, n: true },
{ v: r.windowSeconds, n: true },
{ v: r.trackedSources, n: true },
{ v: r.liveWindows, n: true },
{ h: r.overBudgetNow
? '<span class="warn">' + esc(r.overBudgetNow) + '</span>'
: esc(r.overBudgetNow) },
{ v: r.note },
{ v: r.live === false
? (r.expiresAt || '').replace('T', ' ').slice(0, 19) + ' — EXPIRED, the edge no longer honours it'
: (r.expiresAt || 'never').replace('T', ' ').slice(0, 19) },
{ h: '<button data-act="whobudget" data-k="' + esc(r.id) + '">who</button> '
+ '<button data-act="delraterule" data-k="' + esc(r.id) + '">remove</button>' }
])).join('') || row([{ v: readFailed(pathBudgetsRes)
? 'NOT READ \u2014 the edge could not answer this call'
: 'none — every path shares the one edge-wide budget above' }]);
el('raterulenote').textContent = readFailed(pathBudgetsRes) ? failedRead(pathBudgetsRes)
: state.rateRulesAvailable === false
? 'NOT READ — this database has no rate-rule table (' + (state.rateRulesError || 'no reason given')
+ '), so no path budget is in force. Apply the schema migration; every other pillar is enforcing.'
: (pathBudgets || []).length
? 'a path budget pauses one source on one path for the rest of its window — it is not a ban, the rest of the site stays open'
+ (pathBudgetsRes.truncated ? ' · showing ' + pathBudgets.length + ' of ' + pathBudgetsRes.total + ' rules' : '')
+ (expiredBudgets ? ' · ' + expiredBudgets + ' EXPIRED: those budgets enforce nothing' : '')
: 'no path budgets — the edge-wide budget above is the only one being counted';
// The volume pillar (OPEN-56). The table is the live counter, so it says
// plainly when the pillar is off: an empty table and a disabled budget look
// identical otherwise, and only one of them means nothing is being counted.
const rateRows = (rate && rate.sources) || [];
el('ratetable').tBodies[0].innerHTML = rateRows.length
? rateRows.map((r) => row([
{ v: r.sourceKey },
// The number stays the number; the marking is the colour. A cell that
// reads "3 over" cannot be compared against the budget by anyone.
{ h: r.overBudget ? '<span class="warn">' + esc(r.count) + '</span>' : esc(r.count) },
{ v: rate.limitPerWindow, n: true },
{ v: r.windowEnd ? new Date(r.windowEnd).toLocaleTimeString() : '-' }
])).join('')
: row([{ v: readFailed(rateRes)
? 'NOT READ \u2014 the edge could not answer this call' : 'nothing counted' }]);
el('ratenote').textContent = readFailed(rateRes) ? failedRead(rateRes)
: rate && rate.mode && rate.mode !== 'Off'
? rate.mode.toLowerCase() + ' · ' + rate.limitPerWindow + ' requests per '
+ rate.windowSeconds + ' s per source, counted in this process (' + rate.trackedSources
+ ' sources tracked) · behind more than one edge each edge counts its own traffic'
: 'off — the edge never refuses a request for asking too often; nothing is being counted';
// The select follows the server, unless the operator is holding it right
// now — a five-second refresh that overwrites a half-made choice is how a
// page convinces someone they never clicked anything.
if (document.activeElement !== el('rateMode'))
el('rateMode').value = (rate && rate.mode ? rate.mode.toLowerCase() : 'off');
// Placeholders, not values: they say what an empty box means, and an empty
// box is "keep what is set".
el('rateLimit').placeholder = rate ? 'budget ' + rate.limitPerWindow : 'budget';
el('rateWindow').placeholder = rate ? 'window ' + rate.windowSeconds + ' s' : 'window s';
el('obs').tBodies[0].innerHTML = (obs || []).map((o) => row([
{ h: srcBtn(o.sourceKey) }, { v: o.maxConsecutiveRefusals, n: true }, { v: o.totalRefusals, n: true },
{ v: o.lastStatusCode }, { v: o.lastPath }, { v: [o.lastCountryCode, o.lastCity].filter(Boolean).join(' / ') }
])).join('') || row([{ v: readFailed(obsRes)
? 'NOT READ \u2014 the edge could not answer this call'
: obsSource ? 'nothing recorded for ' + obsSource : 'none' }]);
el('streaks').tBodies[0].innerHTML = (streaks.streaks || []).map((st) => row([
{ h: srcBtn(st.sourceKey) }, { v: st.consecutiveRefusals + ' / ' + streaks.threshold, n: true },
{ v: st.consecutiveServerErrors, n: true }, { v: st.lastStatusCode }, { v: st.lastPath },
{ v: st.lastCountryCode },
{ v: (st.lastSeenAt || '').replace('T', ' ').slice(0, 19) }
])).join('') || row([{ v: readFailed(streaksRes)
? 'NOT READ \u2014 the edge could not answer this call'
: obsSource ? 'nothing standing for ' + obsSource
: 'nothing standing — every tracked source last saw a clean answer' }]);
// "this edge process only" is the scope sentence OPEN-16 earned; the filter
// sentence is the one OPEN-36 adds. Under a filter standingStreaks is the
// FILTERED count while trackedSources stays the whole map, and that pair is
// the honest reading of "one of these many".
el('streaknote').textContent =
readFailed(streaksRes) ? failedRead(streaksRes)
: streaks.scope !== 'this-process' && streaks.scope !== 'shared-database' ? 'unknown scope'
: (streaks.scope === 'shared-database'
// The streaks in this table were counted by every edge sharing the
// database, not only by the one serving this page (OPEN-52). Saying
// "this edge process only" here would understate what the operator
// is looking at.
? 'shared across every edge on this database — '
: 'this edge process only — ')
+ (obsSource
? (Number(streaks.standingStreaks) === 0
? 'filtered to ' + obsSource + ': nothing standing for this source'
: 'filtered to ' + obsSource + ': ' + (streaks.streaks || []).length + ' of '
+ streaks.standingStreaks + ' standing streaks for this source listed')
: (streaks.streaks || []).length + ' of ' + streaks.standingStreaks
+ ' standing streaks listed')
+ '; threshold ' + streaks.threshold
+ ' within ' + streaks.windowMinutes + ' min; '
+ (obsSource ? 'the unfiltered map holds ' : '') + streaks.trackedSources
+ ' sources tracked, '
+ (streaks.maxTrackedSources == null
// Shared store: no cap exists, so the sentence names the bound that
// does — idle rows leave the listing, and rows are deleted with the
// retention window.
? 'idle ones drop out after ' + streaks.trackedIdleMinutes
+ ' min and rows are pruned after ' + streaks.trackedRetentionDays + 'd'
: 'map capped at ' + streaks.maxTrackedSources);
// The bar is a share of the busiest country, not of some absolute scale:
// what an operator wants out of this table is "where is the traffic coming
// from right now", and that is a comparison. Widths are percentages of the
// cell, so the table still fits a 375 px phone (the phone pass of the gate
// measures the document, not this column).
const seen = countries || [];
const busiest = seen.reduce((m, c) => Math.max(m, c.refusals || 0), 0);
const totalSources = seen.reduce((t, c) => t + (c.sources || 0), 0);
const totalRefusals = seen.reduce((t, c) => t + (c.refusals || 0), 0);
// The record of deliberate changes (OPEN-64). The surface column is the
// honest one: the edge has one admin token, so it says which surface wrote,
// not which person.
el('changes').tBodies[0].innerHTML = (changes || []).map((c) => row([
{ v: (c.at || '').replace('T', ' ').slice(0, 19) },
{ v: c.section },
{ v: c.action },
{ v: c.target },
{ v: c.detail || '' },
{ v: c.actor }
])).join('') || row([{ v: readFailed(changesRes)
? 'NOT READ \u2014 the edge could not answer this call'
: 'nothing recorded yet - every operator write from now on leaves a row here' }]);
el('changenote').textContent = readFailed(changesRes) ? failedRead(changesRes)
: Number(changesRes.total) === 0
? 'no config changes recorded. engine bans are not here: they are not decisions.'
: (changesRes.truncated
? 'newest ' + changes.length + ' of ' + changesRes.total + ' records - engine bans are not here, they are not decisions'
: changesRes.total + ' ' + plural(Number(changesRes.total), 'record') + ' - engine bans are not here, they are not decisions');
if (!readFailed(changesRes) && state.changeRetentionDays != null)
el('changenote').textContent += ' - pruned after ' + state.changeRetentionDays + 'd or '
+ state.changeLogMaxRows + ' rows, whichever comes first';
el('countrysum').textContent = readFailed(countriesRes) ? failedRead(countriesRes)
: seen.length
? seen.length + ' ' + plural(seen.length, 'country') + ', '
+ totalSources + ' ' + plural(totalSources, 'source') + ', '
+ totalRefusals + ' ' + plural(totalRefusals, 'refusal') + ' total'
: 'no country-resolved sources yet';
// The alerting pillar is the only one whose whole point is a human reading
// it, so a table nobody renders is a pillar with no top. The two kinds mean
// different things and the page says which: a server error is never a reason
// to ban, and a candidate ban is a rule that has not been allowed to act.
el('alerts').tBodies[0].innerHTML = (alerts || []).map((a) => row([
{ h: a.kind === 'server_error_streak'
? '<span class="warn">' + esc(a.kind) + '</span>' : esc(a.kind) },
{ h: srcBtn(a.sourceKey) },
{ v: a.count, n: true },
{ v: (a.lastStatusCode || '') + ' ' + (a.lastPath || ''), n: true },
{ v: (a.createdAt || '').replace('T', ' ').slice(0, 19) }
])).join('') || row([{ v: readFailed(alertsRes)
? 'NOT READ \u2014 the edge could not answer this call'
: 'nothing — no server-error streaks and no dry-run candidates' }]);
el('alertnote').textContent = readFailed(alertsRes) ? failedRead(alertsRes)
: (alerts || []).length
? 'server_error_streak = your upstream is failing, and the edge will not ban the visitor who saw it; candidate_ban = the rule would have banned, mode is Observe. '
+ (alertsRes.truncated ? 'Newest ' + alerts.length + ' of ' + alertsRes.total + ' alerts.' : 'All ' + alertsRes.total + ' alerts are listed.')
: 'no alerts. server_error_streak means the upstream is failing; candidate_ban means a dry run would have banned.';
if (!readFailed(alertsRes) && state.banRetentionDays != null)
el('alertnote').textContent += ' · alerts are pruned after ' + state.banRetentionDays + 'd';
// Whether a raised alert reaches anything on its own. A row is read by
// whoever opens this page; a push is what fires at 03:00. The host and not
// the URL: a webhook URL carries its secret in the path, and this page is
// rendered from a response an operator's browser fetches.
el('alertnote').textContent += state.alertWebhookConfigured
? ' · pushed to ' + state.alertWebhookHost
+ (state.alertWebhookDelivered > 0 ? ', ' + state.alertWebhookDelivered + ' delivered' : '')
+ (state.alertWebhookFailures > 0 ? ', ' + state.alertWebhookFailures + ' push failures' : '')
+ (state.alertWebhookLost > 0 ? ', ' + state.alertWebhookLost + ' dropped for a full queue' : '')
: ' · not pushed anywhere: each row waits for someone to open this page';
el('countries').tBodies[0].innerHTML = seen.map((c) => row([
{ v: c.code }, { v: c.sources, n: true }, { v: c.refusals, n: true },
{ h: '<span class="sharebar" style="width:'
+ (busiest > 0 ? Math.max(2, Math.round((c.refusals || 0) / busiest * 100)) : 0) + '%"></span>' },
{ v: allowed.has(c.code) ? (allowed.get(c.code) ? 'allowed' : 'denied') : '—' },
{ h: '<button data-act="country" data-k="' + esc(c.code) + '" data-allowed="'
+ (allowed.has(c.code) && allowed.get(c.code) ? 'false' : 'true') + '">'
+ (allowed.has(c.code) && allowed.get(c.code) ? 'deny' : 'allow') + '</button>'
// Flipping a rule to "allowed" leaves the row behind; removing it is the
// only way the table stops claiming a country has a rule at all.
+ (allowed.has(c.code)
? ' <button data-act="countrydel" data-k="' + esc(c.code) + '">remove rule</button>'
: '') }
])).join('') || row([{ v: 'none' }]);
// A refresh that worked must not erase the reason the click before it did
// not: load() runs after every row action, and its green "refreshed" used to
// replace the error line within a second, which is roughly how long an
// operator takes to read it.
// A refresh that worked must not erase the reason the click before it did
// not: every row action ends with load(), and its green "refreshed" used to
// replace the error line inside a second — about how long the line takes to
// read. Only the refresh that follows the failed action holds the note; the
// next one says "refreshed" again, so the page does not stay red forever.
if (holdNote) holdNote = false;
else note('refreshed ' + new Date().toLocaleTimeString(), false);
} catch (e) { /* note() already said why */ }
}
el('save').onclick = () => {
token = el('token').value.trim();
sessionStorage.setItem('openwaf.token', token);
load();
};
// The two writes an operator reaches for during an incident: put a specific
// address behind a block with a reason, and pull a customer range out from
// under it. Both are one call to an endpoint that already exists; the page adds
// no validation beyond "say what the address is" and surfacing the API's own
// error instead of swallowing it.
async function postJson(path, body) {
const r = await apiRaw(path, { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body) });
return !failed(r);
}
el('addBlock').onclick = async () => {
const ip = el('blockIp').value.trim();
if (!ip) { note('an address first', true); return; }
// The same shape as the exemption's minutes field, for the same reason: an
// operator blocking a source during an incident wants it gone by itself
// afterwards, and a block that can only be removed by hand is a block that
// is still there in the morning. Empty stays "until I take it off".
const rawTtl = el('blockTtl').value.trim();
let ttl = null;
if (rawTtl !== '') {
const parsed = Number(rawTtl);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 5256000) {
note('a duration in minutes (1..5256000), or leave it empty for never', true);
return;
}
ttl = parsed;
}
if (await postJson('/admin-api/blocks', { ip,
reason: el('blockReason').value.trim() || 'blocked from the console',
expiresInMinutes: ttl })) {
el('blockIp').value = ''; el('blockReason').value = ''; el('blockTtl').value = '';
done('blocked ' + ip + (ttl ? ' for ' + ttl + ' min' : ''));
load();
}
};
el('addAllow').onclick = async () => {
const match = el('allowMatch').value.trim();
if (!match) { note('an address or CIDR first', true); return; }
// A TTL of 0 used to fall through to null, and null is how this API says
// "never expires" — the one exemption that outranks every ban, arriving from a
// field left at zero. The API refuses that now; the page says so before the
// round trip. Empty is still the way to ask for never, on purpose.
const rawTtl = el('allowTtl').value.trim();
let ttl = null;
if (rawTtl !== '') {
const parsed = Number(rawTtl);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 5256000) {
note('a TTL in minutes (1..5256000), or leave it empty for never', true);
return;
}
ttl = parsed;
}
if (await postJson('/admin-api/allow', { match,
note: el('allowNote').value.trim() || 'allowlisted from the console',
expiresInMinutes: ttl })) {
el('allowMatch').value = ''; el('allowNote').value = ''; el('allowTtl').value = '';
done('allowlisted ' + match);
load();
}
};
el('addRule').onclick = async () => {
const pattern = el('rulePattern').value.trim();
if (!pattern) { note('a path pattern first, e.g. /.env*', true); return; }
// The same TTL field as the other two, with the same rule: empty means
// "never", and a 0 is refused rather than read as never. A path rule is the
// entry most likely to be right during a scan and wrong six weeks later, so
// the page nudges towards a number.
const rawTtl = el('ruleTtl').value.trim();
let ttl = null;
if (rawTtl !== '') {
const parsed = Number(rawTtl);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 5256000) {
note('a TTL in minutes (1..5256000), or leave it empty for never', true);
return;
}
ttl = parsed;
}
if (await postJson('/admin-api/rules', { pattern, action: el('ruleAction').value,
note: el('ruleNote').value.trim() || 'written from the console', expiresInMinutes: ttl })) {
el('rulePattern').value = ''; el('ruleNote').value = ''; el('ruleTtl').value = '';
done(el('ruleAction').value + ' rule added for ' + pattern);
load();
}
};
el('addRateRule').onclick = async () => {
const pattern = el('rateRulePattern').value.trim();
if (!pattern) { note('a path pattern first, e.g. /login*', true); return; }
// Both numbers are optional here and mean "this build's default" when left
// out — unlike the edge-wide budget above, where an empty field means "keep
// what is set", because this is a POST of a new row and not a PUT of one.
const rawLimit = el('rateRuleLimit').value.trim();
const rawWindow = el('rateRuleWindow').value.trim();
if (rawLimit && !/^\d+$/.test(rawLimit)) { note('the budget must be a whole number of requests', true); return; }
if (rawWindow && !/^\d+$/.test(rawWindow)) { note('the window must be a whole number of seconds', true); return; }
const rawTtl = el('rateRuleTtl').value.trim();
let ttl = null;
if (rawTtl !== '') {
const parsed = Number(rawTtl);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 5256000) {
note('a TTL in minutes (1..5256000), or leave it empty for never', true);
return;
}
ttl = parsed;
}
const body = { pattern, note: el('rateRuleNote').value.trim() || 'written from the console', expiresInMinutes: ttl };
if (rawLimit) body.limitPerWindow = parseInt(rawLimit, 10);
if (rawWindow) body.windowSeconds = parseInt(rawWindow, 10);
if (await postJson('/admin-api/rate-rules', body)) {
el('rateRulePattern').value = ''; el('rateRuleLimit').value = ''; el('rateRuleWindow').value = '';
el('rateRuleNote').value = ''; el('rateRuleTtl').value = '';
done('path budget added for ' + pattern);
load();
}
};
el('askDecide').onclick = async () => {
// The dry run asked from the page. It is a read: the edge says so in the body,
// and the volume half of the answer (OPEN-69) is read off the counters without
// spending them — which is the whole reason this button is safe to press while
// the site is live.
const ip = el('askIp').value.trim();
const path = el('askPath').value.trim() || '/';
if (!ip) { note('an address first — a verdict is a claim about a source', true); return; }
const r = await apiRaw('/admin-api/decide?ip=' + encodeURIComponent(ip) + '&path=' + encodeURIComponent(path));
if (failed(r)) return;
const d = r.body;
const v = d.volume || {};
const lines = [];
lines.push('would answer: ' + (d.verdict || '?') + (d.blocked ? ' (' + d.status + ')' : '')
+ (d.reason ? ' — ' + d.reason : ''));
const rule = d.rule;
if (rule) lines.push('path rule ' + rule.id + ' ' + rule.pattern + ' (' + rule.action + ')');
const edge = v.edgeBudget;
lines.push('volume: ' + (v.mode || '?') + ' · ' + (v.verdict || '?') + ' · ' + (v.scope || '?')
+ (edge ? ' · edge budget ' + edge.count + ' of ' + edge.limitPerWindow
+ ' per ' + edge.windowSeconds + ' s, ' + edge.secondsLeft + ' s left'
+ (edge.overBudget ? ' — OVER' : '') : ' · edge budget: no running window'));
const budgets = v.pathBudgets || [];
if (budgets.length) {
lines.push('path budgets for this path: ' + budgets.map((b) => b.pattern + ' '
+ (b.counted ? b.count + ' of ' + b.limitPerWindow + ' per ' + b.windowSeconds + ' s'
: 'in force, nothing counted for this source yet')
+ (b.overBudget ? ' — OVER (pauses this path only, not a ban)' : '')).join(' · '));
} else {
lines.push('path budgets for this path: none — the edge-wide budget is the only one');
}
lines.push(v.note || '');
// textContent, not innerHTML: the address and the path came from the operator's
// keyboard, and an answer page that renders them as markup is an XSS in the one
// place the operator goes to look at an attack.
const box = el('askanswer');
box.textContent = '';
for (const line of lines) {
const div = document.createElement('div');
div.textContent = line;
box.appendChild(div);
}
};
async function showBudgetSources(id) {
// Who a path budget is pausing (OPEN-71). The table has always said "3 over
// budget"; this names them, and puts the one lever an operator actually wants
// beside each — drop this source's window, not the budget for everyone.
const r = await apiRaw('/admin-api/rate-rules/' + encodeURIComponent(id) + '/sources');
const box = el('budgetsources');
box.textContent = '';
if (failed(r)) return;
const d = r.body || {};
const head = document.createElement('div');
head.textContent = 'budget ' + (d.id || id) + ' ' + (d.pattern || '') + ' — ' + (d.limitPerWindow || '?')
+ ' per ' + (d.windowSeconds || '?') + ' s · ' + (d.total || 0) + ' source(s) inside a window · '
+ (d.scope || '?') + (d.live === false ? ' · THIS BUDGET IS EXPIRED, it enforces nothing' : '');
box.appendChild(head);
const note = document.createElement('div');
note.textContent = d.howToRead || '';
box.appendChild(note);
for (const src of (d.sources || [])) {
const line = document.createElement('div');
line.textContent = src.sourceKey + ' — ' + src.count + ' of ' + (d.limitPerWindow || '?')
+ (src.overBudget
? ' OVER: answered 429 on this path for ' + src.secondsLeft + ' more s'
: ', ' + src.secondsLeft + ' s left in its window') + ' ';
const btn = document.createElement('button');
btn.dataset.act = 'letout';
btn.dataset.k = String(d.id || id);
btn.dataset.s = src.sourceKey;
btn.textContent = 'let out';
line.appendChild(btn);
box.appendChild(line);
}
}
el('askSource').onclick = async () => {
// The dossier (OPEN-70). One address in, everything this edge knows about it
// out: the exemption that covers it, the operator's block on it or on a network
// containing it, the engine's own ban, the streak standing in this process, the
// budgets already counting it, its alerts, and the netblocks offered that would
// cover it. A read, like the dry run above it: nothing is written and no
// counter moves, so it is safe to press while the site is live.
const ip = el('dossierIp').value.trim();
if (!ip) { note('an address first - the dossier is a claim about a source', true); return; }
const r = await apiRaw('/admin-api/source?ip=' + encodeURIComponent(ip));
if (failed(r)) return;
const d = r.body || {};
const lines = [];
lines.push('key: ' + (d.sourceKey || '?') + ' - ' + (d.verdict || '?') + ' - ' + (d.answer || ''));
const g = d.geo || {};
lines.push('geo: ' + (g.country || 'unknown') + ' (' + (g.source || '?') + ')'
+ (g.rule ? ' - the country rule says ' + (g.rule.allowed ? 'allowed' : 'denied') : '')
+ (g.wouldDeny ? ' - the geo pillar refuses it' : ''));
const a = d.allow;
lines.push('allow: ' + (a ? a.match + (a.live ? '' : ' (EXPIRED)') + (a.note ? ' - ' + a.note : '')
: 'nothing covers this address'));
const b = d.operatorBlock;
lines.push('operator block: ' + (b
? (b.cameFromRange ? 'from the range ' + b.match : 'written on this key')
+ (b.live ? '' : ' (EXPIRED)') + (b.reason ? ' - ' + b.reason : '')
: 'none'));
const e = d.engineBan;
lines.push('engine ban: ' + (e
? (e.sourceKey || '?') + (e.live ? '' : ' (EXPIRED)')
+ (e.applies ? '' : ' - enforcing nothing in ' + (e.enforcementMode || '?') + ' mode')
+ (e.reason ? ' - ' + e.reason : '')
: 'none'));
const st = d.streak;
lines.push('streak: ' + (st
? st.consecutiveRefusals + ' of ' + st.threshold + ' (' + (st.scope || '?') + ')'
+ (st.maxConsecutiveEver === null || st.maxConsecutiveEver === undefined
? '' : ', worst ever ' + st.maxConsecutiveEver)
: 'nothing standing'));
const v = d.volume || {};
const eb = v.edgeBudget;
lines.push('volume: ' + (v.mode || '?') + ' - '
+ (eb ? 'edge budget ' + eb.count + ' of ' + eb.limitPerWindow + ' per ' + eb.windowSeconds
+ ' s, ' + eb.secondsLeft + ' s left' + (eb.overBudget ? ' - OVER' : '')
: 'no running edge window'));
const pb = v.pathBudgets || [];
lines.push('path budgets counting it: ' + (pb.length
? pb.map((x) => x.pattern + ' ' + x.count + ' of ' + x.limitPerWindow
+ ' per ' + x.windowSeconds + ' s' + (x.overBudget ? ' - OVER (this path only)' : '')).join(' | ')
: 'none'));
const al = d.alerts || [];
lines.push('alerts: ' + (al.length
? al.length + ' recent, newest ' + (al[0].kind || '?') + ' x' + (al[0].count || '?')
: 'none'));
const nb = (d.netblockOffers || []);
if (nb.length) {
lines.push('netblocks offered that cover it: ' + nb.map((c) => c.match + ' (' + c.bans
+ ' bans inside' + (c.alreadyBanned ? ', already banned' : '') + ')').join(' | '));
}
const box = el('dossieranswer');
box.textContent = '';
for (const line of lines) {
const div = document.createElement('div');
div.textContent = line;
box.appendChild(div);
}
};
el('askHistory').onclick = async () => {
// One source through time (OPEN-73). The dossier above answers now and the
// horizon answers soon; this answers what already happened, in the order it
// happened. The six stores that can name a source are joined by the edge, not
// by whoever last opened a listing, and the rows come oldest-first because the
// order is the answer: "the exemption, then the ban" and "the ban, then the
// exemption" are different incidents.
const ip = el('historyIp').value.trim();
if (!ip) { note('an address first - the story is about one source', true); return; }
// Emptied first, and the first line names the address that was asked for: a
// wait for "an answer is in the box" must never be satisfied by the previous
// answer, which is how the dossier scene once read the wrong address.
el('historyanswer').textContent = '';
const r = await apiRaw('/admin-api/history?ip=' + encodeURIComponent(ip));
if (failed(r)) return;
const d = r.body || {};
const searched = d.searched || {};
const lines = [];
lines.push('asked: ' + (d.ip || ip) + ' filed as ' + (d.sourceKey || '?')
+ ' - ' + (d.count === undefined ? '?' : d.count) + ' events'
+ (d.truncated ? ' (showing ' + d.shown + ')' : '')
+ ' - searched: block ' + (searched.block ?? '?') + ', range ' + (searched.range ?? '?')
+ ', allow ' + (searched.allow ?? '?') + ', alert ' + (searched.alert ?? '?')
+ ', change ' + (searched.change ?? '?') + ', seen ' + (searched.observation ?? '?'));
const w = d.window || {};
if (w.since) lines.push('window: ' + w.since + ' \u2192 ' + w.until);
for (const ev of (d.events || [])) {
const when = (ev.at || '').replace('T', ' ').slice(0, 19);
let line = when + ' \u00b7 ' + (ev.kind || '?') + ' \u00b7 ' + (ev.what || '');
if (ev.inForce === true) line += ' \u00b7 in force';
else if (ev.inForce === false) line += ' \u00b7 EXPIRED ' + ((ev.expiresAt || '').replace('T', ' ').slice(0, 19));
if (ev.detail) line += ' \u00b7 ' + ev.detail;
lines.push(line);
}
if (d.note) lines.push(d.note);
const box = el('historyanswer');
for (const line of lines) {
const div = document.createElement('div');
div.textContent = line;
box.appendChild(div);
}
};
el('askFind').onclick = async () => {
// Where does this appear? (OPEN-74). The phrase an operator remembers is not a
// field any listing filters on: it sits in a block's reason, an exemption's
// note, a path rule's note and the change log's detail. One box asks all eight
// stores at once. An address is worth more than a substring here - the row that
// answers for it is often a range that never names it - so the endpoint returns
// those too and says that is why they are in the answer.
const q = el('findq').value.trim();
if (!q) { note('some text first - this searches what an operator wrote', true); return; }
if (q.length < 2) { note('two characters at least - one is a dump, not a search', true); return; }
// Emptied before the call, and the first line names the query that was asked
// for: a scene waiting for an answer must never read the previous one.
el('findanswer').textContent = '';
const r = await apiRaw('/admin-api/find?q=' + encodeURIComponent(q));
if (failed(r)) return;
const d = r.body || {};
const c = d.counts || {};
const lines = [];
lines.push('asked: "' + (d.query || q) + '" - ' + (d.matched === undefined ? '?' : d.matched)
+ ' rows' + (d.truncated ? ' (showing ' + d.shown + ' of them)' : '')
+ ' - block ' + (c.block ?? '?') + ', range ' + (c.range ?? '?')
+ ', allow ' + (c.allow ?? '?') + ', path rule ' + (c.pathRule ?? '?')
+ ', path budget ' + (c.pathBudget ?? '?') + ', alert ' + (c.alert ?? '?')
+ ', change ' + (c.change ?? '?') + ', country ' + (c.countryRule ?? '?'));
const a = d.asAddress;
if (a) lines.push('as an address: filed as ' + (a.sourceKey || '?')
+ ' - rows that cover it are in the answer too, and say so');
for (const row of (d.results || [])) {
const when = (row.at || '').replace('T', ' ').slice(0, 19);
const what = row.match || row.pattern || '?';
let line = row.store + ' \u00b7 ' + what + ' \u00b7 ' + when;
if (row.live === true) line += ' \u00b7 in force';
else if (row.live === false) line += ' \u00b7 EXPIRED ' + ((row.expiresAt || '').replace('T', ' ').slice(0, 19));
if (row.text) line += ' \u00b7 ' + row.text;
line += ' \u00b7 ' + (row.why || '');
lines.push(line);
}
if (d.note) lines.push(d.note);
const box = el('findanswer');
for (const line of lines) {
const div = document.createElement('div');
div.textContent = line;
box.appendChild(div);
}
};
el('askImpact').onclick = async () => {
// What would this ban touch? (OPEN-75). The dry run above answers one named
// request and the horizon answers what stops soon; this answers the question
// asked before the write, over the sources this edge is actually watching
// inside the match. The engine that answers is the one on the wire, with the
// proposed entry added to its snapshot and nothing written, so the split
// between newly refused, already refused and still passing is the wire's split.
const match = el('impactMatch').value.trim();
if (!match) { note('an address or a CIDR first - that is the row being asked about', true); return; }
const path = el('impactPath').value.trim();
// Emptied before the call, and the first line names the match that was asked
// for: a scene waiting for an answer cannot read the previous one.
el('impactanswer').textContent = '';
const r = await apiRaw('/admin-api/impact?match=' + encodeURIComponent(match)
+ (path ? '&path=' + encodeURIComponent(path) : ''));
if (failed(r)) return;
const d = r.body || {};
const c = d.counts || {};
const lines = [];
lines.push('asked: ' + (d.match || match) + ' at ' + (d.path || '/') + ' - '
+ (d.probed === undefined ? '?' : d.probed) + ' sources probed'
+ (d.truncated ? ' (more inside, not shown)' : '')
+ ' - newly refused ' + (c.newlyRefused === undefined ? '?' : c.newlyRefused)
+ ', already refused ' + (c.alreadyRefused === undefined ? '?' : c.alreadyRefused)
+ ', still passing ' + (c.stillPassing === undefined ? '?' : c.stillPassing));
if (d.filedUnder && d.filedUnder !== d.match) lines.push('the write would file it under ' + d.filedUnder);
if (d.alreadyCoveredBy) {
lines.push('already covered at its own address: ' + d.alreadyCoveredBy.verdict
+ ' by ' + (d.alreadyCoveredBy.by || '?') + ' - this write would change nothing there');
}
for (const a of (d.outrankedBy || [])) {
lines.push('an exemption outranks this ban at the match\u0027s own address: ' + a.match
+ (a.note ? ' \u00b7 ' + a.note : '') + (a.expiresAt ? ' \u00b7 until ' + a.expiresAt : ''));
}
for (const a of (d.exemptionsInside || [])) {
lines.push('inside the match, and the ban will not reach it: ' + a.match
+ (a.note ? ' \u00b7 ' + a.note : ''));
}
for (const row of (d.sources || [])) {
let line = row.source + ' \u00b7 ' + row.kind + ' \u00b7 ' + row.before + ' \u2192 ' + row.after
+ ' \u00b7 ' + row.change;
if (row.afterBy) line += ' \u00b7 by ' + row.afterBy;
if (row.refusals) line += ' \u00b7 ' + row.refusals + ' refusals counted';
lines.push(line);
}
if (d.note) lines.push(d.note);
const box = el('impactanswer');
for (const line of lines) {
const div = document.createElement('div');
div.textContent = line;
box.appendChild(div);
}
};
el('askHorizon').onclick = async () => {
// The horizon (OPEN-72). Not "what expires" - a list of dates tells an operator
// nothing about what the site will be doing tomorrow. Each row carries the real
// decision the engine would take for that source with only this entry removed,
// so the answer is "this /28 ages out at 06:00 and the source falls back to the
// engine ban underneath it" rather than a timestamp to interpret by hand.
const raw = el('horizonWithin').value.trim();
let minutes = 30;
if (raw) {
minutes = Number(raw);
if (!Number.isInteger(minutes) || minutes < 1 || minutes > 1440) {
note('the horizon is a whole number of minutes from 1 to 1440', true);
return;
}
}
// The box is emptied before the call, and the first line names the window that
// was asked for: a scene waiting for an answer cannot read the previous one.
el('horizonanswer').textContent = '';
const r = await apiRaw('/admin-api/expiring?within=' + minutes);
if (failed(r)) return;
const d = r.body || {};
const ae = d.alreadyExpired || {};
const lines = [];
lines.push('asked: within ' + (d.withinMinutes === undefined ? minutes : d.withinMinutes)
+ ' minutes of ' + (d.asOf || '?'));
lines.push('expiring: ' + (d.count === undefined ? '?' : d.count)
+ ' - already past: block ' + (ae.block === undefined ? '?' : ae.block)
+ ', range ' + (ae.range === undefined ? '?' : ae.range)
+ ', engine ban ' + (ae.engineBan === undefined ? '?' : ae.engineBan)
+ ', allow ' + (ae.allow === undefined ? '?' : ae.allow)
+ ', path rule ' + (ae.pathRule === undefined ? '?' : ae.pathRule)
+ ', path budget ' + (ae.pathBudget === undefined ? '?' : ae.pathBudget));
for (const row of (d.expiring || [])) {
const what = row.match || row.pattern || '?';
let line = row.kind + ' ' + what + ' - '
+ (row.minutesLeft === undefined ? '?' : row.minutesLeft) + ' min left'
+ (row.note ? ' - ' + row.note : '');
if (row.thenAnswers) {
line += ' - then: ' + row.thenAnswers.verdict + ' by ' + row.thenAnswers.by;
} else if (row.whyNoAnswer) {
line += ' - ' + row.whyNoAnswer;
}
lines.push(line);
}
const box = el('horizonanswer');
for (const line of lines) {
const div = document.createElement('div');
div.textContent = line;
box.appendChild(div);
}
};
// One delegated handler for every row button, so no key or country code is ever
// spliced into an inline onclick string. The values live in data attributes,
// which went through esc() on the way in.
document.addEventListener('click', async (e) => {
const b = e.target.closest('button[data-act]');
if (!b) return;
b.disabled = true;
// A new action owns the status line from now on.
holdNote = false;
try {
if (b.dataset.act === 'delblock') {
const r = await apiRaw('/admin-api/blocks?key=' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
if (!failed(r)) done('deleted ' + (r.body && r.body.deleted !== undefined ? r.body.deleted : '?') + ' block(s)');
} else if (b.dataset.act === 'banrange') {
// The same POST the block form sends. The console does not get a second,
// softer way to write a range, because then it would have a second set of
// rules about what a range means.
// postJson, not a bare POST: the edge refuses a body it cannot name a
// content type for, and the console gate caught this on the first run —
// the button wrote nothing and the page looked idle rather than wrong.
if (await postJson('/admin-api/blocks', {
ip: b.dataset.k, reason: 'netblock the edge noticed: ' + (b.dataset.n || 'several') + ' live engine bans inside it' }))
done('banned the range ' + b.dataset.k);
} else if (b.dataset.act === 'delallow') {
const r = await apiRaw('/admin-api/allow/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
if (!failed(r)) done('allow entry removed');
} else if (b.dataset.act === 'delrule') {
const r = await apiRaw('/admin-api/rules/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
if (!failed(r)) done('path rule removed');
} else if (b.dataset.act === 'delraterule') {
const r = await apiRaw('/admin-api/rate-rules/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
if (!failed(r)) { done('path budget removed'); el('budgetsources').textContent = ''; }
} else if (b.dataset.act === 'whobudget') {
await showBudgetSources(b.dataset.k);
} else if (b.dataset.act === 'letout') {
// One source out of one budget. The answer says what it is: the counter
// restarts at zero, the budget still applies, and the other sources stay
// where they were.
const r = await apiRaw('/admin-api/rate-rules/' + encodeURIComponent(b.dataset.k)
+ '/sources?source=' + encodeURIComponent(b.dataset.s), { method: 'DELETE' });
if (!failed(r)) {
const d = r.body || {};
done(d.cleared
? 'window dropped for ' + d.sourceKey + ' — it counts from zero again, this is not an exemption'
: 'nothing was dropped: ' + (d.note || 'this source has no running window on this budget'));
await showBudgetSources(b.dataset.k);
}
} else if (b.dataset.act === 'country') {
const r = await apiRaw('/admin-api/countries/' + encodeURIComponent(b.dataset.k) + '?allowed=' + b.dataset.allowed, { method: 'PUT' });
if (!failed(r)) done('country ' + b.dataset.k + ' → ' + (b.dataset.allowed === 'true' ? 'allowed' : 'denied'));
} else if (b.dataset.act === 'countrydel') {
const r = await apiRaw('/admin-api/countries/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
if (!failed(r)) done('country rule ' + b.dataset.k + ' removed');
} else if (b.dataset.act === 'srcfilter') {
// A row button carries the key it was drawn from; the filter bar's button
// reads what the operator typed. Either way the box and the filter end up
// saying the same thing, so the page never narrows to a key it is not
// showing. An empty box is "everything", not an empty parameter.
obsSource = b.dataset.k !== undefined ? b.dataset.k : el('srcfilter').value.trim();
el('srcfilter').value = obsSource;
done(obsSource ? 'filtered to ' + obsSource : 'showing every source');
} else if (b.dataset.act === 'srcclear') {
obsSource = '';
el('srcfilter').value = '';
done('showing every source');
}
load();
} catch (err) { /* note() already said why */ }
b.disabled = false;
});
el('refresh').onclick = () => { holdNote = false; load(); };
el('srcfilter').onkeydown = (e) => {
if (e.key !== 'Enter') return;
obsSource = el('srcfilter').value.trim();
el('srcfilter').value = obsSource;
holdNote = false;
load();
};
el('setMode').onclick = async () => {
// The mode select is the one control that decides whether this edge bans
// anyone at all. It used to fire the PUT, ignore the answer and reload: a
// change the storage refused reloaded to the old mode with no explanation.
const wanted = el('mode').value;
const r = await apiRaw('/admin-api/policy', { method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode: wanted }) });
if (!failed(r)) done('mode → ' + wanted);
load();
};
el('setRate').onclick = async () => {
// The budget is a policy write, not a data write, and the two number fields
// are optional: leaving them empty means "keep what is set", because a PUT
// that sends 0 would be refused and an operator who only wants to switch the
// mode on should not have to retype both numbers.
const body = { rateMode: el('rateMode').value };
const limit = el('rateLimit').value.trim();
const window = el('rateWindow').value.trim();
if (limit && !/^\d+$/.test(limit)) { note('the budget must be a whole number of requests'); return; }
if (window && !/^\d+$/.test(window)) { note('the window must be a whole number of seconds'); return; }
if (limit) body.rateLimitPerWindow = parseInt(limit, 10);
if (window) body.rateWindowSeconds = parseInt(window, 10);
rateHold = true;
const r = await apiRaw('/admin-api/policy', { method: 'PUT',
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
if (!failed(r)) done('budget → ' + body.rateMode
+ (limit ? ', ' + limit + ' requests' : '') + (window ? ' per ' + window + ' s' : ''));
load();
};
el('clearEngine').onclick = async () => {
// The most destructive button on the page, and it used to fire the DELETE and
// read nothing back: whatever the edge answered — cleared 7, cleared 0, or
// "the block list could not be written" — the page reloaded and looked the
// same. The count is the only part of this the operator can act on.
const r = await apiRaw('/admin-api/blocks?source=engine', { method: 'DELETE' });
if (!failed(r)) done('engine bans cleared: ' + (r.body && r.body.deleted !== undefined ? r.body.deleted : '?'));
load();
};
setInterval(load, 5000);
load();
</script>
</body>
</html>
""";
}