Files
openwaf/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs
T
Pavlo Ratushnyi 39d08eca51 A pillar that stopped reading its table kept answering, and nothing on the surface said so
Measured on the shipped image (openwaf:ci, the head tree), one stand with a real
upstream:

  PUT /admin-api/policy {"streakThreshold":2,"trustProxyHeaders":true} -> 200
  404 404 from 203.0.113.79, third request -> 403   (the threshold is in force)
  04:44:43  DROP TABLE policy_settings, from outside the process
  04:45:2x  GET /admin-api/policy -> still "streakThreshold": 2, answered plainly
            GET /admin-api/state  -> "snapshotAgeSeconds":0 — the refresh "succeeded",
                                     because the tables it also reads were still there
            /healthz 200, /readyz 200, and exactly 1 line in the log
  docker restart -> GET /admin-api/policy -> "streakThreshold": 10,
                                          "trustProxyHeaders": false
  four 404s from 203.0.113.81, fifth -> 404: nothing banned

Both pillars — the policy provider and the guard's snapshot store — catch
everything their read throws, keep the last value they had, and log one line.
Keeping the last good value is the right failure posture: a database restart must
not open the gate. Keeping it unmentioned is not: for a minute the operator's page
showed a threshold that no longer existed anywhere in storage, readiness said
ready, and after a restart the defence silently came back at the default N=10.

Now: EdgePolicyProvider and EdgeStateStore count consecutive failed reads and keep
the last error; /admin-api/state answers snapshotStale (age against the TTL the
process refuses to start without), snapshotRefreshFailures,
snapshotLastRefreshError, policyReloadFailures and policyLastReadAt;
/admin-api/policy carries X-Policy-Reload-Failures and X-Policy-Last-Read
alongside the policy it is enforcing, the same way a capped listing carries its
completeness in headers; /readyz answers 503 while either counter is non-zero,
naming the pillar and the age of the snapshot it is running on; and the console's
summary line goes warn and says "older than the ttl", "snapshot refresh failing
xN", "policy not re-read from storage xN".

Teeth first: PillarFailureVisibilityTests (4) run against the unfixed tree — 4
failed, 0 passed, all four on a missing field (KeyNotFoundException), which is the
point: the numbers did not exist. The refresh test drops country_rules rather than
block_entries on purpose — only one of them is what /readyz probes, so before the
fix that test saw the refresh failing and readiness still answering 200.

Gates: compose-smoke now drops policy_settings from the running stand through a
--volumes-from sidecar, waits for the failure to be counted, asserts the counters,
the 503 and the header, puts the table back and asserts the recovery (+6
assertions; the counters are consecutive, not cumulative, so recovery is part of
the claim). smoke.sh asserts the healthy case with numbers rather than silence
(+3). console-check drives the page against that state answer and requires the
summary line to be marked and to name both pillars (+3); the state body is served
through a route because the guard refreshes the snapshot on every request — a live
stand cannot be left to age — while the contract being rendered is the one
compose-smoke measures end to end against the shipped image.

Numbers on this tree. Host: build 0 warnings, unit 128/128, integration 117/117,
smoke 25 passed / 0 failed, compose 53 passed / 0 failed, console 53 assertions /
0 failed, image 261 MB. Linux rehearsal, each stage on its own — source in
mcr.microsoft.com/dotnet/sdk:10.0 (Ubuntu 24.04.5, SDK 10.0.401): 128/128,
117/117, 25/0; compose in docker:cli: 53/0, enforcement lag 12 ms; console in
mcr.microsoft.com/playwright:v1.63.0-noble: 53/0.
2026-10-02 07:07:25 +02:00

486 lines
27 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 this address" autocomplete="off" size="18">
<input id="blockReason" placeholder="reason" autocomplete="off" size="20">
<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>
</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>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>Sources the edge is watching</h2>
<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>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;
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');
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, alertsRes, geoRes] = await Promise.all([
apiRaw('/admin-api/state'), apiRaw('/admin-api/blocks?live=false'),
apiRaw('/admin-api/observations?limit=25'), apiRaw('/admin-api/streaks'),
apiRaw('/admin-api/countries/summary'), apiRaw('/admin-api/countries'),
apiRaw('/admin-api/allow?live=false&limit=500'), apiRaw('/admin-api/alerts?limit=25'),
apiRaw('/admin-api/geo')
]);
// 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;
const blocks = blocksRes.body;
const obs = obsRes.body;
const alerts = alertsRes.body;
const streaks = streaksRes.body, countries = countriesRes.body, rules = rulesRes.body,
allow = allowRes.body, geo = geoRes.body;
// 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 = 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');
// 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.
el('obsnote').textContent = 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';
const allowed = new Map((rules || []).map((r) => [r.code, r.isAllowed]));
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">tracked ' + esc(state.trackedSources) + '</span> ' +
'<span class="pill">engine bans ' + esc(state.engineBans) + '</span> ' +
'<span class="pill">operator blocks ' + esc(state.operatorBlocks) + '</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.
' ' + (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([
{ v: 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 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: 'none — everything not blocked is allowed' }]);
el('allownote').textContent = (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';
el('obs').tBodies[0].innerHTML = (obs || []).map((o) => row([
{ v: 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: 'none' }]);
el('streaks').tBodies[0].innerHTML = (streaks.streaks || []).map((st) => row([
{ v: 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: 'nothing standing — every tracked source last saw a clean answer' }]);
el('streaknote').textContent =
streaks.scope === 'this-process'
? 'this edge process only — ' + (streaks.streaks || []).length + ' of ' + streaks.standingStreaks
+ ' standing streaks listed; threshold ' + streaks.threshold
+ ' within ' + streaks.windowMinutes + ' min; ' + streaks.trackedSources
+ ' sources tracked, map capped at ' + streaks.maxTrackedSources
: 'unknown scope';
// 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);
el('countrysum').textContent = 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) },
{ v: 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: 'nothing — no server-error streaks and no dry-run candidates' }]);
el('alertnote').textContent = (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.';
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; }
if (await postJson('/admin-api/blocks', { ip, reason: el('blockReason').value.trim() || 'blocked from the console' })) {
el('blockIp').value = ''; el('blockReason').value = '';
done('blocked ' + ip);
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();
}
};
// 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 === '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 === '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');
}
load();
} catch (err) { /* note() already said why */ }
b.disabled = false;
});
el('refresh').onclick = () => { 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('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>
""";
}