fix: report unusable Claude subscriptions as unauthenticated (#1678)

With `--hide-claude-auth`, clients could see `authenticated` for a
subscription the adapter would refuse at `session/new`. On ACP v1 and
v2, `auth/status` and `auth/status_update` now report `unauthenticated`
with no accounts when the stored subscription cannot be used. Enterprise
subscriptions, API keys and setup tokens remain usable.

Keep the legacy `_auth/status_update` payload separate: it still
describes the stored identity, including a refused subscription. Each
notification is sent only when its own payload changes. No login or
billing policy changes.

**Validation:** `npm run check`, `npm run build`, and `npm run test:run`
passed (4,412 tests). A stdio check with a simulated Max login verified
the query and notification on v1 and v2.
This commit is contained in:
Ben Brandt
2026-11-20 12:59:57 +01:00
committed by GitHub
parent 1c90fb959a
commit a4f0f78bb3
5 changed files with 93 additions and 42 deletions

View File

@@ -228,7 +228,9 @@ The adapter keeps them where they are.
## Auth source display
The connection-scoped `_auth/status_update` continues to report agent-owned authentication, not client-owned `providers/set` routing. The adapter also reports the same identity through the ACP `auth/status` method and `auth/status_update` notification (advertised as `auth.status`), with `kind`, `detail` and `plan` under the account's `_meta.claudeCode`. The account's `description` carries the `detail` too, e.g. `label: "Anthropic API key"` with `description: "ANTHROPIC_API_KEY"`. Each notification is sent when its own payload changed. `auth/status` answers with the identity last reported and starts a new read, whose change arrives as a notification. When the active key source is `apiKeyHelper`, the adapter reads the effective helper command through SDK `resolveSettings` / the session's `SettingsManager`, including programmatic settings overrides.
The connection-scoped `_auth/status_update` reports agent-owned authentication, not client-owned `providers/set` routing. The adapter also reports that login through the ACP `auth/status` method and `auth/status_update` notification (advertised as `auth.status`). Under `--hide-claude-auth`, a subscription the integration cannot use is `unauthenticated`, with no active account; the legacy notification still describes the stored login. Enterprise subscriptions, API keys, and setup tokens remain usable.
For a reported account, `_meta.claudeCode` carries `kind`, `detail` and `plan`. The account's `description` carries the `detail` too, e.g. `label: "Anthropic API key"` with `description: "ANTHROPIC_API_KEY"`. Each notification is sent when its own payload changed. `auth/status` answers with the identity last reported and starts a new read, whose change arrives as a notification. When the active key source is `apiKeyHelper`, the adapter reads the effective helper command through SDK `resolveSettings` / the session's `SettingsManager`, including programmatic settings overrides.
A command containing the whole word `central` and the word sequence `proxy start` is displayed as:

View File

@@ -20,13 +20,19 @@ import {
AUTH_STATUS_PROBE_TIMEOUT_MS,
type AuthStatus,
type AuthStatusKind,
cliAuthIdentity,
fromAccountInfo,
fromCliStatus,
mergeAuthStatus,
parseCliAuthStatus,
sameAuthStatus,
toAcpAuthStatus,
} from "./auth-status.js";
import { claudeCliPath } from "./claude-cli.js";
import {
claudeAuthRefusal,
isClaudeEnterprisePlan,
shouldHideClaudeAuth,
} from "./hide-claude-auth.js";
import type { SettingsManager } from "./settings.js";
const execFileAsync = promisify(execFile);
@@ -81,8 +87,7 @@ export class AuthStatusReporter {
private probeRuns = 0;
/** The latest-started probe run that published its read. */
private publishedRun = 0;
/** The last `auth/status_update` payload sent, as JSON. */
private sentAcp?: string;
private acpStatus: AcpAuthStatus = { state: "unknown" };
constructor(private readonly options: AuthStatusReporterOptions) {}
@@ -100,28 +105,24 @@ export class AuthStatusReporter {
* reach here at all (see the epoch check in the probe and the guards at
* session create).
*/
set(next: AuthStatus | undefined): void {
set(next: AuthStatus | undefined, refused = false): void {
if (!next) {
return;
}
if (sameAuthStatus(this.current, next)) {
if (!sameAuthStatus(this.current, next)) {
this.current = next;
// Older clients still get the actual identity, including one the guard refused.
void Promise.resolve()
.then(() => this.options.push(next))
.catch((error) => {
this.options.logger.error("Failed to send _auth/status_update:", error);
});
}
const acp = toAcpAuthStatus(next, refused);
if (JSON.stringify(acp) === JSON.stringify(this.acpStatus)) {
return;
}
this.current = next;
// ACP notifications get no reply, and clients that do not know the method
// drop it silently — send unconditionally and never fail a caller on it.
void Promise.resolve()
.then(() => this.options.push(next))
.catch((error) => {
this.options.logger.error("Failed to send _auth/status_update:", error);
});
// Compared on its own payload: two identities can map to the same one.
const acp = toAcpAuthStatus(next);
const sent = JSON.stringify(acp);
if (sent === this.sentAcp) {
return;
}
this.sentAcp = sent;
this.acpStatus = acp;
void Promise.resolve()
.then(() => this.options.pushAcp(acp))
.catch((error) => {
@@ -152,7 +153,7 @@ export class AuthStatusReporter {
} else {
await this.probe();
}
return toAcpAuthStatus(this.current);
return this.acpStatus;
}
/** A login or a logout: any probe already running read the world before it. */
@@ -224,8 +225,11 @@ export class AuthStatusReporter {
return;
}
const fromSession = fromAccountInfo(account, apiKeyHelper);
if (fromSession) {
this.set(mergeAuthStatus(this.current, fromSession, "session"));
if (account && fromSession) {
this.set(
mergeAuthStatus(this.current, fromSession, "session"),
shouldHideClaudeAuth() && claudeAuthRefusal(account) !== undefined,
);
} else if (!this.loggedUninformativeAccount) {
this.loggedUninformativeAccount = true;
this.options.logger.log(
@@ -308,19 +312,20 @@ export class AuthStatusReporter {
}
stdout = failed.stdout;
}
let status = fromCliStatus(stdout, apiKeyHelper);
const cli = parseCliAuthStatus(stdout);
if (!cli) {
logger.error("claude auth status returned unparseable output");
return undefined;
}
let status = cliAuthIdentity(cli, apiKeyHelper);
if (!context && status?.kind === "api_key" && status.detail === "API key helper") {
try {
const resolved = await resolveSettings({ cwd: process.cwd() });
status = fromCliStatus(stdout, filterEscalatingDefaultMode(resolved).apiKeyHelper);
status = cliAuthIdentity(cli, filterEscalatingDefaultMode(resolved).apiKeyHelper);
} catch {
logger.error("Could not resolve auth source settings");
}
}
if (!status) {
logger.error("claude auth status returned unparseable output");
return undefined;
}
if (epoch !== this.epoch) {
// A login or logout landed while this probe was running; the newer
// state wins and this answer is discarded, never published.
@@ -338,7 +343,14 @@ export class AuthStatusReporter {
// same login (no organization, say). Keep those extra fields rather than
// regressing the payload; a different identity replaces it wholesale.
const merged = mergeAuthStatus(this.current, status, "cli");
this.set(merged);
// The CLI names the effective credential, not the SDK's accountInfo tokenSource.
// An OAuth setup token can carry a plan but, like an API key, is allowed.
const refused =
shouldHideClaudeAuth() &&
status.kind === "account" &&
cli.authMethod !== "oauth_token" &&
!isClaudeEnterprisePlan(cli.subscriptionType);
this.set(merged, refused);
this.options.onProbe?.(status.kind);
return merged;
}

View File

@@ -109,14 +109,14 @@ export type AcpAuthStatus = Pick<AuthStatusResponse, "state" | "accounts">;
* `_meta.claudeCode` carries the `kind` and `plan`, and the `detail` again
* for clients that read it there.
*
* `--hide-claude-auth` does not change the payload: it reports the login the
* CLI holds, also when the subscription guard refuses to use it.
* The legacy extension still reports a refused identity for display. ACP
* reports that sign-in is needed instead of listing it as an active account.
*/
export function toAcpAuthStatus(status: AuthStatus | undefined): AcpAuthStatus {
export function toAcpAuthStatus(status: AuthStatus | undefined, refused = false): AcpAuthStatus {
if (!status) {
return { state: "unknown" };
}
if (status.kind === "none") {
if (refused || status.kind === "none") {
return { state: "unauthenticated" };
}
const account: AuthAccount = { label: status.label, active: true };
@@ -236,10 +236,8 @@ export function fromAccountInfo(
});
}
/** Pre-session mapping from `claude auth status --json` stdout. Returns
* `undefined` when the output is not the expected JSON object, so callers can
* report "not known" instead of guessing. */
export function fromCliStatus(stdout: string, apiKeyHelper?: string): AuthStatus | undefined {
/** An unreadable `claude auth status --json` result is unknown, not signed out. */
export function parseCliAuthStatus(stdout: string): CliAuthStatus | undefined {
let parsed: unknown;
try {
parsed = JSON.parse(stdout);
@@ -253,6 +251,10 @@ export function fromCliStatus(stdout: string, apiKeyHelper?: string): AuthStatus
if (typeof status.loggedIn !== "boolean") {
return undefined;
}
return status;
}
export function cliAuthIdentity(status: CliAuthStatus, apiKeyHelper?: string): AuthStatus {
// `loggedIn` tracks the claude.ai login only. On a 3P backend (Bedrock,
// Vertex, …) it is false while the credentials live outside the agent, so the
// backend must decide the kind before the logged-out shortcut runs.

View File

@@ -6,9 +6,10 @@ import type { Logger } from "../../logger.js";
import { ClaudeAcpAgent } from "../../v1/acp-agent.js";
import type { AuthStatus } from "../../auth-status.js";
import {
cliAuthIdentity,
fromAccountInfo,
fromCliStatus,
mergeAuthStatus,
parseCliAuthStatus,
sameIdentity,
toAcpAuthStatus,
} from "../../auth-status.js";
@@ -157,6 +158,11 @@ function scriptedTurnQuery(args: any, account: Record<string, unknown>) {
return query;
}
function fromCliStatus(stdout: string, apiKeyHelper?: string) {
const parsed = parseCliAuthStatus(stdout);
return parsed && cliAuthIdentity(parsed, apiKeyHelper);
}
describe("auth status mappers", () => {
it.each([
"central proxy start",
@@ -787,6 +793,30 @@ describe("auth status over ACP", () => {
expect(authStatusUpdate).toHaveBeenCalledTimes(1);
});
it.each([
[CLI_SUBSCRIPTION, "unauthenticated", "account"],
[CLI_SUBSCRIPTION.replace('"max"', '"Claude Enterprise"'), "authenticated", "account"],
[CLI_KEY_HELPER_AND_SUBSCRIPTION, "authenticated", "api_key"],
[CLI_SUBSCRIPTION.replace('"claude.ai"', '"oauth_token"'), "authenticated", "account"],
])(
"reports whether the CLI credential is usable under --hide-claude-auth: %s",
async (stdout, state, kind) => {
const argv = process.argv;
process.argv = [...argv, "--hide-claude-auth"];
try {
statusStdout = stdout;
await initialize();
const status = await agent.authStatusResponse();
expect(status.state).toBe(state);
if (state === "unauthenticated") expect(status.accounts).toBeUndefined();
expect(authStatusUpdate.mock.calls).toEqual([[status]]);
expect(lastPush()?.kind).toBe(kind);
} finally {
process.argv = argv;
}
},
);
it("answers auth/status from the probe in flight while no identity is known", async () => {
deferStatus = true;
const init = agent.initialize({ protocolVersion: 1, clientCapabilities: {} });
@@ -1344,7 +1374,6 @@ describe("auth status over ACP", () => {
} as unknown as AcpClient,
logger as Logger,
);
agent.setAuthStatus({ ...KNOWN });
});
afterEach(() => {
@@ -1353,6 +1382,7 @@ describe("auth status over ACP", () => {
it("bounds the probe at 5 s and keeps the last known state", async () => {
agent.setAuthStatus({ ...KNOWN });
await Promise.resolve();
const pushesBefore = updates().length;
await agent.initialize({ protocolVersion: 1, clientCapabilities: {} });
@@ -1374,7 +1404,6 @@ describe("auth status over ACP", () => {
});
it("answers auth/status with unknown when the first probe times out", async () => {
(agent as any).authStatus.current = undefined;
const status = agent.authStatusResponse();
await vi.advanceTimersByTimeAsync(0);
await vi.advanceTimersByTimeAsync(5000);

View File

@@ -10937,6 +10937,12 @@ describe("ACP v2 subscription guard (--hide-claude-auth)", () => {
await expect(agent.request(v2.methods.agent.session.new, { cwd })).rejects.toMatchObject(
refusal,
);
if (account === SUBSCRIPTION) {
await expect(agent.request(v2.methods.agent.auth.status, {})).resolves.toEqual({
state: "unauthenticated",
});
expect(client.acpAuthUpdates.at(-1)).toEqual({ state: "unauthenticated" });
}
});
});