Files
OmniRoute/bin/cli/commands/update.mjs
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

217 lines
7.6 KiB
JavaScript

import { printHeading, printInfo, printSuccess, printError } from "../io.mjs";
import { homedir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { t } from "../i18n.mjs";
const execFileAsync = promisify(execFile);
// This file lives at <pkgRoot>/bin/cli/commands/update.mjs — resolve package
// paths relative to the script, NOT process.cwd(). On a global npm/brew install
// the user's cwd is not the package root, so cwd-relative lookups break (#3295).
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
const PKG_ROOT = path.resolve(SCRIPT_DIR, "..", "..", "..");
const BIN_DIR = path.join(PKG_ROOT, "bin");
export async function getCurrentVersion() {
try {
const { readFileSync } = await import("node:fs");
const pkg = JSON.parse(readFileSync(path.join(PKG_ROOT, "package.json"), "utf-8"));
return pkg.version;
} catch {
return null;
}
}
// `--prefer-online` forces npm to revalidate its HTTP cache against the registry.
// Without it `npm view` can return a stale cached version (e.g. report 3.8.30 as
// "latest" after 3.8.31 was published), so the updater told users on an old build
// they were already on the latest version (#4376). `execFn` is injectable for tests.
export async function getLatestVersion(execFn = execFileAsync) {
try {
const { stdout } = await execFn("npm", ["view", "omniroute", "version", "--prefer-online"], {
timeout: 15000,
});
return stdout.trim();
} catch {
return null;
}
}
function compareVersions(a, b) {
const pa = a.split(".").map(Number);
const pb = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
if ((pa[i] || 0) > (pb[i] || 0)) return 1;
if ((pa[i] || 0) < (pb[i] || 0)) return -1;
}
return 0;
}
export async function createBackup() {
const binPath = BIN_DIR;
const backupDir = path.join(homedir(), ".omniroute", "backups", `omniroute-${Date.now()}`);
try {
const { mkdirSync, cpSync, existsSync } = await import("node:fs");
if (!existsSync(binPath)) return null;
mkdirSync(backupDir, { recursive: true });
const files = ["omniroute.mjs", "cli", "nodeRuntimeSupport.mjs", "mcp-server.mjs"];
for (const f of files) {
const src = path.join(binPath, f);
if (existsSync(src)) {
// cpSync handles both files and directories; the old copyFileSync threw
// EISDIR on the "cli" directory, which was swallowed by the catch (#3295).
cpSync(src, path.join(backupDir, f), { recursive: true });
}
}
return backupDir;
} catch {
return null;
}
}
export function registerUpdate(program) {
program
.command("update")
.description(t("update.checking"))
.option("--check", "Check for available update — exit 0 if up-to-date, exit 1 if outdated")
.option("--apply", "Install latest version automatically (npm install -g)")
.option("--changelog", "Show changelog for the latest release")
.option("--dry-run", "Show what would be updated without applying")
.option("--no-backup", "Skip backup creation")
.option("--yes", "Skip confirmation prompt")
.action(async (opts, cmd) => {
const globalOpts = cmd.optsWithGlobals();
const exitCode = await runUpdateCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
}
export async function runUpdateCommand(opts = {}) {
const checkOnly = opts.check ?? false;
const applyNow = opts.apply ?? false;
const showChangelog = opts.changelog ?? false;
const dryRun = opts.dryRun ?? false;
const skipBackup = !(opts.backup ?? true);
const skipConfirm = opts.yes ?? applyNow;
const current = await getCurrentVersion();
const latest = await getLatestVersion();
if (!current) {
printError("Could not determine current version");
return 1;
}
if (!latest) {
printError("Could not check latest version. Is npm available?");
return 1;
}
if (showChangelog) {
try {
const { stdout } = await execFileAsync("npm", ["view", "omniroute", "changelog"], {
timeout: 10000,
});
if (stdout.trim()) {
console.log(stdout.trim());
} else {
console.log(`Changelog: https://github.com/your-org/omniroute/releases/tag/v${latest}`);
}
} catch {
console.log(`Changelog: https://github.com/your-org/omniroute/releases/tag/v${latest}`);
}
return 0;
}
printHeading("OmniRoute Update");
console.log(` Current version: ${current}`);
console.log(` Latest version: ${latest}`);
const cmp = compareVersions(current, latest);
if (cmp >= 0) {
printSuccess("You are running the latest version!");
return 0;
}
console.log(`\n Update available: ${current}${latest}`);
if (checkOnly) {
console.log("\n Run `omniroute update --apply` to install automatically.");
return 1; // exit 1 = outdated (useful for scripts)
}
if (dryRun) {
console.log("\n [DRY RUN] Would run: npm install -g omniroute@latest --include=optional");
if (!skipBackup) console.log(" [DRY RUN] Would create backup in ~/.omniroute/backups/");
return 0;
}
if (!skipBackup) {
printInfo("Creating backup...");
const backupPath = await createBackup();
if (backupPath) {
printSuccess(`Backup created: ${backupPath}`);
} else {
printError("Failed to create backup. Aborting update.");
return 1;
}
}
if (!skipConfirm) {
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((resolve) =>
rl.question(`Proceed with update to ${latest}? [y/N] `, resolve)
);
rl.close();
if (!/^y(es)?$/i.test(answer)) {
printInfo("Update aborted.");
return 0;
}
}
printInfo("Updating OmniRoute...");
try {
const { execSync } = await import("child_process");
// --include=optional keeps the optionalDependencies (better-sqlite3, keytar,
// tls-client, llmlingua SLM stack) on update so an omit=optional config can't drop them.
execSync("npm install -g omniroute@latest --include=optional", { stdio: "inherit" });
// Trust-but-verify: `npm install -g` exits 0 even when a shadowing local install
// (e.g. ~/node_modules/omniroute ahead of the global prefix on PATH) means the
// binary the user actually runs was not touched. Re-read the running binary's
// version and warn instead of lying about success (#9475).
const afterVersion = await getCurrentVersion();
if (afterVersion && compareVersions(afterVersion, latest) < 0) {
printError(
`Global install updated to ${latest}, but the running binary still reports ${afterVersion}.`
);
console.log(
" A local `node_modules/omniroute` is likely shadowing the global install on PATH."
);
console.log(" Diagnose with:");
console.log(" which -a omniroute");
console.log(" command -v omniroute");
console.log(" npm prefix -g");
console.log(
" Then remove the shadowing local copy (e.g. `npm uninstall omniroute` from its directory)"
);
console.log(" or reorder PATH so the global bin comes first.");
return 1;
}
printSuccess(`Updated to version ${latest}`);
printInfo("Run `omniroute --version` to verify.");
return 0;
} catch (err) {
printError(`Update failed: ${err.message}`);
printInfo("Restore from backup:");
const backupDir = path.join(homedir(), ".omniroute", "backups");
printInfo(` ls ${backupDir}`);
return 1;
}
}