fix(cc-config): read the live account's quota from the CLI, and ask for every account at once

The quota check failed with `invalid_grant` for the account the user was
logged into - the one profile they would try first. An OAuth refresh token is
single use, so every refresh Claude Code performs on its own account retires
the copy sitting in that account's saved profile: the stored credentials of
the LIVE account are the one set guaranteed to be rejected, however recently
the profile was saved. Confirmed on a real install - the saved profile held a
refresh token three rotations behind `.credentials.json`.

`cc-profiles.liveCredentialsFor` now matches a profile's accountUuid against
the live credentials and, on a hit, the usage call uses what the CLI is
holding. That token is never refreshed and that file is never written:
rotating it would log the user out of their own terminal. An expired live
token answers ELIVEEXPIRED - using Claude Code once makes the CLI refresh it -
and a genuinely spent refresh token is now reported as ESTALE with what to do
about it, instead of echoing Anthropic's raw 400.

Opening the Profiles modal also asks for every saved account at once, rather
than one button per row: comparing accounts is the only reason the panel
exists. The guard against rewriting credentials over and over is no longer
"one row at a time" but the rules above - the live account costs a plain read,
and any other profile refreshes only once its token has actually expired,
which then leaves it valid for hours of further opens. Each row resolves on
its own, so a superseded account still lets its neighbours report.
This commit is contained in:
2026-09-17 23:17:06 +07:00
parent 470f9909b4
commit 1aee080fca
8 changed files with 324 additions and 26 deletions
+62
View File
@@ -195,6 +195,68 @@ describe("profileUsage", () => {
);
});
it("uses the CLI's own token for the account that is logged in, not the saved copy", async () => {
// The saved copy of the LIVE account is the one set of credentials certain
// to fail: the CLI has refreshed since, and that retired the refresh token
// sitting in the profile file. Refreshing it here would also rotate the
// token the user's terminal is using.
const account = { accountUuid: "uuid-live", emailAddress: "a@b.c" };
fs.mkdirSync(profiles.profilesDir(), { recursive: true });
fs.writeFileSync(
path.join(profiles.profilesDir(), "mine.json"),
JSON.stringify({
name: "mine",
account,
credentials: { accessToken: "retired", refreshToken: "retired-r", expiresAt: 1 },
})
);
fs.writeFileSync(
path.join(TMP, ".credentials.json"),
JSON.stringify({
claudeAiOauth: {
accessToken: "live-token",
refreshToken: "live-r",
expiresAt: Date.now() + 3_600_000,
},
})
);
fs.writeFileSync(path.join(TMP, ".claude.json"), JSON.stringify({ oauthAccount: account }));
stubFetch();
const result = await usage.profileUsage("mine");
assert.equal(result.refreshed, false);
assert.match(calls[0].init.headers.Authorization, /live-token/);
assert.equal(
calls.some((c) => c.url.includes("/v1/oauth/token")),
false,
"refreshing the live account would log the user's own terminal out"
);
fs.rmSync(path.join(TMP, ".credentials.json"));
fs.rmSync(path.join(TMP, ".claude.json"));
});
it("names a spent refresh token instead of echoing the upstream 400", async () => {
writeProfileFile("superseded", {
accessToken: "expired",
refreshToken: "already-rotated",
expiresAt: Date.now() - 1000,
});
global.fetch = async (url) => {
calls.push({ url: String(url) });
return {
ok: false,
status: 400,
text: async () => '{"error": "invalid_grant", "error_description": "not found"}',
};
};
await assert.rejects(
() => usage.profileUsage("superseded"),
(e) => e.code === "ESTALE" && /save the profile again/.test(e.message)
);
});
it("reports an unknown profile as ENOTFOUND", async () => {
stubFetch();
await assert.rejects(
+24
View File
@@ -156,6 +156,29 @@ function freeName(base) {
return name;
}
/**
* The LIVE credentials when `stored` is the account logged in right now, else
* null.
*
* A saved profile is a copy, and an OAuth refresh token is single use: every
* time Claude Code refreshes the account it is logged into, the copy sitting in
* the profile file is retired. So for the active account the saved credentials
* are the one set guaranteed NOT to work, and `.credentials.json` — which the
* CLI keeps current — is the only usable source. Nothing here writes: rotating
* the token the live session is holding would log the user out of their own
* terminal.
*
* @param stored a profile as returned by `readProfile`
* @returns the live `claudeAiOauth` block, or null when this is not that account
*/
function liveCredentialsFor(stored) {
const live = readActiveAuth();
if (!live.oauth) return null;
const mine = identityOf(live).accountUuid;
const theirs = identityOf({ oauth: stored.credentials, account: stored.account }).accountUuid;
return mine && mine === theirs ? live.oauth : null;
}
/** Read one stored profile, or null when it does not exist. */
function readProfile(name) {
const stored = readJson(profileFile(name));
@@ -388,6 +411,7 @@ module.exports = {
// Token-bearing reads/writes: for cc-usage.js, never for a route.
readProfile,
writeProfile,
liveCredentialsFor,
// exported for tests
profilesDir,
configPaths,
+47 -14
View File
@@ -17,16 +17,24 @@
* returned, logged or echoed. What leaves this module is two percentages
* and two reset timestamps.
*
* - **Nothing here runs on a poll.** A saved profile's access token is short
* lived — every profile that is not the active one is normally expired — so
* reading its usage means refreshing it first, and a refresh ROTATES the
* stored refresh token. Doing that on a page load would rewrite the user's
* credentials for every account they have, repeatedly, for a number on a
* screen. It is therefore driven by an explicit per-profile request, and the
* rotated tokens are written straight back (`cc-profiles.writeProfile`) —
* a refresh whose result is dropped leaves the profile holding a refresh
* token Anthropic has already retired, i.e. an account the user must log in
* to again.
* - **The active account is read from the CLI, never from its saved copy.**
* A refresh token is single use, so every refresh Claude Code performs on
* the account it is logged into retires the copy stored in that profile:
* the saved credentials of the LIVE account are the one set certain to be
* rejected. `cc-profiles.liveCredentialsFor` hands back what the CLI is
* actually holding, and that token is never refreshed here — rotating it
* would log the user out of their own terminal.
*
* - **Nothing here runs on a poll, and no refresh happens that a token's own
* expiry did not force.** Opening the Profiles modal asks for every saved
* account at once — comparing them is the point — so the guard against
* rewriting a user's credentials over and over is not "one row at a time",
* it is here: the live account never refreshes at all, and any other profile
* refreshes only once its token has actually expired, which then leaves it
* valid for hours of further opens. What a refresh does return is written
* straight back (`cc-profiles.writeProfile`), because Anthropic retires the
* refresh token it was handed and dropping the replacement would leave an
* account the user has to log into again.
*
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
@@ -60,7 +68,18 @@ async function postJson(url, body, headers) {
signal: AbortSignal.timeout(TIMEOUT_MS),
});
const text = await res.text();
if (!res.ok) throw err("EUPSTREAM", `${url} answered ${res.status}: ${text.slice(0, 200)}`);
if (!res.ok) {
// The one upstream failure a user can act on: this profile's refresh token
// has already been spent, which happens whenever a NEWER login or refresh
// for the same account rotated it. Saying so beats echoing a raw 400.
if (text.includes("invalid_grant")) {
throw err(
"ESTALE",
"this profile's saved login has been superseded - activate the account once and save the profile again"
);
}
throw err("EUPSTREAM", `${url} answered ${res.status}: ${text.slice(0, 200)}`);
}
try {
return JSON.parse(text);
} catch {
@@ -146,8 +165,21 @@ async function fetchUsage(accessToken) {
async function profileUsage(name) {
const stored = profiles.readProfile(name);
if (!stored) throw err("ENOTFOUND", `no saved profile named ${name}`);
const creds = stored.credentials || {};
// For the account that is logged in RIGHT NOW the saved copy is the one set
// of credentials guaranteed to fail — the CLI has rotated its refresh token
// since, retiring the profile's. Use what the CLI holds, and never refresh
// it: that would retire the token the user's own terminal is using, and this
// module does not write `.credentials.json` back.
const live = profiles.liveCredentialsFor(stored);
const creds = live || stored.credentials || {};
const fresh = Number(creds.expiresAt) > Date.now() + EXPIRY_MARGIN_MS;
if (live && !fresh) {
throw err(
"ELIVEEXPIRED",
"the active account's token has expired - use Claude Code once so it refreshes, then check again"
);
}
let token = fresh ? creds.accessToken : await refreshProfile(name);
let refreshed = !fresh;
@@ -158,8 +190,9 @@ async function profileUsage(name) {
return { name, refreshed, ...usage, checkedAt: new Date().toISOString() };
} catch (e) {
// A token that looked fresh but was revoked server-side is worth one
// retry through the refresh path; a second 401 is a real answer.
if (e.code !== "EUNAUTHORIZED" || refreshed) throw e;
// retry through the refresh path; a second 401 is a real answer. Not for
// the live account, for the same reason its token is never refreshed here.
if (e.code !== "EUNAUTHORIZED" || refreshed || live) throw e;
token = await refreshProfile(name);
refreshed = true;
const usage = await fetchUsage(token);
+9 -3
View File
@@ -596,9 +596,15 @@ router.post("/profiles/usage", sameOriginGuard, async (req, res) => {
res.json(await ccUsage.profileUsage(name));
} catch (e) {
const status =
{ ENOTFOUND: 404, EBADNAME: 400, ENOREFRESH: 409, ENOAUTH: 409, EUNAUTHORIZED: 401 }[
e.code
] || 502;
{
ENOTFOUND: 404,
EBADNAME: 400,
ENOREFRESH: 409,
ENOAUTH: 409,
ESTALE: 409,
ELIVEEXPIRED: 409,
EUNAUTHORIZED: 401,
}[e.code] || 502;
res.status(status).json({ error: { code: e.code || "EUPSTREAM", message: e.message } });
}
});