mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-07 15:52:52 +03:00
* 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>
133 lines
5.4 KiB
TypeScript
133 lines
5.4 KiB
TypeScript
import { test } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { spawn } from "node:child_process";
|
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { tmpdir } from "node:os";
|
|
|
|
import { quoteClaudeArgs, resolveClaudeSpawn } from "../../../bin/cli/commands/launch.mjs";
|
|
|
|
const isWindows = process.platform === "win32";
|
|
|
|
// Regression guard for #8246: on Windows the `claude` binary is an npm `.cmd`
|
|
// shim that spawn() cannot resolve without a shell (bare "claude" -> ENOENT).
|
|
// #9454: the native installer ships only `claude.exe`, so the resolver now
|
|
// probes PATH first. With no probe injected (the production path runs
|
|
// `where.exe`), the default on a non-Windows CI host finds nothing and falls
|
|
// back to the npm `.cmd` shim + shell — pinning that fallback contract here.
|
|
test("resolveClaudeSpawn: win32 falls back to claude.cmd + shell when no .exe is on PATH", async () => {
|
|
const { command, shell } = await resolveClaudeSpawn("win32", { probe: async () => null });
|
|
assert.equal(command, "claude.cmd");
|
|
assert.equal(shell, true);
|
|
});
|
|
|
|
test("resolveClaudeSpawn: non-Windows platforms spawn the bare binary without a shell", async () => {
|
|
for (const platform of ["linux", "darwin", "freebsd"]) {
|
|
const { command, shell } = await resolveClaudeSpawn(platform);
|
|
assert.equal(command, "claude", `${platform} command`);
|
|
assert.equal(shell, undefined, `${platform} shell`);
|
|
}
|
|
});
|
|
|
|
// Regression guard: `shell: true` makes Node concatenate argv unescaped
|
|
// (DEP0190), so `-p "two words"` reached claude as `-p two` and the rest of the
|
|
// prompt was parsed as separate arguments.
|
|
test("quoteClaudeArgs leaves argv untouched off Windows (no shell, no quoting)", () => {
|
|
const args = ["-p", "two words", "--model", "sonnet"];
|
|
assert.deepEqual(quoteClaudeArgs(args, "linux"), args);
|
|
});
|
|
|
|
test("quoteClaudeArgs escapes every argument on win32", () => {
|
|
// cmd.exe parses the whole line, so each argument is quoted — not just the
|
|
// ones containing spaces. The exact encoding is asserted by the round-trip
|
|
// test below; here we only pin that nothing is passed through raw.
|
|
const input = ["-p", "two words", "--profile", "auto-best-coding"];
|
|
const quoted = quoteClaudeArgs(input, "win32");
|
|
assert.equal(quoted.length, input.length);
|
|
for (const [i, arg] of quoted.entries()) {
|
|
assert.notEqual(arg, input[i], `argument ${i} must be escaped`);
|
|
assert.match(arg, /"/, `argument ${i} must be quoted`);
|
|
}
|
|
});
|
|
|
|
// The cmd.exe round-trip below is the real proof, but it can only run on
|
|
// Windows. These golden strings pin the exact encoding so CI (Linux) still
|
|
// fails if the escaping changes — e.g. if the double caret-escape required by
|
|
// the `.cmd` shim's %* re-parse is ever reduced back to a single pass.
|
|
test("quoteClaudeArgs: exact win32 encoding (golden)", () => {
|
|
const golden: Array<[string, string]> = [
|
|
["-p", '^^^"-p^^^"'],
|
|
["auto-best-coding", '^^^"auto-best-coding^^^"'],
|
|
["two words", '^^^"two^^^ words^^^"'],
|
|
["a & b", '^^^"a^^^ ^^^&^^^ b^^^"'],
|
|
['q"uote', '^^^"q\\^^^"uote^^^"'],
|
|
["trail\\", '^^^"trail\\\\^^^"'],
|
|
["%PATH%", '^^^"^^^%PATH^^^%^^^"'],
|
|
["", '""'],
|
|
];
|
|
for (const [input, expected] of golden) {
|
|
assert.equal(
|
|
quoteClaudeArgs([input], "win32")[0],
|
|
expected,
|
|
`encoding of ${JSON.stringify(input)}`
|
|
);
|
|
}
|
|
});
|
|
|
|
test("quoteClaudeArgs does not mutate the caller's array", () => {
|
|
const input = ["-p", "two words"];
|
|
quoteClaudeArgs(input, "win32");
|
|
assert.deepEqual(input, ["-p", "two words"]);
|
|
});
|
|
|
|
// The real contract: whatever we hand to spawn(shell:true) must arrive at the
|
|
// child's argv byte-identical. Verified against a probe .cmd through the same
|
|
// cmd.exe path the launcher uses.
|
|
test(
|
|
"quoteClaudeArgs survives a real cmd.exe round-trip",
|
|
{ skip: isWindows ? false : "windows-only: exercises the cmd.exe shell path" },
|
|
async () => {
|
|
const dir = mkdtempSync(join(tmpdir(), "omniroute-argv-"));
|
|
try {
|
|
// Mirror the real shape of `claude.cmd`: an npm .cmd shim forwarding %*
|
|
// to a node script. Printing argv as JSON keeps the oracle exact.
|
|
writeFileSync(join(dir, "argv.mjs"), "console.log(JSON.stringify(process.argv.slice(2)));\n");
|
|
const probe = join(dir, "probe.cmd");
|
|
writeFileSync(probe, ["@echo off", 'node "%~dp0argv.mjs" %*'].join("\r\n") + "\r\n");
|
|
|
|
const args = [
|
|
"-p",
|
|
"In one short line: say BANANA",
|
|
"--append-system-prompt",
|
|
'quotes " and & ampersands | pipes',
|
|
"percent %PATH% and caret ^ and bang !",
|
|
"trailing backslash \\",
|
|
"",
|
|
"--profile",
|
|
"auto-best-coding",
|
|
];
|
|
|
|
const received = await new Promise<string[]>((resolve, reject) => {
|
|
const child = spawn(probe, quoteClaudeArgs(args, "win32"), {
|
|
shell: true,
|
|
windowsHide: true,
|
|
});
|
|
let out = "";
|
|
child.stdout.on("data", (c) => (out += c));
|
|
child.on("error", reject);
|
|
child.on("exit", () => {
|
|
try {
|
|
resolve(JSON.parse(out.trim().split(/\r?\n/).pop() ?? "[]"));
|
|
} catch (err) {
|
|
reject(new Error(`probe did not emit argv JSON: ${out}`, { cause: err }));
|
|
}
|
|
});
|
|
});
|
|
|
|
assert.deepEqual(received, args, "child argv must match what the caller passed");
|
|
} finally {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
}
|
|
);
|