Files
OmniRoute/tests/unit/claudeAuthImport-bootstrap-headers-10144.test.ts
stanley 4540d303d7 fix(oauth): send required CLI headers in claude-auth import bootstrap call (#10144)
* fix(oauth): send required CLI headers in claude-auth import bootstrap call

enrichWithBootstrap() in claudeAuthImport.ts was missing the
User-Agent and anthropic-beta headers that the two other callers of
the same /api/claude_cli/bootstrap endpoint (claudeIdentity.ts and
src/lib/oauth/providers/claude.ts) always send. Without them,
Anthropic doesn't recognize the request as coming from a CLI client
and the bootstrap call fails, silently returning a null identity
(accountUUID/organizationUUID/organizationType all null).

createConnectionFromAuthFile()'s identity-verification refusal then
gets bypassed via overwriteExisting: true (the only way imports
currently succeed, since first attempts fail with
identity_unverified because of this same bug), so every imported
Claude connection ends up with unverified identity.

Downstream, resolveAccountUUID() in claudeIdentity.ts falls back to
a hash-derived fake UUID when providerSpecificData.accountUUID is
null. That fake UUID is shape-valid but was never associated with
the real account by Anthropic, so requests carrying it get
classified as unrecognized third-party traffic and routed to the
separate extra-usage pool instead of the account's plan limits --
producing an intermittent (~50% observed) 400:
"Third-party apps now draw from your extra usage, not your plan
limits." on an otherwise perfectly valid, imported subscription
token.

Fixes the header mismatch so bootstrap succeeds and imported
connections get a real, Anthropic-recognized account identity from
the start, same as connections created via the native OAuth flow.

Fixes #10143

* fix(oauth): persist cliUserID device identity on claude-auth import

createConnectionFromAuthFile() in claudeAuthImport.ts never set
providerSpecificData.cliUserID, unlike the native OAuth setup flow in
src/lib/oauth/providers/claude.ts which always mints one. cliUserID is
read by resolveCliUserID() (open-sse/executors/claudeIdentity.ts) as
the request's device_id; when absent it falls back to a lazy-random
device id regenerated fresh every process restart (in-memory Map,
process-lifetime only), so every restart of an imported connection
presents as a brand-new device to Anthropic for the same account --
a second, independent contributor (alongside Part 1's bootstrap
header fix in this same PR) to the intermittent third-party-usage 400
on valid imported subscription tokens.

- "create new connection" branch: always mint a fresh cliUserID.
- "update existing connection" branch: preserve any already-persisted
  cliUserID from existing.providerSpecificData (don't rotate a working
  device identity on re-import); only mint a fresh one if absent.

Adds changelog.d/fixes/10144-claude-import-cli-user-id.md per
CONTRIBUTING.md.

Fixes #10143

* test(oauth): cover claude-auth import bootstrap headers + cliUserID persistence

Adds tests/unit/claudeAuthImport-bootstrap-headers-10144.test.ts (Rule #18
regression guard for #10143):

1. enrichWithBootstrap() sends the required CLI headers on the
   /api/claude_cli/bootstrap call — a claude-cli User-Agent (now sourced
   from CLAUDE_CODE_CLIENT_VERSION, matching the two working call-sites)
   and anthropic-beta: oauth-2025-04-20 — and still falls back to null
   identity fields on non-OK upstream responses.
2. createConnectionFromAuthFile() mints a 64-hex cliUserID device
   identity on create, preserves an already-persisted cliUserID on
   overwrite re-import (no rotation), and mints a fresh one when the
   existing connection has none.

Also aligns the hardcoded claude-cli/1.0.0 User-Agent in the import
bootstrap with the version constant the two working call-sites
(claudeIdentity.ts, oauth/providers/claude.ts) already use.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

* refactor(oauth): source claude-auth import UA from canonical constant (#10144 review nit)

Addresses the hardcoded-version nit from review: the bootstrap User-Agent was
re-typed as `claude-cli/${CLAUDE_CODE_CLIENT_VERSION}` instead of importing
getClaudeCodeUserAgent() — the single source of truth the two working
call-sites (claudeIdentity.ts, oauth/providers/claude.ts) use.

- claudeAuthImport.ts: use getClaudeCodeUserAgent("cli") for the bootstrap call
- test: import the same canonical helper instead of a local copy of the pinned
  version, and assert the outbound UA byte-for-byte against it, so a future
  version bump can't silently desync the wire identity.

Verified: node --import tsx/esm --test on the new test file -> 5/5 pass;
sibling claudeAuthImport.test.ts -> pass; eslint on both changed files ->
no new findings (only the pre-existing @/lib/localDb barrel-import restriction
on an untouched import line).

* test(oauth): exercise claude auth import implementation

Replace copied helper tests with real implementation coverage for bootstrap headers and persistent cliUserID behavior.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
Co-authored-by: stanleytejakusuma <stanleytejakusuma@users.noreply.github.com>
2026-08-17 08:01:45 -03:00

115 lines
4.0 KiB
TypeScript

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";
// The production import helper reaches the real SQLite provider module. Give
// this file its own database even when it is run without the package harness.
const testDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-claude-import-10144-"));
process.env.DATA_DIR = testDataDir;
process.env.DISABLE_SQLITE_AUTO_BACKUP = "true";
process.env.APP_LOG_TO_FILE = "false";
// Import the implementation under test. In particular, do not copy any of
// these helpers here: the regression must fail if claudeAuthImport.ts loses a
// required header or stops persisting the device identity.
const {
createConnectionFromAuthFile,
enrichWithBootstrap,
parseAndValidateClaudeAuth,
} = await import("../../src/lib/oauth/utils/claudeAuthImport.ts");
import { getClaudeCodeUserAgent } from "../../src/shared/constants/claudeCodeClient.ts";
const originalFetch = globalThis.fetch;
test.afterEach(() => {
globalThis.fetch = originalFetch;
});
test.after(() => {
fs.rmSync(testDataDir, { recursive: true, force: true });
});
test("real enrichWithBootstrap sends the required CLI headers", async () => {
const captured: { url: string; headers: Headers } = {
url: "",
headers: new Headers(),
};
globalThis.fetch = (async (input, init) => {
captured.url = String(input);
captured.headers = new Headers(init?.headers);
return new Response(
JSON.stringify({
account_uuid: "unit-account-10144",
organization_uuid: "unit-org-10144",
organization_name: "Unit Test Organization",
organization_type: "team",
rate_limit_tier: "default",
account_email: "unit-10144@example.invalid",
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}) as typeof fetch;
const parsed = parseAndValidateClaudeAuth({
claudeAiOauth: {
accessToken: "unit-test-access-token",
refreshToken: "unit-test-refresh-token",
scopes: ["user:inference"],
},
});
const enriched = await enrichWithBootstrap(parsed);
assert.equal(captured.url, "https://api.anthropic.com/api/claude_cli/bootstrap");
assert.equal(captured.headers.get("authorization"), "Bearer unit-test-access-token");
assert.equal(captured.headers.get("anthropic-version"), "2023-06-01");
assert.equal(captured.headers.get("content-type"), "application/json");
assert.equal(captured.headers.get("user-agent"), getClaudeCodeUserAgent("cli"));
assert.equal(captured.headers.get("anthropic-beta"), "oauth-2025-04-20");
assert.equal(enriched.accountUUID, "unit-account-10144");
assert.equal(enriched.email, "unit-10144@example.invalid");
});
test("real createConnectionFromAuthFile persists and preserves cliUserID", async () => {
const parsed = parseAndValidateClaudeAuth({
claudeAiOauth: {
accessToken: "unit-test-access-token",
refreshToken: "unit-test-refresh-token",
},
});
const enriched = {
...parsed,
email: "unit-10144@example.invalid",
accountUUID: "unit-account-10144-persistent",
organizationUUID: null,
organizationName: null,
organizationType: null,
};
const created = await createConnectionFromAuthFile(enriched, {});
assert.equal(created.created, true);
const createdProviderSpecificData = created.connection.providerSpecificData as Record<
string,
unknown
>;
const cliUserID = createdProviderSpecificData.cliUserID;
assert.equal(typeof cliUserID, "string");
assert.match(cliUserID as string, /^[a-f0-9]{64}$/);
const overwritten = await createConnectionFromAuthFile(
{ ...enriched, accessToken: "unit-test-access-token-rotated" },
{ overwriteExisting: true }
);
assert.equal(overwritten.created, false);
assert.equal(overwritten.connection.id, created.connection.id);
assert.equal(
(overwritten.connection.providerSpecificData as Record<string, unknown>).cliUserID,
cliUserID,
"re-import must preserve the persisted device identity"
);
});