mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-18 13:14:56 +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>
283 lines
9.7 KiB
TypeScript
283 lines
9.7 KiB
TypeScript
/**
|
|
* tests/unit/radar-api-routes.test.ts
|
|
*
|
|
* TDD regression guard for the Radar API routes:
|
|
* - GET /api/radar/catalog: flag off => 404, flag on => shape validated
|
|
* - POST /api/radar/sync: flag off => 404, flag on => delegates to syncRadar
|
|
* - POST /api/radar/settings: flag off => 404, never echoes clear key
|
|
*
|
|
* Error responses must NOT leak stack traces (Hard Rule #12).
|
|
*/
|
|
|
|
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";
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Isolate DB + feature flag state
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-radar-api-"));
|
|
process.env.DATA_DIR = TEST_DATA_DIR;
|
|
process.env.STORAGE_ENCRYPTION_KEY = "test-encryption-key-for-radar-api-tests-32b!";
|
|
|
|
const core = await import("../../src/lib/db/core.ts");
|
|
const radarDb = await import("../../src/lib/db/radar.ts");
|
|
const featureFlags = await import("../../src/shared/utils/featureFlags.ts");
|
|
|
|
// We need to test the route handlers. Since Next.js route handlers are just
|
|
// exported functions, we can import and call them directly with mock Request
|
|
// objects. However, the routes import from @/lib/radar which reads the DB,
|
|
// so we need the DB to be set up.
|
|
|
|
// Helper to create a mock NextRequest-like object
|
|
function mockGetRequest(url = "http://localhost:20128/api/radar/catalog"): Request {
|
|
return new Request(url, { method: "GET" });
|
|
}
|
|
|
|
function mockPostRequest(url: string, body?: unknown): Request {
|
|
return new Request(url, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
});
|
|
}
|
|
|
|
// Helper to reset DB state
|
|
function resetStorage() {
|
|
core.resetDbInstance();
|
|
try {
|
|
if (fs.existsSync(TEST_DATA_DIR)) {
|
|
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
|
}
|
|
} catch {
|
|
// ignore
|
|
}
|
|
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Tests: flag-off behavior (all routes => 404)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("GET /api/radar/catalog: flag off => 404", async () => {
|
|
resetStorage();
|
|
// Ensure flag is off (default)
|
|
delete process.env.RADAR_ENABLED;
|
|
|
|
// Dynamic import to get fresh module state
|
|
const { GET } = await import("../../src/app/api/radar/catalog/route.ts");
|
|
const response = await GET(mockGetRequest());
|
|
const body = await response.json();
|
|
|
|
assert.equal(response.status, 404);
|
|
assert.ok(body.error, "Response should have error field");
|
|
assert.ok(!JSON.stringify(body).includes("at /"), "Response must not leak stack traces");
|
|
});
|
|
|
|
test("POST /api/radar/sync: flag off => 404", async () => {
|
|
resetStorage();
|
|
delete process.env.RADAR_ENABLED;
|
|
|
|
const { POST } = await import("../../src/app/api/radar/sync/route.ts");
|
|
const response = await POST(mockPostRequest("http://localhost:20128/api/radar/sync"));
|
|
const body = await response.json();
|
|
|
|
assert.equal(response.status, 404);
|
|
assert.ok(body.error);
|
|
assert.ok(!JSON.stringify(body).includes("at /"), "Response must not leak stack traces");
|
|
});
|
|
|
|
test("POST /api/radar/settings: flag off => 404", async () => {
|
|
resetStorage();
|
|
delete process.env.RADAR_ENABLED;
|
|
|
|
const { POST } = await import("../../src/app/api/radar/settings/route.ts");
|
|
const response = await POST(
|
|
mockPostRequest("http://localhost:20128/api/radar/settings", { optIn: true }),
|
|
);
|
|
const body = await response.json();
|
|
|
|
assert.equal(response.status, 404);
|
|
assert.ok(body.error);
|
|
assert.ok(!JSON.stringify(body).includes("at /"), "Response must not leak stack traces");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Tests: flag-on behavior
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("GET /api/radar/catalog: flag on, empty cache => baseline entries, meta null", async () => {
|
|
resetStorage();
|
|
process.env.RADAR_ENABLED = "true";
|
|
|
|
// Fresh import to pick up the flag
|
|
const catalogRoute = await import("../../src/app/api/radar/catalog/route.ts");
|
|
const response = await catalogRoute.GET(mockGetRequest());
|
|
const body = await response.json();
|
|
|
|
assert.equal(response.status, 200);
|
|
assert.ok(Array.isArray(body.entries), "entries should be an array");
|
|
assert.ok(body.entries.length > 0, "should have baseline entries");
|
|
assert.equal(body.meta, null, "meta should be null when no cache");
|
|
});
|
|
|
|
test("POST /api/radar/settings: flag on, set opt-in => success, no key in response", async () => {
|
|
resetStorage();
|
|
process.env.RADAR_ENABLED = "true";
|
|
|
|
const settingsRoute = await import("../../src/app/api/radar/settings/route.ts");
|
|
const response = await settingsRoute.POST(
|
|
mockPostRequest("http://localhost:20128/api/radar/settings", {
|
|
optIn: true,
|
|
supporterKey: "omr_abcdef01234567890abcdef01234567890abcdef",
|
|
}),
|
|
);
|
|
const body = await response.json();
|
|
|
|
assert.equal(response.status, 200);
|
|
assert.equal(body.ok, true);
|
|
assert.equal(body.optIn, true);
|
|
// Key must be masked, never the clear value
|
|
assert.ok(body.supporterKey, "should return masked key");
|
|
assert.ok(
|
|
!body.supporterKey.includes("abcdef01234567890abcdef01234567890abcdef"),
|
|
"Must NOT echo the clear key",
|
|
);
|
|
assert.ok(body.supporterKey.startsWith("omr_****"), "Key should be masked with omr_**** prefix");
|
|
assert.ok(body.supporterKey.length <= 12, "Masked key should be short");
|
|
});
|
|
|
|
test("POST /api/radar/settings: invalid body => 400", async () => {
|
|
resetStorage();
|
|
process.env.RADAR_ENABLED = "true";
|
|
|
|
const settingsRoute = await import("../../src/app/api/radar/settings/route.ts");
|
|
const response = await settingsRoute.POST(
|
|
mockPostRequest("http://localhost:20128/api/radar/settings", {
|
|
supporterKey: "invalid-key-format",
|
|
}),
|
|
);
|
|
|
|
assert.equal(response.status, 400);
|
|
const body = await response.json();
|
|
assert.ok(body.error);
|
|
});
|
|
|
|
test("POST /api/radar/settings: empty body => 400", async () => {
|
|
resetStorage();
|
|
process.env.RADAR_ENABLED = "true";
|
|
|
|
const settingsRoute = await import("../../src/app/api/radar/settings/route.ts");
|
|
const response = await settingsRoute.POST(
|
|
mockPostRequest("http://localhost:20128/api/radar/settings", {}),
|
|
);
|
|
|
|
assert.equal(response.status, 400);
|
|
const body = await response.json();
|
|
assert.ok(body.error);
|
|
});
|
|
|
|
test("POST /api/radar/settings: null key clears it", async () => {
|
|
resetStorage();
|
|
process.env.RADAR_ENABLED = "true";
|
|
|
|
const settingsRoute = await import("../../src/app/api/radar/settings/route.ts");
|
|
|
|
// First set a key
|
|
await settingsRoute.POST(
|
|
mockPostRequest("http://localhost:20128/api/radar/settings", {
|
|
supporterKey: "omr_abcdef01234567890abcdef01234567890abcdef",
|
|
}),
|
|
);
|
|
|
|
// Then clear it
|
|
const response = await settingsRoute.POST(
|
|
mockPostRequest("http://localhost:20128/api/radar/settings", {
|
|
supporterKey: null,
|
|
}),
|
|
);
|
|
const body = await response.json();
|
|
|
|
assert.equal(response.status, 200);
|
|
assert.equal(body.supporterKey, null, "Cleared key should return null");
|
|
});
|
|
|
|
test("POST /api/radar/sync: flag on, not opted in => status opt_out", async () => {
|
|
resetStorage();
|
|
process.env.RADAR_ENABLED = "true";
|
|
// Don't set opt-in
|
|
|
|
const syncRoute = await import("../../src/app/api/radar/sync/route.ts");
|
|
const response = await syncRoute.POST(
|
|
mockPostRequest("http://localhost:20128/api/radar/sync"),
|
|
);
|
|
const body = await response.json();
|
|
|
|
assert.equal(response.status, 200);
|
|
assert.equal(body.status, "opt_out");
|
|
});
|
|
|
|
test("POST /api/radar/sync: invalid body => 400", async () => {
|
|
resetStorage();
|
|
process.env.RADAR_ENABLED = "true";
|
|
|
|
const syncRoute = await import("../../src/app/api/radar/sync/route.ts");
|
|
const response = await syncRoute.POST(
|
|
mockPostRequest("http://localhost:20128/api/radar/sync", { unexpected: true }),
|
|
);
|
|
|
|
assert.equal(response.status, 400);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Tests: error sanitization (Hard Rule #12)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("all radar routes: error responses do NOT leak stack traces", async () => {
|
|
resetStorage();
|
|
delete process.env.RADAR_ENABLED;
|
|
|
|
const routes = [
|
|
{ name: "catalog", GET: (await import("../../src/app/api/radar/catalog/route.ts")).GET },
|
|
{ name: "sync", POST: (await import("../../src/app/api/radar/sync/route.ts")).POST },
|
|
{ name: "settings", POST: (await import("../../src/app/api/radar/settings/route.ts")).POST },
|
|
];
|
|
|
|
for (const route of routes) {
|
|
let response: Response;
|
|
if ("GET" in route && route.GET) {
|
|
response = await (route as { GET: (r: Request) => Promise<Response> }).GET(mockGetRequest());
|
|
} else {
|
|
response = await (route as { POST: (r: Request) => Promise<Response> }).POST(
|
|
mockPostRequest(`http://localhost:20128/api/radar/${route.name}`, {}),
|
|
);
|
|
}
|
|
const text = await response.text();
|
|
assert.ok(
|
|
!text.includes("at /"),
|
|
`${route.name}: response must not contain stack-like paths. Got: ${text.slice(0, 200)}`,
|
|
);
|
|
assert.ok(
|
|
!text.includes(".ts:") && !text.includes(".js:"),
|
|
`${route.name}: response must not contain file:line references. Got: ${text.slice(0, 200)}`,
|
|
);
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Cleanup
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test.after(() => {
|
|
core.resetDbInstance();
|
|
delete process.env.RADAR_ENABLED;
|
|
try {
|
|
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
|
} catch {
|
|
// ignore
|
|
}
|
|
});
|