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

350 lines
13 KiB
JavaScript

import { setTimeout as sleep } from "node:timers/promises";
import { apiFetch } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";
const PROVIDERS_WITH_OAUTH = [
{ id: "gemini", name: "Google Gemini", flow: "browser" },
{ id: "antigravity", name: "Antigravity", flow: "browser" },
{ id: "windsurf", name: "Windsurf", flow: "browser" },
{ id: "cursor", name: "Cursor", flow: "import" },
{ id: "zed", name: "Zed", flow: "import" },
{ id: "kiro", name: "Amazon Kiro", flow: "social" },
{ id: "claude-code", name: "Claude Code (OAuth)", flow: "browser" },
{ id: "codex", name: "OpenAI Codex (OAuth)", flow: "device" },
{ id: "copilot", name: "GitHub Copilot", flow: "device" },
];
// The user-facing provider id (the one shown by `omniroute oauth providers`)
// is NOT always the backend OAuth provider key the server's /api/oauth/[provider]/...
// route expects. `claude-code` is the CLI-facing alias for Anthropic's Claude
// OAuth, which the server registers under the key `claude` (see
// src/lib/oauth/providers/index.ts). Routing `claude-code` to the unrelated
// `command-code` (CommandCode.ai) provider — as the previous code did — sent
// the device-flow request to /api/providers/command-code/auth/start, which is
// gated by requireManagementAuth and returned 401 for a fresh CLI context
// (issue #9474). Map the alias to the real backend key instead.
const BACKEND_OAUTH_KEY = {
"claude-code": "claude",
};
function resolveBackendKey(id) {
return BACKEND_OAUTH_KEY[id] ?? id;
}
const oauthProviderSchema = [
{ key: "id", header: "Provider ID", width: 16 },
{ key: "name", header: "Name", width: 28 },
{ key: "flow", header: "Flow", width: 10 },
];
const connectionSchema = [
{ key: "id", header: "Connection ID", width: 22 },
{ key: "provider", header: "Provider", width: 16 },
{ key: "name", header: "Name", width: 24 },
{ key: "isActive", header: "Active", formatter: (v) => (v ? "✓" : "✗") },
{ key: "testStatus", header: "Status", width: 12 },
];
async function openBrowser(url) {
try {
const { default: open } = await import("open");
await open(url);
} catch {
// open package not available, ignore silently
}
}
async function pollStatus(endpoint, timeoutMs) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
await sleep(2000);
const res = await apiFetch(endpoint);
if (!res.ok) continue;
const data = await res.json();
if (data.status === "complete" || data.status === "completed") return data;
if (data.status === "error" || data.status === "failed") {
process.stderr.write(`OAuth failed: ${data.error ?? data.message ?? "unknown"}\n`);
process.exit(1);
}
}
process.stderr.write("Timeout waiting for OAuth callback\n");
process.exit(124);
}
async function runBrowserFlow(def, opts) {
// The user-facing id (`def.id`, e.g. "claude-code") must be translated to the
// backend OAuth provider key the server's /api/oauth/[provider]/... route
// expects (e.g. "claude"). The previous implementation called a non-existent
// `/api/oauth/${def.id}/start` action — no such action exists on the server
// (src/app/api/oauth/[provider]/[action]/route.ts), so the browser flow was
// broken for every browser-flow provider. Use the real `authorize` action and
// complete the PKCE (authorization_code / authorization_code_pkce) flow with a
// manual code paste, mirroring the dashboard's manual "input" step.
const backendKey = resolveBackendKey(def.id);
const redirectUri = opts.redirectUri ?? null;
const authorizeUrl = `/api/oauth/${backendKey}/authorize${
redirectUri ? `?redirect_uri=${encodeURIComponent(redirectUri)}` : ""
}`;
const startRes = await apiFetch(authorizeUrl, { method: "GET" });
if (!startRes.ok) {
const detail = await safeErrorBody(startRes);
process.stderr.write(`Failed to start OAuth for ${def.id}: ${startRes.status}${detail}\n`);
process.exit(1);
}
const start = await startRes.json();
const url = start.authUrl ?? start.authorizeUrl ?? start.url;
if (!url) {
const hint = start.error ?? "no authUrl returned by the server";
process.stderr.write(`OAuth unavailable for ${def.id}: ${hint}\n`);
process.exit(1);
}
const { codeVerifier, state, redirectUri: returnedRedirectUri } = start;
const finalRedirectUri = returnedRedirectUri || redirectUri;
process.stdout.write(`\nOpen this URL to authorize:\n ${url}\n\n`);
if (opts.browser !== false) await openBrowser(url);
process.stdout.write(
"After authorizing, paste the callback URL (or the Authentication Code\n" +
"shown on the confirmation page) here:\n"
);
const { createPrompt } = await import("../io.mjs");
const prompt = createPrompt();
const input = await prompt.ask("Callback URL or code");
prompt.close();
const trimmed = input.trim();
if (!trimmed) {
process.stderr.write("No authorization code provided.\n");
process.exit(1);
}
// The Anthropic Claude confirmation page (platform.claude.com/oauth/code/callback)
// shows a raw "Authentication Code" like `code#state` rather than a full URL.
// The dashboard's manual submit (src/shared/components/OAuthModal.tsx) parses
// both forms; mirror that here.
let code = null;
let codeState = state || null;
try {
const cbUrl = new URL(trimmed);
code = cbUrl.searchParams.get("code");
const stateParam = cbUrl.searchParams.get("state") || cbUrl.hash.replace(/^#/, "");
if (stateParam) codeState = stateParam;
} catch {
const [rawCode, rawState] = trimmed.split("#", 2);
code = rawCode || null;
if (rawState) codeState = rawState;
}
if (!code) {
process.stderr.write(
"No authorization code found. Paste the callback URL or the Authentication Code.\n"
);
process.exit(1);
}
const exchangeRes = await apiFetch(`/api/oauth/${backendKey}/exchange`, {
method: "POST",
body: {
code,
redirectUri: finalRedirectUri,
codeVerifier,
...(codeState ? { state: codeState } : {}),
},
});
if (!exchangeRes.ok) {
const detail = await safeErrorBody(exchangeRes);
process.stderr.write(`Token exchange failed: ${exchangeRes.status}${detail}\n`);
process.exit(1);
}
const result = await exchangeRes.json();
const conn = result.connection ?? {};
process.stdout.write(`Authorized: ${conn.email ?? conn.displayName ?? conn.id ?? "connected"}\n`);
}
async function safeErrorBody(res) {
try {
const data = await res.json();
if (data?.error) {
const msg = typeof data.error === "string" ? data.error : data.error?.message;
if (msg) return `: ${msg}`;
}
if (data?.message) return `: ${data.message}`;
} catch {
/* ignore */
}
return "";
}
async function runImportFlow(def, opts) {
const endpoint = opts.importFromSystem
? `/api/oauth/${def.id}/auto-import`
: `/api/oauth/${def.id}/import`;
const res = await apiFetch(endpoint, { method: "POST" });
if (!res.ok) {
process.stderr.write(`Import failed: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
process.stdout.write(`Imported ${data.count ?? 0} connection(s) from ${def.name}\n`);
}
async function runSocialFlow(def, opts) {
let social = opts.social;
if (!social) {
process.stderr.write("--social <google|github> required for kiro\n");
process.exit(2);
}
const startRes = await apiFetch(`/api/oauth/${def.id}/social-authorize`, {
method: "POST",
body: { social },
});
if (!startRes.ok) {
process.stderr.write(`Failed: ${startRes.status}\n`);
process.exit(1);
}
const start = await startRes.json();
const url = start.authorizeUrl ?? start.url;
process.stdout.write(`\nOpen this URL:\n ${url}\n\n`);
if (opts.browser !== false) await openBrowser(url);
process.stderr.write("Waiting for social authorization...\n");
const result = await pollStatus(
`/api/oauth/${def.id}/social-exchange?state=${encodeURIComponent(start.state ?? "")}`,
opts.timeout ?? 300000
);
process.stdout.write(`Authorized: ${result.email ?? result.userId ?? "connected"}\n`);
}
async function runDeviceFlow(def, opts) {
const providerKey = resolveBackendKey(def.id);
const startRes = await apiFetch(`/api/providers/${providerKey}/auth/start`, { method: "POST" });
if (!startRes.ok) {
process.stderr.write(`Failed to start device flow: ${startRes.status}\n`);
process.exit(1);
}
const start = await startRes.json();
process.stdout.write(
`\nDevice code: ${start.userCode ?? start.user_code ?? ""}\nVisit: ${start.verificationUri ?? start.verification_uri}\n\n`
);
if (opts.browser !== false)
await openBrowser(start.verificationUri ?? start.verification_uri ?? "");
process.stderr.write("Waiting for device authorization...\n");
const deadline = Date.now() + (opts.timeout ?? 300000);
const intervalMs = (start.intervalMs ?? start.interval ?? 5) * 1000;
while (Date.now() < deadline) {
await sleep(intervalMs);
const statusRes = await apiFetch(
`/api/providers/${providerKey}/auth/status?state=${encodeURIComponent(start.state ?? "")}`
);
if (!statusRes.ok) continue;
const status = await statusRes.json();
if (status.status === "complete" || status.status === "authorized") {
await apiFetch(`/api/providers/${providerKey}/auth/apply`, {
method: "POST",
body: { state: start.state },
});
process.stdout.write(`Authorized: ${status.account ?? status.email ?? "connected"}\n`);
return;
}
if (status.status === "error") {
process.stderr.write(`Device auth failed: ${status.error}\n`);
process.exit(1);
}
}
process.stderr.write("Timeout\n");
process.exit(124);
}
export async function runOAuthStart(opts, cmd) {
const def = PROVIDERS_WITH_OAUTH.find((p) => p.id === opts.provider);
if (!def) {
process.stderr.write(
`Unknown OAuth provider: ${opts.provider}\nRun: omniroute oauth providers\n`
);
process.exit(2);
}
switch (def.flow) {
case "browser":
return runBrowserFlow(def, opts);
case "import":
return runImportFlow(def, opts);
case "social":
return runSocialFlow(def, opts);
case "device":
return runDeviceFlow(def, opts);
}
}
export async function runOAuthStatus(opts, cmd) {
const globalOpts = cmd.optsWithGlobals();
const params = new URLSearchParams();
if (opts.provider) params.set("provider", opts.provider);
const res = await apiFetch(`/api/providers?${params}`);
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
const data = await res.json();
const connections = (data.providers ?? data.items ?? data).filter(
(c) => c.authType === "oauth" || c.authType === "oauth2"
);
emit(connections, globalOpts, connectionSchema);
}
export async function runOAuthRevoke(opts, cmd) {
if (!opts.yes) {
process.stdout.write(
`Revoke OAuth for ${opts.provider}${opts.connectionId ? ` (${opts.connectionId})` : ""}? (yes/no) `
);
const answer = await new Promise((resolve) => {
process.stdin.setEncoding("utf8");
process.stdin.once("data", (c) => resolve(c.toString().trim().toLowerCase()));
});
if (!answer.startsWith("y")) process.exit(0);
}
const id = opts.connectionId;
const res = id
? await apiFetch(`/api/providers/${id}`, { method: "DELETE" })
: await apiFetch(`/api/oauth/${opts.provider}/revoke`, { method: "POST" });
if (!res.ok) {
process.stderr.write(`Error: ${res.status}\n`);
process.exit(1);
}
process.stdout.write(`Revoked\n`);
}
export function registerOAuth(program) {
const oauth = program.command("oauth").description(t("oauth.description"));
oauth
.command("providers")
.description(t("oauth.providers.description"))
.action(async (opts, cmd) => {
emit(PROVIDERS_WITH_OAUTH, cmd.optsWithGlobals(), oauthProviderSchema);
});
oauth
.command("start")
.description(t("oauth.start.description"))
.requiredOption("--provider <id>", t("oauth.start.provider"))
.option("--no-browser", t("oauth.start.no_browser"))
.option("--import-from-system", t("oauth.start.import_system"))
.option("--social <s>", t("oauth.start.social"))
.option("--timeout <ms>", t("oauth.start.timeout"), parseInt, 300000)
.action(runOAuthStart);
oauth
.command("status")
.description(t("oauth.status.description"))
.option("--provider <id>", t("oauth.status.provider"))
.action(runOAuthStatus);
oauth
.command("revoke")
.description(t("oauth.revoke.description"))
.requiredOption("--provider <id>", t("oauth.revoke.provider"))
.option("--connection-id <id>", t("oauth.revoke.connection_id"))
.option("--yes", t("oauth.revoke.yes"))
.action(runOAuthRevoke);
}