Compare commits

..

1 Commits

Author SHA1 Message Date
diegosouzapw
92fc61374a fix(oauth): align codebuddy-cn OAuth User-Agent with chat/usage (#12702)
OAuth device-code auth/poll and token-refresh for codebuddy-cn presented
CLI/2.63.2 CodeBuddy/2.63.2 while chat-completion and usage/quota requests
presented CLI/2.108.1 CodeBuddy/2.108.1 for the same account. A 45-minor-
version-apart client fingerprint across auth vs. chat calls is exactly the
kind of internally-inconsistent signal an anti-abuse WAF flags as anomalous
(Tencent gateway code 11128 'request illegal').

Centralize the version string into CODEBUDDY_CN_USER_AGENT (exported from
src/lib/oauth/constants/oauth.ts) and reference it from the chat registry
entry and the usage handler so all three surfaces can never drift apart
again. Adds a permanent regression test asserting the OAuth, chat and
usage User-Agent headers all match.
2026-09-10 15:22:15 -03:00
8 changed files with 55 additions and 146 deletions

View File

@@ -35,24 +35,16 @@ export function resolveOpencodeTarget(opts = {}) {
baseUrl = `http://localhost:${Number(opts.port ?? process.env.PORT ?? 20128) || 20128}`;
}
// Precedence: explicit --api-key flag > OMNIROUTE_API_KEY env var > active
// context's management token. A context's accessToken/apiKey is a CLI
// management credential (oma_live_...) with no /v1/* inference scope — it
// must never silently outrank a real inference key the caller supplied
// either as a flag or via the ambient env var (mirrors the explicit >
// ambient-env > context precedence documented in bin/cli/api.mjs's
// buildHeaders()). Only fall back to the context token when neither an
// explicit flag nor the env var is set.
let apiKey = opts.apiKey ?? opts["api-key"];
if (!apiKey) apiKey = process.env.OMNIROUTE_API_KEY || "";
if (!apiKey) {
try {
const c = resolveActiveContext(opts.context ?? process.env.OMNIROUTE_CONTEXT);
apiKey = c?.accessToken || c?.apiKey || "";
apiKey = c?.accessToken || c?.apiKey;
} catch {
/* no context auth */
}
}
if (!apiKey) apiKey = process.env.OMNIROUTE_API_KEY || "";
return { baseUrl: baseUrl.replace(/\/+$/, ""), apiKey };
}
@@ -185,17 +177,8 @@ export function registerSetupOpencode(program) {
"--allow-container-write",
"Write even when the target is inside a container and not mounted from the host"
)
.action(async (opts, cmd) => {
// Commander parses the ancestor program's own global --api-key option
// (bin/cli/program.mjs, bound to .env("OMNIROUTE_API_KEY")) against any
// occurrence of the flag in argv, so it wins the value even when the
// user typed --api-key AFTER `setup-opencode` — this local option's own
// `opts.apiKey` never sees it. cmd.optsWithGlobals() resolves to the
// correct value either way ("globals overwrite locals" is exactly the
// outcome we want here, since the global option is where the value
// always actually lands).
const resolvedOpts = { ...opts, apiKey: cmd.optsWithGlobals().apiKey ?? opts.apiKey };
const code = await runSetupOpencodeCommand(resolvedOpts);
.action(async (opts) => {
const code = await runSetupOpencodeCommand(opts);
if (code !== 0) process.exit(code);
});
}

View File

@@ -0,0 +1 @@
- fix(oauth): align codebuddy-cn OAuth User-Agent with the chat/usage CLI version to avoid WAF false positives (#12702)

View File

@@ -1 +0,0 @@
- fix(cli): setup-opencode no longer sends an active context's management token to `/v1/models` when `--api-key`/`OMNIROUTE_API_KEY` is supplied — an explicit flag or the env var now always outranks the context's token, and the flag itself is no longer swallowed by the parent program's global `--api-key` option (#12783)

View File

@@ -1,3 +1,4 @@
import { CODEBUDDY_CN_USER_AGENT } from "@/lib/oauth/constants/oauth";
import type { RegistryEntry } from "../../shared.ts";
/**
@@ -20,7 +21,7 @@ export const codebuddy_cnProvider: RegistryEntry = {
authType: "oauth",
authHeader: "bearer",
headers: {
"User-Agent": "CLI/2.108.1 CodeBuddy/2.108.1",
"User-Agent": CODEBUDDY_CN_USER_AGENT,
"X-Product": "SaaS",
"X-IDE-Type": "CLI",
"X-IDE-Name": "CLI",

View File

@@ -14,6 +14,8 @@
* packs, "Bonus Pack N" for bonus packs (soonest-expiring first).
*/
import { CODEBUDDY_CN_USER_AGENT } from "@/lib/oauth/constants/oauth";
const USAGE_URL = "https://copilot.tencent.com/v2/billing/meter/get-user-resource";
interface TencentAccount {
@@ -130,7 +132,7 @@ export async function getCodeBuddyCnUsage(
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Accept: "application/json",
"User-Agent": "CLI/2.108.1 CodeBuddy/2.108.1",
"User-Agent": CODEBUDDY_CN_USER_AGENT,
"X-Product": "SaaS",
"X-IDE-Type": "CLI",
"X-IDE-Name": "CLI",

View File

@@ -106,12 +106,21 @@ export const QODER_CONFIG = {
// CodeBuddy CN (Tencent — copilot.tencent.com) OAuth Configuration
// (Custom Device-Auth Flow: POST stateUrl → open authUrl → GET pollUrl?state=).
// No client_id/secret — the upstream CLI ships none.
//
// CODEBUDDY_CN_USER_AGENT is the single source of truth for the CLI/CodeBuddy version
// string. It MUST stay identical across OAuth (this file), chat completions
// (open-sse/config/providers/registry/codebuddy-cn/index.ts) and usage/quota
// (open-sse/services/usage/codebuddy-cn.ts) — a mismatched version string across a
// single account's auth vs. chat calls is exactly the kind of internally-inconsistent
// client fingerprint Tencent's WAF flags as anomalous (#12702).
export const CODEBUDDY_CN_USER_AGENT = "CLI/2.108.1 CodeBuddy/2.108.1";
export const CODEBUDDY_CN_CONFIG = {
baseUrl: "https://copilot.tencent.com",
stateUrl: "https://copilot.tencent.com/v2/plugin/auth/state",
tokenUrl: "https://copilot.tencent.com/v2/plugin/auth/token",
refreshUrl: "https://copilot.tencent.com/v2/plugin/auth/token/refresh",
userAgent: "CLI/2.63.2 CodeBuddy/2.63.2",
userAgent: CODEBUDDY_CN_USER_AGENT,
platform: "CLI",
pollInterval: 5000,
};

View File

@@ -585,3 +585,38 @@ test("codebuddy-cn is treated as a managed dual-auth provider (oauth + apikey ac
"codebuddy-cn must be admitted by the dual-auth gate"
);
});
test("#12702: codebuddy-cn presents the same CLI/CodeBuddy version across OAuth, chat and usage calls", async () => {
// A mismatched version string across a single account's auth vs. chat calls is exactly the
// kind of internally-inconsistent client fingerprint Tencent's WAF flags as anomalous
// (code 11128 "request illegal" / "blocked by security policy"). All three surfaces must
// read from the same CODEBUDDY_CN_USER_AGENT constant so they can never drift apart again.
const oauthUserAgent = CODEBUDDY_CN_CONFIG.userAgent;
const chatUserAgent = REGISTRY["codebuddy-cn"].headers?.["User-Agent"];
assert.equal(
oauthUserAgent,
chatUserAgent,
`codebuddy-cn OAuth User-Agent (${oauthUserAgent}) must match the chat User-Agent (${chatUserAgent})`
);
const { CODEBUDDY_CN_USER_AGENT } = await import("../../src/lib/oauth/constants/oauth.ts");
assert.equal(oauthUserAgent, CODEBUDDY_CN_USER_AGENT);
const origFetch = globalThis.fetch;
let capturedUserAgent: string | undefined;
globalThis.fetch = (async (_url: unknown, init?: RequestInit) => {
capturedUserAgent = (init?.headers as Record<string, string> | undefined)?.["User-Agent"];
return new Response(JSON.stringify({}), { status: 200 });
}) as typeof fetch;
try {
const { getCodeBuddyCnUsage } = await import("../../open-sse/services/usage/codebuddy-cn.ts");
await getCodeBuddyCnUsage("ACCESS_TOKEN", undefined, undefined);
assert.equal(
capturedUserAgent,
CODEBUDDY_CN_USER_AGENT,
"codebuddy-cn usage/quota User-Agent must match the shared constant"
);
} finally {
globalThis.fetch = origFetch;
}
});

View File

@@ -1,121 +0,0 @@
import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { resolveOpencodeTarget } from "../../bin/cli/commands/setup-opencode.mjs";
/** Point OMNIROUTE_CONTEXT config resolution at an isolated, throwaway DATA_DIR. */
function withIsolatedContext(contextConfig, fn) {
const dir = mkdtempSync(join(tmpdir(), "omniroute-setup-opencode-test-"));
const originalDataDir = process.env.DATA_DIR;
process.env.DATA_DIR = dir;
writeFileSync(
join(dir, "config.json"),
JSON.stringify({
version: 1,
currentContext: "remote",
contexts: { remote: contextConfig },
})
);
try {
return fn();
} finally {
if (originalDataDir === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = originalDataDir;
rmSync(dir, { recursive: true, force: true });
}
}
function withEnvApiKey(value, fn) {
const original = process.env.OMNIROUTE_API_KEY;
if (value === undefined) delete process.env.OMNIROUTE_API_KEY;
else process.env.OMNIROUTE_API_KEY = value;
try {
return fn();
} finally {
if (original === undefined) delete process.env.OMNIROUTE_API_KEY;
else process.env.OMNIROUTE_API_KEY = original;
}
}
test("setup-opencode: --api-key typed AFTER the subcommand name is not stolen by the parent program's global option", async () => {
const { createProgram } = await import("../../bin/cli/program.mjs");
const program = createProgram();
const setupOpencode = program.commands.find((c) => c.name() === "setup-opencode");
assert.ok(setupOpencode, "setup-opencode subcommand must be registered");
let capturedApiKey;
setupOpencode._actionHandler = null; // avoid the real network-calling action
setupOpencode.action((opts, cmd) => {
capturedApiKey = cmd.optsWithGlobals().apiKey ?? opts.apiKey;
});
await program.parseAsync(
[
"node",
"omniroute",
"setup-opencode",
"--remote",
"http://100.64.0.1:20128",
"--api-key",
"sk-TESTKEY123",
],
{ from: "node" }
);
assert.equal(
capturedApiKey,
"sk-TESTKEY123",
"the CLI-supplied --api-key value must reach the setup-opencode action handler"
);
});
test("resolveOpencodeTarget: (a) explicit --api-key flag wins over an active context's management token", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ apiKey: "sk-FLAG", context: "remote" });
assert.equal(apiKey, "sk-FLAG");
}
);
});
});
test("resolveOpencodeTarget: (b) OMNIROUTE_API_KEY env wins over an active context's management token when no flag is passed", () => {
withEnvApiKey("sk-ENVKEY", () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ context: "remote" });
assert.equal(apiKey, "sk-ENVKEY");
}
);
});
});
test("resolveOpencodeTarget: (c) the context's token is used only when neither a flag nor the env var is set", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ context: "remote" });
assert.equal(apiKey, "oma_live_CONTEXT_TOKEN");
}
);
});
});
test("resolveOpencodeTarget: falls back to '' when neither a flag, env var, nor a resolvable context is present", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext({ baseUrl: "http://100.64.0.1:20128" }, () => {
const { apiKey } = resolveOpencodeTarget({
remote: "http://100.64.0.1:20128",
context: "__no-such-context__",
});
assert.equal(apiKey, "");
});
});
});