Files
OmniRoute/tests/unit/cli-stop-supervisor-respawn-9455.test.ts
Diego Rodrigues de Sa e Souza e7f6b1d130 feat(radar): flag-gated signed free-model catalog overlay (#9515)
* feat(dashboard): add RADAR_ENABLED flag (default off)

* feat(db): radar feed cache + settings with encrypted supporter key

* feat(radar): signed feed sync with pinned key and version floor

- feedSchema.ts: Zod v4 schema mirroring the server feed format
  (discriminated union on budget.kind, enum constraints, etc.)
- pinnedKeys.ts: Ed25519 SPKI-DER pinned key + env override for forks
- verify.ts: signature verification over exact wire bytes, never throws
- sync.ts: full download/verify/validate/cache pipeline with injectable
  deps, feature-flag gate, opt-in gate, version floor (numeric compare),
  and sanitized error reasons (no stack traces)
- 40 tests covering: contract hash, key handling, sig verification,
  schema validation, version compare, all sync paths (disabled, opt_out,
  invalid_signature, invalid_schema, stale, updated, error), auth header
  injection, and cache-untouched assertions for every failure mode

* feat(radar): read-time overlay merge rules over the free catalog

Pure function applyFeed() merges the cached Radar feed over the static
baseline catalog at read time, honoring 4 rules:

1. Feed never overwrites a local override field.
2. enabled:false disables the entry with disabledBy:"radar" provenance.
3. User-added entry NOT in the feed survives untouched.
4. User deletion tombstone prevents feed resurrection.

getRadarCatalog() accessor in index.ts: flag off / no cache / corrupt
payload all fall back to baseline. Valid cache applies the overlay and
returns feed metadata (version, tier, fetchedAt).

TDD: 19 tests (4 rules + dedup + origin + accessor flag/cache/corrupt/
valid/bad-feed + baselineToMergedEntries converter).

* feat(dashboard): radar catalog and guided setup screens

- API routes: GET /api/radar/catalog, POST /api/radar/sync, POST /api/radar/settings
  - All gated on RADAR_ENABLED flag (404 when off)
  - Error responses via buildErrorBody(), never raw stack/message
  - Settings never echoes clear supporter key (masked omr_****<last4>)
  - Sync delegates to syncRadar() server-side, never proxies feed URL
- Dashboard pages:
  - /dashboard/radar: 4 states (flag off, opt-in pending, empty, populated)
  - /dashboard/radar/setup?provider=X: guided setup with steps, key URL, test connection
  - Uses existing Card component and next-intl patterns
- Sidebar: radar entry in costs group with icon
- i18n: pt-BR and en keys for radarPage and radarSetupPage namespaces
- Tests:
  - radar-api-routes.test.ts: 11 tests (flag-off 404, flag-on shape, error sanitization)
  - radar-page-state.test.ts: 5 tests (pure state logic)
  - All 90 radar tests pass (including prior 74)

* docs(radar): module doc and flag-off inertia test

Add docs/frameworks/RADAR.md covering the flag gate, the separate data-sync
opt-in and privacy promise, the Ed25519 signature/pinned-key security model,
tiers, the read-time overlay merge rules, and the self-hosting env vars —
plus index entries in CLAUDE.md/AGENTS.md/docs/README.md/REPOSITORY_MAP.md.

Document RADAR_FEED_URL and RADAR_FEED_PUBKEY in .env.example and
docs/reference/ENVIRONMENT.md to satisfy check:env-doc-sync, which was
failing on this branch since the sync.ts commit added the reads.

Add tests/unit/radar-inertia.test.ts as the single canonical place asserting
the "RADAR_ENABLED off => zero behavioral delta" claim end to end: the three
/api/radar/* routes 404, the flag resolves to the definition default with no
override, getRadarCatalog() returns exactly the baseline without touching the
cache, and computeFreeModelTotals() keeps its pinned values with the Radar
module imported alongside it.

* fix(db): renumber radar migration to 135 after collision with 134

The base branch introduced 134_proxy_logs_egress_ip while this branch carried
134_radar_cache_settings; the migration runner rejects duplicate numeric prefixes.
This migration has never been applied to a real database (the PR is unmerged), so
no retroactive isSchemaAlreadyApplied guard is needed.

* i18n(radar): translate radar catalog and setup strings to all locales

The UI-coverage ratchet measures (present - placeholder) / total_en, so the
__MISSING__ sentinels that i18n:sync-ui writes do not count as covered — only
real translations restore the metric. Scoped to this PR's namespaces
(radarPage, radarSetupPage, sidebar.radar*) instead of a bulk sync, which would
have pulled ~978 unrelated pending keys into this diff.

Placeholders and code identifiers verified preserved across all 1682 strings.

* fix(radar): trust the served-tier header instead of the signed body field

The signed feed body always carries tier:"live" by design (one signed
artifact per version — rewriting the field server-side per request
would break the exact-bytes Ed25519 signature). The server now returns
the tier ACTUALLY served via the x-omniroute-feed-tier response
header, so free users on a delayed community snapshot no longer see
"Ao vivo (tempo real)" in the UI.

sync.ts now reads and validates that header (falling back to the
body's tier only when the header is absent or holds an unrecognized
value) and stores the served tier in the cache; index.ts already
surfaces cache.tier to the UI unchanged.

* test(combo): shorten an assert message that exceeded the line limit

The assertion added by #9507 was 104 chars, so prettier reformatted it into
five lines on the next commit that touched the file, pushing it past its
frozen size (3449) and failing check:file-size. The message is shortened
(the issue reference stays in the comment directly above); the assertion
itself is unchanged, and the file is back to 3448 lines and prettier-clean.

* i18n(radar): use the canonical zh-TW glossary terms

The machine translation produced retired renderings the glossary gate blocks:
供應商 for provider (canonical 提供者) and 文檔 for documentation (canonical 文件).
Fixed across the 11 affected radar strings; tests/unit/i18n-glossary-consistency-check.test.ts
is back to 17/17.

* fix(radar): point the default feed URL at the domain that exists

radar.omniroute.dev was a placeholder for a domain that was never registered,
so an out-of-the-box sync would fail DNS resolution for every user. The live
feed is served from radar.omniroute.online (the subdomain the design always
specified), now behind Cloudflare TLS. Forks still override it via
RADAR_FEED_URL.

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-08-06 05:58:58 -03:00

230 lines
8.6 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
// Repro for #9455: omniroute stop reports success but supervisor respawns child.
//
// Defect 1: runStopCommand() kills the child ("server") PID but never stops the
// supervisor, which immediately respawns the child. The fix must have stop.mjs
// read the "supervisor" PID file and SIGTERM the supervisor FIRST (its handler
// sets isShuttingDown=true, kills the child, exits cleanly — no respawn).
// Plus serve.mjs must persist the supervisor PID via writePidFile("supervisor", ...).
//
// Defect 2: killByPort() was a no-op on win32 (`if (process.platform === "win32") return;`)
// yet runStopCommand still printed "Server stopped." and returned 0. The fix must
// implement a win32 path using netstat -ano + process.kill.
const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
const ORIGINAL_FETCH = globalThis.fetch;
const ORIGINAL_PLATFORM = process.platform;
type KillByPortDeps = {
platform?: string;
execFileAsync?: (cmd: string, args: string[]) => Promise<{ stdout: string; stderr: string }>;
processKill?: (pid: number, signal: string | number) => boolean;
isPidRunning?: (pid: number) => boolean;
sleep?: (ms: number) => Promise<void>;
};
type KillByPortFn = (port: number, deps?: KillByPortDeps) => Promise<boolean>;
function createTempDataDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-stop-sup-"));
}
function setupDataDir(dataDir: string) {
fs.mkdirSync(path.join(dataDir, "server"), { recursive: true });
fs.mkdirSync(path.join(dataDir, "supervisor"), { recursive: true });
}
function setServerPid(dataDir: string, p: number) {
fs.writeFileSync(path.join(dataDir, "server", ".pid"), String(p), "utf8");
}
function setSupervisorPid(dataDir: string, p: number) {
fs.writeFileSync(path.join(dataDir, "supervisor", ".pid"), String(p), "utf8");
}
async function withEnv(fn: (dataDir: string) => Promise<void>) {
const dataDir = createTempDataDir();
process.env.DATA_DIR = dataDir;
globalThis.fetch = (async () => {
throw new Error("server offline");
}) as typeof fetch;
const origLog = console.log;
const origErr = console.error;
console.log = () => {};
console.error = () => {};
try {
await fn(dataDir);
} finally {
console.log = origLog;
console.error = origErr;
globalThis.fetch = ORIGINAL_FETCH;
if (ORIGINAL_DATA_DIR === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = ORIGINAL_DATA_DIR;
}
}
// Track process.kill calls so the test can assert which PIDs were signalled
// without touching real processes. PIDs >= 1000000 are treated as alive.
function trackKills() {
const kills: Array<{ pid: number; signal: string | number }> = [];
const origKill = process.kill.bind(process);
type KillFn = (pid: number, signal?: NodeJS.Signals | number) => boolean;
const stub: KillFn = (pid, signal = 0) => {
if (signal === 0) {
return pid >= 1000000 ? true : (origKill(pid, 0), true);
}
if (pid >= 1000000) {
kills.push({ pid, signal: signal as string | number });
return true;
}
try {
origKill(pid, signal as NodeJS.Signals);
kills.push({ pid, signal: signal as string | number });
return true;
} catch {
return false;
}
};
(process as unknown as { kill: KillFn }).kill = stub;
return {
kills,
restore() {
(process as unknown as { kill: KillFn }).kill = origKill as KillFn;
},
};
}
test("Defect 1: stop must SIGTERM the supervisor BEFORE the child so it does not respawn (#9455)", async () => {
await withEnv(async (dataDir) => {
setupDataDir(dataDir);
const SUPERVISOR_PID = 1000123;
const CHILD_PID = 1000456;
setSupervisorPid(dataDir, SUPERVISOR_PID);
setServerPid(dataDir, CHILD_PID);
const tracker = trackKills();
try {
const { runStopCommand } = await import("../../bin/cli/commands/stop.mjs");
await runStopCommand({});
const signalled = tracker.kills.map((k) => k.pid);
assert.ok(
signalled.includes(SUPERVISOR_PID),
`supervisor PID ${SUPERVISOR_PID} must be signalled; got ${JSON.stringify(signalled)}`
);
// Supervisor must be signalled before the child (cascade order).
const supIdx = signalled.indexOf(SUPERVISOR_PID);
const childIdx = signalled.indexOf(CHILD_PID);
if (childIdx !== -1) {
assert.ok(
supIdx < childIdx,
`supervisor must be killed before child (supIdx=${supIdx} childIdx=${childIdx})`
);
}
} finally {
tracker.restore();
}
});
});
test("Defect 1b: pid.mjs SERVICES array must include supervisor so killAllSubprocesses reaches it (#9455)", async () => {
const tmpDir = os.tmpdir() + "/omniroute-sup-pid-" + Date.now();
process.env.DATA_DIR = tmpDir;
try {
const { writePidFile, readPidFile } = await import("../../bin/cli/utils/pid.mjs");
const ok = writePidFile("supervisor", 555555);
assert.equal(ok, true, "writePidFile('supervisor', ...) must succeed");
assert.equal(readPidFile("supervisor"), 555555);
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
if (ORIGINAL_DATA_DIR === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = ORIGINAL_DATA_DIR;
}
const pidSrc = fs.readFileSync(path.join(process.cwd(), "bin/cli/utils/pid.mjs"), "utf8");
assert.ok(
/SERVICES\s*=\s*\[[^\]]*"supervisor"[^\]]*\]/.test(pidSrc),
'pid.mjs SERVICES array must include "supervisor"'
);
});
test("Defect 2: killByPort on win32 must actually kill the port listener via netstat -ano (#9455)", async () => {
const FAKE_WIN_PID = 1000789;
const kills: Array<{ pid: number; signal: string | number }> = [];
const deps = {
platform: "win32",
execFileAsync: async (cmd: string, args: string[]) => {
if (cmd.endsWith("netstat")) {
return {
stdout: ` TCP 0.0.0.0:20128 0.0.0.0:0 LISTENING ${FAKE_WIN_PID}\r\n`,
stderr: "",
};
}
return { stdout: "", stderr: "" };
},
processKill: (p: number, sig: string | number) => {
kills.push({ pid: p, signal: sig });
return true;
},
isPidRunning: (_p: number) => false, // pretend SIGTERM already killed it
sleep: async (_ms: number) => {},
};
const { killByPort } = await import("../../bin/cli/commands/stop.mjs");
const freed = await (killByPort as unknown as KillByPortFn)(20128, deps);
assert.equal(freed, true, "port must be reported free after killing the listener");
assert.ok(
kills.some((k) => k.pid === FAKE_WIN_PID),
`win32 killByPort must signal the netstat PID ${FAKE_WIN_PID}; got ${JSON.stringify(kills)}`
);
});
test("Defect 2b: killByPort on win32 with no listener returns true and signals nothing (#9455)", async () => {
const kills: Array<{ pid: number; signal: string | number }> = [];
const deps = {
platform: "win32",
execFileAsync: async (_cmd: string, _args: string[]) => ({ stdout: "", stderr: "" }),
processKill: (p: number, sig: string | number) => {
kills.push({ pid: p, signal: sig });
return true;
},
isPidRunning: (_p: number) => false,
sleep: async (_ms: number) => {},
};
const { killByPort } = await import("../../bin/cli/commands/stop.mjs");
const freed = await (killByPort as unknown as KillByPortFn)(20128, deps);
assert.equal(freed, true);
assert.equal(kills.length, 0, "no PIDs should be signalled when none are listening");
});
test("netstat parsing: only LISTENING lines matching the exact port are selected (#9455)", async () => {
const stdout = [
" TCP 0.0.0.0:20128 0.0.0.0:0 LISTENING 111",
" TCP 127.0.0.1:20128 0.0.0.0:0 LISTENING 222",
" TCP 0.0.0.0:120128 0.0.0.0:0 LISTENING 333", // different port (prefix)
" TCP 0.0.0.0:20128 0.0.0.0:0 TIME_WAIT 444", // not listening
].join("\r\n");
const kills: Array<{ pid: number; signal: string | number }> = [];
const deps = {
platform: "win32",
execFileAsync: async (_cmd: string, _args: string[]) => ({ stdout, stderr: "" }),
processKill: (p: number, sig: string | number) => {
kills.push({ pid: p, signal: sig });
return true;
},
isPidRunning: (_p: number) => false,
sleep: async (_ms: number) => {},
};
const { killByPort } = await import("../../bin/cli/commands/stop.mjs");
await (killByPort as unknown as KillByPortFn)(20128, deps);
const signalled = kills.map((k) => k.pid).sort();
assert.deepEqual(signalled, [111, 222], "only exact-port LISTENING PIDs must be killed");
void ORIGINAL_PLATFORM;
});