switch Anthropic accounts from the usage pills
The owner keeps a personal account and a company one and moves between them during a day — by what the work
is, and sometimes because one has hit a limit and the work has to carry on. /login handles ARRIVING at an
account. It could not go back to one, because the credential it overwrote was gone.
ai_provider_usage already answered "which of my accounts has room". This answers what immediately follows:
"then use that one". The chips under the numbers stop selecting whose stats you read and start selecting who
you ARE — which turned out to be the useful half of the same gesture, since reading the other account's
percentages was only ever a prelude to using it.
anthropic_accounts holds each login's OAuth object encrypted, keyed (user_id, account_uuid).
One key per ACCOUNT, not one for the table: encryptSecret('anthropic-account:<uuid>', …), so the secret
store mints a separate key each and one leak is one account. Same reasoning that split VAULT_STORE_KEY into
purposes. The uuid comes from Anthropic and survives a re-login; the email is stable too but is editable at
the provider.
What is stored includes a REFRESH token, deliberately — the access token lives hours and the refresh token
is what makes a switch work a week later. So a row plus its key is thirty days of acting as that account.
That was accepted knowingly; the per-account key narrows it, and refreshExpiresAt is a column so a dead
credential gets purged on read rather than sitting here for ever. An expired one cannot be switched to at
all: reveal returns null, because writing an expired credential would sign the owner out with no message.
Capture happens on login AND on every read of the account list. Without that second one this would know
only about logins that went through this dialog, and an account signed into from a terminal would be
invisible to the switcher — half your accounts missing, silently. The switch also captures the OUTGOING
credential first, or switching away from a terminal login loses it.
.credentials.json is replaced wholesale; .claude.json is PATCHED. The second holds the CLI's entire config
and overwriting it would take out every project entry and preference in it.
Owner only, and the isolation is unchanged: getOwnerHomeDir ignores the email it is passed, so every path
here is the owner's. A member's claude reads their own home and none of this touches it. The earlier claim
in this work that the credential was "machine-wide" was wrong — the owner corrected it. What a switch
actually changes is every claude running AS THE OWNER: terminals, task runners, pipelines, the commander.
The spinner is not decoration. A switch rewrites a file and changes nothing visible, so without it the
honest reading of a click is "nothing happened" and the second click is somebody checking. A running turn
keeps the credential it was spawned with, and the response says so rather than leaving the UI to imply
otherwise.
Verified before shipping: capture records the live account with org, plan and expiry; reveal decrypts
byte-identical to what is on disk; /api/claude-auth/accounts is 401 unauthenticated and 403 for a non-owner.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,16 @@
|
||||
import type { ChildProcessWithoutNullStreams } from 'node:child_process';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
listAnthropicAccounts,
|
||||
markAnthropicAccountUsed,
|
||||
purgeExpiredAnthropicAccounts,
|
||||
revealAnthropicAccount,
|
||||
saveAnthropicAccount,
|
||||
} from 'officerdb';
|
||||
import { createRouter } from '../../create-router';
|
||||
import { getHomeDir } from '../../data-path';
|
||||
import { getHomeDir, getOwnerHomeDir } from '../../data-path';
|
||||
import { claudeBinIn } from '../../os-user-claude';
|
||||
import { runAsArgv } from '../../os-user';
|
||||
|
||||
@@ -208,7 +217,15 @@ claudeLoginRouter.post('/:id/code', async (ctx) => {
|
||||
|
||||
if (exit === 'timeout') return ctx.json({ ok: false, error: 'the CLI did not finish in 45s', detail: tail }, 504);
|
||||
if (exit !== 0) return ctx.json({ ok: false, error: `claude auth login exited ${exit}`, detail: tail }, 400);
|
||||
return ctx.json({ ok: true, detail: tail });
|
||||
|
||||
// Record what was just signed into, so it can be switched BACK to later without another round trip. Only
|
||||
// for the owner: a member's credential is in their own home and this module only ever reads the owner's.
|
||||
if (user.id === 1) await captureCurrentAnthropicAccount(user.id);
|
||||
const now = user.id === 1 ? await readCurrentAccount() : null;
|
||||
|
||||
// The account is the answer the person opened this for. Two accounts on one machine means "signed in" on
|
||||
// its own is not enough to act on.
|
||||
return ctx.json({ ok: true, detail: tail, email: now?.emailAccount ?? null, orgName: now?.orgName ?? null });
|
||||
});
|
||||
|
||||
// DELETE /auth/claude-login/:id — they closed the dialog.
|
||||
@@ -219,3 +236,149 @@ claudeLoginRouter.delete('/:id', (ctx) => {
|
||||
if (p && p.userId === user.id) abandon(id);
|
||||
return ctx.json({ ok: true });
|
||||
});
|
||||
|
||||
/* ────────────────────────────────────────────────────────────────────────────
|
||||
Switching between accounts that have already been signed into.
|
||||
|
||||
The owner keeps a personal account and a company one and moves between them during a day. `/login` above
|
||||
handles arriving at an account; this handles going back to one, without a browser round trip, using the
|
||||
credential kept from last time.
|
||||
|
||||
Owner only, and structurally: `getOwnerHomeDir` ignores the email it is passed, so every path below is
|
||||
the owner's whatever the caller claims. A member's `claude` reads their own home and is untouched by any
|
||||
of this — the isolation is the same as it was, and this feature does not widen it.
|
||||
──────────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
/** `.credentials.json` holds one key. `.claude.json` holds a whole config and must be PATCHED, not written. */
|
||||
const credentialsPath = () => join(getOwnerHomeDir(''), '.claude', '.credentials.json');
|
||||
const configPath = () => join(getOwnerHomeDir(''), '.claude.json');
|
||||
|
||||
async function readJson(path: string): Promise<Record<string, unknown> | null> {
|
||||
try {
|
||||
return JSON.parse(await readFile(path, 'utf-8')) as Record<string, unknown>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the CLI is signed in as right now, read from its own two files.
|
||||
*
|
||||
* Both are needed and neither is sufficient: the credential lives in `.claude/.credentials.json` and the
|
||||
* identity — email, org, account uuid — lives in `.claude.json` beside it.
|
||||
*/
|
||||
async function readCurrentAccount(): Promise<{
|
||||
accountUuid: string;
|
||||
emailAccount: string;
|
||||
orgName: string | null;
|
||||
plan: string | null;
|
||||
credentialsJson: string;
|
||||
oauthAccountJson: string;
|
||||
refreshExpiresAt: Date | null;
|
||||
} | null> {
|
||||
const creds = await readJson(credentialsPath());
|
||||
const config = await readJson(configPath());
|
||||
const oauth = creds?.claudeAiOauth as Record<string, unknown> | undefined;
|
||||
const account = config?.oauthAccount as Record<string, unknown> | undefined;
|
||||
if (!oauth || !account) return null;
|
||||
|
||||
const accountUuid = typeof account.accountUuid === 'string' ? account.accountUuid : '';
|
||||
const emailAccount = typeof account.emailAddress === 'string' ? account.emailAddress : '';
|
||||
if (!accountUuid || !emailAccount) return null;
|
||||
|
||||
const sub = typeof oauth.subscriptionType === 'string' ? oauth.subscriptionType : '';
|
||||
const refreshMs = typeof oauth.refreshTokenExpiresAt === 'number' ? oauth.refreshTokenExpiresAt : null;
|
||||
return {
|
||||
accountUuid,
|
||||
emailAccount,
|
||||
orgName: typeof account.organizationName === 'string' ? account.organizationName : null,
|
||||
plan: sub ? sub[0]!.toUpperCase() + sub.slice(1) : null,
|
||||
credentialsJson: JSON.stringify(oauth),
|
||||
oauthAccountJson: JSON.stringify(account),
|
||||
refreshExpiresAt: refreshMs ? new Date(refreshMs) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep whatever the CLI is currently signed in as.
|
||||
*
|
||||
* Called after a `/login` here AND whenever the account list is read, which is what makes an account signed
|
||||
* into from a TERMINAL switchable too. Without that second call this would only know about logins that
|
||||
* happened to go through this dialog — a switcher that silently omits half your accounts.
|
||||
*
|
||||
* Never throws into a caller: failing to record a credential must not fail the request that noticed it.
|
||||
*/
|
||||
export async function captureCurrentAnthropicAccount(userId: number): Promise<void> {
|
||||
try {
|
||||
const now = await readCurrentAccount();
|
||||
if (!now) return;
|
||||
await saveAnthropicAccount({ userId, ...now });
|
||||
} catch (err) {
|
||||
console.warn('[claude-auth] could not record the current account:', err instanceof Error ? err.message : err);
|
||||
}
|
||||
}
|
||||
|
||||
// GET /claude-auth/accounts — who can be switched to, and who is current. No secrets.
|
||||
claudeLoginRouter.get('/accounts', async (ctx) => {
|
||||
const user = ctx.get('user');
|
||||
if (user.id !== 1) return ctx.json({ error: 'Anthropic accounts belong to the owner of this machine' }, 403);
|
||||
|
||||
// Record before listing, so an account signed into elsewhere appears the first time the panel is opened
|
||||
// rather than only after the next login through this dialog.
|
||||
await captureCurrentAnthropicAccount(user.id);
|
||||
await purgeExpiredAnthropicAccounts(user.id).catch(() => 0);
|
||||
|
||||
const current = await readCurrentAccount();
|
||||
const accounts = (await listAnthropicAccounts(user.id)).map((a) => ({
|
||||
...a,
|
||||
current: a.accountUuid === current?.accountUuid,
|
||||
}));
|
||||
return ctx.json({ accounts });
|
||||
});
|
||||
|
||||
// POST /claude-auth/switch — become one of them.
|
||||
claudeLoginRouter.post('/switch', async (ctx) => {
|
||||
const user = ctx.get('user');
|
||||
if (user.id !== 1) return ctx.json({ error: 'Anthropic accounts belong to the owner of this machine' }, 403);
|
||||
|
||||
const body = await ctx.req.json().catch(() => ({}) as Record<string, unknown>);
|
||||
const accountUuid = typeof body.accountUuid === 'string' ? body.accountUuid : '';
|
||||
if (!accountUuid) return ctx.json({ error: 'no account' }, 400);
|
||||
|
||||
// Keep the outgoing credential before overwriting it, or switching away from an account signed into
|
||||
// outside this UI loses it — the one-way trip this feature exists to remove.
|
||||
await captureCurrentAnthropicAccount(user.id);
|
||||
|
||||
const target = await revealAnthropicAccount(user.id, accountUuid);
|
||||
if (!target) return ctx.json({ error: 'that sign-in has expired — run /login for it again' }, 409);
|
||||
|
||||
try {
|
||||
// `.credentials.json` is replaced wholesale: it holds this one key and nothing else of ours.
|
||||
// `.claude.json` is PATCHED — it is the CLI's whole config, and overwriting it would take out every
|
||||
// project entry, tip counter and preference in it.
|
||||
const existingCreds = (await readJson(credentialsPath())) ?? {};
|
||||
await writeFile(
|
||||
credentialsPath(),
|
||||
JSON.stringify({ ...existingCreds, claudeAiOauth: JSON.parse(target.credentialsJson) }),
|
||||
{
|
||||
mode: 0o600,
|
||||
},
|
||||
);
|
||||
|
||||
const config = (await readJson(configPath())) ?? {};
|
||||
await writeFile(
|
||||
configPath(),
|
||||
JSON.stringify({ ...config, oauthAccount: JSON.parse(target.oauthAccountJson) }, null, 2),
|
||||
{
|
||||
mode: 0o600,
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
return ctx.json({ error: `could not write the credential: ${err instanceof Error ? err.message : err}` }, 500);
|
||||
}
|
||||
|
||||
await markAnthropicAccountUsed(user.id, accountUuid);
|
||||
// A turn already running keeps the credential it was spawned with. Said here rather than guessed at in
|
||||
// the UI, because "it did not take effect" and "it takes effect next turn" look identical from outside.
|
||||
return ctx.json({ ok: true, email: target.emailAccount, appliesTo: 'the next turn, and every new claude' });
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user