fix(panel): stop shipping a fabricated router in the binary
mock.ts was a static import and the mock switch was read from the query string at runtime, so the bundle that ships inside the daemon carried a complete fictional router and a link ending in ?dev rendered it: protected, 119 of 122 nodes alive, without a single request to the daemon. The only tell was a line in the footer. That is worse than any wrong number — there is no data at all and nothing says so. It is out of the production bundle now, which is 21 kB smaller for it. Unknown state stopped reading as good news in two more places. The kill-switch tile treated an absent plane as armed, because the check was "not none" and undefined satisfies it — the contract in the API types says the opposite. And the apply page announced "daemon auto-rolled back" from its own timer, while the daemon, seeing the state generation move, disarms and says it is NOT rolling back in the log only. Alerts moved to Settings. They are about the kill switch, apply failures, new devices and subscription expiry, and they lived at the bottom of the DNS page, while Settings mentioned them in prose with nothing to click. Findings truncation is visible now: the notice that says how many were suppressed arrives as info, and the attention list keeps only critical and warning, so past fifty findings the operator saw forty-nine and no hint of the rest. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
4078334d85
commit
6476722372
19 files changed
+2121
-641
No files matched your search
@@ -262,6 +262,65 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- fixture band (dev builds only; see App.tsx MockBanner) ----
|
||||
Deliberately outside the crit/amber vocabulary: nothing is wrong with the
|
||||
router, there is no router. The hazard hatch is the service-sticker language a
|
||||
piece of network hardware already uses for "this unit is not in service". */
|
||||
.mock-band {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: calc(var(--u, 8px) * 1.5);
|
||||
margin-top: calc(var(--u, 8px) * 2);
|
||||
padding: 10px 14px;
|
||||
border: 1px dashed var(--faint);
|
||||
border-radius: 9px;
|
||||
background: repeating-linear-gradient(
|
||||
-45deg,
|
||||
var(--sink),
|
||||
var(--sink) 9px,
|
||||
var(--panel) 9px,
|
||||
var(--panel) 18px
|
||||
);
|
||||
}
|
||||
.mock-band-tag {
|
||||
flex-shrink: 0;
|
||||
align-self: flex-start;
|
||||
padding: 3px 7px;
|
||||
border: 1px solid var(--faint);
|
||||
border-radius: 4px;
|
||||
background: var(--raised);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.14em;
|
||||
color: var(--dim);
|
||||
}
|
||||
.mock-band-copy {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.mock-band-headline {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12.5px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--ink);
|
||||
}
|
||||
.mock-band-detail {
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
color: var(--dim);
|
||||
max-width: 76ch;
|
||||
}
|
||||
.mock-band-detail code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11.5px;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
/* ---- commit-confirm band (every page except Apply, which has the full panel) ----
|
||||
Same plate as the protection banner so the two read as one family; the seconds
|
||||
are the loud element because they are the only thing that is running out. */
|
||||
@@ -397,6 +456,13 @@
|
||||
.finding--warning {
|
||||
border-color: color-mix(in srgb, var(--amber) 40%, var(--groove));
|
||||
}
|
||||
/* The daemon's "the list is capped" disclosure. Dashed, because the row is about
|
||||
what ISN'T here — it must not read as one more finding to work through. */
|
||||
.finding--truncated {
|
||||
border-style: dashed;
|
||||
border-color: color-mix(in srgb, var(--amber) 40%, var(--groove));
|
||||
background: var(--panel);
|
||||
}
|
||||
.finding-copy {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
+31
-1
@@ -8,6 +8,7 @@ import { usePendingConfirm } from './pendingConfirm'
|
||||
import { bootstrapSession } from './session'
|
||||
import { ROUTES, navigate, useRoute } from './router'
|
||||
import { engineState, protectionState } from './planeState'
|
||||
import { truncationNote } from './findings'
|
||||
import type { Route } from './router'
|
||||
import { Overview, Placeholder, Nodes, Routing, Apply, DNS, Devices, Targets, Settings, Profiles, Insights, Networks } from './pages'
|
||||
|
||||
@@ -100,6 +101,7 @@ export function App() {
|
||||
footer={<StatusBar status={status} />}
|
||||
>
|
||||
<Nav route={route} />
|
||||
<MockBanner />
|
||||
<PlaneBanner status={status} route={route} />
|
||||
<ConfirmBand route={route} onChanged={() => void refreshStatus()} />
|
||||
<Page route={route} status={status} onStatusChange={() => void refreshStatus()} />
|
||||
@@ -170,6 +172,31 @@ function ConfirmBand({ route, onChanged }: { route: Route; onChanged: () => void
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Says, on every page, that nothing on screen came from a router.
|
||||
*
|
||||
* Only a DEV build can ever render this — the fixtures are not in a production
|
||||
* bundle (api.ts initMockBackend), so an operator cannot reach this state at all.
|
||||
* It is here for the person who CAN: a footer line reading "DEMO DATA" is easy to
|
||||
* work past for an afternoon and then screenshot into a bug report, and every
|
||||
* number above it is invented.
|
||||
*/
|
||||
function MockBanner() {
|
||||
if (!MOCK) return null
|
||||
return (
|
||||
<div className="mock-band" role="status">
|
||||
<span className="mock-band-tag">FIXTURES</span>
|
||||
<div className="mock-band-copy">
|
||||
<span className="mock-band-headline">No router is being read</span>
|
||||
<span className="mock-band-detail">
|
||||
Every reading on this page is invented by <code>src/mock.ts</code> for offline
|
||||
development. Drop <code>?mock</code> from the address to talk to a daemon.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The protection state, pinned under the nav on every page EXCEPT Overview
|
||||
* (which shows the same state as its own headline readout — see planeState.ts).
|
||||
@@ -195,12 +222,15 @@ function PlaneBanner({ status, route }: { status: Status | null; route: Route })
|
||||
|
||||
const criticals = (status.warnings ?? []).filter((w) => w.severity === 'critical').length
|
||||
const state = protectionState(status)
|
||||
// The published list is capped at 50, so with a note attached the count is a
|
||||
// floor. Say "at least" rather than quoting a total the daemon didn't send.
|
||||
const atLeast = truncationNote(status.warnings) ? 'At least ' : ''
|
||||
|
||||
// Wording comes from the shared source of truth so the banner and Overview can
|
||||
// never describe the same router differently.
|
||||
const headline = state.alarm
|
||||
? state.headline
|
||||
: `${criticals} protection ${criticals === 1 ? 'gap' : 'gaps'} from the last apply`
|
||||
: `${atLeast}${criticals} protection ${criticals === 1 ? 'gap' : 'gaps'} from the last apply`
|
||||
const detail = state.alarm
|
||||
? state.detail
|
||||
: 'Something you configured isn’t in effect. Review the findings before relying on it.'
|
||||
|
||||
+78
-27
@@ -13,8 +13,12 @@
|
||||
// serves in-memory fixtures instead of hitting the network, so `npm run dev`
|
||||
// and screenshot runs render without a live backend. A real backend in dev is
|
||||
// reachable instead via the Vite proxy in vite.config.ts (no flag ⇒ real fetch).
|
||||
//
|
||||
// THE FIXTURES ARE A DEV-BUILD-ONLY ARTEFACT — see initMockBackend below. They
|
||||
// used to be a plain static import, decided at RUNTIME off `location.search`, so
|
||||
// the invented router shipped inside the binary that goes on real hardware and a
|
||||
// link ending in `?dev` painted a healthy appliance without making one request.
|
||||
|
||||
import * as mock from './mock'
|
||||
import { armPendingConfirm, clearPendingConfirm, noteConfirmTimeout } from './pendingConfirm'
|
||||
|
||||
// --- error type -------------------------------------------------------------
|
||||
@@ -1120,12 +1124,59 @@ export interface Model {
|
||||
|
||||
// --- transport --------------------------------------------------------------
|
||||
|
||||
/** True when the URL asks for the offline fixture backend (?mock or ?dev). */
|
||||
export const MOCK: boolean = (() => {
|
||||
// --- the offline fixture backend (dev builds only) ---------------------------
|
||||
|
||||
/**
|
||||
* True when the in-memory fixtures are serving this session instead of the
|
||||
* daemon. ALWAYS false in a production build — see {@link initMockBackend}.
|
||||
*
|
||||
* A live binding, not a constant: it is decided once during boot, before the
|
||||
* first render, and every importer sees the same value for the whole session.
|
||||
*/
|
||||
export let MOCK = false
|
||||
|
||||
/** The loaded fixture module. `null` unless a dev build was asked for `?mock`. */
|
||||
let fixtures: typeof import('./mock') | null = null
|
||||
|
||||
/**
|
||||
* Load the fixture backend, if this build has one and the URL asks for it.
|
||||
* Call ONCE from the entry point and await it before the first render — the
|
||||
* pages read {@link MOCK} while they render, so flipping it afterwards would
|
||||
* leave a half-mocked screen.
|
||||
*
|
||||
* Two gates, and the order matters. `import.meta.env.DEV` is folded to a literal
|
||||
* `false` by Vite at build time, so in a production build the whole body is
|
||||
* unreachable, `import('./mock')` is tree-shaken out of the module graph, and the
|
||||
* fixtures are not in the emitted bundle AT ALL — not lazily, not behind a flag.
|
||||
* `vite.config.ts` fails the build if that ever stops being true.
|
||||
*
|
||||
* This is deliberately stronger than "hide the mock behind a query flag". The
|
||||
* flag was the bug: `?dev` on a production URL rendered an invented healthy
|
||||
* router — 119 of 122 nodes alive, "Protected" — with no request made and one
|
||||
* line of small print in the footer to say so. A person cannot audit a bundle;
|
||||
* the only honest guarantee is that the invented data is not in it.
|
||||
*/
|
||||
export async function initMockBackend(): Promise<boolean> {
|
||||
if (import.meta.env.DEV && mockRequested()) {
|
||||
fixtures = await import('./mock')
|
||||
MOCK = true
|
||||
}
|
||||
return MOCK
|
||||
}
|
||||
|
||||
/** Does the URL ask for the offline fixture backend (`?mock` or `?dev`)? */
|
||||
function mockRequested(): boolean {
|
||||
if (typeof location === 'undefined') return false
|
||||
const q = new URLSearchParams(location.search)
|
||||
return q.has('mock') || q.has('dev')
|
||||
})()
|
||||
}
|
||||
|
||||
/** The fixture backend, for the `MOCK ? … : …` branches below. Throws rather
|
||||
* than inventing data if it is ever reached without having been loaded. */
|
||||
function mock(): NonNullable<typeof fixtures> {
|
||||
if (!fixtures) throw new Error('mock backend not loaded — call initMockBackend() first')
|
||||
return fixtures
|
||||
}
|
||||
|
||||
/** A decoded response plus the raw Headers, for endpoints whose contract puts
|
||||
* pagination metadata outside the JSON body (see the stats log endpoints). */
|
||||
@@ -1174,11 +1225,11 @@ async function req<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
// --- endpoints --------------------------------------------------------------
|
||||
|
||||
export function getStatus(): Promise<Status> {
|
||||
return MOCK ? mock.getStatus() : req<Status>('api/status')
|
||||
return MOCK ? mock().getStatus() : req<Status>('api/status')
|
||||
}
|
||||
|
||||
export async function getConfig(): Promise<Model> {
|
||||
const m = await (MOCK ? mock.getConfig() : req<Model>('api/config'))
|
||||
const m = await (MOCK ? mock().getConfig() : req<Model>('api/config'))
|
||||
// Every page reads the config, and the commit-confirm window's length is the
|
||||
// only thing needed to arm a countdown — so it is captured here once instead of
|
||||
// being threaded through eight pages. See pendingConfirm.ts.
|
||||
@@ -1188,7 +1239,7 @@ export async function getConfig(): Promise<Model> {
|
||||
|
||||
export function putConfig(m: Model): Promise<{ ok: boolean; applied: boolean }> {
|
||||
return MOCK
|
||||
? mock.putConfig(m)
|
||||
? mock().putConfig(m)
|
||||
: req('api/config', { method: 'PUT', body: JSON.stringify(m) })
|
||||
}
|
||||
|
||||
@@ -1203,25 +1254,25 @@ export function putConfig(m: Model): Promise<{ ok: boolean; applied: boolean }>
|
||||
* state. See pendingConfirm.ts.
|
||||
*/
|
||||
export async function apply(): Promise<ApplyResult> {
|
||||
const r = await (MOCK ? mock.apply() : req<ApplyResult>('api/apply', { method: 'POST' }))
|
||||
const r = await (MOCK ? mock().apply() : req<ApplyResult>('api/apply', { method: 'POST' }))
|
||||
if (!r.error && r.changed) armPendingConfirm()
|
||||
return r
|
||||
}
|
||||
|
||||
export async function confirm(): Promise<ApplyResult> {
|
||||
const r = await (MOCK ? mock.confirm() : req<ApplyResult>('api/confirm', { method: 'POST' }))
|
||||
const r = await (MOCK ? mock().confirm() : req<ApplyResult>('api/confirm', { method: 'POST' }))
|
||||
if (!r.error) clearPendingConfirm()
|
||||
return r
|
||||
}
|
||||
|
||||
export async function rollback(): Promise<ApplyResult> {
|
||||
const r = await (MOCK ? mock.rollback() : req<ApplyResult>('api/rollback', { method: 'POST' }))
|
||||
const r = await (MOCK ? mock().rollback() : req<ApplyResult>('api/rollback', { method: 'POST' }))
|
||||
if (!r.error) clearPendingConfirm()
|
||||
return r
|
||||
}
|
||||
|
||||
export function getStats(): Promise<Stats> {
|
||||
return MOCK ? mock.getStats() : req<Stats>('api/stats')
|
||||
return MOCK ? mock().getStats() : req<Stats>('api/stats')
|
||||
}
|
||||
|
||||
// --- daemon log download ------------------------------------------------------
|
||||
@@ -1273,7 +1324,7 @@ function saveBlob(blob: Blob, filename: string): void {
|
||||
*/
|
||||
export async function downloadLog(range: LogRange): Promise<void> {
|
||||
if (MOCK) {
|
||||
saveBlob(new Blob([mock.getLogText(range)], { type: 'text/plain' }), `shater-log-${range}.txt`)
|
||||
saveBlob(new Blob([mock().getLogText(range)], { type: 'text/plain' }), `shater-log-${range}.txt`)
|
||||
return
|
||||
}
|
||||
let res: Response
|
||||
@@ -1352,14 +1403,14 @@ function logPage<T>(env: { body: T[] | null; headers: Headers }): StatsLogPage<T
|
||||
/** GET /api/stats/log — one page of the DNS query log with its cursor metadata. */
|
||||
export function getStatsLogPage(q: StatsLogQuery = {}): Promise<StatsLogPage<QueryLogEntry>> {
|
||||
return MOCK
|
||||
? mock.getStatsLogPage(q)
|
||||
? mock().getStatsLogPage(q)
|
||||
: reqFull<QueryLogEntry[] | null>(`api/stats/log${statsLogQS(q)}`).then(logPage)
|
||||
}
|
||||
|
||||
/** GET /api/stats/conns — one page of the connection log with its cursor metadata. */
|
||||
export function getStatsConnsPage(q: StatsLogQuery = {}): Promise<StatsLogPage<ConnLogEntry>> {
|
||||
return MOCK
|
||||
? mock.getStatsConnsPage(q)
|
||||
? mock().getStatsConnsPage(q)
|
||||
: reqFull<ConnLogEntry[] | null>(`api/stats/conns${statsLogQS(q)}`).then(logPage)
|
||||
}
|
||||
|
||||
@@ -1367,13 +1418,13 @@ export function getStatsConnsPage(q: StatsLogQuery = {}): Promise<StatsLogPage<C
|
||||
* Rows only; callers that tail the stream want {@link getStatsLogPage} instead. */
|
||||
export function getStatsLog(q: number | StatsLogQuery = {}): Promise<QueryLogEntry[]> {
|
||||
const o: StatsLogQuery = typeof q === 'number' ? { limit: q } : q
|
||||
return MOCK ? mock.getStatsLog(o) : req<QueryLogEntry[]>(`api/stats/log${statsLogQS(o)}`)
|
||||
return MOCK ? mock().getStatsLog(o) : req<QueryLogEntry[]>(`api/stats/log${statsLogQS(o)}`)
|
||||
}
|
||||
|
||||
/** GET /api/stats/conns — the live connection-event log (device→dest), newest first. */
|
||||
export function getStatsConns(q: number | StatsLogQuery = {}): Promise<ConnLogEntry[]> {
|
||||
const o: StatsLogQuery = typeof q === 'number' ? { limit: q } : q
|
||||
return MOCK ? mock.getStatsConns(o) : req<ConnLogEntry[]>(`api/stats/conns${statsLogQS(o)}`)
|
||||
return MOCK ? mock().getStatsConns(o) : req<ConnLogEntry[]>(`api/stats/conns${statsLogQS(o)}`)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1428,12 +1479,12 @@ export interface RulesReachability {
|
||||
|
||||
/** GET /api/rules/reachability — which routing rules can never fire, and why. */
|
||||
export function getRulesReachability(): Promise<RulesReachability> {
|
||||
return MOCK ? mock.getRulesReachability() : req<RulesReachability>('api/rules/reachability')
|
||||
return MOCK ? mock().getRulesReachability() : req<RulesReachability>('api/rules/reachability')
|
||||
}
|
||||
|
||||
/** GET /api/ruleset/status — remote rule-set / blocklist freshness + rule counts. */
|
||||
export function getRulesetStatus(): Promise<RulesetStatus[]> {
|
||||
return MOCK ? mock.getRulesetStatus() : req<RulesetStatus[]>('api/ruleset/status')
|
||||
return MOCK ? mock().getRulesetStatus() : req<RulesetStatus[]>('api/ruleset/status')
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1444,7 +1495,7 @@ export function getRulesetStatus(): Promise<RulesetStatus[]> {
|
||||
*/
|
||||
export function updateRuleset(tag: string): Promise<RulesetStatus | { ok: boolean }> {
|
||||
return MOCK
|
||||
? mock.updateRuleset(tag)
|
||||
? mock().updateRuleset(tag)
|
||||
: req('api/ruleset/update', { method: 'POST', body: JSON.stringify({ tag }) })
|
||||
}
|
||||
|
||||
@@ -1472,7 +1523,7 @@ export interface RulesetCheck {
|
||||
*/
|
||||
export function checkRulesetCategory(source: string, category: string): Promise<RulesetCheck> {
|
||||
return MOCK
|
||||
? mock.checkRulesetCategory(source, category)
|
||||
? mock().checkRulesetCategory(source, category)
|
||||
: req<RulesetCheck>('api/ruleset/check', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ source, category }),
|
||||
@@ -1501,18 +1552,18 @@ export interface RulesetCategories {
|
||||
*/
|
||||
export function getRulesetCategories(source: string): Promise<RulesetCategories> {
|
||||
return MOCK
|
||||
? mock.getRulesetCategories(source)
|
||||
? mock().getRulesetCategories(source)
|
||||
: req<RulesetCategories>(`api/ruleset/categories?source=${encodeURIComponent(source)}`)
|
||||
}
|
||||
|
||||
/** GET /api/devices — discovered LAN clients merged with per-device config. */
|
||||
export function getDevices(): Promise<DiscoveredDevice[]> {
|
||||
return MOCK ? mock.getDevices() : req<DiscoveredDevice[]>('api/devices')
|
||||
return MOCK ? mock().getDevices() : req<DiscoveredDevice[]>('api/devices')
|
||||
}
|
||||
|
||||
/** GET /api/interfaces — the router's UCI network interfaces for the egress picker. */
|
||||
export function getInterfaces(): Promise<Interface[]> {
|
||||
return MOCK ? mock.getInterfaces() : req<Interface[]>('api/interfaces')
|
||||
return MOCK ? mock().getInterfaces() : req<Interface[]>('api/interfaces')
|
||||
}
|
||||
|
||||
/** POST /api/session — exchange a single-use handoff token for a session cookie. */
|
||||
@@ -1548,7 +1599,7 @@ export function importWg(conf: string): Promise<{ uri: string; name: string }> {
|
||||
*/
|
||||
export function updateSubscription(name: string): Promise<{ added: number }> {
|
||||
return MOCK
|
||||
? mock.updateSubscription(name)
|
||||
? mock().updateSubscription(name)
|
||||
: req('api/subscription/update', { method: 'POST', body: JSON.stringify({ name }) })
|
||||
}
|
||||
|
||||
@@ -1568,7 +1619,7 @@ export function updateSubscription(name: string): Promise<{ added: number }> {
|
||||
export function getGroupsHealth(
|
||||
opts: { group?: string; members?: boolean } = {},
|
||||
): Promise<GroupsHealth> {
|
||||
if (MOCK) return mock.getGroupsHealth(opts)
|
||||
if (MOCK) return mock().getGroupsHealth(opts)
|
||||
const p = new URLSearchParams()
|
||||
if (opts.group) p.set('group', opts.group)
|
||||
if (opts.members) p.set('members', '1')
|
||||
@@ -1683,11 +1734,11 @@ export interface GroupTestStart {
|
||||
*/
|
||||
export function postGroupsTest(name = ''): Promise<GroupTestStart> {
|
||||
return MOCK
|
||||
? mock.postGroupsTest(name)
|
||||
? mock().postGroupsTest(name)
|
||||
: req<GroupTestStart>('api/groups/test', { method: 'POST', body: JSON.stringify({ name }) })
|
||||
}
|
||||
|
||||
/** GET /api/groups/test — progress + results of the current/last group test. */
|
||||
export function getGroupsTest(): Promise<GroupTestStatus> {
|
||||
return MOCK ? mock.getGroupsTest() : req<GroupTestStatus>('api/groups/test')
|
||||
return MOCK ? mock().getGroupsTest() : req<GroupTestStatus>('api/groups/test')
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// findings.ts — which apply-time finding is shown where.
|
||||
//
|
||||
// Run with `npm test` (node's built-in test runner + native TypeScript
|
||||
// stripping; no test dependency is added to the SPA, which ships inside the
|
||||
// daemon binary).
|
||||
//
|
||||
// Two defects are pinned here.
|
||||
//
|
||||
// 1. THE TRUNCATION NOTE WAS UNREACHABLE. The daemon caps Status.warnings at 50
|
||||
// and overwrites the last slot with an `info` note counting what it dropped.
|
||||
// Overview filtered `info` away wholesale, and the settings-page route keys on
|
||||
// a section (`generate`) that no page owns — so the single line telling the
|
||||
// operator "you are not seeing all of it" reached no screen at all.
|
||||
//
|
||||
// 2. FINDINGS ABOUT AN ENTITY NEVER REACHED THAT ENTITY'S PAGE. The generator
|
||||
// drops a node it cannot build and names it; the Nodes page rendered that node
|
||||
// as an ordinary row with a green toggle, because it never read the findings.
|
||||
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import {
|
||||
attentionFindings,
|
||||
entityFindings,
|
||||
findingsByName,
|
||||
sectionNotes,
|
||||
truncationNote,
|
||||
worstSeverity,
|
||||
} from './findings.ts'
|
||||
import type { StatusWarning } from './api.ts'
|
||||
|
||||
const crit = (section: string, name: string, message = 'broken'): StatusWarning => ({
|
||||
severity: 'critical',
|
||||
section,
|
||||
name,
|
||||
message,
|
||||
})
|
||||
const warn = (section: string, name: string, message = 'degraded'): StatusWarning => ({
|
||||
severity: 'warning',
|
||||
section,
|
||||
name,
|
||||
message,
|
||||
})
|
||||
const info = (section: string, name: string, message: string): StatusWarning => ({
|
||||
severity: 'info',
|
||||
section,
|
||||
name,
|
||||
message,
|
||||
})
|
||||
|
||||
/** Verbatim from apply/warnings.go finalizeWarnings. */
|
||||
const SUPPRESSED = info(
|
||||
'generate',
|
||||
'',
|
||||
'7 further warning(s) suppressed; run `logread -e shater` for the full list',
|
||||
)
|
||||
|
||||
// --- the truncation note ----------------------------------------------------
|
||||
|
||||
test('the truncation note is found, whatever else is in the list', () => {
|
||||
const note = truncationNote([crit('rule', 'a'), warn('node', 'b'), SUPPRESSED])
|
||||
assert.notEqual(note, null)
|
||||
assert.match(note!.message, /7 further warning/)
|
||||
})
|
||||
|
||||
test('a whole list has no truncation note', () => {
|
||||
assert.equal(truncationNote([crit('rule', 'a'), warn('node', 'b')]), null)
|
||||
assert.equal(truncationNote([]), null)
|
||||
assert.equal(truncationNote(undefined), null)
|
||||
})
|
||||
|
||||
test('an ordinary info note is not mistaken for the truncation note', () => {
|
||||
const notes = [info('untunnelable', 'block', 'Ping and traceroute do not work…')]
|
||||
assert.equal(truncationNote(notes), null)
|
||||
})
|
||||
|
||||
test('the truncation note is kept out of the settings-page notes it would pollute', () => {
|
||||
const all = [info('generate', '', 'cache: moved to /overlay'), SUPPRESSED]
|
||||
const notes = sectionNotes(all, 'generate')
|
||||
assert.equal(notes.length, 1)
|
||||
assert.match(notes[0].message, /cache:/)
|
||||
})
|
||||
|
||||
test('the attention list still carries only critical and warning', () => {
|
||||
const all = [crit('rule', 'a'), warn('node', 'b'), info('untunnelable', 'block', 'x'), SUPPRESSED]
|
||||
const attention = attentionFindings(all)
|
||||
assert.equal(attention.length, 2)
|
||||
assert.ok(attention.every((w) => w.severity !== 'info'))
|
||||
})
|
||||
|
||||
// --- per-entity findings ----------------------------------------------------
|
||||
|
||||
test('a page takes only the sections it owns', () => {
|
||||
const all = [
|
||||
crit('node', 'tokyo-01', 'parse share-link: bad scheme (skipped)'),
|
||||
warn('subscription', 'qomar', 'fetch failed'),
|
||||
crit('rule', 'default', 'never applies'),
|
||||
info('generate', '', 'cache: x'),
|
||||
]
|
||||
const mine = entityFindings(all, ['node', 'subscription'])
|
||||
assert.deepEqual(
|
||||
mine.map((w) => w.name),
|
||||
['tokyo-01', 'qomar'],
|
||||
)
|
||||
})
|
||||
|
||||
test('entity findings never include info notes', () => {
|
||||
const all = [info('node', 'tokyo-01', 'just a note'), SUPPRESSED]
|
||||
assert.equal(entityFindings(all, ['node', 'generate']).length, 0)
|
||||
})
|
||||
|
||||
test('findings index by name, and global (unnamed) ones are left out', () => {
|
||||
const all = [
|
||||
crit('node', 'tokyo-01', 'first'),
|
||||
warn('node', 'tokyo-01', 'second'),
|
||||
crit('node', '', 'global to the section'),
|
||||
]
|
||||
const byName = findingsByName(entityFindings(all, ['node']))
|
||||
assert.equal(byName.size, 1)
|
||||
assert.equal(byName.get('tokyo-01')!.length, 2)
|
||||
})
|
||||
|
||||
test('one lamp per row takes the loudest severity', () => {
|
||||
assert.equal(worstSeverity([warn('node', 'a'), crit('node', 'a')]), 'critical')
|
||||
assert.equal(worstSeverity([warn('node', 'a')]), 'warning')
|
||||
assert.equal(worstSeverity([]), null)
|
||||
})
|
||||
+91
-2
@@ -6,7 +6,8 @@
|
||||
//
|
||||
// critical / warning — something needs attention: a protection promise is
|
||||
// broken, or something you configured isn't in effect. These belong on
|
||||
// Overview, where the operator looks first.
|
||||
// Overview, where the operator looks first — and, when they name an entity,
|
||||
// ALSO on the page that owns that entity (see `entityFindings`).
|
||||
//
|
||||
// info — a statement ABOUT the configuration, not a problem. It never clears,
|
||||
// because nothing is wrong: it is simply describing a choice that was made.
|
||||
@@ -16,9 +17,49 @@
|
||||
// page that never goes away and never asks for anything trains people to skim
|
||||
// the list — which is exactly how a real critical finding gets missed. Anything
|
||||
// standing in the findings list should be something you could act on.
|
||||
//
|
||||
// The one exception is carved out below: the daemon's own note that it dropped
|
||||
// findings to fit the cap. It is `info` by severity and unactionable by nature,
|
||||
// and it is the single most important line in the list, because it is the list
|
||||
// telling you it is not the whole list.
|
||||
|
||||
import type { StatusWarning } from './api'
|
||||
|
||||
/**
|
||||
* The daemon's truncation disclosure, verbatim from apply/warnings.go
|
||||
* finalizeWarnings:
|
||||
*
|
||||
* "%d further warning(s) suppressed; run `logread -e shater` for the full list"
|
||||
*
|
||||
* Matched on the stable clause rather than the whole sentence so a reworded tail
|
||||
* still registers. If this ever stops matching, the failure mode is a list that
|
||||
* silently claims to be complete — which is why `truncationNote` is tested.
|
||||
*/
|
||||
const SUPPRESSED_RE = /further warning\(s\) suppressed/
|
||||
|
||||
/**
|
||||
* The daemon's "this list is incomplete" note, or null when the list is whole.
|
||||
*
|
||||
* Status.warnings is capped at 50, sorted critical-first, and the last slot is
|
||||
* REPLACED by an `info` note counting what was dropped. That note therefore
|
||||
* arrives on the one channel the panel filtered away wholesale: `info` never
|
||||
* reached Overview, and the settings-page route (`sectionNotes`) keys on
|
||||
* section `generate`, which no page owns. So the single line saying "there are
|
||||
* findings you are not being shown" was the only one guaranteed to be invisible.
|
||||
*
|
||||
* Callers must render this WITH the attention list, not instead of it.
|
||||
*/
|
||||
export function truncationNote(warnings: StatusWarning[] | undefined): StatusWarning | null {
|
||||
return (
|
||||
(warnings ?? []).find((w) => w.severity === 'info' && SUPPRESSED_RE.test(w.message)) ?? null
|
||||
)
|
||||
}
|
||||
|
||||
/** Is this the truncation disclosure rather than an ordinary note? */
|
||||
function isTruncationNote(w: StatusWarning): boolean {
|
||||
return w.severity === 'info' && SUPPRESSED_RE.test(w.message)
|
||||
}
|
||||
|
||||
/** Findings that need attention — the Overview list. Info notes are excluded. */
|
||||
export function attentionFindings(warnings: StatusWarning[] | undefined): StatusWarning[] {
|
||||
return (warnings ?? []).filter((w) => w.severity === 'critical' || w.severity === 'warning')
|
||||
@@ -29,10 +70,58 @@ export function attentionFindings(warnings: StatusWarning[] | undefined): Status
|
||||
* (e.g. `untunnelable` → the Networks page's "Other traffic" section). Only info:
|
||||
* a critical/warning is an attention item and stays on Overview, so it can't be
|
||||
* quietly buried on a settings page instead.
|
||||
*
|
||||
* The truncation note is excluded: it is about the LIST, not about any section,
|
||||
* and it has its own home beside the list ({@link truncationNote}).
|
||||
*/
|
||||
export function sectionNotes(
|
||||
warnings: StatusWarning[] | undefined,
|
||||
section: string,
|
||||
): StatusWarning[] {
|
||||
return (warnings ?? []).filter((w) => w.severity === 'info' && w.section === section)
|
||||
return (warnings ?? []).filter(
|
||||
(w) => w.severity === 'info' && w.section === section && !isTruncationNote(w),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The attention findings about entities ONE page owns — for that page to show
|
||||
* beside the entities themselves.
|
||||
*
|
||||
* Overview is where you look when you already suspect something; a page like
|
||||
* Nodes is where you look when you don't. The generator drops a node it cannot
|
||||
* build — an unparseable share link, a WireGuard key materialised twice — and
|
||||
* says so by name ("node \"x\": parse share-link: … (skipped)"), yet that node
|
||||
* kept rendering as an ordinary row with a green toggle, because the page never
|
||||
* read the findings at all. The switch says on; the engine has no such outbound.
|
||||
*
|
||||
* This does NOT move anything off Overview: the same finding appears in both
|
||||
* places, which is correct — one list is "what is wrong with this router", the
|
||||
* other is "what is wrong with this node".
|
||||
*/
|
||||
export function entityFindings(
|
||||
warnings: StatusWarning[] | undefined,
|
||||
sections: readonly string[],
|
||||
): StatusWarning[] {
|
||||
const want = new Set(sections)
|
||||
return attentionFindings(warnings).filter((w) => want.has(w.section))
|
||||
}
|
||||
|
||||
/** Index attention findings by entity name, for badging a row directly. Entries
|
||||
* with an empty `name` are global to their section and are left out. */
|
||||
export function findingsByName(findings: StatusWarning[]): Map<string, StatusWarning[]> {
|
||||
const out = new Map<string, StatusWarning[]>()
|
||||
for (const f of findings) {
|
||||
if (!f.name) continue
|
||||
const list = out.get(f.name)
|
||||
if (list) list.push(f)
|
||||
else out.set(f.name, [f])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** The loudest severity in a set — for a row badge that has room for one lamp. */
|
||||
export function worstSeverity(findings: StatusWarning[]): 'critical' | 'warning' | null {
|
||||
if (findings.some((f) => f.severity === 'critical')) return 'critical'
|
||||
if (findings.length > 0) return 'warning'
|
||||
return null
|
||||
}
|
||||
+25
-9
@@ -2,17 +2,33 @@ import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './tokens.css'
|
||||
import { App } from './App'
|
||||
import { initMockBackend } from './api'
|
||||
import { ConfirmProvider } from './components'
|
||||
|
||||
const rootEl = document.getElementById('root')
|
||||
if (!rootEl) throw new Error('#root not found')
|
||||
|
||||
// ConfirmProvider sits ABOVE <App> so it survives App's early returns (the
|
||||
// unauth / no-link plates) — useConfirm() can never find itself without a host.
|
||||
createRoot(rootEl).render(
|
||||
<StrictMode>
|
||||
<ConfirmProvider>
|
||||
<App />
|
||||
</ConfirmProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
// Settle the fixture question BEFORE the first render: pages read `MOCK` while
|
||||
// they render, so a backend that arrives afterwards would paint half a screen
|
||||
// from the daemon and half from fixtures. In a production build this resolves
|
||||
// immediately and to `false` — the fixtures are not in the bundle to load (see
|
||||
// api.ts initMockBackend and the assertNoMockFixtures plugin in vite.config.ts).
|
||||
function mount() {
|
||||
// ConfirmProvider sits ABOVE <App> so it survives App's early returns (the
|
||||
// unauth / no-link plates) — useConfirm() can never find itself without a host.
|
||||
createRoot(rootEl!).render(
|
||||
<StrictMode>
|
||||
<ConfirmProvider>
|
||||
<App />
|
||||
</ConfirmProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
}
|
||||
|
||||
// A fixture module that fails to load is a broken dev checkout, not a reason to
|
||||
// hand the operator a blank plate — mount anyway and let the shell report that it
|
||||
// cannot reach a daemon, which by then is the truth.
|
||||
void initMockBackend().then(mount, (e) => {
|
||||
console.error('mock backend failed to load; continuing against the real API', e)
|
||||
mount()
|
||||
})
|
||||
+52
-4
@@ -500,7 +500,15 @@ export async function getRulesetCategories(source: string): Promise<RulesetCateg
|
||||
// the field case the readout used to call "Protected" (one
|
||||
// rule, `default → direct`); `unknown` is a daemon too old to
|
||||
// report. Default: tunnel.
|
||||
function mockPlane(): { plane: 'full' | 'hold' | 'none'; engine: boolean; killSwitch: string } {
|
||||
// ?mock&plane=unreported → a daemon that sends NO `plane` field. The panel then
|
||||
// knows nothing about what is installed, which is the state
|
||||
// the Kill-switch module used to render as a green "ARMED"
|
||||
// (`undefined !== 'none'` is true).
|
||||
function mockPlane(): {
|
||||
plane: 'full' | 'hold' | 'none' | undefined
|
||||
engine: boolean
|
||||
killSwitch: string
|
||||
} {
|
||||
const q = typeof location === 'undefined' ? '' : location.search
|
||||
const params = new URLSearchParams(q)
|
||||
const killSwitch = params.get('ks') === 'open' ? 'open' : 'closed'
|
||||
@@ -508,6 +516,7 @@ function mockPlane(): { plane: 'full' | 'hold' | 'none'; engine: boolean; killSw
|
||||
if (p === 'hold') return { plane: 'hold', engine: false, killSwitch: 'closed' }
|
||||
if (p === 'none') return { plane: 'none', engine: false, killSwitch }
|
||||
if (p === 'open') return { plane: 'none', engine: false, killSwitch: 'open' }
|
||||
if (p === 'unreported') return { plane: undefined, engine: true, killSwitch }
|
||||
return { plane: 'full', engine: true, killSwitch }
|
||||
}
|
||||
|
||||
@@ -515,7 +524,7 @@ function mockPlane(): { plane: 'full' | 'hold' | 'none'; engine: boolean; killSw
|
||||
// meaningful with the plane installed: with the engine down there is no running
|
||||
// config to judge, and the daemon reports the unknown/zero value — so do the same
|
||||
// here rather than leaving a stale "tunnel" behind a dead engine.
|
||||
function mockTraffic(plane: 'full' | 'hold' | 'none'): Traffic | undefined {
|
||||
function mockTraffic(plane: 'full' | 'hold' | 'none' | undefined): Traffic | undefined {
|
||||
if (plane !== 'full') return { verdict: '', default: '', tunnel_rules: 0 }
|
||||
const params = new URLSearchParams(typeof location === 'undefined' ? '' : location.search)
|
||||
switch (params.get('traffic')) {
|
||||
@@ -560,6 +569,29 @@ const MOCK_WARNINGS: StatusWarning[] = [
|
||||
name: 'fakeip-pool',
|
||||
message: 'fake-IP resolver cannot be used as a fallback; the failover chain was not built',
|
||||
},
|
||||
// Two findings the generator attributes to a NODE by name — the class that the
|
||||
// Nodes page never showed, leaving a node the engine threw away rendered as an
|
||||
// ordinary row with a green toggle. Both name real fixture nodes so the row
|
||||
// badge, the collapsed-bucket "N flagged" count and the per-row strip all fire.
|
||||
{
|
||||
severity: 'warning',
|
||||
section: 'node',
|
||||
name: 'fi-trojan',
|
||||
message: 'parse share-link: unsupported scheme "trojan+ws" (skipped)',
|
||||
},
|
||||
{
|
||||
severity: 'warning',
|
||||
section: 'node',
|
||||
name: 'home-wg',
|
||||
message:
|
||||
'this WireGuard node is materialised twice in the engine config — as "home-wg" and as "group-stealth-m1-home-wg" — and traffic can reach both. A WireGuard peer keeps ONE session per public key, so two devices built from one private key evict each other continuously and NEITHER tunnel passes traffic. Only "home-wg" is kept; everything that routed through "group-stealth-m1-home-wg" is fail-closed (blocked) instead of leaving over the plain WAN',
|
||||
},
|
||||
{
|
||||
severity: 'warning',
|
||||
section: 'subscription',
|
||||
name: 'backup',
|
||||
message: 'fetch failed: dial tcp 203.0.113.9:443: i/o timeout — serving the nodes cached earlier',
|
||||
},
|
||||
{
|
||||
severity: 'info',
|
||||
section: 'generate',
|
||||
@@ -568,6 +600,19 @@ const MOCK_WARNINGS: StatusWarning[] = [
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* The daemon's truncation disclosure, exactly as apply/warnings.go writes it when
|
||||
* the published set overflows the 50-entry cap. Served under `?mock&trunc` so the
|
||||
* "this list is incomplete" rendering is exercisable — it used to be dropped
|
||||
* wholesale by the panel's `info` filter and reached no screen at all.
|
||||
*/
|
||||
const MOCK_TRUNCATION: StatusWarning = {
|
||||
severity: 'info',
|
||||
section: 'generate',
|
||||
name: '',
|
||||
message: '7 further warning(s) suppressed; run `logread -e shater` for the full list',
|
||||
}
|
||||
|
||||
/**
|
||||
* The standing `untunnelable` note the daemon reports. It is INFO, never a
|
||||
* problem: it states a correct, chosen configuration. Two shapes, mirroring the
|
||||
@@ -614,9 +659,12 @@ function mockWarnings(killSwitch: string): StatusWarning[] {
|
||||
const params = new URLSearchParams(q)
|
||||
const mode = (CONFIG.Globals as { Untunnelable?: string }).Untunnelable ?? 'block'
|
||||
const notes = untunnelableNote(mode, killSwitch)
|
||||
// `?trunc` adds the daemon's "the published list is capped" disclosure, which
|
||||
// it appends IN PLACE OF the last entry it had room for.
|
||||
const trunc = params.has('trunc') ? [{ ...MOCK_TRUNCATION }] : []
|
||||
// A degraded plane always comes with the findings that explain it.
|
||||
if (params.has('warn') || params.get('plane')) {
|
||||
return [...MOCK_WARNINGS.map((w) => ({ ...w })), ...notes]
|
||||
if (params.has('warn') || params.get('plane') || trunc.length > 0) {
|
||||
return [...MOCK_WARNINGS.map((w) => ({ ...w })), ...notes, ...trunc]
|
||||
}
|
||||
return notes
|
||||
}
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
/* Alerts section (rendered on Settings) — inherits the Faceplate tokens and the
|
||||
* shared page chrome from App.css (.toast, .mono). Every rule below is a
|
||||
* one-to-one copy of the DNS.css rule the markup used before the section moved
|
||||
* here, renamed `dns-*` → `alr-*` so nothing collides. Orange stays an accent. */
|
||||
|
||||
/* ---- section shell (matches the Settings group plates one-to-one) ---- */
|
||||
.alr-section {
|
||||
margin-top: calc(var(--u, 8px) * 3.5);
|
||||
}
|
||||
.alr-sec-hd {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 12px;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px solid var(--groove);
|
||||
}
|
||||
.alr-sec-title {
|
||||
margin: 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
letter-spacing: var(--track-label, 0.18em);
|
||||
text-transform: uppercase;
|
||||
color: var(--dim);
|
||||
}
|
||||
.alr-sec-count {
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--faint);
|
||||
}
|
||||
.alr-sec-note {
|
||||
margin: 10px 2px 0;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.55;
|
||||
color: var(--dim);
|
||||
max-width: 56ch;
|
||||
}
|
||||
|
||||
/* ---- add form ---- */
|
||||
.alr-add {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-top: calc(var(--u, 8px) * 2);
|
||||
}
|
||||
.alr-add-top {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.alr-input {
|
||||
min-width: 0;
|
||||
padding: 9px 12px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 7px;
|
||||
background: var(--sink);
|
||||
color: var(--ink);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12.5px;
|
||||
letter-spacing: 0.02em;
|
||||
box-shadow: 0 1px 2px var(--shadow) inset;
|
||||
transition: border-color 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
.alr-input::placeholder {
|
||||
color: var(--faint);
|
||||
}
|
||||
.alr-input:focus-visible {
|
||||
border-color: var(--accent);
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.alr-input:disabled {
|
||||
opacity: 0.55;
|
||||
}
|
||||
.alr-input--name {
|
||||
flex: 0 1 14rem;
|
||||
}
|
||||
|
||||
/* segmented type picker */
|
||||
.alr-seg {
|
||||
display: inline-flex;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 7px;
|
||||
overflow: hidden;
|
||||
background: var(--sink);
|
||||
}
|
||||
.alr-seg-btn {
|
||||
padding: 8px 14px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--dim);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
.alr-seg-btn + .alr-seg-btn {
|
||||
border-left: 1px solid var(--groove);
|
||||
}
|
||||
.alr-seg-btn.on {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
.alr-seg-btn:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.alr-resp {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.alr-resp-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-label, 0.18em);
|
||||
text-transform: uppercase;
|
||||
color: var(--faint);
|
||||
}
|
||||
.alr-select {
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 7px;
|
||||
background: var(--sink);
|
||||
color: var(--ink);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11.5px;
|
||||
letter-spacing: 0.04em;
|
||||
cursor: pointer;
|
||||
}
|
||||
.alr-select:focus-visible {
|
||||
border-color: var(--accent);
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
.alr-add-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.alr-field-err {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.5;
|
||||
color: var(--crit);
|
||||
}
|
||||
|
||||
/* ---- rows ---- */
|
||||
.alr-rows {
|
||||
list-style: none;
|
||||
margin: calc(var(--u, 8px) * 2) 0 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.alr-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: calc(var(--u, 8px) * 1.5);
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
var(--raised),
|
||||
color-mix(in srgb, var(--raised) 82%, var(--panel))
|
||||
);
|
||||
box-shadow: 0 1px 0 var(--edge) inset;
|
||||
}
|
||||
.alr-row-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.alr-row-l1 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.alr-row-name {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.01em;
|
||||
color: var(--ink);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 24ch;
|
||||
}
|
||||
.alr-row-l2 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
font-size: 11.5px;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
.alr-row-detail {
|
||||
color: var(--dim);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 40ch;
|
||||
}
|
||||
|
||||
/* badge — groove-bordered, not orange (accent stays reserved) */
|
||||
.alr-badge {
|
||||
display: inline-block;
|
||||
padding: 2px 7px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 5px;
|
||||
background: color-mix(in srgb, var(--sink) 60%, transparent);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
color: var(--dim);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.alr-badge--accent {
|
||||
border-color: color-mix(in srgb, var(--accent) 55%, var(--groove));
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.alr-masked {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--faint);
|
||||
text-transform: uppercase;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.alr-del {
|
||||
flex: none;
|
||||
padding: 6px 12px;
|
||||
font-size: 10.5px;
|
||||
}
|
||||
|
||||
/* ---- empty plate ---- */
|
||||
.alr-empty {
|
||||
margin-top: calc(var(--u, 8px) * 2);
|
||||
padding: calc(var(--u, 8px) * 3);
|
||||
border: 1px dashed var(--groove);
|
||||
border-radius: 9px;
|
||||
background: color-mix(in srgb, var(--raised) 55%, transparent);
|
||||
text-align: center;
|
||||
}
|
||||
.alr-empty-title {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--dim);
|
||||
}
|
||||
.alr-empty-body {
|
||||
margin: 8px auto 0;
|
||||
max-width: 48ch;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
color: var(--dim);
|
||||
}
|
||||
|
||||
/* ---- loading skeleton ---- */
|
||||
.alr-skel {
|
||||
height: 62px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(90deg, var(--raised), var(--sink), var(--raised));
|
||||
background-size: 200% 100%;
|
||||
animation: alr-skel-shift 1.4s ease-in-out infinite;
|
||||
}
|
||||
@keyframes alr-skel-shift {
|
||||
from {
|
||||
background-position: 200% 0;
|
||||
}
|
||||
to {
|
||||
background-position: -200% 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* the per-row delivery picker sits inline in the row */
|
||||
.alr-detour {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
}
|
||||
.alr-detour-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-label, 0.18em);
|
||||
text-transform: uppercase;
|
||||
color: var(--faint);
|
||||
}
|
||||
.alr-detour-select {
|
||||
max-width: 22rem;
|
||||
}
|
||||
|
||||
/* current delivery-path readout on the row */
|
||||
.alr-path {
|
||||
color: var(--faint);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.alr-path[data-active='on'] {
|
||||
color: var(--dim);
|
||||
}
|
||||
.alr-path-name {
|
||||
color: var(--led-on);
|
||||
font-weight: 600;
|
||||
}
|
||||
.alr-path[data-missing='y'] .alr-path-name {
|
||||
color: var(--amber);
|
||||
}
|
||||
.alr-path-flag {
|
||||
color: var(--amber);
|
||||
}
|
||||
|
||||
/* alert delivery: deliver-via picker + fallback toggle + caution note */
|
||||
.alr-delivery {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px 20px;
|
||||
}
|
||||
.alr-fallback {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.alr-fallback-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-label, 0.18em);
|
||||
text-transform: uppercase;
|
||||
color: var(--faint);
|
||||
}
|
||||
/* the per-row delivery controls sit inline in the row (like .alr-detour) */
|
||||
.alr-ctl {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.alr-note {
|
||||
margin: 0;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.5;
|
||||
color: var(--amber);
|
||||
max-width: 56ch;
|
||||
}
|
||||
.alr-note--row {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
/* alert event checkboxes */
|
||||
.alr-events {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 16px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
.alr-event {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--fp-text, inherit);
|
||||
cursor: pointer;
|
||||
}
|
||||
.alr-event input {
|
||||
accent-color: var(--fp-accent, currentColor);
|
||||
}
|
||||
|
||||
/* ---- responsive ---- */
|
||||
@media (max-width: 640px) {
|
||||
.alr-row {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.alr-row-main {
|
||||
flex-basis: calc(100% - 90px);
|
||||
}
|
||||
.alr-del {
|
||||
margin-left: auto;
|
||||
}
|
||||
.alr-input--name {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
.alr-detour {
|
||||
flex-basis: 100%;
|
||||
order: 3;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
/* A <select> won't shrink below its widest option unless it's allowed to:
|
||||
without min-width:0 the long detour labels push the page into a horizontal
|
||||
scroll at 390px. Let them fill the row and clip instead. */
|
||||
.alr-detour-select,
|
||||
.alr-resp .alr-select {
|
||||
max-width: 100%;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
.alr-resp {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
max-width: 100%;
|
||||
}
|
||||
.alr-ctl {
|
||||
flex-basis: 100%;
|
||||
order: 3;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.alr-skel {
|
||||
animation: none;
|
||||
}
|
||||
.alr-input,
|
||||
.alr-seg-btn {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
import './Alerts.css'
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import { Button, Toggle, useConfirm } from '../components'
|
||||
import type { Alert, Model } from '../api'
|
||||
|
||||
// The Alerts section — out-of-band notifications (Telegram bot / webhook) for
|
||||
// kill-switch trips, apply failures, new devices and subscription expiry. It
|
||||
// lived at the bottom of the DNS page, which is the last place an operator
|
||||
// looking for "tell me when the tunnel dies" would think to look; it now renders
|
||||
// as a group on Settings. The component owns no I/O: every mutation goes through
|
||||
// the `onSave` prop so Settings keeps a single dirty banner and a single toast.
|
||||
//
|
||||
// NOTE on duplication: the detour helpers below (DetourCatalog, canonDetour,
|
||||
// detourValues, describeDetour, DetourSelect) plus asArray / uniqueName /
|
||||
// maskUrl / EmptyPlate are deliberate copies of the ones in DNS.tsx. DNS keeps
|
||||
// its own for resolvers and DNS rules; extracting a shared module would couple
|
||||
// two pages that otherwise share nothing, and that refactor is out of scope
|
||||
// here. If a third consumer ever appears, promote them then.
|
||||
|
||||
// ---- local Model extension --------------------------------------------------
|
||||
|
||||
/** The Model with the Alerts slice surfaced (index-signature passthrough). */
|
||||
type AlertsModel = Model & { Alerts?: Alert[] | null }
|
||||
|
||||
/**
|
||||
* Every event the daemon actually sends. A retired health-probe event was left
|
||||
* out on purpose: nothing ever fired it, so a channel that subscribed to it would
|
||||
* just stay quiet forever — the one failure mode an alert must not have. Only
|
||||
* events with a live firing path are offered here.
|
||||
*/
|
||||
const ALERT_EVENTS: ReadonlyArray<{ id: string; label: string }> = [
|
||||
{ id: 'killswitch', label: 'Kill-switch' },
|
||||
{ id: 'apply_fail', label: 'Apply failure' },
|
||||
{ id: 'new_device', label: 'New device' },
|
||||
{ id: 'sub_expiry', label: 'Subscription expiring' },
|
||||
]
|
||||
|
||||
// Shown when an alert routes through a detour with no direct fallback — the exact
|
||||
// case where a tunnel-down alert could fail to send. The user asked for this.
|
||||
const VIA_NO_FALLBACK_NOTE =
|
||||
'A kill-switch/tunnel-down alert may not send if it routes through the affected tunnel — enable fallback.'
|
||||
|
||||
// ---- helpers (copies of DNS.tsx — see the header note) ----------------------
|
||||
|
||||
const asArray = <T,>(a: T[] | null | undefined): T[] => (a ? a : [])
|
||||
|
||||
const HTTP_RE = /^https?:\/\//i
|
||||
|
||||
/** A remote URL often carries a token in its query/path — show host only. */
|
||||
function maskUrl(url: string): { host: string; masked: boolean } {
|
||||
try {
|
||||
const u = new URL(url)
|
||||
return { host: u.host, masked: u.search !== '' || u.pathname.replace(/\/+$/, '') !== '' }
|
||||
} catch {
|
||||
return { host: url || '—', masked: false }
|
||||
}
|
||||
}
|
||||
|
||||
function uniqueName(base: string, taken: Set<string>): string {
|
||||
const seed = base.trim() || 'alert'
|
||||
if (!taken.has(seed)) return seed
|
||||
let i = 2
|
||||
while (taken.has(`${seed}-${i}`)) i++
|
||||
return `${seed}-${i}`
|
||||
}
|
||||
|
||||
/** The live targets an alert's delivery can be pinned to (the picker). */
|
||||
interface DetourCatalog {
|
||||
groups: string[]
|
||||
chains: string[]
|
||||
egresses: { name: string; type: string }[]
|
||||
nodes: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise a stored `Via` to a picker option value. Empty/`direct` ⇒
|
||||
* `direct`; already-prefixed values (`group:`/`chain:`/`egress:`/`node:`) pass
|
||||
* through; a bare legacy name is resolved against the catalog so a still-valid
|
||||
* setup isn't mislabelled; anything unresolved is kept verbatim (shown stale).
|
||||
*/
|
||||
function canonDetour(raw: string | undefined, cat: DetourCatalog): string {
|
||||
const d = (raw ?? '').trim()
|
||||
if (!d || d.toLowerCase() === 'direct') return 'direct'
|
||||
if (/^(node|group|chain|egress):/i.test(d)) return d
|
||||
if (cat.egresses.some((e) => e.name === d)) return `egress:${d}`
|
||||
if (cat.groups.includes(d)) return `group:${d}`
|
||||
if (cat.chains.includes(d)) return `chain:${d}`
|
||||
if (cat.nodes.includes(d)) return `node:${d}`
|
||||
return d
|
||||
}
|
||||
|
||||
/** Every valid option value for a catalog, including `direct`. */
|
||||
function detourValues(cat: DetourCatalog): Set<string> {
|
||||
const s = new Set<string>(['direct'])
|
||||
for (const g of cat.groups) s.add(`group:${g}`)
|
||||
for (const c of cat.chains) s.add(`chain:${c}`)
|
||||
for (const e of cat.egresses) s.add(`egress:${e.name}`)
|
||||
for (const n of cat.nodes) s.add(`node:${n}`)
|
||||
return s
|
||||
}
|
||||
|
||||
/** Describe a canonical detour value for the row readout. */
|
||||
function describeDetour(
|
||||
canon: string,
|
||||
cat: DetourCatalog,
|
||||
valid: Set<string>,
|
||||
): { direct: boolean; prefix: string; name: string; missing: boolean } {
|
||||
if (canon === 'direct') return { direct: true, prefix: '', name: '', missing: false }
|
||||
const i = canon.indexOf(':')
|
||||
const kind = i === -1 ? '' : canon.slice(0, i)
|
||||
const name = i === -1 ? canon : canon.slice(i + 1)
|
||||
const missing = !valid.has(canon)
|
||||
let prefix = 'via'
|
||||
if (kind === 'group') prefix = 'via group'
|
||||
else if (kind === 'chain') prefix = 'via chain'
|
||||
else if (kind === 'node') prefix = 'via node'
|
||||
else if (kind === 'egress') {
|
||||
const eg = cat.egresses.find((e) => e.name === name)
|
||||
prefix = eg?.type === 'interface' ? 'via interface' : 'via egress'
|
||||
}
|
||||
return { direct: false, prefix, name, missing }
|
||||
}
|
||||
|
||||
// ---- section ----------------------------------------------------------------
|
||||
|
||||
export function AlertsSection({
|
||||
config,
|
||||
busy,
|
||||
loading,
|
||||
onSave,
|
||||
}: {
|
||||
/** Full desired-state model; null until it has loaded. */
|
||||
config: Model | null
|
||||
/** A save/apply is in flight — controls lock. */
|
||||
busy: boolean
|
||||
/** The config is still loading — show a skeleton row. */
|
||||
loading: boolean
|
||||
/** Persist the whole next model; resolves true on success (Settings' `save`). */
|
||||
onSave: (next: Model, okMsg: string) => Promise<boolean>
|
||||
}): JSX.Element {
|
||||
const confirm = useConfirm()
|
||||
const model = config as AlertsModel | null
|
||||
const alerts = useMemo<Alert[]>(() => asArray(model?.Alerts), [model])
|
||||
|
||||
// Alerts route through Direct/group/node/egress only (no chains) — the contract
|
||||
// vocabulary for Alert.Via. Built straight from the Model with chains dropped.
|
||||
const alertCatalog = useMemo<DetourCatalog>(
|
||||
() => ({
|
||||
groups: asArray(config?.Groups).map((g) => g.Name),
|
||||
chains: [],
|
||||
egresses: asArray(config?.Egresses).map((e) => ({ name: e.Name, type: e.Type })),
|
||||
nodes: asArray(config?.Nodes).map((n) => n.Name),
|
||||
}),
|
||||
[config],
|
||||
)
|
||||
const alertValid = useMemo(() => detourValues(alertCatalog), [alertCatalog])
|
||||
|
||||
const alertNames = useMemo(() => new Set(alerts.map((a) => a.Name)), [alerts])
|
||||
const alertsOn = alerts.filter((a) => a.Enabled).length
|
||||
|
||||
// ---- mutations — all writes go through onSave -----------------------------
|
||||
const addAlert = useCallback(
|
||||
(draft: Alert): Promise<boolean> => {
|
||||
if (!model) return Promise.resolve(false)
|
||||
const taken = new Set(alerts.map((a) => a.Name))
|
||||
const a: Alert = { ...draft, Name: uniqueName(draft.Name, taken) }
|
||||
return onSave({ ...model, Alerts: [...alerts, a] }, `Added ${a.Name}`)
|
||||
},
|
||||
[model, alerts, onSave],
|
||||
)
|
||||
|
||||
const toggleAlert = useCallback(
|
||||
(idx: number, on: boolean) => {
|
||||
if (!model) return
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Enabled: on } : a))
|
||||
void onSave({ ...model, Alerts: next }, `${next[idx].Name} ${on ? 'enabled' : 'disabled'}`)
|
||||
},
|
||||
[model, alerts, onSave],
|
||||
)
|
||||
|
||||
const removeAlert = useCallback(
|
||||
async (idx: number) => {
|
||||
if (!model) return
|
||||
const target = alerts[idx]
|
||||
const ok = await confirm({
|
||||
label: 'Delete alert',
|
||||
title: `Delete alert “${target.Name}”?`,
|
||||
body: 'This removes it from the config.',
|
||||
})
|
||||
if (!ok) return
|
||||
const next = alerts.filter((_, i) => i !== idx)
|
||||
void onSave({ ...model, Alerts: next }, `Deleted ${target.Name}`)
|
||||
},
|
||||
[model, alerts, onSave, confirm],
|
||||
)
|
||||
|
||||
const setAlertVia = useCallback(
|
||||
(idx: number, v: string) => {
|
||||
if (!model) return
|
||||
const via = v === 'direct' ? '' : v
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Via: via || undefined } : a))
|
||||
void onSave(
|
||||
{ ...model, Alerts: next },
|
||||
via ? `${next[idx].Name} delivers via ${via}` : `${next[idx].Name} delivers direct`,
|
||||
)
|
||||
},
|
||||
[model, alerts, onSave],
|
||||
)
|
||||
|
||||
const setAlertFallback = useCallback(
|
||||
(idx: number, on: boolean) => {
|
||||
if (!model) return
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Fallback: on || undefined } : a))
|
||||
void onSave(
|
||||
{ ...model, Alerts: next },
|
||||
`${next[idx].Name} direct fallback ${on ? 'on' : 'off'}`,
|
||||
)
|
||||
},
|
||||
[model, alerts, onSave],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="alr-section" aria-label="Alerts">
|
||||
<header className="alr-sec-hd">
|
||||
<h2 className="alr-sec-title">Alerts</h2>
|
||||
<span className="alr-sec-count mono">
|
||||
{alertsOn} / {alerts.length} on
|
||||
</span>
|
||||
</header>
|
||||
<p className="alr-sec-note">
|
||||
Out-of-band notifications. Delivered <strong>direct to the internet</strong> by default — so a
|
||||
kill-switch or engine-down alert still reaches you when the proxy is down. You can route one
|
||||
through a group, node or egress instead, with a direct fallback if that detour fails.
|
||||
</p>
|
||||
|
||||
<AddAlertForm
|
||||
busy={busy}
|
||||
disabled={!config}
|
||||
taken={alertNames}
|
||||
catalog={alertCatalog}
|
||||
valid={alertValid}
|
||||
onAdd={addAlert}
|
||||
/>
|
||||
|
||||
{loading ? (
|
||||
<ul className="alr-rows" aria-hidden="true">
|
||||
<li className="alr-skel" />
|
||||
</ul>
|
||||
) : alerts.length === 0 ? (
|
||||
<EmptyPlate
|
||||
title="No alerts"
|
||||
body="Add a Telegram bot or a webhook above to get notified when the kill-switch trips, a new device joins, or an apply fails."
|
||||
/>
|
||||
) : (
|
||||
<ul className="alr-rows">
|
||||
{alerts.map((a, i) => (
|
||||
<AlertRow
|
||||
key={`${a.Name}-${i}`}
|
||||
alert={a}
|
||||
busy={busy}
|
||||
catalog={alertCatalog}
|
||||
valid={alertValid}
|
||||
onToggle={(on) => toggleAlert(i, on)}
|
||||
onVia={(v) => setAlertVia(i, v)}
|
||||
onFallback={(on) => setAlertFallback(i, on)}
|
||||
onDelete={() => removeAlert(i)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---- alert add form + row ----------------------------------------------------
|
||||
|
||||
function AddAlertForm({
|
||||
busy,
|
||||
disabled,
|
||||
taken,
|
||||
catalog,
|
||||
valid,
|
||||
onAdd,
|
||||
}: {
|
||||
busy: boolean
|
||||
disabled: boolean
|
||||
taken: Set<string>
|
||||
catalog: DetourCatalog
|
||||
valid: Set<string>
|
||||
onAdd: (a: Alert) => Promise<boolean>
|
||||
}) {
|
||||
const [name, setName] = useState('')
|
||||
const [type, setType] = useState<'telegram' | 'webhook'>('telegram')
|
||||
const [token, setToken] = useState('')
|
||||
const [chatId, setChatId] = useState('')
|
||||
const [url, setUrl] = useState('')
|
||||
const [events, setEvents] = useState<string[]>(['killswitch'])
|
||||
const [via, setVia] = useState('direct')
|
||||
const [fallback, setFallback] = useState(false)
|
||||
const [err, setErr] = useState<string | null>(null)
|
||||
|
||||
const reset = () => {
|
||||
setName('')
|
||||
setType('telegram')
|
||||
setToken('')
|
||||
setChatId('')
|
||||
setUrl('')
|
||||
setEvents(['killswitch'])
|
||||
setVia('direct')
|
||||
setFallback(false)
|
||||
}
|
||||
|
||||
const toggleEvent = (id: string) =>
|
||||
setEvents((prev) => (prev.includes(id) ? prev.filter((e) => e !== id) : [...prev, id]))
|
||||
|
||||
const submit = async () => {
|
||||
const nm = name.trim()
|
||||
if (!nm) {
|
||||
setErr('Give the alert a name.')
|
||||
return
|
||||
}
|
||||
if (taken.has(nm)) {
|
||||
setErr(`An alert named “${nm}” already exists.`)
|
||||
return
|
||||
}
|
||||
if (type === 'telegram') {
|
||||
if (!token.trim() || !chatId.trim()) {
|
||||
setErr('Telegram needs a bot token and a chat ID.')
|
||||
return
|
||||
}
|
||||
} else if (!HTTP_RE.test(url.trim())) {
|
||||
setErr('Enter an http(s):// webhook URL.')
|
||||
return
|
||||
}
|
||||
if (events.length === 0) {
|
||||
setErr('Pick at least one event to notify on.')
|
||||
return
|
||||
}
|
||||
setErr(null)
|
||||
const routed = via !== 'direct'
|
||||
const routing = { Via: routed ? via : undefined, Fallback: routed && fallback ? true : undefined }
|
||||
const draft: Alert =
|
||||
type === 'telegram'
|
||||
? { Name: nm, Enabled: true, Type: 'telegram', Token: token.trim(), ChatID: chatId.trim(), Events: events, ...routing }
|
||||
: { Name: nm, Enabled: true, Type: 'webhook', URL: url.trim(), Events: events, ...routing }
|
||||
const ok = await onAdd(draft)
|
||||
if (ok) reset()
|
||||
}
|
||||
|
||||
const routed = via !== 'direct'
|
||||
|
||||
return (
|
||||
<form
|
||||
className="alr-add"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
void submit()
|
||||
}}
|
||||
>
|
||||
<div className="alr-add-top">
|
||||
<input
|
||||
className="alr-input alr-input--name"
|
||||
type="text"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Alert name"
|
||||
aria-label="Alert name"
|
||||
value={name}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<div className="alr-seg" role="group" aria-label="Alert type">
|
||||
<button
|
||||
type="button"
|
||||
className={type === 'telegram' ? 'alr-seg-btn on' : 'alr-seg-btn'}
|
||||
aria-pressed={type === 'telegram'}
|
||||
onClick={() => setType('telegram')}
|
||||
disabled={busy || disabled}
|
||||
>
|
||||
Telegram
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={type === 'webhook' ? 'alr-seg-btn on' : 'alr-seg-btn'}
|
||||
aria-pressed={type === 'webhook'}
|
||||
onClick={() => setType('webhook')}
|
||||
disabled={busy || disabled}
|
||||
>
|
||||
Webhook
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{type === 'telegram' ? (
|
||||
<>
|
||||
<input
|
||||
className="alr-input"
|
||||
type="password"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Bot token (kept secret)"
|
||||
aria-label="Telegram bot token"
|
||||
value={token}
|
||||
onChange={(e) => {
|
||||
setToken(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<input
|
||||
className="alr-input"
|
||||
type="text"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Chat ID (e.g. -1001234567890)"
|
||||
aria-label="Telegram chat ID"
|
||||
value={chatId}
|
||||
onChange={(e) => {
|
||||
setChatId(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<input
|
||||
className="alr-input"
|
||||
type="text"
|
||||
inputMode="url"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="https://hooks.example.com/…"
|
||||
aria-label="Webhook URL"
|
||||
value={url}
|
||||
onChange={(e) => {
|
||||
setUrl(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
)}
|
||||
|
||||
<fieldset className="alr-events" aria-label="Events to notify on">
|
||||
{ALERT_EVENTS.map((ev) => (
|
||||
<label key={ev.id} className="alr-event">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={events.includes(ev.id)}
|
||||
onChange={() => toggleEvent(ev.id)}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<span>{ev.label}</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
|
||||
<div className="alr-delivery">
|
||||
<label className="alr-resp">
|
||||
<span className="alr-resp-label mono">Deliver via</span>
|
||||
<DetourSelect
|
||||
value={via}
|
||||
catalog={catalog}
|
||||
valid={valid}
|
||||
busy={busy}
|
||||
disabled={disabled}
|
||||
ariaLabel="Deliver alert via"
|
||||
onChange={setVia}
|
||||
directLabel="Direct (default)"
|
||||
/>
|
||||
</label>
|
||||
<label className="alr-fallback">
|
||||
<Toggle
|
||||
pressed={fallback}
|
||||
onChange={setFallback}
|
||||
label={fallback ? 'Disable direct fallback' : 'Enable direct fallback'}
|
||||
disabled={busy || disabled || !routed}
|
||||
/>
|
||||
<span className="alr-fallback-label mono">Fallback to direct</span>
|
||||
</label>
|
||||
</div>
|
||||
{routed && !fallback && (
|
||||
<p className="alr-note" role="note">
|
||||
{VIA_NO_FALLBACK_NOTE}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="alr-add-actions">
|
||||
{err && (
|
||||
<p className="alr-field-err" role="alert">
|
||||
{err}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" variant="primary" disabled={busy || disabled}>
|
||||
{busy ? 'Saving…' : 'Add alert'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertRow({
|
||||
alert,
|
||||
busy,
|
||||
catalog,
|
||||
valid,
|
||||
onToggle,
|
||||
onVia,
|
||||
onFallback,
|
||||
onDelete,
|
||||
}: {
|
||||
alert: Alert
|
||||
busy: boolean
|
||||
catalog: DetourCatalog
|
||||
valid: Set<string>
|
||||
onToggle: (on: boolean) => void
|
||||
onVia: (v: string) => void
|
||||
onFallback: (on: boolean) => void
|
||||
onDelete: () => void
|
||||
}) {
|
||||
// Never render the token/URL in clear — show a masked descriptor only.
|
||||
const detail = useMemo(() => {
|
||||
if (alert.Type === 'telegram') {
|
||||
return { text: `chat ${alert.ChatID || '—'}`, masked: !!alert.Token }
|
||||
}
|
||||
const { host, masked } = maskUrl(alert.URL ?? '')
|
||||
return { text: host, masked: masked || !!alert.URL }
|
||||
}, [alert.Type, alert.ChatID, alert.Token, alert.URL])
|
||||
|
||||
const events = asArray(alert.Events)
|
||||
const canon = useMemo(() => canonDetour(alert.Via, catalog), [alert.Via, catalog])
|
||||
const route = useMemo(() => describeDetour(canon, catalog, valid), [canon, catalog, valid])
|
||||
const routed = canon !== 'direct'
|
||||
const fallback = alert.Fallback ?? false
|
||||
|
||||
return (
|
||||
<li className="alr-row">
|
||||
<Toggle
|
||||
pressed={alert.Enabled}
|
||||
onChange={onToggle}
|
||||
label={`${alert.Enabled ? 'Disable' : 'Enable'} alert ${alert.Name}`}
|
||||
disabled={busy}
|
||||
/>
|
||||
<div className="alr-row-main">
|
||||
<div className="alr-row-l1">
|
||||
<span className="alr-row-name">{alert.Name}</span>
|
||||
<span className="alr-badge">{alert.Type}</span>
|
||||
{events.map((e) => (
|
||||
<span key={e} className="alr-badge alr-badge--accent">
|
||||
{e}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="alr-row-l2 mono">
|
||||
<span className="alr-row-detail">{detail.text}</span>
|
||||
{detail.masked && (
|
||||
<span className="alr-masked" title="Secret is stored but hidden here">
|
||||
secret hidden
|
||||
</span>
|
||||
)}
|
||||
{route.direct ? (
|
||||
<span className="alr-path">direct</span>
|
||||
) : (
|
||||
<span className="alr-path" data-active="on" data-missing={route.missing ? 'y' : undefined}>
|
||||
{route.prefix} <strong className="alr-path-name">{route.name}</strong>
|
||||
{route.missing && <span className="alr-path-flag"> (missing)</span>}
|
||||
{fallback ? ' · +direct fallback' : ' · no fallback'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{routed && !fallback && <p className="alr-note alr-note--row">{VIA_NO_FALLBACK_NOTE}</p>}
|
||||
</div>
|
||||
<div className="alr-ctl">
|
||||
<label className="alr-detour">
|
||||
<span className="alr-detour-label mono">Deliver via</span>
|
||||
<DetourSelect
|
||||
value={canon}
|
||||
catalog={catalog}
|
||||
valid={valid}
|
||||
busy={busy}
|
||||
disabled={false}
|
||||
ariaLabel={`Deliver alert ${alert.Name} via`}
|
||||
onChange={onVia}
|
||||
directLabel="Direct (default)"
|
||||
/>
|
||||
</label>
|
||||
<label className="alr-fallback">
|
||||
<Toggle
|
||||
pressed={fallback}
|
||||
onChange={onFallback}
|
||||
label={`${fallback ? 'Disable' : 'Enable'} direct fallback for ${alert.Name}`}
|
||||
disabled={busy || !routed}
|
||||
/>
|
||||
<span className="alr-fallback-label mono">Fallback to direct</span>
|
||||
</label>
|
||||
</div>
|
||||
<Button
|
||||
className="alr-del"
|
||||
onClick={onDelete}
|
||||
disabled={busy}
|
||||
aria-label={`Delete alert ${alert.Name}`}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/** The live delivery picker: option list built from the Model's targets. */
|
||||
function DetourSelect({
|
||||
value,
|
||||
catalog,
|
||||
valid,
|
||||
busy,
|
||||
disabled,
|
||||
ariaLabel,
|
||||
onChange,
|
||||
directLabel = 'Direct (no proxy)',
|
||||
}: {
|
||||
value: string // canonical value
|
||||
catalog: DetourCatalog
|
||||
valid: Set<string>
|
||||
busy: boolean
|
||||
disabled: boolean
|
||||
ariaLabel: string
|
||||
onChange: (v: string) => void
|
||||
directLabel?: string
|
||||
}) {
|
||||
const missing = value !== 'direct' && !valid.has(value)
|
||||
return (
|
||||
<select
|
||||
className="alr-select alr-detour-select"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={busy || disabled}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
<option value="direct">{directLabel}</option>
|
||||
{catalog.groups.length > 0 && (
|
||||
<optgroup label="Groups">
|
||||
{catalog.groups.map((g) => (
|
||||
<option key={g} value={`group:${g}`}>
|
||||
Group {g} (balancer)
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{catalog.chains.length > 0 && (
|
||||
<optgroup label="Chains">
|
||||
{catalog.chains.map((c) => (
|
||||
<option key={c} value={`chain:${c}`}>
|
||||
Chain {c}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{catalog.egresses.length > 0 && (
|
||||
<optgroup label="Interfaces / egresses">
|
||||
{catalog.egresses.map((e) => (
|
||||
<option key={e.name} value={`egress:${e.name}`}>
|
||||
Interface/egress {e.name}
|
||||
{e.type ? ` (${e.type})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{catalog.nodes.length > 0 && (
|
||||
<optgroup label="Nodes">
|
||||
{catalog.nodes.map((n) => (
|
||||
<option key={n} value={`node:${n}`}>
|
||||
Node {n}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{missing && <option value={value}>{value} (missing)</option>}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyPlate({ title, body }: { title: string; body: string }) {
|
||||
return (
|
||||
<div className="alr-empty">
|
||||
<span className="alr-empty-title mono">{title}</span>
|
||||
<p className="alr-empty-body">{body}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+76
-32
@@ -11,7 +11,7 @@ import {
|
||||
ApiError,
|
||||
} from '../api'
|
||||
import type { Globals, Status } from '../api'
|
||||
import { engineReadout } from '../planeState'
|
||||
import { engineReadout, killSwitchReadout } from '../planeState'
|
||||
import { onPendingConfirmExpire, usePendingConfirm } from '../pendingConfirm'
|
||||
|
||||
// Short, readable config hash — drops the "sha256:" prefix like the footer does.
|
||||
@@ -103,30 +103,64 @@ export default function Apply() {
|
||||
void loadConfig()
|
||||
}, [loadConfig])
|
||||
|
||||
// The window running out is the daemon reverting on its own — observe it and
|
||||
// say so. The countdown itself ticks inside usePendingConfirm; this only reacts
|
||||
// to the end of it, and the store makes sure that fires exactly once even with
|
||||
// the app-wide band mounted alongside.
|
||||
// The window running out does NOT mean the daemon rolled back.
|
||||
//
|
||||
// apply.ArmRollback captures the data-plane generation when it arms, and on
|
||||
// expiry it compares. If anything re-applied the plane in between — another
|
||||
// panel apply, SIGHUP, a hotplug or the once-a-minute cron reconcile, the WAN
|
||||
// profile auto-switch — it disarms and KEEPS the running config, logging "NOT
|
||||
// rolling back" and nothing else. That is the common case on a production
|
||||
// router, and this page used to print "daemon auto-rolled back to last-good
|
||||
// config" for it: a confident report of an event that did not happen, with a
|
||||
// hash pair underneath that quietly said "unchanged".
|
||||
//
|
||||
// The panel cannot see which branch ran — the daemon says so only in its log.
|
||||
// So it reports the one thing it CAN observe, the live config hash, and waits
|
||||
// for the revert to land before reading it (a rollback is a full re-apply and
|
||||
// does not complete the instant the timer fires).
|
||||
const liveHashRef = useRef('')
|
||||
liveHashRef.current = status?.hash ?? ''
|
||||
useEffect(
|
||||
() =>
|
||||
onPendingConfirmExpire(() => {
|
||||
const before = liveHashRef.current
|
||||
flash('Auto-rolled back')
|
||||
void (async () => {
|
||||
const after = (await refreshStatus())?.hash ?? ''
|
||||
setResult({
|
||||
kind: 'expire',
|
||||
tone: 'warn',
|
||||
text: 'Confirm window elapsed — daemon auto-rolled back to last-good config.',
|
||||
before,
|
||||
after,
|
||||
})
|
||||
})()
|
||||
}),
|
||||
[flash, refreshStatus],
|
||||
)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
const off = onPendingConfirmExpire(() => {
|
||||
const before = liveHashRef.current
|
||||
flash('Confirm window elapsed')
|
||||
setResult({
|
||||
kind: 'expire',
|
||||
tone: 'warn',
|
||||
text: 'Confirm window elapsed. Reading what the daemon did…',
|
||||
before,
|
||||
after: before,
|
||||
})
|
||||
void (async () => {
|
||||
let after = before
|
||||
for (let i = 0; i < 4 && !cancelled; i++) {
|
||||
await new Promise((r) => window.setTimeout(r, 1500))
|
||||
if (cancelled) return
|
||||
after = (await refreshStatus())?.hash ?? after
|
||||
if (after !== before) break
|
||||
}
|
||||
if (cancelled) return
|
||||
setResult({
|
||||
kind: 'expire',
|
||||
tone: 'warn',
|
||||
text:
|
||||
after !== before
|
||||
? 'Confirm window elapsed and the live config changed — the daemon reverted to its last-good config.'
|
||||
: 'Confirm window elapsed and the live config has not changed, so this config is still running. ' +
|
||||
'The daemon only reverts if nothing else re-applied the data plane while the window was open; ' +
|
||||
'otherwise it stands down and keeps what is live. Which one happened is in the daemon log — ' +
|
||||
'download it from Settings, or run `logread -e shater`.',
|
||||
before,
|
||||
after,
|
||||
})
|
||||
})()
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
off()
|
||||
}
|
||||
}, [flash, refreshStatus])
|
||||
|
||||
const confirmWindow = globals?.ConfirmTimeout ?? 0
|
||||
|
||||
@@ -241,6 +275,17 @@ export default function Apply() {
|
||||
// is a status readout, and the config on disk can already differ from what is
|
||||
// installed. Falls back to the config only while /api/status is unread.
|
||||
const killArmed = (status?.kill_switch ?? globals?.KillSwitch ?? 'closed') === 'closed'
|
||||
// Whether that setting is actually installed — same three-plus-unknown reading
|
||||
// as Overview, so the two pages cannot disagree about the same router.
|
||||
const kill = killSwitchReadout(status, globals?.KillSwitch)
|
||||
const killWord =
|
||||
kill.state === 'open'
|
||||
? 'open'
|
||||
: kill.state === 'armed'
|
||||
? 'fail-closed'
|
||||
: kill.state === 'inert'
|
||||
? 'closed · not in effect'
|
||||
: 'closed · not reported'
|
||||
// Every engine mark on this page comes from ONE reading, and that reading is
|
||||
// able to say "stopped" — see planeState.engineState for why `status.running`
|
||||
// could not. This page is where someone lands when the network is down; three
|
||||
@@ -282,11 +327,7 @@ export default function Apply() {
|
||||
variant={dataVariant}
|
||||
value={status?.table ? 'nft installed' : 'no table'}
|
||||
/>
|
||||
<StatusPip
|
||||
label="Kill-switch"
|
||||
variant={killArmed ? 'on' : 'amber'}
|
||||
value={killArmed ? 'fail-closed' : 'open'}
|
||||
/>
|
||||
<StatusPip label="Kill-switch" variant={kill.variant} value={killWord} />
|
||||
</div>
|
||||
|
||||
{statusError && (
|
||||
@@ -320,7 +361,7 @@ export default function Apply() {
|
||||
v: status?.table ? 'nft installed' : 'no table',
|
||||
hot: dataVariant === 'crit',
|
||||
},
|
||||
{ k: 'kill-switch', v: killArmed ? 'fail-closed' : 'open', hot: !killArmed },
|
||||
{ k: 'kill-switch', v: killWord, hot: kill.variant === 'crit' || !killArmed },
|
||||
]}
|
||||
/>
|
||||
<Module
|
||||
@@ -374,8 +415,9 @@ export default function Apply() {
|
||||
is what "live but not kept" means — so the readout survives a
|
||||
reload instead of depending on what this tab remembers. */}
|
||||
Applied config <span className="mono">{liveHash}</span> is live but not yet kept.
|
||||
Confirm to keep it — otherwise the daemon rolls back to the last-good config when
|
||||
the timer hits zero.
|
||||
Confirm to keep it. At zero the daemon rolls back to the last-good config — unless
|
||||
something else re-applies the data plane first, in which case it stands down and
|
||||
keeps whatever is live.
|
||||
</p>
|
||||
<div className="cc-bar" aria-hidden="true">
|
||||
<span className="cc-bar-fill" style={{ width: `${pct}%` }} />
|
||||
@@ -492,7 +534,9 @@ function labelFor(kind: ActionKind): string {
|
||||
case 'rollback':
|
||||
return 'Rollback'
|
||||
case 'expire':
|
||||
return 'Auto-rollback'
|
||||
// NOT "Auto-rollback": on expiry the daemon either reverts or stands down,
|
||||
// and this page cannot tell which. Name the event it did observe.
|
||||
return 'Window elapsed'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -648,73 +648,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* alert delivery: deliver-via picker + fallback toggle + caution note */
|
||||
.dns-alert-delivery {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px 20px;
|
||||
}
|
||||
.dns-fallback {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.dns-fallback-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-label, 0.18em);
|
||||
text-transform: uppercase;
|
||||
color: var(--faint);
|
||||
}
|
||||
/* the per-alert-row delivery controls sit inline in the row (like .dns-detour) */
|
||||
.dns-alert-ctl {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.dns-alert-note {
|
||||
margin: 0;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.5;
|
||||
color: var(--amber);
|
||||
max-width: 56ch;
|
||||
}
|
||||
.dns-alert-note--row {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.dns-alert-ctl {
|
||||
flex-basis: 100%;
|
||||
order: 3;
|
||||
}
|
||||
}
|
||||
|
||||
/* alert event checkboxes */
|
||||
.dns-events {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 16px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
.dns-event {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--fp-text, inherit);
|
||||
cursor: pointer;
|
||||
}
|
||||
.dns-event input {
|
||||
accent-color: var(--fp-accent, currentColor);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.dns-skel {
|
||||
animation: none;
|
||||
|
||||
+1
-480
@@ -9,7 +9,7 @@ import {
|
||||
updateRuleset as apiUpdateRuleset,
|
||||
ApiError,
|
||||
} from '../api'
|
||||
import type { Alert, DNSRule, Model, Resolver, RulesetStatus } from '../api'
|
||||
import type { DNSRule, Model, Resolver, RulesetStatus } from '../api'
|
||||
import { everyLabel, relFetch } from '../format'
|
||||
|
||||
// The DNS / Blocklists page is a thin editor over the desired-state Model —
|
||||
@@ -60,28 +60,9 @@ type GlobalsX = Model['Globals'] & { DNSFilter?: boolean }
|
||||
type DNSModel = Model & {
|
||||
Blocklists?: Blocklist[] | null
|
||||
Allowlists?: Allowlist[] | null
|
||||
Alerts?: Alert[] | null
|
||||
DNSRules?: DNSRule[] | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Every event the daemon actually sends. A retired health-probe event was left
|
||||
* out on purpose: nothing ever fired it, so a channel that subscribed to it would
|
||||
* just stay quiet forever — the one failure mode an alert must not have. Only
|
||||
* events with a live firing path are offered here.
|
||||
*/
|
||||
const ALERT_EVENTS: ReadonlyArray<{ id: string; label: string }> = [
|
||||
{ id: 'killswitch', label: 'Kill-switch' },
|
||||
{ id: 'apply_fail', label: 'Apply failure' },
|
||||
{ id: 'new_device', label: 'New device' },
|
||||
{ id: 'sub_expiry', label: 'Subscription expiring' },
|
||||
]
|
||||
|
||||
// Shown when an alert routes through a detour with no direct fallback — the exact
|
||||
// case where a tunnel-down alert could fail to send. The user asked for this.
|
||||
const VIA_NO_FALLBACK_NOTE =
|
||||
'A kill-switch/tunnel-down alert may not send if it routes through the affected tunnel — enable fallback.'
|
||||
|
||||
// ---- helpers ---------------------------------------------------------------
|
||||
|
||||
const asArray = <T,>(a: T[] | null | undefined): T[] => (a ? a : [])
|
||||
@@ -310,7 +291,6 @@ export default function DNS() {
|
||||
const blocklists = useMemo(() => asArray(config?.Blocklists), [config])
|
||||
const allowlists = useMemo(() => asArray(config?.Allowlists), [config])
|
||||
const resolvers = useMemo<Resolver[]>(() => asArray(config?.Resolvers), [config])
|
||||
const alerts = useMemo<Alert[]>(() => asArray(config?.Alerts), [config])
|
||||
// Ascending Order — the engine evaluates DNS rules first-match, so the list is
|
||||
// shown and edited in the order it actually runs.
|
||||
const dnsRules = useMemo<DNSRule[]>(
|
||||
@@ -719,78 +699,6 @@ export default function DNS() {
|
||||
[config, dnsRules, save, confirm],
|
||||
)
|
||||
|
||||
// ---- alert mutations ------------------------------------------------------
|
||||
const addAlert = useCallback(
|
||||
(draft: Alert): Promise<boolean> => {
|
||||
if (!config) return Promise.resolve(false)
|
||||
const taken = new Set(alerts.map((a) => a.Name))
|
||||
const a: Alert = { ...draft, Name: uniqueName(draft.Name, taken) }
|
||||
return save({ ...config, Alerts: [...alerts, a] }, `Added ${a.Name}`)
|
||||
},
|
||||
[config, alerts, save],
|
||||
)
|
||||
|
||||
const toggleAlert = useCallback(
|
||||
(idx: number, on: boolean) => {
|
||||
if (!config) return
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Enabled: on } : a))
|
||||
void save({ ...config, Alerts: next }, `${next[idx].Name} ${on ? 'enabled' : 'disabled'}`)
|
||||
},
|
||||
[config, alerts, save],
|
||||
)
|
||||
|
||||
const removeAlert = useCallback(
|
||||
async (idx: number) => {
|
||||
if (!config) return
|
||||
const target = alerts[idx]
|
||||
const ok = await confirm({
|
||||
label: 'Delete alert',
|
||||
title: `Delete alert “${target.Name}”?`,
|
||||
body: 'This removes it from the config.',
|
||||
})
|
||||
if (!ok) return
|
||||
const next = alerts.filter((_, i) => i !== idx)
|
||||
void save({ ...config, Alerts: next }, `Deleted ${target.Name}`)
|
||||
},
|
||||
[config, alerts, save, confirm],
|
||||
)
|
||||
|
||||
const setAlertVia = useCallback(
|
||||
(idx: number, v: string) => {
|
||||
if (!config) return
|
||||
const via = v === 'direct' ? '' : v
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Via: via || undefined } : a))
|
||||
void save(
|
||||
{ ...config, Alerts: next },
|
||||
via ? `${next[idx].Name} delivers via ${via}` : `${next[idx].Name} delivers direct`,
|
||||
)
|
||||
},
|
||||
[config, alerts, save],
|
||||
)
|
||||
|
||||
const setAlertFallback = useCallback(
|
||||
(idx: number, on: boolean) => {
|
||||
if (!config) return
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Fallback: on || undefined } : a))
|
||||
void save(
|
||||
{ ...config, Alerts: next },
|
||||
`${next[idx].Name} direct fallback ${on ? 'on' : 'off'}`,
|
||||
)
|
||||
},
|
||||
[config, alerts, save],
|
||||
)
|
||||
|
||||
// Alerts route through Direct/group/node/egress only (no chains) — the contract
|
||||
// vocabulary for Alert.Via. Reuse the resolver detour catalog with chains dropped.
|
||||
const alertCatalog = useMemo<DetourCatalog>(
|
||||
() => ({ ...detourCatalog, chains: [] }),
|
||||
[detourCatalog],
|
||||
)
|
||||
const alertValid = useMemo(() => detourValues(alertCatalog), [alertCatalog])
|
||||
|
||||
const alertNames = useMemo(() => new Set(alerts.map((a) => a.Name)), [alerts])
|
||||
const alertsOn = alerts.filter((a) => a.Enabled).length
|
||||
|
||||
const loading = config === null && loadError === null
|
||||
|
||||
return (
|
||||
@@ -1211,57 +1119,6 @@ export default function DNS() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ---- 5. ALERTS ---- */}
|
||||
<div className="dns-section" aria-label="Alerts">
|
||||
<header className="dns-sec-hd">
|
||||
<h2 className="dns-sec-title">Alerts</h2>
|
||||
<span className="dns-sec-count mono">
|
||||
{alertsOn} / {alerts.length} on
|
||||
</span>
|
||||
</header>
|
||||
<p className="dns-sec-note">
|
||||
Out-of-band notifications. Delivered <strong>direct to the internet</strong> by default — so a
|
||||
kill-switch or engine-down alert still reaches you when the proxy is down. You can route one
|
||||
through a group, node or egress instead, with a direct fallback if that detour fails.
|
||||
</p>
|
||||
|
||||
<AddAlertForm
|
||||
busy={busy}
|
||||
disabled={!config}
|
||||
taken={alertNames}
|
||||
catalog={alertCatalog}
|
||||
valid={alertValid}
|
||||
onAdd={addAlert}
|
||||
/>
|
||||
|
||||
{loading ? (
|
||||
<ul className="dns-rows" aria-hidden="true">
|
||||
<li className="dns-skel" />
|
||||
</ul>
|
||||
) : alerts.length === 0 ? (
|
||||
<EmptyPlate
|
||||
title="No alerts"
|
||||
body="Add a Telegram bot or a webhook above to get notified when the kill-switch trips, a new device joins, or an apply fails."
|
||||
/>
|
||||
) : (
|
||||
<ul className="dns-rows">
|
||||
{alerts.map((a, i) => (
|
||||
<AlertRow
|
||||
key={`${a.Name}-${i}`}
|
||||
alert={a}
|
||||
busy={busy}
|
||||
catalog={alertCatalog}
|
||||
valid={alertValid}
|
||||
onToggle={(on) => toggleAlert(i, on)}
|
||||
onVia={(v) => setAlertVia(i, v)}
|
||||
onFallback={(on) => setAlertFallback(i, on)}
|
||||
onDelete={() => removeAlert(i)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{toast && (
|
||||
<div className="toast" role="status">
|
||||
{toast}
|
||||
@@ -1271,342 +1128,6 @@ export default function DNS() {
|
||||
)
|
||||
}
|
||||
|
||||
// ---- alert add form + row --------------------------------------------------
|
||||
|
||||
function AddAlertForm({
|
||||
busy,
|
||||
disabled,
|
||||
taken,
|
||||
catalog,
|
||||
valid,
|
||||
onAdd,
|
||||
}: {
|
||||
busy: boolean
|
||||
disabled: boolean
|
||||
taken: Set<string>
|
||||
catalog: DetourCatalog
|
||||
valid: Set<string>
|
||||
onAdd: (a: Alert) => Promise<boolean>
|
||||
}) {
|
||||
const [name, setName] = useState('')
|
||||
const [type, setType] = useState<'telegram' | 'webhook'>('telegram')
|
||||
const [token, setToken] = useState('')
|
||||
const [chatId, setChatId] = useState('')
|
||||
const [url, setUrl] = useState('')
|
||||
const [events, setEvents] = useState<string[]>(['killswitch'])
|
||||
const [via, setVia] = useState('direct')
|
||||
const [fallback, setFallback] = useState(false)
|
||||
const [err, setErr] = useState<string | null>(null)
|
||||
|
||||
const reset = () => {
|
||||
setName('')
|
||||
setType('telegram')
|
||||
setToken('')
|
||||
setChatId('')
|
||||
setUrl('')
|
||||
setEvents(['killswitch'])
|
||||
setVia('direct')
|
||||
setFallback(false)
|
||||
}
|
||||
|
||||
const toggleEvent = (id: string) =>
|
||||
setEvents((prev) => (prev.includes(id) ? prev.filter((e) => e !== id) : [...prev, id]))
|
||||
|
||||
const submit = async () => {
|
||||
const nm = name.trim()
|
||||
if (!nm) {
|
||||
setErr('Give the alert a name.')
|
||||
return
|
||||
}
|
||||
if (taken.has(nm)) {
|
||||
setErr(`An alert named “${nm}” already exists.`)
|
||||
return
|
||||
}
|
||||
if (type === 'telegram') {
|
||||
if (!token.trim() || !chatId.trim()) {
|
||||
setErr('Telegram needs a bot token and a chat ID.')
|
||||
return
|
||||
}
|
||||
} else if (!HTTP_RE.test(url.trim())) {
|
||||
setErr('Enter an http(s):// webhook URL.')
|
||||
return
|
||||
}
|
||||
if (events.length === 0) {
|
||||
setErr('Pick at least one event to notify on.')
|
||||
return
|
||||
}
|
||||
setErr(null)
|
||||
const routed = via !== 'direct'
|
||||
const routing = { Via: routed ? via : undefined, Fallback: routed && fallback ? true : undefined }
|
||||
const draft: Alert =
|
||||
type === 'telegram'
|
||||
? { Name: nm, Enabled: true, Type: 'telegram', Token: token.trim(), ChatID: chatId.trim(), Events: events, ...routing }
|
||||
: { Name: nm, Enabled: true, Type: 'webhook', URL: url.trim(), Events: events, ...routing }
|
||||
const ok = await onAdd(draft)
|
||||
if (ok) reset()
|
||||
}
|
||||
|
||||
const routed = via !== 'direct'
|
||||
|
||||
return (
|
||||
<form
|
||||
className="dns-add"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
void submit()
|
||||
}}
|
||||
>
|
||||
<div className="dns-add-top">
|
||||
<input
|
||||
className="dns-input dns-input--name"
|
||||
type="text"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Alert name"
|
||||
aria-label="Alert name"
|
||||
value={name}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<div className="dns-seg" role="group" aria-label="Alert type">
|
||||
<button
|
||||
type="button"
|
||||
className={type === 'telegram' ? 'dns-seg-btn on' : 'dns-seg-btn'}
|
||||
aria-pressed={type === 'telegram'}
|
||||
onClick={() => setType('telegram')}
|
||||
disabled={busy || disabled}
|
||||
>
|
||||
Telegram
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={type === 'webhook' ? 'dns-seg-btn on' : 'dns-seg-btn'}
|
||||
aria-pressed={type === 'webhook'}
|
||||
onClick={() => setType('webhook')}
|
||||
disabled={busy || disabled}
|
||||
>
|
||||
Webhook
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{type === 'telegram' ? (
|
||||
<>
|
||||
<input
|
||||
className="dns-input"
|
||||
type="password"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Bot token (kept secret)"
|
||||
aria-label="Telegram bot token"
|
||||
value={token}
|
||||
onChange={(e) => {
|
||||
setToken(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<input
|
||||
className="dns-input"
|
||||
type="text"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Chat ID (e.g. -1001234567890)"
|
||||
aria-label="Telegram chat ID"
|
||||
value={chatId}
|
||||
onChange={(e) => {
|
||||
setChatId(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<input
|
||||
className="dns-input"
|
||||
type="text"
|
||||
inputMode="url"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="https://hooks.example.com/…"
|
||||
aria-label="Webhook URL"
|
||||
value={url}
|
||||
onChange={(e) => {
|
||||
setUrl(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
)}
|
||||
|
||||
<fieldset className="dns-events" aria-label="Events to notify on">
|
||||
{ALERT_EVENTS.map((ev) => (
|
||||
<label key={ev.id} className="dns-event">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={events.includes(ev.id)}
|
||||
onChange={() => toggleEvent(ev.id)}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<span>{ev.label}</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
|
||||
<div className="dns-alert-delivery">
|
||||
<label className="dns-resp">
|
||||
<span className="dns-resp-label mono">Deliver via</span>
|
||||
<DetourSelect
|
||||
value={via}
|
||||
catalog={catalog}
|
||||
valid={valid}
|
||||
busy={busy}
|
||||
disabled={disabled}
|
||||
ariaLabel="Deliver alert via"
|
||||
onChange={setVia}
|
||||
directLabel="Direct (default)"
|
||||
/>
|
||||
</label>
|
||||
<label className="dns-fallback">
|
||||
<Toggle
|
||||
pressed={fallback}
|
||||
onChange={setFallback}
|
||||
label={fallback ? 'Disable direct fallback' : 'Enable direct fallback'}
|
||||
disabled={busy || disabled || !routed}
|
||||
/>
|
||||
<span className="dns-fallback-label mono">Fallback to direct</span>
|
||||
</label>
|
||||
</div>
|
||||
{routed && !fallback && (
|
||||
<p className="dns-alert-note" role="note">
|
||||
{VIA_NO_FALLBACK_NOTE}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="dns-add-actions">
|
||||
{err && (
|
||||
<p className="dns-field-err" role="alert">
|
||||
{err}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" variant="primary" disabled={busy || disabled}>
|
||||
{busy ? 'Saving…' : 'Add alert'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertRow({
|
||||
alert,
|
||||
busy,
|
||||
catalog,
|
||||
valid,
|
||||
onToggle,
|
||||
onVia,
|
||||
onFallback,
|
||||
onDelete,
|
||||
}: {
|
||||
alert: Alert
|
||||
busy: boolean
|
||||
catalog: DetourCatalog
|
||||
valid: Set<string>
|
||||
onToggle: (on: boolean) => void
|
||||
onVia: (v: string) => void
|
||||
onFallback: (on: boolean) => void
|
||||
onDelete: () => void
|
||||
}) {
|
||||
// Never render the token/URL in clear — show a masked descriptor only.
|
||||
const detail = useMemo(() => {
|
||||
if (alert.Type === 'telegram') {
|
||||
return { text: `chat ${alert.ChatID || '—'}`, masked: !!alert.Token }
|
||||
}
|
||||
const { host, masked } = maskUrl(alert.URL ?? '')
|
||||
return { text: host, masked: masked || !!alert.URL }
|
||||
}, [alert.Type, alert.ChatID, alert.Token, alert.URL])
|
||||
|
||||
const events = asArray(alert.Events)
|
||||
const canon = useMemo(() => canonDetour(alert.Via, catalog), [alert.Via, catalog])
|
||||
const route = useMemo(() => describeDetour(canon, catalog, valid), [canon, catalog, valid])
|
||||
const routed = canon !== 'direct'
|
||||
const fallback = alert.Fallback ?? false
|
||||
|
||||
return (
|
||||
<li className="dns-row">
|
||||
<Toggle
|
||||
pressed={alert.Enabled}
|
||||
onChange={onToggle}
|
||||
label={`${alert.Enabled ? 'Disable' : 'Enable'} alert ${alert.Name}`}
|
||||
disabled={busy}
|
||||
/>
|
||||
<div className="dns-row-main">
|
||||
<div className="dns-row-l1">
|
||||
<span className="dns-row-name">{alert.Name}</span>
|
||||
<span className="dns-badge">{alert.Type}</span>
|
||||
{events.map((e) => (
|
||||
<span key={e} className="dns-badge dns-badge--accent">
|
||||
{e}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="dns-row-l2 mono">
|
||||
<span className="dns-row-detail">{detail.text}</span>
|
||||
{detail.masked && (
|
||||
<span className="dns-masked" title="Secret is stored but hidden here">
|
||||
secret hidden
|
||||
</span>
|
||||
)}
|
||||
{route.direct ? (
|
||||
<span className="dns-path">direct</span>
|
||||
) : (
|
||||
<span className="dns-path" data-active="on" data-missing={route.missing ? 'y' : undefined}>
|
||||
{route.prefix} <strong className="dns-path-name">{route.name}</strong>
|
||||
{route.missing && <span className="dns-path-flag"> (missing)</span>}
|
||||
{fallback ? ' · +direct fallback' : ' · no fallback'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{routed && !fallback && <p className="dns-alert-note dns-alert-note--row">{VIA_NO_FALLBACK_NOTE}</p>}
|
||||
</div>
|
||||
<div className="dns-alert-ctl">
|
||||
<label className="dns-detour">
|
||||
<span className="dns-detour-label mono">Deliver via</span>
|
||||
<DetourSelect
|
||||
value={canon}
|
||||
catalog={catalog}
|
||||
valid={valid}
|
||||
busy={busy}
|
||||
disabled={false}
|
||||
ariaLabel={`Deliver alert ${alert.Name} via`}
|
||||
onChange={onVia}
|
||||
directLabel="Direct (default)"
|
||||
/>
|
||||
</label>
|
||||
<label className="dns-fallback">
|
||||
<Toggle
|
||||
pressed={fallback}
|
||||
onChange={onFallback}
|
||||
label={`${fallback ? 'Disable' : 'Enable'} direct fallback for ${alert.Name}`}
|
||||
disabled={busy || !routed}
|
||||
/>
|
||||
<span className="dns-fallback-label mono">Fallback to direct</span>
|
||||
</label>
|
||||
</div>
|
||||
<Button
|
||||
className="dns-del"
|
||||
onClick={onDelete}
|
||||
disabled={busy}
|
||||
aria-label={`Delete alert ${alert.Name}`}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
// ---- add form --------------------------------------------------------------
|
||||
|
||||
interface AddDraft {
|
||||
|
||||
@@ -196,6 +196,52 @@
|
||||
border-color: color-mix(in srgb, var(--amber) 55%, var(--groove));
|
||||
color: var(--amber);
|
||||
}
|
||||
/* "not built" — the saved switch says on and the engine has no such outbound. */
|
||||
.badge--crit {
|
||||
border-color: color-mix(in srgb, var(--crit) 55%, var(--groove));
|
||||
color: var(--crit);
|
||||
}
|
||||
|
||||
/* ---- last-apply findings, attached to the row they are about ----
|
||||
Sits under the row's own two lines, inside the row plate, so a node the
|
||||
generator threw away cannot read as an ordinary enabled node. Severity carries
|
||||
the colour; the accent stays reserved for controls. */
|
||||
.row-findings {
|
||||
margin: 6px 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
.row-finding {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid color-mix(in srgb, var(--amber) 40%, var(--groove));
|
||||
border-radius: 6px;
|
||||
background: color-mix(in srgb, var(--sink) 35%, transparent);
|
||||
}
|
||||
.row-finding--critical {
|
||||
border-color: color-mix(in srgb, var(--crit) 45%, var(--groove));
|
||||
}
|
||||
.row-finding-msg {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--ink);
|
||||
max-width: 82ch;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
/* Findings that belong to no single row (see Nodes.tsx globalFindings). */
|
||||
.node-findings {
|
||||
margin-bottom: calc(var(--u, 8px) * 2);
|
||||
}
|
||||
.node-findings .row-findings {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
/* masked-credential marker */
|
||||
.masked {
|
||||
@@ -641,6 +687,20 @@ select.fp-input {
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--faint);
|
||||
}
|
||||
/* A collapsed bucket has to carry its own bad news: a 300-node subscription is
|
||||
closed by default, and the per-row findings inside it are otherwise unreachable
|
||||
without knowing to look. */
|
||||
.group-flagged {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10.5px;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--amber);
|
||||
}
|
||||
.group-rows {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
+131
-2
@@ -6,12 +6,14 @@ import { Button, Led, Toggle, useConfirm } from '../components'
|
||||
import {
|
||||
apply as apiApply,
|
||||
getConfig,
|
||||
getStatus,
|
||||
putConfig,
|
||||
importWg,
|
||||
updateSubscription,
|
||||
ApiError,
|
||||
} from '../api'
|
||||
import type { Model, Node as NodeCfg, Subscription } from '../api'
|
||||
import type { Model, Node as NodeCfg, StatusWarning, Subscription } from '../api'
|
||||
import { entityFindings, findingsByName } from '../findings'
|
||||
import { fmtBytes, fmtDate, fmtUntil } from '../format'
|
||||
|
||||
// The whole page is a thin editor over the desired-state Model: every mutation
|
||||
@@ -519,6 +521,43 @@ export default function Nodes() {
|
||||
void loadConfig()
|
||||
}, [loadConfig])
|
||||
|
||||
// ---- what the last apply said about these nodes ---------------------------
|
||||
//
|
||||
// The generator drops a node it cannot build and names it: an unparseable
|
||||
// share link (generate/outbound.go), a name colliding with a reserved tag, a
|
||||
// WireGuard private key materialised twice (generate/wgdedup.go). Until now
|
||||
// this page never read /api/status, so a node the engine had thrown away
|
||||
// rendered as an ordinary row with a green toggle — the switch said on and
|
||||
// there was no such outbound anywhere in the running config.
|
||||
//
|
||||
// Findings are attached to the ROWS, not summarised at the top: a 300-node
|
||||
// subscription makes a list of names useless, and the row is where the false
|
||||
// reassurance was.
|
||||
const [findings, setFindings] = useState<StatusWarning[]>([])
|
||||
const loadFindings = useCallback(async () => {
|
||||
try {
|
||||
const s = await getStatus()
|
||||
setFindings(entityFindings(s.warnings, ['node', 'subscription']))
|
||||
} catch {
|
||||
// Status is a supplement here, not the page. Keep the last set rather than
|
||||
// clearing it — a dropped poll is not the same as "the problem is fixed".
|
||||
}
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
void loadFindings()
|
||||
}, [loadFindings])
|
||||
|
||||
const nodeFindings = useMemo(
|
||||
() => findingsByName(findings.filter((w) => w.section === 'node')),
|
||||
[findings],
|
||||
)
|
||||
const subFindings = useMemo(
|
||||
() => findingsByName(findings.filter((w) => w.section === 'subscription')),
|
||||
[findings],
|
||||
)
|
||||
// Findings about nodes/subscriptions in general, which belong to no single row.
|
||||
const globalFindings = useMemo(() => findings.filter((w) => !w.name), [findings])
|
||||
|
||||
// ---- toast + persistent apply banner --------------------------------------
|
||||
const [toast, setToast] = useState<string | null>(null)
|
||||
const toastTimer = useRef<number | undefined>(undefined)
|
||||
@@ -573,8 +612,11 @@ export default function Nodes() {
|
||||
flash(`Apply failed — ${errText(e)}`)
|
||||
} finally {
|
||||
setApplying(false)
|
||||
// An apply is exactly what rewrites the findings — including clearing the
|
||||
// ones the operator just fixed.
|
||||
void loadFindings()
|
||||
}
|
||||
}, [flash, loadConfig])
|
||||
}, [flash, loadConfig, loadFindings])
|
||||
|
||||
// ---- node mutations -------------------------------------------------------
|
||||
const nodes = useMemo(() => asArray(config?.Nodes), [config])
|
||||
@@ -994,6 +1036,14 @@ export default function Nodes() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Findings about nodes in general — no single row owns them, so they sit
|
||||
above the lists rather than being dropped for having no name. */}
|
||||
{globalFindings.length > 0 && (
|
||||
<div className="node-findings">
|
||||
<RowFindings findings={globalFindings} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ---- NODES ---- */}
|
||||
<div className="node-section" aria-label="Nodes">
|
||||
<header className="sec-hd">
|
||||
@@ -1149,6 +1199,7 @@ export default function Nodes() {
|
||||
<NodeGroup
|
||||
key={g.key || '__manual__'}
|
||||
group={g}
|
||||
findings={nodeFindings}
|
||||
open={isGroupOpen(g)}
|
||||
busy={busy}
|
||||
egressNames={egressNames}
|
||||
@@ -1238,6 +1289,7 @@ export default function Nodes() {
|
||||
busy={busy}
|
||||
catalog={detourCatalog}
|
||||
valid={detourValid}
|
||||
findings={subFindings.get(s.Name) ?? EMPTY_FINDINGS}
|
||||
onToggle={(on) => toggleSub(i, on)}
|
||||
onDelete={() => removeSub(i)}
|
||||
onEdit={(patch) => editSub(i, patch)}
|
||||
@@ -1264,6 +1316,7 @@ function NodeGroup({
|
||||
open,
|
||||
busy,
|
||||
egressNames,
|
||||
findings,
|
||||
onToggle,
|
||||
onToggleNode,
|
||||
onRemoveNode,
|
||||
@@ -1274,6 +1327,8 @@ function NodeGroup({
|
||||
open: boolean
|
||||
busy: boolean
|
||||
egressNames: string[]
|
||||
/** Last-apply findings per node name (findings.ts findingsByName). */
|
||||
findings: Map<string, StatusWarning[]>
|
||||
onToggle: () => void
|
||||
onToggleNode: (idx: number, on: boolean) => void
|
||||
onRemoveNode: (idx: number) => void
|
||||
@@ -1283,6 +1338,13 @@ function NodeGroup({
|
||||
const panelId = `node-group-${group.key || 'manual'}`
|
||||
// The same inventory count as the section header, scoped to this bucket.
|
||||
const count = useMemo(() => fmtEnabled(group.items.map((i) => i.node)), [group.items])
|
||||
// How many nodes in this bucket the last apply had something to say about —
|
||||
// shown on the COLLAPSED header, because a subscription of 300 nodes is
|
||||
// collapsed by default and the row badge below would never be seen otherwise.
|
||||
const flagged = useMemo(
|
||||
() => group.items.filter(({ node }) => findings.has(node.Name)).length,
|
||||
[group.items, findings],
|
||||
)
|
||||
return (
|
||||
<section className={`node-group${open ? ' node-group--open' : ''}`}>
|
||||
<h3 className="group-hd-wrap">
|
||||
@@ -1296,6 +1358,12 @@ function NodeGroup({
|
||||
<span className="group-caret" aria-hidden="true" />
|
||||
<span className="group-name">{group.label}</span>
|
||||
<span className="group-count mono">{count}</span>
|
||||
{flagged > 0 && (
|
||||
<span className="group-flagged" title="Findings from the last apply">
|
||||
<Led variant="amber" />
|
||||
{flagged} flagged
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</h3>
|
||||
{open && group.key !== '' && (
|
||||
@@ -1312,6 +1380,7 @@ function NodeGroup({
|
||||
node={node}
|
||||
busy={busy}
|
||||
egressNames={egressNames}
|
||||
findings={findings.get(node.Name) ?? EMPTY_FINDINGS}
|
||||
onToggle={(on) => onToggleNode(idx, on)}
|
||||
onDelete={() => onRemoveNode(idx)}
|
||||
onRename={(name, onError) => onRenameNode(idx, name, onError)}
|
||||
@@ -1324,10 +1393,29 @@ function NodeGroup({
|
||||
)
|
||||
}
|
||||
|
||||
/** One shared empty array, so a clean row doesn't get a fresh identity per render. */
|
||||
const EMPTY_FINDINGS: StatusWarning[] = []
|
||||
|
||||
/**
|
||||
* Did the generator say it left this entity OUT of the engine config?
|
||||
*
|
||||
* The producers all end the sentence with the same word — "(skipped)" for an
|
||||
* unparseable share link or a bad WireGuard endpoint (generate/outbound.go),
|
||||
* "skipped" for a name colliding with a reserved tag — and wgdedup says only one
|
||||
* of the duplicates "is kept". Read the daemon's word rather than inventing a
|
||||
* verdict: a finding that does NOT say this may well be about a node that is
|
||||
* running perfectly, and badging it "not built" would be a new lie in place of
|
||||
* the old one.
|
||||
*/
|
||||
function skipped(findings: StatusWarning[]): boolean {
|
||||
return findings.some((f) => /\bskipped\b|\bis kept\b/i.test(f.message))
|
||||
}
|
||||
|
||||
function NodeRow({
|
||||
node,
|
||||
busy,
|
||||
egressNames,
|
||||
findings,
|
||||
onToggle,
|
||||
onDelete,
|
||||
onRename,
|
||||
@@ -1336,6 +1424,8 @@ function NodeRow({
|
||||
node: NodeCfg
|
||||
busy: boolean
|
||||
egressNames: string[]
|
||||
/** What the last apply said about THIS node; empty when it said nothing. */
|
||||
findings: StatusWarning[]
|
||||
onToggle: (on: boolean) => void
|
||||
onDelete: () => void
|
||||
onRename: (name: string, onError: (msg: string) => void) => Promise<boolean>
|
||||
@@ -1483,6 +1573,16 @@ function NodeRow({
|
||||
)}
|
||||
<span className="badge">{proto}</span>
|
||||
{node.Stale && <span className="badge badge--warn">stale</span>}
|
||||
{/* The toggle above is the SAVED state. When the last apply couldn't
|
||||
build this node the engine has no such outbound, and the two
|
||||
disagree — so the row says which, rather than leaving a green
|
||||
switch to imply the node is carrying traffic. The word is the
|
||||
daemon's own where it used one. */}
|
||||
{findings.length > 0 && (
|
||||
<span className={`badge badge--${skipped(findings) ? 'crit' : 'warn'}`}>
|
||||
{skipped(findings) ? 'not built' : 'flagged'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{renameErr && (
|
||||
<p className="row-err" role="alert">
|
||||
@@ -1506,6 +1606,7 @@ function NodeRow({
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<RowFindings findings={findings} />
|
||||
</div>
|
||||
<div className="row-actions">
|
||||
{canPin && (
|
||||
@@ -1625,6 +1726,7 @@ function SubRow({
|
||||
busy,
|
||||
catalog,
|
||||
valid,
|
||||
findings,
|
||||
onToggle,
|
||||
onDelete,
|
||||
onEdit,
|
||||
@@ -1635,6 +1737,8 @@ function SubRow({
|
||||
busy: boolean
|
||||
catalog: DetourCatalog
|
||||
valid: Set<string>
|
||||
/** What the last apply said about THIS subscription; empty when it said nothing. */
|
||||
findings: StatusWarning[]
|
||||
onToggle: (on: boolean) => void
|
||||
onDelete: () => void
|
||||
onEdit: (patch: Subscription) => Promise<boolean>
|
||||
@@ -1659,6 +1763,7 @@ function SubRow({
|
||||
<span className="row-name">{sub.Name}</span>
|
||||
{sub.Format && sub.Format !== 'auto' && <span className="badge">{sub.Format}</span>}
|
||||
{sub.FetchVia === 'proxy' && <span className="badge">via proxy</span>}
|
||||
{findings.length > 0 && <span className="badge badge--warn">flagged</span>}
|
||||
</div>
|
||||
<div className="row-line2 mono">
|
||||
<span className="row-host">{host}</span>
|
||||
@@ -1671,6 +1776,7 @@ function SubRow({
|
||||
every {interval} · {count} node{count === 1 ? '' : 's'}
|
||||
</span>
|
||||
</div>
|
||||
<RowFindings findings={findings} />
|
||||
</div>
|
||||
<div className="row-actions">
|
||||
<Button
|
||||
@@ -2142,6 +2248,29 @@ function HeaderRows({
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* What the last apply said about THIS row, under the row it is about.
|
||||
*
|
||||
* Deliberately inside the row rather than in a list at the top of the page: the
|
||||
* failure being fixed is a node that looks fine, and a name in a summary three
|
||||
* screens up does not fix that. The wording is the daemon's own — these messages
|
||||
* already name the entity and say what was done about it ("(skipped)", "only X
|
||||
* is kept"), so paraphrasing them here would only invent a second vocabulary.
|
||||
*/
|
||||
function RowFindings({ findings }: { findings: StatusWarning[] }) {
|
||||
if (findings.length === 0) return null
|
||||
return (
|
||||
<ul className="row-findings" aria-label="Findings from the last apply">
|
||||
{findings.map((f, i) => (
|
||||
<li key={i} className={`row-finding row-finding--${f.severity}`}>
|
||||
<Led variant={f.severity === 'critical' ? 'crit' : 'amber'} />
|
||||
<span className="row-finding-msg">{f.message}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyPlate({ title, body }: { title: string; body: string }) {
|
||||
return (
|
||||
<div className="empty-plate">
|
||||
|
||||
@@ -14,8 +14,8 @@ import type { Model, Stats, Status, StatusWarning } from '../api'
|
||||
import { confirmTimeout } from '../pendingConfirm'
|
||||
import { navigate } from '../router'
|
||||
import type { Route } from '../router'
|
||||
import { attentionFindings } from '../findings'
|
||||
import { engineReadout, protectionState } from '../planeState'
|
||||
import { attentionFindings, truncationNote } from '../findings'
|
||||
import { engineReadout, killSwitchReadout, protectionState } from '../planeState'
|
||||
|
||||
// null-safe length for a Go slice that may arrive as null.
|
||||
const len = (a: unknown[] | null | undefined): number => (a ? a.length : 0)
|
||||
@@ -309,15 +309,19 @@ export function Overview({
|
||||
const engineVariant: LedVariant = engine.variant
|
||||
|
||||
const protection = protectionState(status)
|
||||
// Configured fail-closed AND actually enforcing it. `none` means nothing is
|
||||
// installed, so the setting is inert no matter what it says.
|
||||
const killInEffect = killArmed && status?.plane !== 'none'
|
||||
// Configured fail-closed, actually enforcing it, or not known — three answers,
|
||||
// and the third is not folded into the first. See planeState.killSwitchReadout.
|
||||
const kill = killSwitchReadout(status, g?.KillSwitch)
|
||||
|
||||
// Findings that need attention. `info` notes are statements about the config,
|
||||
// not problems, so they live beside the setting they describe (see findings.ts)
|
||||
// — keeping this list to things someone could actually act on.
|
||||
const warnings = attentionFindings(status?.warnings)
|
||||
const criticalCount = warnings.filter((w) => w.severity === 'critical').length
|
||||
// The daemon caps the published list at 50 and says so in an `info` note — the
|
||||
// one channel this page filters away. Carried separately so the list can admit
|
||||
// it is not the whole list. See findings.ts truncationNote.
|
||||
const truncated = truncationNote(status?.warnings)
|
||||
|
||||
return (
|
||||
<section className="page" aria-label="Overview">
|
||||
@@ -340,7 +344,7 @@ export function Overview({
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Findings warnings={warnings} criticalCount={criticalCount} />
|
||||
<Findings warnings={warnings} criticalCount={criticalCount} truncated={truncated} />
|
||||
|
||||
<div className="grid">
|
||||
{/* Groups, not nodes: a group is where a dial path is defined, so it is the
|
||||
@@ -447,17 +451,17 @@ export function Overview({
|
||||
/>
|
||||
|
||||
{/* A kill-switch set to fail-closed is only ARMED if something is actually
|
||||
installed to enforce it. With no plane it is configured but inert, and
|
||||
saying "ARMED" there would be a false reassurance next to a readout
|
||||
that says nothing is protected. */}
|
||||
installed to enforce it, and "we haven't been told" is neither. With no
|
||||
plane it is configured but inert; with no reading the lamp stays unlit
|
||||
rather than joining the healthy branch by default. */}
|
||||
<Module
|
||||
name="Kill-switch"
|
||||
value={killInEffect ? 'ARMED' : killArmed ? 'NOT IN EFFECT' : 'OPEN'}
|
||||
led={{ variant: killInEffect ? 'on' : killArmed ? 'crit' : 'amber' }}
|
||||
value={kill.value}
|
||||
led={{ variant: kill.variant }}
|
||||
rows={[
|
||||
{ k: 'setting', v: killArmed ? 'fail-closed' : 'fail-open', hot: !killArmed },
|
||||
...(killArmed && !killInEffect
|
||||
? [{ k: 'blocking now', v: 'no — nothing installed', hot: true }]
|
||||
...(kill.blockingNow
|
||||
? [{ k: 'blocking now', v: kill.blockingNow, hot: kill.hot }]
|
||||
: [{ k: 'ipv6', v: g?.IPv6 ? 'covered' : 'off' }]),
|
||||
{ k: 'confirm', v: g?.ConfirmTimeout ? `${g.ConfirmTimeout}s window` : 'no auto-rollback' },
|
||||
]}
|
||||
@@ -536,11 +540,23 @@ const SECTION_ROUTE: Record<string, Route> = {
|
||||
rule: 'routing',
|
||||
ruleset: 'routing',
|
||||
blocklist: 'dns',
|
||||
allowlist: 'dns',
|
||||
resolver: 'dns',
|
||||
dns_rule: 'dns',
|
||||
device: 'devices',
|
||||
chain: 'targets',
|
||||
group: 'targets',
|
||||
// A node the generator dropped (unparseable share link, duplicate WireGuard
|
||||
// key, name colliding with a reserved tag) is reported under `node` — and had
|
||||
// nowhere to jump to, so the one page that could show it a green toggle was
|
||||
// also the one page the finding could not reach.
|
||||
node: 'nodes',
|
||||
subscription: 'nodes',
|
||||
egress: 'targets',
|
||||
inbound: 'networks',
|
||||
interface: 'networks',
|
||||
profile: 'profiles',
|
||||
alert: 'settings',
|
||||
// The standing note about non-TCP/UDP traffic — its control lives on Networks.
|
||||
untunnelable: 'networks',
|
||||
}
|
||||
@@ -558,11 +574,14 @@ const SECTION_ROUTE: Record<string, Route> = {
|
||||
function Findings({
|
||||
warnings,
|
||||
criticalCount,
|
||||
truncated,
|
||||
}: {
|
||||
warnings: StatusWarning[]
|
||||
criticalCount: number
|
||||
/** The daemon's "N further suppressed" note, when the list was capped. */
|
||||
truncated: StatusWarning | null
|
||||
}) {
|
||||
if (warnings.length === 0) return null
|
||||
if (warnings.length === 0 && !truncated) return null
|
||||
|
||||
const rank = { critical: 0, warning: 1, info: 2 } as const
|
||||
const sorted = [...warnings].sort((a, b) => rank[a.severity] - rank[b.severity])
|
||||
@@ -572,6 +591,10 @@ function Findings({
|
||||
<header className="findings-hd">
|
||||
<h2 className="findings-title">Last apply</h2>
|
||||
<span className="findings-count mono">
|
||||
{/* "at least" whenever the list was capped: the counts below it are a
|
||||
floor, not a total, and the cap drops the least severe FIRST — so
|
||||
on a config with fifty criticals the thing it drops is a critical. */}
|
||||
{truncated ? 'at least ' : ''}
|
||||
{criticalCount > 0
|
||||
? `${criticalCount} critical · ${warnings.length} total`
|
||||
: `${warnings.length} note${warnings.length === 1 ? '' : 's'}`}
|
||||
@@ -610,6 +633,20 @@ function Findings({
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
{/* The list saying it is not the whole list. Last, because it is about
|
||||
everything above it — and never filtered out with the other `info`
|
||||
notes, which is where it used to disappear. */}
|
||||
{truncated && (
|
||||
<li className="finding finding--truncated">
|
||||
<Led variant="amber" />
|
||||
<div className="finding-copy">
|
||||
<span className="finding-where mono">list truncated</span>
|
||||
<span className="finding-msg">
|
||||
Some findings are missing from this list. {truncated.message}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@ import './Settings.css'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { Button, Led, Select, Toggle, useConfirm } from '../components'
|
||||
import { AlertsSection } from './Alerts'
|
||||
import { apply as apiApply, downloadLog, getConfig, putConfig, ApiError } from '../api'
|
||||
import type { Globals, LogRange, Model } from '../api'
|
||||
|
||||
@@ -406,7 +407,7 @@ export default function Settings() {
|
||||
|
||||
<Field
|
||||
label="Log level"
|
||||
note="Verbosity of the daemon log. “none” silences the engine and drops the control-plane to panic-only — a turn-down, not a true off: even warnings and errors are hidden. The toggles below decide where whatever is emitted gets written; turning both off is the only full silence. Failures still raise alerts regardless of this level."
|
||||
note="Verbosity of the daemon log. “none” silences the engine and drops the control-plane to panic-only — a turn-down, not a true off: even warnings and errors are hidden. The toggles below decide where whatever is emitted gets written; turning both off is the only full silence. Failures still raise alerts regardless of this level — set up where they go in the Alerts section below."
|
||||
>
|
||||
<Select
|
||||
value={globals?.LogLevel || 'warning'}
|
||||
@@ -620,6 +621,13 @@ export default function Settings() {
|
||||
</Field>
|
||||
</Group>
|
||||
|
||||
{/* ---- ALERTS ---- */}
|
||||
{/* Extracted from the DNS page — out-of-band notifications belong with
|
||||
the appliance-wide knobs, next to the log level whose note points
|
||||
here. Renders its own section header (same plate as a Group); all
|
||||
writes go through `save`, so the dirty banner and toast stay one. */}
|
||||
<AlertsSection config={config} busy={busy} loading={loading} onSave={save} />
|
||||
|
||||
{/* ---- STATISTICS & LOGGING ---- */}
|
||||
<Group
|
||||
title="Statistics & logging"
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { engineReadout, engineState, protectionState } from './planeState.ts'
|
||||
import { engineReadout, engineState, killSwitchReadout, protectionState } from './planeState.ts'
|
||||
import type { Status, Traffic } from './api.ts'
|
||||
|
||||
/** A healthy, fully-installed router; `traffic` is what each case varies. */
|
||||
@@ -189,3 +189,65 @@ test('no status at all is unknown, not down', () => {
|
||||
assert.equal(engineReadout(null).variant, 'off')
|
||||
assert.equal(engineReadout(null).word, 'checking…')
|
||||
})
|
||||
|
||||
// --- killSwitchReadout: "I don't know" is not "it's armed" -------------------
|
||||
//
|
||||
// The Overview module read `killArmed && status?.plane !== 'none'`, and
|
||||
// `undefined !== 'none'` is true — so a daemon that never reported `plane`, and
|
||||
// the seconds before the first status arrives, both lit a green lamp over the
|
||||
// word ARMED. These pin the fourth answer that expression could not express.
|
||||
|
||||
test('a daemon that does not report `plane` reads as not reported, never ARMED', () => {
|
||||
const { plane, ...noPlane } = status()
|
||||
void plane
|
||||
const k = killSwitchReadout(noPlane as Status)
|
||||
assert.equal(k.state, 'unknown')
|
||||
assert.notEqual(k.value, 'ARMED')
|
||||
assert.equal(k.variant, 'off')
|
||||
assert.notEqual(k.variant, 'on')
|
||||
assert.equal(k.blockingNow, 'not known')
|
||||
})
|
||||
|
||||
test('no status at all is unknown too, and says there is no reading', () => {
|
||||
const k = killSwitchReadout(null)
|
||||
assert.equal(k.state, 'unknown')
|
||||
assert.equal(k.variant, 'off')
|
||||
assert.equal(k.blockingNow, 'no reading yet')
|
||||
})
|
||||
|
||||
test('fail-closed with a plane installed is armed', () => {
|
||||
for (const plane of ['full', 'hold'] as const) {
|
||||
const k = killSwitchReadout(status({ plane }))
|
||||
assert.equal(k.state, 'armed')
|
||||
assert.equal(k.value, 'ARMED')
|
||||
assert.equal(k.variant, 'on')
|
||||
assert.equal(k.blockingNow, null)
|
||||
}
|
||||
})
|
||||
|
||||
test('fail-closed with no plane is configured but blocking nothing', () => {
|
||||
const k = killSwitchReadout(status({ plane: 'none', table: false }))
|
||||
assert.equal(k.state, 'inert')
|
||||
assert.equal(k.value, 'NOT IN EFFECT')
|
||||
assert.equal(k.variant, 'crit')
|
||||
assert.equal(k.hot, true)
|
||||
})
|
||||
|
||||
test('fail-open is the operator’s choice — amber, and never a plane question', () => {
|
||||
for (const plane of ['full', 'none', undefined] as const) {
|
||||
const k = killSwitchReadout(status({ kill_switch: 'open', plane }))
|
||||
assert.equal(k.state, 'open')
|
||||
assert.equal(k.value, 'OPEN')
|
||||
assert.equal(k.variant, 'amber')
|
||||
}
|
||||
})
|
||||
|
||||
test('the live kill_switch wins over the saved one; the saved one only fills a gap', () => {
|
||||
const { kill_switch, ...noKill } = status()
|
||||
void kill_switch
|
||||
// Live says open, config says closed → live wins.
|
||||
assert.equal(killSwitchReadout(status({ kill_switch: 'open' }), 'closed').state, 'open')
|
||||
// Nothing live → fall back to the saved policy.
|
||||
assert.equal(killSwitchReadout(noKill as Status, 'open').state, 'open')
|
||||
assert.equal(killSwitchReadout(noKill as Status, 'closed').state, 'armed')
|
||||
})
|
||||
@@ -71,6 +71,85 @@ export function engineReadout(status: Status | null): { variant: LedVariant; wor
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Is the kill-switch actually blocking anything?
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Four answers, and "unknown" is one of them.
|
||||
*
|
||||
* armed — configured fail-closed AND a data plane is installed to enforce it.
|
||||
* inert — configured fail-closed, but there is no plane. Nothing is blocking.
|
||||
* unknown — the daemon has not said how much plane is installed, so whether the
|
||||
* setting is in force is not known. NEVER paint this green.
|
||||
* open — configured fail-open. Nothing is meant to be blocked.
|
||||
*/
|
||||
export type KillSwitchState = 'armed' | 'inert' | 'unknown' | 'open'
|
||||
|
||||
export interface KillSwitchReadout {
|
||||
state: KillSwitchState
|
||||
/** The word the module puts in its readout. */
|
||||
value: string
|
||||
variant: LedVariant
|
||||
/** Is it blocking right now — the row under the readout. `null` ⇒ nothing to add. */
|
||||
blockingNow: string | null
|
||||
/** True when `blockingNow` is bad news and should be drawn hot. */
|
||||
hot: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* THE UNKNOWN BRANCH IS THE WHOLE POINT. This used to be
|
||||
*
|
||||
* killArmed && status?.plane !== 'none'
|
||||
*
|
||||
* and `undefined !== 'none'` is true — so a daemon that had not reported `plane`
|
||||
* at all, and a panel that had not yet received its first status, both landed in
|
||||
* the "ARMED" branch under a green lamp. Every other unknown in this file is an
|
||||
* unlit socket for exactly this reason (see engineReadout): the kill-switch is
|
||||
* the last thing standing between the LAN and the plain WAN, and "I don't know
|
||||
* whether it is installed" must never be dressed as "it is".
|
||||
*
|
||||
* `configured` is the SAVED policy from /api/config, used only while
|
||||
* /api/status has not reported one. The live value wins wherever it exists, as
|
||||
* everywhere else in the panel: this is a status readout, and the config on disk
|
||||
* can already differ from what is installed.
|
||||
*/
|
||||
export function killSwitchReadout(
|
||||
status: Status | null,
|
||||
configured?: string,
|
||||
): KillSwitchReadout {
|
||||
const closed = (status?.kill_switch ?? configured ?? 'closed') === 'closed'
|
||||
|
||||
if (!closed) {
|
||||
return { state: 'open', value: 'OPEN', variant: 'amber', blockingNow: null, hot: false }
|
||||
}
|
||||
|
||||
switch (status?.plane) {
|
||||
case 'full':
|
||||
case 'hold':
|
||||
// Something is installed, so the fail-closed guard is really in the path.
|
||||
return { state: 'armed', value: 'ARMED', variant: 'on', blockingNow: null, hot: false }
|
||||
case 'none':
|
||||
return {
|
||||
state: 'inert',
|
||||
value: 'NOT IN EFFECT',
|
||||
variant: 'crit',
|
||||
blockingNow: 'no — nothing installed',
|
||||
hot: true,
|
||||
}
|
||||
default:
|
||||
return {
|
||||
state: 'unknown',
|
||||
value: 'NOT REPORTED',
|
||||
variant: 'off',
|
||||
// Terse on purpose: this is a two-column readout row, and the long form
|
||||
// wrapped onto three lines beside a one-word key.
|
||||
blockingNow: status ? 'not known' : 'no reading yet',
|
||||
hot: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `plane` + `engine_running` express the state more precisely than the three
|
||||
* booleans the old status strip exposed (engine active / config enabled / nft
|
||||
|
||||
+48
-1
@@ -1,15 +1,62 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import type { Plugin } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// Minimal ambient for the dev-proxy target override — avoids pulling in @types/node
|
||||
// just for one env read. Vite runs this file under Node where `process` exists.
|
||||
declare const process: { env: Record<string, string | undefined> }
|
||||
|
||||
/** `src/mock.ts`, as the module graph spells it (POSIX-normalised for Windows). */
|
||||
const MOCK_MODULE = 'src/mock.ts'
|
||||
|
||||
/**
|
||||
* Refuse to emit a production bundle that contains the offline fixture backend.
|
||||
*
|
||||
* `src/mock.ts` describes an invented, healthy router: a full config, 122 nodes
|
||||
* with 119 of them alive, "Protected". It exists so `npm run dev` renders without
|
||||
* a daemon. It shipped inside the binary that goes on real hardware, switched on
|
||||
* by nothing more than a `?dev` on the end of the URL — so a link someone was
|
||||
* sent, or a bookmark they saved, showed an appliance in perfect health while
|
||||
* making no request to the appliance at all.
|
||||
*
|
||||
* api.ts now loads it behind `import.meta.env.DEV`, which Vite folds to a literal
|
||||
* `false` for a build, so Rollup drops the dynamic import and the module never
|
||||
* enters the graph. That is a property of a build tool's optimiser, and an
|
||||
* optimiser is not a promise: one refactor that makes the condition non-static
|
||||
* silently puts the fixtures back. So the property is CHECKED rather than
|
||||
* trusted — if `src/mock.ts` reaches any emitted chunk, the build fails here
|
||||
* instead of shipping.
|
||||
*/
|
||||
function assertNoMockFixtures(): Plugin {
|
||||
return {
|
||||
name: 'shater:assert-no-mock-fixtures',
|
||||
apply: 'build',
|
||||
generateBundle(_options, bundle) {
|
||||
const guilty: string[] = []
|
||||
for (const [file, output] of Object.entries(bundle)) {
|
||||
if (output.type !== 'chunk') continue
|
||||
for (const id of output.moduleIds) {
|
||||
if (id.replace(/\\/g, '/').endsWith(MOCK_MODULE)) guilty.push(`${file} ← ${id}`)
|
||||
}
|
||||
}
|
||||
if (guilty.length > 0) {
|
||||
this.error(
|
||||
`the offline fixture backend (${MOCK_MODULE}) reached the production bundle:\n ` +
|
||||
guilty.join('\n ') +
|
||||
`\nFixtures describe a router that does not exist. Keep every path to them behind ` +
|
||||
`\`import.meta.env.DEV\` so Rollup can drop them, and never gate them on a runtime ` +
|
||||
`flag such as a query parameter.`,
|
||||
)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// The SPA is embedded in the forked sing-box binary and served by the daemon on
|
||||
// its own port. Relative base so it works under any mount path; single small
|
||||
// bundle (no code-splitting) keeps the embed simple and the flash budget low.
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
plugins: [react(), assertNoMockFixtures()],
|
||||
base: './',
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
|
||||
Reference in new issue
Block a user