SLOPSHOPPER

rice-session-accounts

Choose an Anthropic OAuth account by email and tier inside ordinary Claude, with session-local authentication, selected-account reporting and resumable setup…

paneguardcommandtoaststatusprompt
v0.6.0MITupdated 2026-10-25moabualruz/rice-session-accounts
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · rice-session-accounts
│ ┃ Choose account ✕ › fix the failing auth test and add an audit log call │ ┃ Choose an account for this session │ ┃ Other sessions keep their accounts. Escape ⏺ Read(src/auth.ts) │ ┃ closes this list. ⎿ Read 6 lines │ ┃ Loading saved accounts... ⏺ Update(src/auth.ts) │ ┃ [ Cancel ] ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /rice-account │ ⎿ rice-session-accounts: Choose an account in the account list. Th │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Choose account
Choose an account for this session Other sessions keep their accounts. Escape closes this list. Loading saved accounts... [ Cancel ]
README

Rice Accounts

Rice Accounts lets you switch between saved Anthropic (Claude.ai) OAuth accounts inside one Claude Code session. Run /rice-account, pick an account by name, email and plan, and that session (its subagents, compaction and any claude -p it starts) uses it from the next request. Other sessions keep their own account, and your machine login is never changed.

It is a plugin ("mod") for ordinary, unmodified claude. It installs no launcher, alias, preload, proxy or gateway. "Rice" is just the name of the marketplace it ships in (rice-mods). Model and provider setup (Codex, OpenRouter, local models) belongs to rice-multi-models.

Requirements

  • Claude Code 2.1.296 or newer. Tested with 2.1.296, 2.1.299, 2.1.301 and 2.1.302; the real-binary account-switching proofs run on 2.1.301 and 2.1.302.
  • Node.js 22 or newer on the PATH of the environment where Claude runs, and in the terminal where you run the setup helper. WSL needs its own Linux Node.js.
  • claude available in that terminal for setup (set RICE_ACCOUNTS_CLAUDE to an absolute path if it is not on PATH).
  • A Claude plan for each account you add (Pro, Max, Team or Enterprise).
  • macOS, Linux, WSL or native Windows.

Install, update, remove

claude plugin install rice-session-accounts --marketplace moabualruz/rice-mods

Start a new Claude Code session and approve the capabilities it asks for. Installing does not sign you into anything.

Update (then /reload-plugins or restart Claude Code):

claude plugin marketplace update rice-mods
claude plugin update rice-session-accounts@rice-mods

Remove: claude plugin uninstall rice-session-accounts@rice-mods. This leaves your saved accounts in place; see Uninstall and cleanup.

First use

/rice-account

shows the built-in login account (this machine's normal Claude login) and every saved account, each with its cached email and plan. Pick one with the arrow keys and Enter; Escape closes the list. Without a graphical surface the same list is printed as text. Unknown means no local metadata was found, Not signed in means no login exists yet. Opening the list makes no network request; run /rice-account check <name> to verify a login with Anthropic.

Add another account

  1. In Claude Code:
   /rice-account add personal

This saves the name (kind claudeai, a separate claude.ai sign-in) and prints one terminal command containing this installation's exact paths.

  1. Paste that command into a terminal on the same machine (inside the same WSL distribution for WSL). The helper checks prerequisites, opens the browser login and verifies the account. Useful flags, appended to the command:
FlagUse
--manual --email you@example.comPrint a sign-in URL instead of opening the default browser, so you can open it in the browser that holds the right account.
--browser <executable>Have Claude open a specific browser (not combinable with --manual).
--loginSign in again even if a valid login is found.
  1. Back in Claude Code, check it and switch:
   /rice-account check personal
   /rice-account personal

If setup stops halfway, /rice-account setup personal prints the command again.

For a long-lived setup token instead of a browser login:

/rice-account add ci-token claudeai-token

The helper runs claude setup-token and asks you to paste the token into a hidden prompt in the terminal. Never type a token into Claude Code itself.

Account names

1 to 40 characters from A-Z a-z 0-9 . _ -, starting with a letter or digit. Names must be unique ignoring case, must not end with a dot, must not be a Windows device name (con, nul, com1, ...), and must not be a command word (list, use, setup, ...) or an object key such as toString. An account that already had a now-reserved name keeps working: reach it with /rice-account use <name>.

Commands

CommandResult
/rice-accountOpen the account list (text list where no list can be shown).
/rice-account <name>, /rice-account use <name>Switch this session. login is the machine login. use also reaches an account named like a command.
/rice-account listText list of saved accounts with email and plan.
/rice-account usageThe session account's usage limits.
/rice-account check [name]Verify a login with Anthropic (default: the session account).
/rice-account add <name> [kind] [label=...] [service=...]Save an account and print its setup command. Kinds: claudeai (default), claudeai-token.
/rice-account setup <name>Print a saved account's setup command again.
/rice-account remove <name>Remove it from accounts.json. Its login is kept; sessions already using it keep it until they switch.
/rice-account default, set-default <name>Switch to, or change, the saved default. New sessions still start on the machine login.
/rice-account setup-nativeWithdrawn. Prints how to delete 0.3.0 launcher files by hand.
/rice-account helpEvery subcommand.

/usage and interactive /status report the session account while you have selected one (the engine would report the machine account). Back on the machine login they are the engine's own again. The status entry shows the session account's name, email, plan and usage windows.

What the selected account does

  • Requests. The session's model requests use the account's bearer token. It is carried in ANTHROPIC_CUSTOM_HEADERS, the supported request-header override, set only in the running Claude process.
  • Children. Anything the session starts (Bash commands, hooks, MCP servers, claude -p) inherits that variable like any other ANTHROPIC_* setting, so a claude started from Bash uses the selected account. Any process in the session can therefore read the token. There is no separate relay variable and no file.
  • Commands run exactly as you typed them. Rice Accounts does not rewrite Bash commands or child environments, so your permission rules match as usual.
  • Other plugins. A plugin that asks for the session's authorization gets an opaque handle, usable only for https://api.anthropic.com and only by that same plugin, never while nonessential network traffic is disabled.
  • Gateways. If the session was started with a custom ANTHROPIC_BASE_URL, requests (and the account's token) go to that host; switching tells you so.
  • Not confirmed means locked. If a switch cannot be verified or undone, the status line shows "account not confirmed" and model requests, compaction, subagents, web tools and child claude runs are refused until you run /rice-account login or select an account again. The unconfirmed token is replaced by one no server accepts, so requests that no plugin hook sees (the permission classifier, titles, MCP servers) fail instead of using the wrong account. The lockout survives a plugin reload and /clear. A prompt you type while locked is refused at once with the reason and leaves no row in the conversation; messages the engine generates itself (task notifications, scheduled runs) are answered with the same reason.
  • /clear plus a reload. When you clear a conversation that has a selected account, the plugin keeps a short-lived, non-secret note of the account name in its own store (never in the environment, so children cannot inherit it). A reload that follows locks the session instead of mistaking the still-selected account's header for your launch login.
  • Renewals. Expiring browser logins are renewed automatically in the background (and before a turn that starts after expiry), with backoff after a failure. A running session keeps working if you remove its account elsewhere.
  • A new session always starts on your machine login; select an account explicitly in each session.

Native panels that read Claude's internal cached identity directly (outside /usage, interactive /status and the status entry) can still show the machine account.

Limits

  • The engine has no seam for switching its own account, so a few things still follow the machine login while another account is selected: the account id each request carries in its metadata, plan gating and upgrade prompts, telemetry, and the native panels other than /usage and /status.
  • While the session is locked, a request that no plugin hook sees (the permission classifier, titles, MCP servers) fails with Claude Code's own "invalid bearer token" error, which can read like a reason to run /login. Run /rice-account login.
  • Anthropic requests identify as claude-cli/<version> (external, cli). session.usage lists only the five-hour and weekly windows the engine declares; a model's own window appears in /rice-account usage and the status entry.
  • A switch is refused, with the cause and the fix, when Claude Code's own credential would override the selected account: an apiKeyHelper setting from any settings source, an API key passed through CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR, workload identity federation (ANTHROPIC_FEDERATION_RULE_ID with ANTHROPIC_ORGANIZATION_ID), or a session not started signed in with a Claude subscription. Settings that cannot be read refuse it too. login, list, check and usage keep working, and an account already selected stays in effect.
  • An ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN or provider selector at launch does not block a switch when the session is also signed in with a Claude subscription: the switch clears them for this session, and /rice-account login restores them.
  • The values your session started with (an API key, a launch CLAUDE_CODE_OAUTH_TOKEN, provider settings) are kept in the session's plugin state so /rice-account login can restore them exactly, even after a reload. Plugin state is readable by every plugin in the session, as the environment already is. If you start sessions without such variables there is nothing to keep.
  • If the selected account cannot be put back after a reload (network down, locked keychain), the session stays locked until you select it again rather than guess.
  • A claude started from a shell is recognized by name (quotes, wrappers, eval, env -S and nested shells are handled); a renamed copy of the binary is not, but the replaced token above still stops it from using an unconfirmed account.

Credentials on each system

SystemWhere a claudeai login lives
macOSLogin keychain item Claude Code-credentials-<8 hex of the login folder>, account $USER (or claude-code-user).
Linux, WSL, Windows<config>/rice-session-accounts/logins/<name>/.credentials.json, owner-only (0600; owner-only ACL on Windows).
Setup tokensmacOS Keychain, Linux Secret Service (secret-tool, needs a running keyring) or Windows Credential Manager.

<config> is ~/.claude, or CLAUDE_CONFIG_DIR when set. The isolated login folders hold only the extra logins; your settings, plugins, skills, hooks and MCP servers are untouched.

Claude Code can keep a login where Rice Accounts does not read it, and Rice Accounts then says so instead of reporting the account as signed out. On macOS it falls back to a plaintext .credentials.json in the login folder when the keychain cannot store a login; unlock the keychain and run the setup command again with --login. On Windows it uses Credential Manager when CLAUDE_CODE_FORCE_WINDOWS_CREDMAN=1 is set or its cached tengu_windows_credman setting is on in that folder's .claude.json; use a claudeai-token account there.

A renewed login is never lost. The server rotates the refresh token on every renewal, so the new login is first written to a private .credentials.json.rice-pending file (and kept in memory), then saved, then the file is removed. If saving fails (antivirus holding the file, full disk, locked keychain) the file is kept and is saved on the next use. The file records which stored login it continues, so it is only ever adopted when the store still holds that login; reading never changes anything, and only a renewal (under its lock) promotes or removes a pending file, and removes only one it wrote itself. So a session that stalls between its write-ahead and its save cannot cost a newer login: the newer renewal is saved over it. A renewal kept unsaved is saved again after a plugin reload as soon as the renewal lock is free. On macOS a login too large for the keychain's line limit is stored without optional keys such as mcpOAuth; it is never truncated. A renewal records the refresh token's expiry (refreshTokenExpiresAt) and uses the login's own OAuth client, as Claude Code does.

Limits of that guarantee: the macOS keychain has no atomic compare-and-swap, so a sign-in that finishes within milliseconds of a renewal of the same account can be overwritten (sign it in again); a token request that hangs for more than 10 minutes stops renewing the lock (its answer is still saved if one arrives); and a power loss right after a renewal can lose the write-ahead copy, because macOS fsync does not flush to the physical disk.

On WSL a config folder under /mnt/c/... cannot be made private (Windows drives ignore Unix modes); setup warns and recommends a Linux-side folder.

Network and privacy

Rice Accounts contacts only Anthropic: https://api.anthropic.com (usage and profile lookups) and https://platform.claude.com (token renewal). It sends no analytics. Secrets never appear in command lines, logs or toasts, and the helper reads tokens only from hidden prompts or stdin.

Troubleshooting

SymptomWhat to do
/rice-account is unknownConfirm the plugin is installed and enabled, then restart Claude Code.
Setup says claude or Node is missingInstall Node.js 22+ and make claude available in that terminal, or set RICE_ACCOUNTS_CLAUDE to its absolute path. On WSL use a Linux Node.
"account not confirmed"Run /rice-account login, or select a saved account again.
The account is saved but not signed inRun /rice-account setup <name> and execute the printed command.
Browser login used the wrong accountRe-run setup with --login --manual --email intended@example.com and open the URL in the intended browser.
A copied setup command stopped working after an updateThe command embeds the installed plugin path; run /rice-account setup <name> again.
A native panel shows the machine accountUse the status entry, /usage or interactive /status.
/status is unavailable in print modeClaude rejects it before plugins run in print mode; use /usage.
A Linux setup-token account says secret-tool is missingsudo apt-get install libsecret-tools (Debian/Ubuntu) and a running Secret Service; or use a claudeai browser account.
Windows: ConstrainedLanguage or path-length errorsThe helper names the cause; use a shorter profile path or a full-language PowerShell.

Uninstall and cleanup

claude plugin uninstall rice-session-accounts@rice-mods removes the plugin only. To remove saved data as well, in <config>/rice-session-accounts/: delete accounts.json and logins/ (sign each login out first with the command /rice-account remove <name> prints), and remove any rice-session-accounts entries from your OS credential manager. If you used 0.3.0, run /rice-account setup-native for the launcher files to delete by hand.

Files

  • rice-session-accounts/accounts.json - account names, kinds and credential references.
  • rice-session-accounts/logins/<name>/ - each browser account's isolated login folder.
  • rice-session-accounts/locks/ - renewal locks shared by sessions.

Contributing

See CONTRIBUTING.md. Adapted from simplecore-inc/claude-mods (MIT); see THIRD_PARTY_NOTICES.md. Release history is in CHANGELOG.md.

License

MIT, see LICENSE. The adapted code keeps its own MIT notice in LICENSES/.

Source 20 files
hooks/register.ts 1356 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, HookFailure, HttpInit, HttpResponse, Register, Timer, On } from 'claude-code'
3
4import type { AccountSnapshot, ActiveAccount, EnvSnapshot } from '../types'
5import { loginEmail, materialFor } from './accounts'
6import type { Machine } from './accounts'
7import { ARGUMENT_HINT, completions, helpText, parseCommand } from './command-line'
8import { ADD_OPTIONS, addAccount, defaultConfig, describeAccount, KINDS, LOGIN_NAME, parseConfig, pathsFor, removeAccount, serializeConfig, UNPARSED_CONFIG } from './config'
9import type { AccountConfig, Config, Kind } from './config'
10import { readLogin } from './credentials'
11import { argvInvokesClaude, commandInvokesClaude, GUARD_FAILED } from './descendants'
12import { BLOCKING_VARIABLES, headerToken, MANAGED, oauthHeaders, planEnv, switchBlocker, withoutAuthHeaders } from './env'
13import type { Managed, Originals, SwitchContext } from './env'
14import { accountIdentity } from './identity'
15import type { EnvName, Io } from './io'
16import { message } from './io'
17import { withLock } from './lock'
18import { loginSourceOf, NOT_OAUTH_LOGIN } from './login'
19import type { LoginSource } from './login'
20import { EXPIRY_MARGIN_MS, oauthInit, parseProfile, parseUsage, PROFILE_URL, sessionRateLimits, USAGE_URL, withUserAgent } from './oauth'
21import { ACCOUNT_PICKER_ID, openAccountPicker, refreshAccountPicker, renderAccountPicker, resetAccountPicker } from './picker'
22import type { AccountRow, PickerEntry } from './picker'
23import { refusalText, SessionAuthorizations, UNKNOWN_HANDLE } from './session-auth'
24import { legacyCleanupText, setupText, signOutHint } from './setup'
25
26const PLUGIN = 'rice-session-accounts'
27const activeAtom = atom({ plugin: 'rice-session-accounts', key: 'active' } as const, null)
28const originalsAtom = atom({ plugin: 'rice-session-accounts', key: 'originals' } as const, null)
29const problemAtom = atom({ plugin: 'rice-session-accounts', key: 'problem' } as const, null)
30const authorizationsAtom = atom({ plugin: 'rice-session-accounts', key: 'authorizations' } as const, null)
31
32const ACCOUNT_RECOVERY = 'The session account is not confirmed. Run /rice-account login or select a saved account again before continuing.'
33const ACCOUNT_CHANGING = 'The session account is changing. Retry when the selection completes.'
34const ACCOUNT_CHANGED = 'The session account changed while this request was prepared. Retry the request.'
35const LOCKOUT_STATUS = 'account not confirmed | run /rice-account login or select an account'
36/** At most one usage lookup per this long after a turn, and after /usage. */
37const USAGE_REFRESH_MS = 60_000
38/** A failed renewal waits this long, doubling per failure up to the maximum, before it is tried again. */
39const RENEWAL_BACKOFF_MS = 30_000
40const RENEWAL_BACKOFF_MAX_MS = 600_000
41const LOADING_USAGE = 'loading usage'
42/** What a lockout puts in place of the unconfirmed bearer, so requests nothing hooks fail loudly instead of using the wrong account. */
43const LOCKOUT_BEARER = 'rice-session-accounts-account-not-confirmed'
44
45type ReportedLimit = { kind: string; percentUsed: number; resetsAt?: string }
46type AccountReport = { name: string; generation: number; email: string; tier: string; rateLimits: ReportedLimit[]; problem?: string; isStale?: boolean }
47
48/**
49 * Everything this module holds in memory. `$.state` and the process
50 * environment outlive a reload of this module, and the module outlives a
51 * /clear (which empties the state while this process keeps the account it
52 * switched to): each puts the other back. A fresh load of the module (first
53 * start, reload, worker respawn, enable) is the only time `session.start`
54 * reaches it, so that hook starts from `freshModule()` and then restores the
55 * safety state from `$.state`.
56 */
57function freshModule() {
58  return {
59    isStarted: false,
60    mirror: { active: null as ActiveAccount | null, originals: null as EnvSnapshot | null },
61    renewal: undefined as Timer | undefined,
62    expiresAt: undefined as number | undefined,
63    knownNames: [LOGIN_NAME] as string[],
64    /** Explicit selections in the order they began, and the newest one committed. */
65    selections: 0,
66    committedSelection: 0,
67    /** Advanced by each committed switch; reports of an older generation are discarded. */
68    transitionGeneration: 0,
69    /** Advanced by each attempt to change the environment, committed or rolled back. */
70    commitAttempts: 0,
71    commitTail: Promise.resolve() as Promise<void>,
72    committingAccount: false,
73    accountReport: undefined as AccountReport | undefined,
74    transitionProblem: undefined as string | undefined,
75    usageCheckedAt: undefined as number | undefined,
76    renewalFailures: new Map<string, { streak: number; retryAt: number }>(),
77    authorizations: new SessionAuthorizations(),
78  }
79}
80
81let local = freshModule()
82
83// Claude 2.1.296 follows `$` only into helpers declared in this module.
84
85/**
86 * The selected account. Before `session.start` reached a freshly loaded
87 * module (a reload's first moments), the one a previous load kept in
88 * `$.state` counts, since the environment still carries its header.
89 */
90async function activeAccount($: EngineInterface): Promise<ActiveAccount | null> {
91  if (local.mirror.active || local.isStarted) return local.mirror.active
92  return (await read($, activeAtom)) ?? null
93}
94
95/** The bearer requests on this session carry: the selected header's, or the machine login's. */
96async function currentAccessToken($: EngineInterface, active: ActiveAccount | null): Promise<string | undefined> {
97  if (active) return headerToken(await $.env.get('ANTHROPIC_CUSTOM_HEADERS'))
98  const login = await loginToken($)
99  return 'token' in login ? login.token : undefined
100}
101
102async function variable($: EngineInterface, name: EnvName): Promise<string | undefined> {
103  switch (name) {
104    case 'HOME':
105      return $.env.get('HOME')
106    case 'USER':
107      return $.env.get('USER')
108    case 'OS':
109      return $.env.get('OS')
110    case 'USERPROFILE':
111      return $.env.get('USERPROFILE')
112    case 'USERNAME':
113      return $.env.get('USERNAME')
114    case 'SystemRoot':
115      return $.env.get('SystemRoot')
116    case 'WINDIR':
117      return $.env.get('WINDIR')
118    case 'CLAUDE_CODE_FORCE_WINDOWS_CREDMAN':
119      return $.env.get('CLAUDE_CODE_FORCE_WINDOWS_CREDMAN')
120    case 'CLAUDE_CONFIG_DIR':
121      return $.env.get('CLAUDE_CONFIG_DIR')
122    case 'CLAUDE_SECURESTORAGE_CONFIG_DIR':
123      return $.env.get('CLAUDE_SECURESTORAGE_CONFIG_DIR')
124    case 'CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR':
125      return $.env.get('CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR')
126    case 'ANTHROPIC_FEDERATION_RULE_ID':
127      return $.env.get('ANTHROPIC_FEDERATION_RULE_ID')
128    case 'ANTHROPIC_ORGANIZATION_ID':
129      return $.env.get('ANTHROPIC_ORGANIZATION_ID')
130  }
131}
132
133async function getManaged($: EngineInterface, name: Managed): Promise<string | undefined> {
134  switch (name) {
135    case 'ANTHROPIC_API_KEY':
136      return $.env.get('ANTHROPIC_API_KEY')
137    case 'ANTHROPIC_AUTH_TOKEN':
138      return $.env.get('ANTHROPIC_AUTH_TOKEN')
139    case 'ANTHROPIC_CUSTOM_HEADERS':
140      return $.env.get('ANTHROPIC_CUSTOM_HEADERS')
141    case 'CLAUDE_CODE_OAUTH_TOKEN':
142      return $.env.get('CLAUDE_CODE_OAUTH_TOKEN')
143    case 'CLAUDE_SECURESTORAGE_CONFIG_DIR':
144      return $.env.get('CLAUDE_SECURESTORAGE_CONFIG_DIR')
145    case 'ANTHROPIC_BASE_URL':
146      return $.env.get('ANTHROPIC_BASE_URL')
147    case 'CLAUDE_CODE_USE_BEDROCK':
148      return $.env.get('CLAUDE_CODE_USE_BEDROCK')
149    case 'CLAUDE_CODE_USE_VERTEX':
150      return $.env.get('CLAUDE_CODE_USE_VERTEX')
151    case 'CLAUDE_CODE_USE_FOUNDRY':
152      return $.env.get('CLAUDE_CODE_USE_FOUNDRY')
153    case 'CLAUDE_CODE_USE_ANTHROPIC_AWS':
154      return $.env.get('CLAUDE_CODE_USE_ANTHROPIC_AWS')
155    case 'CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD':
156      return $.env.get('CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD')
157    case 'CLAUDE_CODE_USE_MANTLE':
158      return $.env.get('CLAUDE_CODE_USE_MANTLE')
159    case 'CLAUDE_CODE_USE_GATEWAY':
160      return $.env.get('CLAUDE_CODE_USE_GATEWAY')
161    case 'CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR':
162      return $.env.get('CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR')
163    case 'CLAUDE_CODE_GATEWAY_TOKEN_FILE_DESCRIPTOR':
164      return $.env.get('CLAUDE_CODE_GATEWAY_TOKEN_FILE_DESCRIPTOR')
165    case 'CLAUDE_BG_AUTH_SNAPSHOT_PATH':
166      return $.env.get('CLAUDE_BG_AUTH_SNAPSHOT_PATH')
167    case 'CLAUDE_CODE_HOST_CREDS_FILE':
168      return $.env.get('CLAUDE_CODE_HOST_CREDS_FILE')
169    case 'CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST':
170      return $.env.get('CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST')
171    case 'CLAUDE_CODE_HOST_AUTH_ENV_VAR':
172      return $.env.get('CLAUDE_CODE_HOST_AUTH_ENV_VAR')
173    case 'AWS_PROFILE':
174      return $.env.get('AWS_PROFILE')
175    case 'AWS_REGION':
176      return $.env.get('AWS_REGION')
177    case 'AWS_BEARER_TOKEN_BEDROCK':
178      return $.env.get('AWS_BEARER_TOKEN_BEDROCK')
179    case 'ANTHROPIC_BEDROCK_BASE_URL':
180      return $.env.get('ANTHROPIC_BEDROCK_BASE_URL')
181    case 'ANTHROPIC_VERTEX_PROJECT_ID':
182      return $.env.get('ANTHROPIC_VERTEX_PROJECT_ID')
183    case 'CLOUD_ML_REGION':
184      return $.env.get('CLOUD_ML_REGION')
185    case 'ANTHROPIC_VERTEX_BASE_URL':
186      return $.env.get('ANTHROPIC_VERTEX_BASE_URL')
187    case 'ANTHROPIC_FOUNDRY_RESOURCE':
188      return $.env.get('ANTHROPIC_FOUNDRY_RESOURCE')
189    case 'ANTHROPIC_FOUNDRY_BASE_URL':
190      return $.env.get('ANTHROPIC_FOUNDRY_BASE_URL')
191    case 'ANTHROPIC_FOUNDRY_API_KEY':
192      return $.env.get('ANTHROPIC_FOUNDRY_API_KEY')
193  }
194}
195
196async function setManaged($: EngineInterface, name: Managed, value: string | undefined): Promise<unknown> {
197  switch (name) {
198    case 'ANTHROPIC_API_KEY':
199      return $.env.set('ANTHROPIC_API_KEY', value)
200    case 'ANTHROPIC_AUTH_TOKEN':
201      return $.env.set('ANTHROPIC_AUTH_TOKEN', value)
202    case 'ANTHROPIC_CUSTOM_HEADERS':
203      return $.env.set('ANTHROPIC_CUSTOM_HEADERS', value)
204    case 'CLAUDE_CODE_OAUTH_TOKEN':
205      return $.env.set('CLAUDE_CODE_OAUTH_TOKEN', value)
206    case 'CLAUDE_SECURESTORAGE_CONFIG_DIR':
207      return $.env.set('CLAUDE_SECURESTORAGE_CONFIG_DIR', value)
208    case 'ANTHROPIC_BASE_URL':
209      return $.env.set('ANTHROPIC_BASE_URL', value)
210    case 'CLAUDE_CODE_USE_BEDROCK':
211      return $.env.set('CLAUDE_CODE_USE_BEDROCK', value)
212    case 'CLAUDE_CODE_USE_VERTEX':
213      return $.env.set('CLAUDE_CODE_USE_VERTEX', value)
214    case 'CLAUDE_CODE_USE_FOUNDRY':
215      return $.env.set('CLAUDE_CODE_USE_FOUNDRY', value)
216    case 'CLAUDE_CODE_USE_ANTHROPIC_AWS':
217      return $.env.set('CLAUDE_CODE_USE_ANTHROPIC_AWS', value)
218    case 'CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD':
219      return $.env.set('CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD', value)
220    case 'CLAUDE_CODE_USE_MANTLE':
221      return $.env.set('CLAUDE_CODE_USE_MANTLE', value)
222    case 'CLAUDE_CODE_USE_GATEWAY':
223      return $.env.set('CLAUDE_CODE_USE_GATEWAY', value)
224    case 'CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR':
225      return $.env.set('CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR', value)
226    case 'CLAUDE_CODE_GATEWAY_TOKEN_FILE_DESCRIPTOR':
227      return $.env.set('CLAUDE_CODE_GATEWAY_TOKEN_FILE_DESCRIPTOR', value)
228    case 'CLAUDE_BG_AUTH_SNAPSHOT_PATH':
229      return $.env.set('CLAUDE_BG_AUTH_SNAPSHOT_PATH', value)
230    case 'CLAUDE_CODE_HOST_CREDS_FILE':
231      return $.env.set('CLAUDE_CODE_HOST_CREDS_FILE', value)
232    case 'CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST':
233      return $.env.set('CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST', value)
234    case 'CLAUDE_CODE_HOST_AUTH_ENV_VAR':
235      return $.env.set('CLAUDE_CODE_HOST_AUTH_ENV_VAR', value)
236    case 'AWS_PROFILE':
237      return $.env.set('AWS_PROFILE', value)
238    case 'AWS_REGION':
239      return $.env.set('AWS_REGION', value)
240    case 'AWS_BEARER_TOKEN_BEDROCK':
241      return $.env.set('AWS_BEARER_TOKEN_BEDROCK', value)
242    case 'ANTHROPIC_BEDROCK_BASE_URL':
243      return $.env.set('ANTHROPIC_BEDROCK_BASE_URL', value)
244    case 'ANTHROPIC_VERTEX_PROJECT_ID':
245      return $.env.set('ANTHROPIC_VERTEX_PROJECT_ID', value)
246    case 'CLOUD_ML_REGION':
247      return $.env.set('CLOUD_ML_REGION', value)
248    case 'ANTHROPIC_VERTEX_BASE_URL':
249      return $.env.set('ANTHROPIC_VERTEX_BASE_URL', value)
250    case 'ANTHROPIC_FOUNDRY_RESOURCE':
251      return $.env.set('ANTHROPIC_FOUNDRY_RESOURCE', value)
252    case 'ANTHROPIC_FOUNDRY_BASE_URL':
253      return $.env.set('ANTHROPIC_FOUNDRY_BASE_URL', value)
254    case 'ANTHROPIC_FOUNDRY_API_KEY':
255      return $.env.set('ANTHROPIC_FOUNDRY_API_KEY', value)
256  }
257}
258
259/** Sets one managed variable and reads it back; a refusal or a value that did not stick throws. */
260/** A refusal text that may echo the value it was asked to set, with that value and any bearer removed. */
261function redacted(text: string, value: string | undefined): string {
262  const hidden = value && value.length >= 8 ? text.split(value).join('[value]') : text
263  return hidden.replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')
264}
265
266async function setManagedChecked($: EngineInterface, name: Managed, value: string | undefined): Promise<void> {
267  let refusal: string | undefined
268  try {
269    const outcome = await setManaged($, name, value)
270    // The engine holds a write it will not make by resolving with a reason.
271    if (typeof outcome === 'object' && outcome !== null && 'deny' in outcome && typeof outcome.deny === 'string') refusal = outcome.deny
272  } catch (error) { refusal = message(error) }
273  if (refusal !== undefined) refusal = redacted(refusal, value)
274  if (refusal !== undefined || (await getManaged($, name)) !== value) {
275    throw new Error(`Claude refused the session environment change for ${name}${refusal ? ` (${refusal.replace(/\.$/, '')})` : ''}. The account was not switched.`)
276  }
277}
278
279/** `$.http.fetch` for the Anthropic OAuth endpoints, with the User-Agent Claude Code of this version sends. */
280async function oauthFetch($: EngineInterface, url: string, init: HttpInit | undefined): Promise<HttpResponse> {
281  const version = await $.session.version().then(running => running.version, () => undefined)
282  return $.http.fetch(url, withUserAgent(init, version))
283}
284
285function machineIo($: EngineInterface): Io {
286  return {
287    run: (argv, init) => $.process.run(argv, init),
288    read: path => $.fs.read(path),
289    write: (path, text) => $.fs.write(path, text),
290    exists: path => $.fs.exists(path),
291    stat: path => $.fs.stat(path),
292    env: name => variable($, name),
293    now: () => $.clock.now(),
294    sleep: ms => $.clock.sleep(ms),
295    fetch: (url, init) => oauthFetch($, url, init),
296    log: text => $.ui.log(text, { to: 'debug' }),
297  }
298}
299
300async function machineOf($: EngineInterface): Promise<Machine> {
301  const configDir = await variable($, 'CLAUDE_CONFIG_DIR')
302  const windows = await variable($, 'OS') === 'Windows_NT'
303  const home = (windows ? await variable($, 'USERPROFILE') : undefined) || await variable($, 'HOME')
304  if (!configDir && !home) {
305    throw new Error(`Rice Accounts cannot find the Claude configuration folder: ${windows ? 'USERPROFILE' : 'HOME'} and CLAUDE_CONFIG_DIR are both unset. Start Claude with one of them set.`)
306  }
307  const originals = (await read($, originalsAtom)) ?? local.mirror.originals
308
309  return {
310    claudeDir: configDir || `${home}/.claude`,
311    user: (windows ? await variable($, 'USERNAME') : undefined) ?? await variable($, 'USER'),
312    storage: { configDir: configDir || undefined, secureStorageDir: originals ? originals.CLAUDE_SECURESTORAGE_CONFIG_DIR ?? undefined : await variable($, 'CLAUDE_SECURESTORAGE_CONFIG_DIR') },
313  }
314}
315
316function oauthNames(config: Config): string[] {
317  return Object.entries(config.accounts).filter(([, account]) => (KINDS as readonly string[]).includes(account.kind)).map(([name]) => name)
318}
319
320async function loadConfig($: EngineInterface): Promise<{ config: Config; problems: string[] }> {
321  const paths = pathsFor((await machineOf($)).claudeDir)
322  if (!(await $.fs.exists(paths.config))) {
323    local.knownNames = [LOGIN_NAME]
324    return { config: defaultConfig(), problems: [] }
325  }
326  const loaded = parseConfig(await $.fs.read(paths.config))
327  local.knownNames = oauthNames(loaded.config)
328
329  return loaded
330}
331
332/** Defaults stand in for a file that does not parse; writing them would discard every saved entry. */
333async function writableConfig($: EngineInterface): Promise<Config> {
334  const { config, problems } = await loadConfig($)
335  const unparsed = problems.find(problem => problem.startsWith(UNPARSED_CONFIG))
336  if (unparsed) throw new Error(`${unparsed}. Repair accounts.json first; it was left unchanged.`)
337  return config
338}
339
340/**
341 * Reads, changes and writes accounts.json under a lock beside it, so two
342 * sessions editing at once cannot lose each other's change. The file is read
343 * again inside the lock; `edit` decides from that copy.
344 */
345async function editConfig<T>($: EngineInterface, edit: (config: Config) => { config?: Config; result: T }): Promise<T> {
346  const machine = await machineOf($)
347  const paths = pathsFor(machine.claudeDir)
348  // A file that does not parse is refused before any lock is taken.
349  await writableConfig($)
350  return withLock(machineIo($), `${paths.config}.lock`, { staleMs: 30_000, tries: 20 }, async () => {
351    const config = await writableConfig($)
352    const edited = edit(config)
353    if (edited.config && edited.config !== config) {
354      await $.fs.write(paths.config, serializeConfig(edited.config))
355      local.knownNames = oauthNames(edited.config)
356    }
357    return edited.result
358  })
359}
360
361/** The managed variables as this process started, taken once and kept across reloads and /clear. */
362async function originalsOf($: EngineInterface): Promise<Originals> {
363  const kept = (await read($, originalsAtom)) ?? local.mirror.originals
364  if (kept) {
365    if (!local.mirror.originals) local.mirror = { ...local.mirror, originals: kept }
366    if (!(await read($, originalsAtom))) await update($, originalsAtom, () => kept)
367
368    return kept as Originals
369  }
370  const taken = {} as Originals
371  for (const name of MANAGED) taken[name] = (await getManaged($, name)) ?? null
372  // A lockout leaves its placeholder bearer in the header; it is not a launch value.
373  if (headerToken(taken.ANTHROPIC_CUSTOM_HEADERS ?? undefined) === LOCKOUT_BEARER) taken.ANTHROPIC_CUSTOM_HEADERS = withoutAuthHeaders(taken.ANTHROPIC_CUSTOM_HEADERS ?? undefined) ?? null
374  local.mirror = { ...local.mirror, originals: taken }
375  await update($, originalsAtom, () => taken)
376
377  return taken
378}
379
380/**
381 * The machine login's OAuth token for usage and profile lookups, or why there
382 * is none: one rule for every caller, in native precedence (an API key or a
383 * provider has no subscription usage; a launch CLAUDE_CODE_OAUTH_TOKEN comes
384 * before the stored /login, which is read only when nothing else was given).
385 */
386async function loginToken($: EngineInterface): Promise<{ token: string } | { problem: string }> {
387  const source = await loginSource($)
388  if (source.kind === 'not-oauth') return { problem: NOT_OAUTH_LOGIN }
389  if (source.kind === 'launch-token') return { token: source.token }
390  const machine = await machineOf($)
391  const stored = await readLogin(machineIo($), { storage: machine.storage, defaultConfigDir: machine.claudeDir, user: machine.user })
392  return stored ? { token: stored.claudeAiOauth.accessToken } : { problem: 'This machine has no saved Claude OAuth login. Run claude auth login in a terminal.' }
393}
394
395/**
396 * How the machine login authenticates, from the launch values. Read-only, so
397 * a render hook (the account picker) may ask: until the launch values are
398 * kept, nothing has changed the environment, which then still holds them.
399 */
400async function loginSource($: EngineInterface): Promise<LoginSource> {
401  const kept = (await read($, originalsAtom)) ?? local.mirror.originals
402  if (kept) return loginSourceOf(kept as Originals)
403  const current = {} as Originals
404  for (const name of MANAGED) current[name] = (await getManaged($, name)) ?? null
405  return loginSourceOf(current)
406}
407
408function snapshotOf(account: AccountConfig): AccountSnapshot | undefined {
409  if (account.kind !== 'claudeai' && account.kind !== 'claudeai-token') return undefined
410  return {
411    kind: account.kind,
412    ...(account.loginDir ? { loginDir: account.loginDir } : {}),
413    ...(account.secret ? { secret: { service: account.secret.service, account: account.secret.account } } : {}),
414    ...(account.label ? { label: account.label } : {}),
415  }
416}
417
418/** The kept account of a switch, when the state holds a usable one (state written by 0.4.1 holds none). */
419function keptAccount(active: ActiveAccount | null | undefined): AccountConfig | undefined {
420  const kept = active?.account
421  if (!kept || kept.kind !== 'claudeai' && kept.kind !== 'claudeai-token') return undefined
422  if (kept.kind === 'claudeai' && typeof kept.loginDir !== 'string') return undefined
423  if (kept.kind === 'claudeai-token' && (typeof kept.secret?.service !== 'string' || typeof kept.secret.account !== 'string')) return undefined
424  return { kind: kept.kind, loginDir: kept.loginDir, secret: kept.secret, label: kept.label }
425}
426
427/** The session account's configuration: the copy taken when it was selected, else the machine login. */
428function sessionAccount(): { name: string; account: AccountConfig | undefined } {
429  const active = local.mirror.active
430  if (!active) return { name: LOGIN_NAME, account: { kind: 'login' } }
431  return { name: active.name, account: keptAccount(active) }
432}
433
434/**
435 * The unconfirmed-account problem: this module's, or, until `session.start`
436 * has taken the kept state back, one a previous load left in `$.state`.
437 */
438async function lockoutProblem($: EngineInterface): Promise<string | undefined> {
439  if (local.transitionProblem || local.isStarted) return local.transitionProblem
440  const kept: unknown = await read($, problemAtom)
441  if (kept === null || kept === undefined) return undefined
442  // A stored lockout that is not text is damaged state: stay locked rather than guess.
443  return typeof kept === 'string' && kept !== '' ? kept : ACCOUNT_RECOVERY
444}
445
446/** Locks the session account out until a verified selection: kept in `$.state` so a reload keeps it. */
447async function enterLockout($: EngineInterface, problem: string): Promise<void> {
448  local.transitionProblem = problem
449  local.accountReport = undefined
450  // A lookup begun before the lockout must not overwrite its status.
451  local.commitAttempts += 1
452  await neutralizeBearer($)
453  local.renewal?.cancel()
454  local.renewal = undefined
455  $.ui.status(LOCKOUT_STATUS)
456  try { await update($, problemAtom, () => problem) } catch (error) { $.ui.log(`The account lockout could not be kept for a reload: ${message(error)}`, { to: 'debug' }) }
457}
458
459/**
460 * While the account is unconfirmed, requests that no hook sees (the permission
461 * classifier, titles, MCP servers, other tools) must not go out on a bearer
462 * nobody confirmed: the generated bearer line becomes one no server accepts.
463 * Best effort; a verified switch or `login` sets the real headers again.
464 */
465async function neutralizeBearer($: EngineInterface): Promise<void> {
466  try {
467    const headers = await $.env.get('ANTHROPIC_CUSTOM_HEADERS')
468    if (!headerToken(headers) || headerToken(headers) === LOCKOUT_BEARER) return
469    await $.env.set('ANTHROPIC_CUSTOM_HEADERS', oauthHeaders(headers, LOCKOUT_BEARER))
470  } catch (error) {
471    $.ui.log(`The unconfirmed bearer could not be neutralized: ${message(error)}`, { to: 'debug' })
472  }
473}
474
475async function leaveLockout($: EngineInterface): Promise<void> {
476  local.transitionProblem = undefined
477  try {
478    if (await read($, problemAtom)) await update($, problemAtom, () => null)
479  } catch (error) { $.ui.log(`The cleared account lockout could not be kept for a reload: ${message(error)}`, { to: 'debug' }) }
480}
481
482async function keepAuthorizations($: EngineInterface): Promise<void> {
483  try { await update($, authorizationsAtom, () => local.authorizations.snapshot()) } catch (error) { $.ui.log(`The authorization table could not be kept for a reload: ${message(error)}`, { to: 'debug' }) }
484}
485
486function reportStatus(report: AccountReport): string {
487  const limits = report.rateLimits.map(limit => `${limit.kind === 'five_hour' ? '5h' : limit.kind === 'seven_day' ? 'wk' : limit.kind} ${Math.round(limit.percentUsed)}%`).join(', ')
488  return `account ${report.name} | ${report.email} | ${report.tier}${limits ? ` | ${limits}${report.isStale ? ' (stale)' : ''}` : ''}${report.problem ? ` | ${report.problem}` : ''}`
489}
490
491function withReportedLimits<T>(result: T, rateLimits: ReportedLimit[]): T {
492  if (typeof result !== 'object' || result === null || !('value' in result) || typeof result.value !== 'object' || result.value === null) return result
493  return { ...result, value: { ...result.value, rateLimits: sessionRateLimits(rateLimits) } }
494}
495
496function reportedLimits(text: string): ReportedLimit[] {
497  return parseUsage(JSON.parse(text)).map(limit => ({
498    kind: limit.label === '5h' ? 'five_hour' : limit.label === 'wk' ? 'seven_day' : limit.label,
499    percentUsed: limit.percent,
500    ...(limit.resetsAt ? { resetsAt: limit.resetsAt } : {}),
501  }))
502}
503
504/** Which selection a piece of report work belongs to; it is applied only while that selection still stands. */
505type Selection = { name: string; generation: number; attempt: number }
506
507function selection(): Selection {
508  return { name: local.mirror.active?.name ?? LOGIN_NAME, generation: local.transitionGeneration, attempt: local.commitAttempts }
509}
510
511function isCurrent(taken: Selection): boolean {
512  return !local.committingAccount && taken.generation === local.transitionGeneration && taken.attempt === local.commitAttempts && taken.name === (local.mirror.active?.name ?? LOGIN_NAME)
513}
514
515/**
516 * Looks up the selected account's identity and usage for the status line and
517 * `session.usage`. Never rejects: every failure becomes the report's problem.
518 * A lookup begun for A can finish after B was selected, so the result is
519 * applied only while the selection it was begun for still stands.
520 */
521async function refreshReport($: EngineInterface, taken: Selection, account: AccountConfig, secret?: string): Promise<void> {
522  const previous = local.accountReport?.name === taken.name ? local.accountReport : undefined
523  let identity = { email: previous?.email ?? 'Unknown', tier: previous?.tier ?? 'Unknown' }
524  let rateLimits: ReportedLimit[] = [], problem: string | undefined
525  try {
526    const machine = await machineOf($)
527    identity = await accountIdentity(machineIo($), account, machine, account.kind === 'login' ? await loginSource($) : undefined)
528    let token = secret
529    if (account.kind === 'login') {
530      const login = await loginToken($)
531      if ('problem' in login) problem = 'usage unavailable for this login'
532      else token = login.token
533    }
534    if (!problem) {
535      if (!token) problem = 'usage unavailable'
536      else {
537        local.usageCheckedAt = await $.clock.now()
538        const response = await oauthFetch($, USAGE_URL, oauthInit({ token }))
539        if (!response.ok) problem = `usage unavailable (HTTP ${response.status})`
540        else {
541          try { rateLimits = reportedLimits(response.text) } catch { problem = 'usage unavailable (the usage response did not parse)' }
542        }
543      }
544    }
545  } catch (error) {
546    problem = `usage unavailable (${message(error).replace(/\.$/, '')})`
547  }
548  if (!isCurrent(taken)) return
549  // A failed lookup keeps the limits already shown, marked stale, rather than blanking them.
550  local.accountReport = problem !== undefined && previous && previous.rateLimits.length > 0
551    ? { ...previous, generation: taken.generation, ...identity, isStale: true, problem: problem.replace(/^usage unavailable/, 'usage not refreshed') }
552    : { name: taken.name, generation: taken.generation, ...identity, rateLimits, problem }
553  $.ui.status(reportStatus(local.accountReport))
554}
555
556/** After a main-loop turn: at most one usage lookup a minute, none while nonessential traffic is off. */
557async function refreshAfterTurn($: EngineInterface): Promise<void> {
558  const report = local.accountReport
559  if (!report || local.transitionProblem || local.committingAccount) return
560  const now = await $.clock.now()
561  const isLoading = report.problem === LOADING_USAGE
562  if (!isLoading && local.usageCheckedAt !== undefined && now - local.usageCheckedAt < USAGE_REFRESH_MS) return
563  if (await $.env.get('CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC')) return
564  const taken = selection()
565  const { account } = sessionAccount()
566  if (!account) return
567  const token = account.kind === 'login' ? undefined : await currentAccessToken($, local.mirror.active)
568  if (!isCurrent(taken)) return
569  local.usageCheckedAt = now
570  await refreshReport($, taken, account, token)
571}
572
573function scheduleRenewal($: EngineInterface, name: string, wait: number): void {
574  local.renewal?.cancel()
575  local.renewal = $.clock.after(Math.max(1_000, wait), () => {
576    void renewIfActive($, name)
577  })
578}
579
580function scheduleExpiry($: EngineInterface, name: string, now: number): void {
581  local.renewal?.cancel()
582  local.renewal = undefined
583  if (local.expiresAt === undefined) return
584  scheduleRenewal($, name, Math.max(30_000, local.expiresAt - EXPIRY_MARGIN_MS - now))
585}
586
587/**
588 * Renews the session account's credential before it expires. A failure backs
589 * off per account (30 s doubling to 10 minutes, reset by a success) and tells
590 * the person once per run of failures.
591 */
592async function renewIfActive($: EngineInterface, name: string): Promise<void> {
593  if (local.transitionProblem || local.mirror.active?.name !== name) return
594  const now = await $.clock.now()
595  const failure = local.renewalFailures.get(name)
596  if (failure && now < failure.retryAt) return
597  try {
598    await switchTo($, name, true)
599    local.renewalFailures.delete(name)
600  } catch (error) {
601    const streak = (failure?.streak ?? 0) + 1
602    const wait = Math.min(RENEWAL_BACKOFF_MAX_MS, RENEWAL_BACKOFF_MS * 2 ** (streak - 1))
603    local.renewalFailures.set(name, { streak, retryAt: now + wait })
604    $.ui.log(`Could not renew ${name}: ${message(error)} Next attempt in ${Math.round(wait / 1000)} s.`, { to: 'debug' })
605    if (streak === 1) $.ui.toast(`Rice Accounts could not renew ${name}: ${message(error).replace(/\.$/, '')}. It retries in the background.`)
606    if (local.mirror.active?.name === name && !local.transitionProblem) scheduleRenewal($, name, wait)
607  }
608}
609
610/**
611 * What a switch is checked against (`SWITCH_BLOCKERS`), read without changing
612 * anything. Settings that cannot be read refuse the switch; a machine login that cannot be read does not.
613 */
614async function switchContext($: EngineInterface): Promise<SwitchContext> {
615  let settings: SwitchContext['settings']
616  try { settings = await $.settings.read() } catch (error) { $.ui.log(`The settings were not read before the switch: ${message(error)}`, { to: 'debug' }) }
617  const variables: Partial<Record<EnvName, string>> = {}
618  for (const name of BLOCKING_VARIABLES) {
619    const value = await variable($, name)
620    if (value) variables[name] = value
621  }
622  // Claude Code's own login as the process started: a launch OAuth token, else the stored /login.
623  const kept = ((await read($, originalsAtom)) ?? local.mirror.originals) as Originals | null
624  const launched = async (name: 'CLAUDE_CODE_OAUTH_TOKEN' | 'CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR') => kept ? kept[name] ?? undefined : await getManaged($, name)
625  let isOAuthLogin: boolean | undefined = Boolean(await launched('CLAUDE_CODE_OAUTH_TOKEN') || await launched('CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR'))
626  if (!isOAuthLogin) {
627    try {
628      const machine = await machineOf($)
629      isOAuthLogin = Boolean((await readLogin(machineIo($), { storage: machine.storage, defaultConfigDir: machine.claudeDir, user: machine.user }))?.claudeAiOauth.accessToken)
630    } catch (error) {
631      isOAuthLogin = undefined
632      $.ui.log(`The machine login was not read before the switch: ${message(error)}`, { to: 'debug' })
633    }
634  }
635  return { settings, variables, isOAuthLogin }
636}
637
638/**
639 * Puts this process on an account: its secret read, the managed variables
640 * set, the state and status updated. `isQuiet` renews or restores the
641 * account the session holds, from the copy taken when it was selected.
642 */
643async function switchTo($: EngineInterface, name: string, isQuiet = false, expectedSelection?: number): Promise<string> {
644  const sequence = isQuiet ? expectedSelection ?? local.committedSelection : ++local.selections
645  let account = isQuiet && local.mirror.active?.name === name ? keptAccount(local.mirror.active) : undefined
646  if (!account) {
647    const { config, problems } = await loadConfig($)
648    account = config.accounts[name]
649    if (!account) {
650      const extra = problems.length > 0 ? ` (accounts.json: ${problems.join('; ')})` : ''
651      throw new Error(`No account named ${name}. Saved: ${oauthNames(config).join(', ')}${extra}.`)
652    }
653  }
654  if (!(KINDS as readonly string[]).includes(account.kind)) throw new Error('Rice Accounts switches Anthropic OAuth accounts only. Configure provider accounts in rice-multi-models. This saved entry was kept.')
655  // A new selection that Claude Code's own credential would override is refused
656  // before anything changes; a selection already in effect keeps renewing.
657  if (!isQuiet && account.kind !== 'login') {
658    const blocker = switchBlocker(await switchContext($))
659    if (blocker) throw new Error(blocker)
660  }
661  const machine = await machineOf($)
662  const originals = await originalsOf($)
663  const material = await materialFor(machineIo($), name, account, pathsFor(machine.claudeDir), machine)
664  // Credential refresh may finish after the person selected another account.
665  // Prepare in parallel, then serialize environment/state commits and reject old work.
666  const preceding = local.commitTail
667  let releaseCommit = () => {}
668  local.commitTail = new Promise<void>(resolve => { releaseCommit = resolve })
669  await preceding
670  let taken = selection()
671  let keepsReport = false
672  try {
673    if (isQuiet ? local.committedSelection !== sequence || local.mirror.active?.name !== name : sequence < local.committedSelection) {
674      if (isQuiet) return ''
675      throw new Error('Another account choice superseded this switch. The newer selection was kept.')
676    }
677    // A renewal keeps the account and its report; only a new selection reports afresh.
678    keepsReport = isQuiet && local.accountReport?.name === name && local.accountReport.problem !== LOADING_USAGE
679    const plan = planEnv(account, material.secret, originals)
680    const previous = {
681      mirror: local.mirror, active: (await read($, activeAtom)) ?? null, expiresAt: local.expiresAt,
682      report: local.accountReport, problem: local.transitionProblem,
683    }
684    local.committingAccount = true
685    local.commitAttempts += 1
686    const precedingValues = new Map<Managed, string | undefined>()
687    let stateAttempted = false, timerChanged = false
688    try {
689      for (const variableName of MANAGED) {
690        const before = await getManaged($, variableName)
691        if (before === plan[variableName]) continue
692        precedingValues.set(variableName, before)
693        await setManagedChecked($, variableName, plan[variableName])
694      }
695      const now = await $.clock.now()
696      const snapshot = snapshotOf(account)
697      const active: ActiveAccount | null = name === LOGIN_NAME ? null : { name, switchedAt: now, ...(snapshot ? { account: snapshot } : {}) }
698      stateAttempted = true
699      await update($, activeAtom, () => active)
700      const saved = await read($, activeAtom)
701      if ((saved?.name ?? null) !== (active?.name ?? null) || saved?.switchedAt !== active?.switchedAt) throw new Error('Claude refused the session account state change. The account was not switched.')
702      local.mirror = { ...local.mirror, active }
703      local.expiresAt = material.expiresAt
704      timerChanged = true
705      scheduleExpiry($, name, now)
706    } catch (error) {
707      const rollbackProblems: string[] = []
708      local.mirror = previous.mirror
709      local.expiresAt = previous.expiresAt
710      local.accountReport = previous.report
711      local.transitionProblem = previous.problem
712      if (stateAttempted) {
713        try {
714          await update($, activeAtom, () => previous.active)
715          const saved = await read($, activeAtom)
716          if ((saved?.name ?? null) !== (previous.active?.name ?? null) || saved?.switchedAt !== previous.active?.switchedAt) rollbackProblems.push('account state')
717        } catch { rollbackProblems.push('account state') }
718      }
719      for (const [variableName, before] of [...precedingValues.entries()].reverse()) {
720        try { await setManagedChecked($, variableName, before) } catch { rollbackProblems.push(variableName) }
721      }
722      if (timerChanged) {
723        try { scheduleExpiry($, previous.mirror.active?.name ?? LOGIN_NAME, await $.clock.now()) } catch { rollbackProblems.push('renewal timer') }
724      }
725      if (rollbackProblems.length > 0) {
726        await enterLockout($, ACCOUNT_RECOVERY)
727        throw new Error(`${message(error)} Rollback could not restore ${rollbackProblems.join(', ')}. ${ACCOUNT_RECOVERY}`)
728      }
729      $.ui.status(previous.report ? reportStatus(previous.report) : undefined)
730      throw error
731    }
732    // Committed: everything after this point reports, and never fails the switch.
733    local.transitionGeneration += 1
734    local.committedSelection = Math.max(local.committedSelection, sequence)
735    if (local.transitionProblem) await leaveLockout($)
736    taken = { name, generation: local.transitionGeneration, attempt: local.commitAttempts }
737    local.accountReport = keepsReport && local.accountReport
738      ? { ...local.accountReport, generation: taken.generation }
739      : { name, generation: taken.generation, email: 'Loading account', tier: 'Unknown', rateLimits: [], problem: LOADING_USAGE }
740    $.ui.status(reportStatus(local.accountReport))
741  } finally { local.committingAccount = false; releaseCommit() }
742  if (!isQuiet) {
743    local.renewalFailures.delete(name)
744    refreshAccountPicker()
745  }
746  if (!keepsReport) await refreshReport($, taken, account, material.secret)
747  if (isQuiet) return ''
748  if (local.committedSelection !== sequence) return 'A newer account choice superseded this selection. The newer account was kept.'
749  const reported = local.accountReport?.name === name && local.accountReport.email !== 'Unknown' ? local.accountReport.email : undefined
750  const email = reported ?? await loginEmail(machineIo($), account.loginDir).catch(() => undefined)
751  const gateway = await foreignGateway($)
752  const notice = gateway ? ` This session sends its requests to ${gateway}, not api.anthropic.com, so that host receives the account's token.` : ''
753  return name === LOGIN_NAME
754    ? `This session is back on this machine's /login. Other sessions were not touched.`
755    : `This session now uses ${name} (${account.kind}${email ? `, ${email}` : ''}) from its next request, for its subagents and any claude -p it starts. Other sessions keep their own account.${notice}`
756}
757
758/** The host this session sends requests to when it is not Anthropic's own API (a gateway), else undefined. */
759async function foreignGateway($: EngineInterface): Promise<string | undefined> {
760  const base = await $.env.get('ANTHROPIC_BASE_URL')
761  if (!base) return undefined
762  try {
763    const host = new URL(base).host
764    return host && host !== 'api.anthropic.com' ? host : undefined
765  } catch { return 'an address Claude could not parse' }
766}
767
768/**
769 * After a reload (state kept) or a /clear (module kept), the account this
770 * process holds is put back in both. Fail closed: when it cannot be put back,
771 * requests stay refused until a verified selection rather than leaving the
772 * environment on an account the reports do not show.
773 */
774async function restore($: EngineInterface): Promise<void> {
775  if (await lockoutProblem($)) return
776  // A selection the person commits while this restore awaits must not be undone by it.
777  const startedAt = local.committedSelection
778  let kept: ActiveAccount | null = null
779  try {
780    const saved = await read($, activeAtom)
781    kept = saved ?? local.mirror.active
782    if (!kept) {
783      // The machine login: take the launch values now, before anything changes them.
784      await originalsOf($).catch(error => $.ui.log(`The launch environment was not recorded yet: ${message(error)}`, { to: 'debug' }))
785      return
786    }
787    await originalsOf($)
788    if (local.committedSelection !== startedAt) return
789    if (!saved) await update($, activeAtom, () => kept)
790    local.mirror = { ...local.mirror, active: kept }
791    await switchTo($, kept.name, true, startedAt)
792  } catch (error) {
793    if (local.committedSelection !== startedAt) return
794    const problem = `The session account${kept ? ` ${kept.name}` : ''} could not be put back (${message(error).replace(/\.$/, '')}). ${ACCOUNT_RECOVERY}`
795    await enterLockout($, problem)
796    $.ui.toast(problem)
797  }
798}
799
800function formatLimits(limits: { label: string; percent: number; resetsAt?: string }[]): string {
801  if (limits.length === 0) return 'No usage windows were reported.'
802
803  return limits
804    .map(limit => {
805      const at = limit.resetsAt ? new Date(limit.resetsAt) : undefined
806      const when = at && !Number.isNaN(at.getTime()) ? `, resets ${at.toLocaleString()}` : ''
807
808      return `${limit.label} ${Math.round(limit.percent)}%${when}`
809    })
810    .join('\n')
811}
812
813async function usageText($: EngineInterface): Promise<string> {
814  const problem = await lockoutProblem($)
815  if (problem) return problem
816  const taken = selection()
817  const { name, account: kept } = sessionAccount()
818  const account = kept ?? (await loadConfig($)).config.accounts[name]
819  if (!account) return `No account named ${name}.`
820  if (!(KINDS as readonly string[]).includes(account.kind)) return 'Rice Accounts supports Anthropic OAuth accounts only. This provider entry is retained for compatibility; use rice-multi-models for providers.'
821  let token: string
822  if (account.kind === 'login') {
823    const login = await loginToken($)
824    if ('problem' in login) return login.problem
825    token = login.token
826  } else {
827    const machine = await machineOf($)
828    const material = await materialFor(machineIo($), name, account, pathsFor(machine.claudeDir), machine)
829    if (!material.secret) return `${name} has no token. Run /rice-account setup ${name}.`
830    token = material.secret
831  }
832  local.usageCheckedAt = await $.clock.now()
833  const response = await oauthFetch($, USAGE_URL, oauthInit({ token }))
834  if (!response.ok) return `${name}: the usage lookup answered HTTP ${response.status}${account.kind === 'claudeai-token' ? ' (setup tokens may not reach it)' : ''}.`
835  const body: unknown = JSON.parse(response.text)
836  const report = local.accountReport
837  if (report && report.name === name && isCurrent(taken)) {
838    local.accountReport = { ...report, rateLimits: reportedLimits(response.text), isStale: false, problem: undefined }
839    $.ui.status(reportStatus(local.accountReport))
840  }
841
842  return `${name} usage:\n${formatLimits(parseUsage(body))}`
843}
844
845function selectedReportProblem(detail: string | undefined): string {
846  return local.transitionProblem ?? `The selected session account report is unavailable${detail ? ` (${detail.replace(/\.$/, '')})` : ''}. The machine login was not reported in its place. Retry, or run /rice-account check.`
847}
848
849async function statusText($: EngineInterface): Promise<string> {
850  const problem = await lockoutProblem($)
851  if (problem) return problem
852  const [version, model, cwd] = await Promise.all([$.session.version(), $.session.model(), $.session.cwd()])
853  const report = local.accountReport
854  const name = local.mirror.active?.name ?? LOGIN_NAME
855  const selected = report && report.name === name
856    ? `Session account: ${report.name}\nEmail: ${report.email}\nPlan: ${report.tier}`
857    : name === LOGIN_NAME ? 'Session account: machine login' : `Session account: ${name}\nEmail: loading\nPlan: loading`
858  return `${selected}\nClaude Code: ${version.version}\nModel: ${model}\nWorking directory: ${cwd}\n\n${await usageText($)}\n\nRice Accounts reports this session selection. The machine login is unchanged.`
859}
860
861async function checkText($: EngineInterface, name: string): Promise<string> {
862  const { config } = await loadConfig($)
863  const current = sessionAccount()
864  const account = name === current.name && current.account ? current.account : config.accounts[name]
865  if (!account) return `No account named ${name}.`
866  if (!(KINDS as readonly string[]).includes(account.kind)) return 'Rice Accounts supports Anthropic OAuth accounts only. This provider entry is retained; use rice-multi-models for providers.'
867  if (account.kind === 'login') {
868    const login = await loginToken($)
869    if ('problem' in login) return `login: ${login.problem}`
870    const response = await oauthFetch($, PROFILE_URL, oauthInit({ token: login.token }))
871    if (!response.ok) return `login: the profile lookup answered HTTP ${response.status}.`
872    return `login: signed in as ${parseProfile(response.text).email}.`
873  }
874  const machine = await machineOf($)
875  const material = await materialFor(machineIo($), name, account, pathsFor(machine.claudeDir), machine)
876  const response = await oauthFetch($, PROFILE_URL, oauthInit({ token: material.secret ?? '' }))
877  if (!response.ok) return `${name}: token found; the profile lookup answered HTTP ${response.status}.`
878  const owner = parseProfile(response.text)
879
880  return `${name}: signed in as ${owner.email}${owner.organizationName ? ` (${owner.organizationName})` : ''}.`
881}
882
883async function listText($: EngineInterface): Promise<string> {
884  const { config, problems } = await loadConfig($)
885  const rows = await accountRows($)
886  const lines = rows.map(row => `${row.selected ? '*' : ' '} ${describeAccount(row.name, config.accounts[row.name]!)} | ${row.email} | ${row.tier}${row.selected ? ' [this session]' : ''}`)
887  const notes = problems.length > 0 ? `\nSkipped in accounts.json: ${problems.join('; ')}.` : ''
888
889  return `${lines.join('\n')}${notes}\n\n/rice-account <name> switches this session only. /rice-account add <name> [kind] saves another (default: claudeai). /rice-account help lists every subcommand.`
890}
891
892function entriesFrom(config: Config): PickerEntry[] {
893  return Object.entries(config.accounts)
894    .filter(([, account]) => (KINDS as readonly string[]).includes(account.kind))
895    .map(([name, account]) => ({ name, kind: account.kind }))
896    .sort((left, right) => left.name.localeCompare(right.name))
897}
898
899async function accountEntries($: EngineInterface): Promise<PickerEntry[]> {
900  const { config } = await loadConfig($)
901  return entriesFrom(config)
902}
903
904async function accountRows($: EngineInterface, page?: readonly PickerEntry[]): Promise<AccountRow[]> {
905  const { config } = await loadConfig($)
906  const machine = await machineOf($)
907  const io = machineIo($)
908  const source = await loginSource($)
909  const current = local.mirror.active?.name ?? LOGIN_NAME
910  const entries = page ?? entriesFrom(config)
911  return Promise.all(entries.map(async ({ name, kind }) => {
912    const account = config.accounts[name]
913    if (!account || account.kind !== kind || !(KINDS as readonly string[]).includes(account.kind)) throw new Error('Saved accounts changed while the picker was loading. Retry to refresh the list.')
914    return { name, kind, selected: name === current, ...await accountIdentity(io, account, machine, source) }
915  }))
916}
917
918function parseOptions(words: readonly string[]): Record<string, string> {
919  const options: Record<string, string> = {}
920  for (const word of words) {
921    const at = word.indexOf('=')
922    if (at <= 0 || at === word.length - 1) throw new Error('Expected key=value for each option; credentials are entered in the terminal helper.')
923    const key = word.slice(0, at)
924    if (!(ADD_OPTIONS as readonly string[]).includes(key)) throw new Error(`Unknown option: ${key}.`)
925    if (options[key] !== undefined) throw new Error(`Repeated option: ${key}.`)
926    options[key] = word.slice(at + 1)
927  }
928
929  return options
930}
931
932const PROVIDER_ENTRY = 'Rice Accounts supports Anthropic OAuth accounts only. This provider entry is retained; use rice-multi-models for providers.'
933
934function withPeriod(text: string): string {
935  return /[.!?:]$/.test(text.trimEnd()) || text.includes('\n') ? text : `${text.trimEnd()}.`
936}
937
938async function platformOf($: EngineInterface): Promise<'win32' | 'posix'> {
939  return (await variable($, 'OS')) === 'Windows_NT' ? 'win32' : 'posix'
940}
941
942async function runCommand($: EngineInterface, args: string): Promise<string> {
943  const parsed = parseCommand(args)
944  try {
945    switch (parsed.kind) {
946      case 'picker':
947        if (await openAccountPicker(() => $.ui.open({ id: ACCOUNT_PICKER_ID, title: 'Choose account', focus: true, closeOnEscape: true }))) return 'Choose an account in the account list. This changes only this session.'
948        return await listText($)
949      case 'help':
950        return helpText()
951      case 'refused':
952        return parsed.text
953      case 'list':
954        return await listText($)
955      case 'usage':
956        return await usageText($)
957      case 'check':
958        return await checkText($, parsed.name ?? local.mirror.active?.name ?? LOGIN_NAME)
959      case 'default':
960        return await switchTo($, (await loadConfig($)).config.default)
961      case 'setup-native':
962        return `Use this plugin inside ordinary claude: it installs no launcher. ${legacyCleanupText((await machineOf($)).claudeDir, await platformOf($))}`
963      case 'setup': {
964        const { config } = await loadConfig($)
965        const account = config.accounts[parsed.name]
966        if (!account) return `${parsed.name} is not saved. Run /rice-account add ${parsed.name} first.`
967        if (!(KINDS as readonly string[]).includes(account.kind)) return PROVIDER_ENTRY
968        if (parsed.name === LOGIN_NAME) return 'The built-in login uses this machine\'s Claude Code authentication. Run claude auth login in a terminal.'
969        return setupText($.plugin.root, (await machineOf($)).claudeDir, parsed.name, false, await platformOf($))
970      }
971      case 'add': {
972        const [word, ...tail] = parsed.rest
973        const kindWord = word !== undefined && !word.includes('=') ? word : undefined
974        const usage = `Usage: /rice-account add <name> [kind] [key=value ...]\nDefault kind: claudeai\nKinds: ${KINDS.filter(each => each !== 'login').join(', ')}\nOptions: label=, service= (setup tokens only). Configure provider accounts in rice-multi-models.`
975        if (kindWord !== undefined && (kindWord === 'login' || !(KINDS as readonly string[]).includes(kindWord))) return usage
976        // Options are checked before accounts.json is locked or read.
977        const options = parseOptions(kindWord !== undefined ? tail : parsed.rest)
978        const machine = await machineOf($)
979        const outcome = await editConfig($, config => {
980          const kind: string = kindWord ?? config.accounts[parsed.name]?.kind ?? 'claudeai'
981          if (kind === 'login' || !(KINDS as readonly string[]).includes(kind)) return { result: { usage: true, isNew: false } }
982          const added = addAccount(config, parsed.name, kind as Kind, options, pathsFor(machine.claudeDir))
983          return { config: added.config, result: { usage: false, isNew: !config.accounts[parsed.name] } }
984        })
985        if (outcome.usage) return usage
986        return setupText($.plugin.root, machine.claudeDir, parsed.name, outcome.isNew, await platformOf($))
987      }
988      case 'remove': {
989        const name = parsed.name
990        if (local.mirror.active?.name === name) return `${name} is this session's account. Switch to another account first, for example /rice-account login.`
991        const refusal = (config: Config): string | undefined => {
992          const account = config.accounts[name]
993          if (config.legacy && Object.hasOwn(config.legacy, name) || account && !(KINDS as readonly string[]).includes(account.kind)) return 'This provider entry is retained. Rice Accounts manages OAuth accounts only.'
994          if (name === LOGIN_NAME) return "This machine's login cannot be removed."
995          if (!account) return `No account named ${name}.`
996          return undefined
997        }
998        // Refused before any lock is taken; checked again inside it.
999        const early = refusal(await writableConfig($))
1000        if (early) return early
1001        const removed = await editConfig($, config => {
1002          const refused = refusal(config)
1003          return refused ? { result: { refused, account: undefined } } : { config: removeAccount(config, name), result: { refused, account: config.accounts[name] } }
1004        })
1005        if (removed.refused) return removed.refused
1006        const account = removed.account
1007        const cleanup =
1008          account?.kind === 'claudeai'
1009            ? `\nIts native login is retained. To sign it out in a terminal: ${signOutHint(account.loginDir ?? '', await platformOf($))}`
1010            : account?.secret
1011              ? '\nIts credential is retained in the OS keyring. Remove it with your OS credential manager when no account uses it.'
1012              : ''
1013
1014        return `Removed ${name} from accounts.json. Sessions already using it keep it until they switch.${cleanup}`
1015      }
1016      case 'set-default': {
1017        const name = parsed.name
1018        const isUnsaved = (config: Config) => !config.accounts[name] || !(KINDS as readonly string[]).includes(config.accounts[name]!.kind)
1019        const unsaved = `${name} is not a saved OAuth account. Run /rice-account list to see the saved accounts.`
1020        if (isUnsaved(await writableConfig($))) return unsaved
1021        const refused = await editConfig($, config => isUnsaved(config) ? { result: true } : { config: { ...config, default: name }, result: false })
1022        if (refused) return unsaved
1023        return `The saved default account is now ${name}. /rice-account default switches this session to it; new sessions still start on this machine's login.`
1024      }
1025      case 'switch':
1026        return await switchTo($, parsed.name)
1027    }
1028  } catch (error) {
1029    return withPeriod(message(error).replace(/^(?:rice-session-accounts:\s*)+/, ''))
1030  }
1031}
1032
1033/**
1034 * /clear empties `$.state` while the process keeps the selected account's
1035 * environment and goes on under a new session id with no `session.start`. At
1036 * that `session.end` the account's name (never a credential) is left in the
1037 * plugin store; the next prompt puts the state back from memory and removes it.
1038 * A load that finds it while the state is empty is a reload in between, which
1039 * can no longer tell the environment's header from a launch value.
1040 */
1041const CLEAR_KEY = 'cleared-with-account'
1042const CLEAR_WINDOW_MS = 15 * 60 * 1000
1043
1044async function clearedWithAccount($: EngineInterface): Promise<boolean> {
1045  try {
1046    const kept = await $.store.get(CLEAR_KEY)
1047    if (kept === undefined || kept === null) return false
1048    await $.store.delete(CLEAR_KEY)
1049    const at = typeof kept === 'object' && kept !== null && 'at' in kept && typeof kept.at === 'number' ? kept.at : 0
1050    return (await $.clock.now()) - at < CLEAR_WINDOW_MS
1051  } catch (error) {
1052    $.ui.log(`The /clear record was not read: ${message(error)}`, { to: 'debug' })
1053    return false
1054  }
1055}
1056
1057/**
1058 * What a failed account guard refuses with. A hook that threw or overran
1059 * cannot say the account is confirmed, so it refuses; one asked in place of a
1060 * re-entry was never run, and refuses only on a lockout this module holds.
1061 */
1062function whenFailed(failure: HookFailure): string | undefined {
1063  return String(failure.kind) === 're-entry' ? local.transitionProblem : local.transitionProblem ?? ACCOUNT_RECOVERY
1064}
1065
1066/**
1067 * Whether /usage and /status answer for the session selection rather than natively. They do while an account
1068 * is selected (the engine would report the machine account) or the session is locked; back on the machine
1069 * login the engine's own panels are right, with the fields this module cannot reproduce.
1070 */
1071async function reportsSelection($: EngineInterface): Promise<boolean> {
1072  return Boolean(await lockoutProblem($) || await activeAccount($))
1073}
1074
1075/** A prompt a person typed (or an SDK host sent) that would start a model turn: not a slash command, not a machine-made message. */
1076function typedPrompt(e: { command?: unknown; isMeta?: true; origin: { kind: string; asUser?: true } }): boolean {
1077  return e.command === undefined && !e.isMeta && (e.origin.kind === 'composer' || e.origin.kind === 'bridge' || e.origin.kind === 'sdk' || (e.origin.kind === 'plugin' && e.origin.asUser === true))
1078}
1079
1080/**
1081 * Refuses a child `claude` while the session account is unconfirmed. Everything else,
1082 * and every child while the account is confirmed, passes through unchanged.
1083 */
1084function registerLockoutGuard(on: On): void {
1085  on('process.run', async ($, e, next) => {
1086    if (argvInvokesClaude(e.argv)) {
1087      const problem = await lockoutProblem($)
1088      if (problem) return { deny: problem }
1089    }
1090    return next(e)
1091  }).catch((_host, e, next) => next.called || !argvInvokesClaude(e.argv) ? next(e) : { deny: GUARD_FAILED })
1092
1093  on('process.spawn', async function* ($, e, next) {
1094    if (argvInvokesClaude(e.argv)) {
1095      const problem = await lockoutProblem($)
1096      if (problem) return { deny: problem }
1097    }
1098    return yield* next(e)
1099  }).catch(async function* (_host, e, next) {
1100    if (next.called || !argvInvokesClaude(e.argv)) return yield* next(e)
1101    return { deny: GUARD_FAILED }
1102  })
1103
1104  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
1105    if (commandInvokesClaude(e.command)) {
1106      const problem = await lockoutProblem($)
1107      if (problem) return { deny: problem }
1108    }
1109    return next(e)
1110  }).catch((_host, e, next) => next.called || !commandInvokesClaude(e.command) ? next(e) : { deny: GUARD_FAILED })
1111}
1112
1113export const register: Register = on => {
1114  registerLockoutGuard(on)
1115  on('ui.render', { component: 'Pane' }, ($, e, next) => {
1116    if (e.requestId !== ACCOUNT_PICKER_ID) return next(e)
1117    return renderAccountPicker(
1118      $.ui.resolve(e),
1119      () => accountEntries($),
1120      page => accountRows($, page),
1121      local.mirror.active?.name ?? LOGIN_NAME,
1122      name => switchTo($, name),
1123      {
1124        invalidate: () => $.ui.invalidate('ui.render'),
1125        log: text => $.ui.log(text),
1126        close: () => $.ui.close({ id: ACCOUNT_PICKER_ID }),
1127        after: (ms, fn) => $.clock.after(ms, fn),
1128        surface: e.surface,
1129      },
1130    )
1131  })
1132  on('ui.close', { id: ACCOUNT_PICKER_ID }, (_$, e, next) => {
1133    resetAccountPicker()
1134    return next(e)
1135  })
1136
1137  on('session.start', async ($, e, next) => {
1138    resetAccountPicker()
1139    // Reached only by a fresh load of this module (first start, reload,
1140    // respawn, enable; never /clear): start from nothing held in memory, then
1141    // take the safety state back from `$.state` before anything else runs.
1142    local.renewal?.cancel()
1143    local = freshModule()
1144    let problem: string | null
1145    try { problem = await read($, problemAtom) } catch (error) { problem = `The kept account state could not be read (${message(error).replace(/\.$/, '')}). ${ACCOUNT_RECOVERY}` }
1146    local.authorizations.restore(await read($, authorizationsAtom).catch(() => null))
1147    // A handle another plugin received while this load was starting is kept with the rest.
1148    const table = local.authorizations.snapshot()
1149    if (table.native.length > 0 || table.issued.length > 0) await keepAuthorizations($)
1150    const active = await read($, activeAtom).catch(() => null)
1151    if (active) local.mirror = { ...local.mirror, active }
1152    if (problem) {
1153      local.transitionProblem = problem
1154      $.ui.status(LOCKOUT_STATUS)
1155    }
1156    local.isStarted = true
1157    // /clear empties `$.state` while the process keeps the selected account's environment; a
1158    // reload before the next turn then finds a generated bearer it can no longer attribute.
1159    if (!problem && !active && !(await read($, originalsAtom).catch(() => null)) && await clearedWithAccount($)) {
1160      await enterLockout($, ACCOUNT_RECOVERY)
1161      $.ui.toast(ACCOUNT_RECOVERY)
1162    }
1163    const started = await next(e)
1164    // Saved names for the typeahead from the start, not only after a first lookup.
1165    await loadConfig($).catch(error => $.ui.log(`accounts.json was not read: ${message(error)}`, { to: 'debug' }))
1166    // Putting the account back comes before anything that could fail without bearing on it.
1167    await restore($)
1168    await $.command.register({
1169      name: 'rice-account',
1170      description: 'Choose the Claude OAuth account for this session by email and plan, or add, set up and check accounts',
1171      argumentHint: ARGUMENT_HINT,
1172    }).catch(error => $.ui.log(`The /rice-account command was not registered: ${message(error)}`, { to: 'debug' }))
1173
1174    return started
1175  })
1176
1177  on('turn.start', async ($, e, next) => {
1178    // /clear empties the state while this module keeps the account: put it
1179    // back, and keep a lockout and the authorization table for a later reload.
1180    if (local.mirror.active && !(await read($, activeAtom))) await restore($)
1181    await $.store.delete(CLEAR_KEY).catch(() => {})
1182    if (local.transitionProblem && !(await read($, problemAtom))) await enterLockout($, local.transitionProblem)
1183    const table = local.authorizations.snapshot()
1184    if ((table.native.length > 0 || table.issued.length > 0) && !(await read($, authorizationsAtom))) await keepAuthorizations($)
1185    const active = local.mirror.active
1186    if (active && !local.transitionProblem && local.expiresAt !== undefined && local.expiresAt - EXPIRY_MARGIN_MS <= (await $.clock.now())) await renewIfActive($, active.name)
1187
1188    return next(e)
1189  })
1190
1191  on('session.end', async ($, e, next) => {
1192    resetAccountPicker()
1193    if (e.reason === 'clear' && local.mirror.active) {
1194      await $.store.set(CLEAR_KEY, { name: local.mirror.active.name, at: await $.clock.now() }).catch(error => $.ui.log(`The /clear record was not kept: ${message(error)}`, { to: 'debug' }))
1195    }
1196    return next(e)
1197  })
1198
1199  on('command.run', { command: 'rice-account' }, async ($, e) => ({ text: await runCommand($, e.args) }))
1200
hooks/accounts.ts 231 lines
1import type { AccountConfig, Paths } from './config'
2import { checkRenewable, inspectLogin, promoteLogin, readLogin, readSecret, saveRenewal } from './credentials'
3import type { LoginLocation } from './credentials'
4import type { Io } from './io'
5import { message } from './io'
6import { isSameGrant } from './keychain'
7import type { Credential, StorageVariables } from './keychain'
8import { LockBusyError, LockLostError, withLock } from './lock'
9import type { Lock, LockOptions } from './lock'
10import { AnthropicError, applyRefresh, needsRefresh, networkProblem, RefreshResponseError, refreshFailure, refreshInit, TOKEN_URL } from './oauth'
11
12/** Where Claude Code keeps this machine's own login. */
13export type Machine = { claudeDir: string; user: string | undefined; storage: StorageVariables }
14
15/** What a switch needs from an account's credential store; the secret stays in memory only. */
16export type Material = { secret?: string; expiresAt?: number }
17
18/**
19 * The renewal lock. Its critical section can last two 15 s store reads, the
20 * token request, a keychain re-read, a 15 s write and a read-back, so a lock
21 * is taken as abandoned only after 150 s. The holder renews its time
22 * (heartbeat) before the token request, every `LOCK_HEARTBEAT_MS` while the
23 * request is pending (for at most `LOCK_HEARTBEAT_LIMIT_MS`), and after the
24 * renewal is written ahead, before the store write.
25 */
26export const RENEWAL_LOCK = { staleMs: 150_000, tries: 20 } as const
27
28/** How often the renewal lock is renewed while the token request is pending: well inside its stale time. */
29export const LOCK_HEARTBEAT_MS = 45_000
30
31/**
32 * How long a pending token request keeps the lock. A connection that went
33 * silent (half-open after a network change) never answers; past this the lock
34 * is left to go stale so other sessions are not locked out for hours. The
35 * request is still awaited, and its answer saved: the compare-and-swap and the
36 * rotation make a takeover in the meantime safe.
37 */
38export const LOCK_HEARTBEAT_LIMIT_MS = 10 * 60_000
39
40/** The secret, and when it expires for a login that does, read from its platform store. */
41export async function materialFor(io: Io, name: string, account: AccountConfig, paths: Paths, machine: Machine): Promise<Material> {
42  if (account.kind === 'claudeai') {
43    const credential = await freshLogin(io, name, account, paths, machine)
44
45    return { secret: credential.claudeAiOauth.accessToken, expiresAt: credential.claudeAiOauth.expiresAt }
46  }
47  if (!account.secret) return {}
48  const text = await readSecret(io, account.secret)
49  if (text === null || text.trim() === '') {
50    throw new Error(
51      `${name} has no stored secret yet: /rice-account setup ${name}`,
52    )
53  }
54
55  return { secret: text.trim() }
56}
57
58async function machineLogin(io: Io, machine: Machine): Promise<Credential | null> {
59  return readLogin(io, { storage: machine.storage, defaultConfigDir: machine.claudeDir, user: machine.user })
60}
61
62/**
63 * Refuse to renew the machine's own grant: it is not this mod's to spend. When
64 * the machine store cannot be read (a locked keychain, for example) the
65 * renewal fails closed, and says why.
66 */
67async function refuseMachineGrant(io: Io, name: string, current: Credential, machine: Machine): Promise<void> {
68  let own: Credential | null
69  try {
70    own = await machineLogin(io, machine)
71  } catch (error) {
72    throw new Error(`Cannot renew ${name}: this machine's own login could not be read to check that ${name} is a different sign-in (${message(error).replace(/\.$/, '')}). No token request was made; unlock or repair the machine's credential store, then retry.`)
73  }
74  if (isSameGrant(current, own)) throw new Error(`${name} holds this machine's own /login; switch to "login" instead`)
75}
76
77type TokenResponse = Awaited<ReturnType<Io['fetch']>>
78
79/**
80 * The token request, renewing the lock every `LOCK_HEARTBEAT_MS` while it is
81 * pending. The request itself is never timed out: the server may already have
82 * rotated the refresh token, and that answer must be saved. After it settles,
83 * heartbeat failures are ignored; a lock taken over meanwhile, or no longer
84 * renewed because the request outlasted `LOCK_HEARTBEAT_LIMIT_MS`, is reported
85 * in `lockLost`, and the answer is still returned for saving.
86 */
87async function requestKeepingLock(io: Io, lock: Lock, name: string, current: Credential): Promise<{ response: TokenResponse; lockLost: boolean }> {
88  let request: Promise<TokenResponse>
89  try {
90    request = io.fetch(TOKEN_URL, refreshInit(current))
91  } catch (error) {
92    request = Promise.reject(error)
93  }
94  // Attached first, so a request that is already answered stops the loop before any heartbeat.
95  let settled = false
96  const done = request.then(() => { settled = true }, () => { settled = true })
97  let lockLost = false
98  const keeping = (async () => {
99    for (let beat = 0; ; beat += 1) {
100      try {
101        await Promise.race([io.sleep(LOCK_HEARTBEAT_MS), done])
102      } catch {
103        return
104      }
105      if (settled) return
106      if ((beat + 1) * LOCK_HEARTBEAT_MS > LOCK_HEARTBEAT_LIMIT_MS) {
107        lockLost = true
108        io.log(`the ${name} token request has been pending for ${Math.round(LOCK_HEARTBEAT_LIMIT_MS / 60_000)} minutes; its renewal lock is no longer renewed, and the answer is still saved if one arrives`)
109        return
110      }
111      try {
112        await lock.heartbeat()
113      } catch (error) {
114        if (settled) return
115        if (error instanceof LockLostError) {
116          lockLost = true
117          io.log(`another session took over the ${name} renewal lock while its token request was pending; this session still saves what the server returns`)
118          return
119        }
120        io.log(`could not renew the ${name} renewal lock while its token request was pending: ${message(error)}`)
121      }
122    }
123  })()
124  let response: TokenResponse | undefined
125  let failure: unknown
126  try {
127    response = await request
128  } catch (error) {
129    failure = error
130  }
131  await keeping
132  if (response === undefined) throw new AnthropicError(`the ${name} login could not be renewed: ${networkProblem(failure)}; the saved login was kept, retry`)
133
134  return { response, lockLost }
135}
136
137/**
138 * The isolated login of a claudeai account, renewed when it expires within
139 * five minutes. Its folder is signed in only for this mod, so renewing it
140 * (the server rotates the refresh token) spends nobody else's grant; the lock
141 * and the inspection inside it keep two sessions from renewing it at once.
142 *
143 * Under the lock the store and its pending renewal are inspected, and the
144 * login to renew is chosen by lineage (rule B in credentials.ts), never by
145 * expiry. Once the server answers, the old refresh token is spent: the renewal
146 * is written ahead to the pending file with the refresh token the store holds
147 * as its base, then saved to the store only if the store still holds that
148 * token (`saveRenewal`). A renewal that could not be saved stays usable and is
149 * saved on a later use. Nothing that could make the store write impossible is
150 * discovered only after the token request: the size check runs before it.
151 */
152export async function freshLogin(io: Io, name: string, account: AccountConfig, paths: Paths, machine: Machine): Promise<Credential> {
153  if (!account.loginDir) throw new Error(`${name} has no loginDir`)
154  const location: LoginLocation = {
155    storage: { configDir: account.loginDir, secureStorageDir: account.loginDir },
156    defaultConfigDir: machine.claudeDir,
157    user: machine.user,
158  }
159  const signedOut = () => new Error(`${name} is not signed in yet: /rice-account setup ${name}`)
160  // Read only. A saved login that does not expire soon is answered without the lock.
161  const first = await inspectLogin(io, location)
162  if (first.login === null) throw signedOut()
163  const usable = !needsRefresh(first.login, await io.now())
164  if (usable && first.source === 'store') return first.login
165  // A renewal kept unsaved (a failed store write, or before a plugin reload) works as it is, and is saved when the lock is free.
166  const options = { ...RENEWAL_LOCK, cwd: machine.claudeDir, ...(usable ? { tries: 1 } : {}) }
167  try {
168    return await renewing(io, name, location, paths, machine, options)
169  } catch (error) {
170    if (usable && error instanceof LockBusyError) return first.login
171    throw error
172  }
173}
174
175async function renewing(io: Io, name: string, location: LoginLocation, paths: Paths, machine: Machine, options: LockOptions): Promise<Credential> {
176  const signedOut = () => new Error(`${name} is not signed in yet: /rice-account setup ${name}`)
177
178  return withLock(io, paths.lock(name), options, async lock => {
179    const state = await inspectLogin(io, location)
180    const current = state.login
181    if (current === null) throw signedOut()
182    // A usable renewal that does not need renewing is saved now if it can be; a failure is only logged.
183    if (!needsRefresh(current, await io.now())) return (await promoteLogin(io, location, state)) ?? current
184    await refuseMachineGrant(io, name, current, machine)
185    await checkRenewable(io, location, current)
186    try {
187      await lock.heartbeat()
188    } catch (error) {
189      if (error instanceof LockLostError) throw new Error(`Another session took over renewing ${name}; this session made no token request. Retry the account switch.`)
190      throw new Error(`Cannot keep the ${name} renewal lock (${message(error)}); this session made no token request. Retry the account switch.`)
191    }
192    const { response, lockLost } = await requestKeepingLock(io, lock, name, current)
193    // The refresh token is spent once the answer arrives: the lock is extended after the renewal is written ahead (a failure only logged; the store write checks the grant).
194    const extend = async (): Promise<void> => {
195      if (!lockLost) await lock.heartbeat().catch((error: unknown) => io.log(`the ${name} renewal lock heartbeat failed before saving: ${message(error)}`))
196    }
197    if (!response.ok) throw refreshFailure(name, response)
198    let fresh: Credential
199    try {
200      fresh = applyRefresh(current, response.text, await io.now())
201    } catch (error) {
202      // The response may still have rotated the refresh token: save that before reporting.
203      if (error instanceof RefreshResponseError && error.salvage) {
204        try {
205          await saveRenewal(io, location, error.salvage, state, extend)
206        } catch (saving) {
207          throw new AnthropicError(`the ${name} renewal returned no usable access token. ${message(saving)}`)
208        }
209        throw new AnthropicError(`the ${name} renewal returned no usable access token; its rotated refresh token was saved, retry the account switch`)
210      }
211      throw new AnthropicError(`the ${name} login could not be renewed: ${message(error)}; retry, and if this repeats sign it in again: /rice-account setup ${name}`)
212    }
213    const saved = await saveRenewal(io, location, fresh, state, extend)
214    io.log(lockLost ? `renewed the ${name} login; its renewal lock was no longer held meanwhile, so this session starts no other renewal` : `renewed the ${name} login`)
215
216    return saved
217  })
218}
219
220/** The email an isolated login folder records (not secret), for the listing. */
221export async function loginEmail(io: Io, loginDir: string | undefined): Promise<string | undefined> {
222  if (!loginDir) return undefined
223  try {
224    const raw = JSON.parse(await io.read(`${loginDir}/.claude.json`)) as { oauthAccount?: { emailAddress?: unknown } }
225
226    return typeof raw.oauthAccount?.emailAddress === 'string' ? raw.oauthAccount.emailAddress : undefined
227  } catch {
228    return undefined
229  }
230}
231
hooks/command-line.ts 105 lines
1/**
2 * The /rice-account command line: its subcommands, their argument counts,
3 * the help text and the typeahead rows. Pure; register.ts runs the result.
4 */
5
6export const COMMAND = 'rice-account'
7
8type Subcommand = { name: string; usage: string; summary: string; min: number; max: number; takesName?: true }
9
10/** Every subcommand, in the order help lists them. `max` -1 takes any number. */
11export const SUBCOMMANDS: readonly Subcommand[] = [
12  { name: 'use', usage: 'use <name>', summary: 'Switch this session to a saved account (also reaches an account named like a subcommand).', min: 1, max: 1, takesName: true },
13  { name: 'list', usage: 'list', summary: 'List the saved accounts with their email and plan.', min: 0, max: 0 },
14  { name: 'usage', usage: 'usage', summary: "Show the session account's usage limits.", min: 0, max: 0 },
15  { name: 'check', usage: 'check [name]', summary: "Check that an account's login answers (default: the session account).", min: 0, max: 1, takesName: true },
16  { name: 'add', usage: 'add <name> [kind] [label=...] [service=...]', summary: 'Save an account (kind claudeai, the default, or claudeai-token) and print its terminal setup command.', min: 1, max: -1 },
17  { name: 'setup', usage: 'setup <name>', summary: "Print a saved account's terminal setup command again.", min: 1, max: 1, takesName: true },
18  { name: 'remove', usage: 'remove <name>', summary: 'Remove a saved account from accounts.json; its login is kept.', min: 1, max: 1, takesName: true },
19  { name: 'default', usage: 'default', summary: 'Switch this session to the saved default account.', min: 0, max: 0 },
20  { name: 'set-default', usage: 'set-default <name>', summary: 'Change the saved default account; new sessions still start on the machine login.', min: 1, max: 1, takesName: true },
21  { name: 'setup-native', usage: 'setup-native', summary: 'Withdrawn: Rice Accounts runs inside ordinary claude.', min: 0, max: -1 },
22  { name: 'help', usage: 'help', summary: 'Show this list.', min: 0, max: -1 },
23]
24
25const HELP_WORDS = new Set(['help', '--help', '-h', '?'])
26
27export const ARGUMENT_HINT = '[<name> | use <name> | list | usage | check [name] | add <name> [kind] | setup <name> | remove <name> | default | set-default <name> | setup-native | help]'
28
29export function usageLine(name: string): string {
30  const found = SUBCOMMANDS.find(each => each.name === name)
31  return `Usage: /${COMMAND} ${found?.usage ?? '<name>'}\nRun /${COMMAND} help to list every subcommand.`
32}
33
34export function helpText(): string {
35  const rows: [string, string][] = [
36    ['', 'Choose an account in a list. This changes only this session.'],
37    ['<name>', 'Switch this session to a saved account; login is the machine login.'],
38    ...SUBCOMMANDS.map(each => [each.usage, each.summary] as [string, string]),
39  ]
40  const width = Math.max(...rows.map(([usage]) => usage.length))
41  const lines = rows.map(([usage, summary]) => `/${COMMAND}${usage ? ` ${usage}` : ''}${' '.repeat(width - usage.length + 2)}${summary}`)
42  return `Rice Accounts chooses the Claude OAuth account for this session only. Other sessions keep their own account.\n\n${lines.join('\n')}`
43}
44
45export type Parsed =
46  | { kind: 'picker' }
47  | { kind: 'help' }
48  | { kind: 'switch'; name: string }
49  | { kind: 'refused'; text: string }
50  | { kind: 'list' | 'usage' | 'default' | 'setup-native' }
51  | { kind: 'check'; name?: string }
52  | { kind: 'setup' | 'remove' | 'set-default'; name: string }
53  | { kind: 'add'; name: string; rest: string[] }
54
55/** Reads the words after /rice-account, refusing a wrong argument count with the usage line. */
56export function parseCommand(args: string): Parsed {
57  const [first, ...rest] = args.trim().split(/\s+/).filter(Boolean)
58  if (first === undefined) return { kind: 'picker' }
59  if (HELP_WORDS.has(first)) return { kind: 'help' }
60  const subcommand = SUBCOMMANDS.find(each => each.name === first)
61  if (!subcommand) {
62    if (rest.length > 0) return { kind: 'refused', text: `Usage: /${COMMAND} <name> or /${COMMAND} use <name>\nRun /${COMMAND} help to list every subcommand.` }
63    return { kind: 'switch', name: first }
64  }
65  if (rest.length < subcommand.min || subcommand.max >= 0 && rest.length > subcommand.max) return { kind: 'refused', text: usageLine(subcommand.name) }
66  switch (subcommand.name) {
67    case 'use': return { kind: 'switch', name: rest[0]! }
68    case 'list': return { kind: 'list' }
69    case 'usage': return { kind: 'usage' }
70    case 'default': return { kind: 'default' }
71    case 'setup-native': return { kind: 'setup-native' }
72    case 'check': return rest[0] === undefined ? { kind: 'check' } : { kind: 'check', name: rest[0] }
73    case 'setup': return { kind: 'setup', name: rest[0]! }
74    case 'remove': return { kind: 'remove', name: rest[0]! }
75    case 'set-default': return { kind: 'set-default', name: rest[0]! }
76    case 'add': return { kind: 'add', name: rest[0]!, rest: rest.slice(1) }
77    default: return { kind: 'help' }
78  }
79}
80
81export type Suggestion = { text: string; description: string }
82
83/**
84 * Typeahead rows for the token being typed after /rice-account: subcommands
85 * and saved names first, then names after a subcommand that takes one, and
86 * the account kinds after `add <name>`.
87 */
88export function completions(text: string, start: number, token: string, names: readonly string[], kinds: readonly string[]): Suggestion[] {
89  const prefix = `/${COMMAND} `
90  if (!text.startsWith(prefix) || start < prefix.length) return []
91  const before = text.slice(prefix.length, start).trim().split(/\s+/).filter(Boolean)
92  let rows: Suggestion[] = []
93  if (before.length === 0) {
94    rows = [
95      ...SUBCOMMANDS.map(each => ({ text: each.name, description: each.summary })),
96      ...names.filter(name => !SUBCOMMANDS.some(each => each.name === name)).map(name => ({ text: name, description: 'Switch this session to this account.' })),
97    ]
98  } else if (before.length === 1 && SUBCOMMANDS.find(each => each.name === before[0])?.takesName) {
99    rows = names.map(name => ({ text: name, description: `${before[0]} ${name}` }))
100  } else if (before.length === 2 && before[0] === 'add') {
101    rows = kinds.map(kind => ({ text: kind, description: kind === 'claudeai' ? 'A browser login in its own folder (default).' : 'A one-year token from claude setup-token.' }))
102  }
103  return rows.filter(row => row.text.startsWith(token) && row.text !== token)
104}
105
hooks/config.ts 287 lines
1/**
2 * The saved accounts: a JSON file of names, kinds and where each one's secret
3 * lives. This file holds no credentials.
4 */
5
6import {
7  accountNameProblem,
8  caseConflict,
9  isAccountName as sharedIsAccountName,
10  isStoredAccountName,
11  legacyNameNote,
12  RESERVED_NAMES as SHARED_RESERVED_NAMES,
13} from '../scripts/account-names.mjs'
14
15/** Command words and inherited object keys that a new account cannot be named. */
16export const RESERVED_NAMES: readonly string[] = SHARED_RESERVED_NAMES
17
18/** A dictionary without inherited keys, so a name like toString finds nothing it did not save. */
19function dictionary<T>(entries: Iterable<readonly [string, T]> = []): Record<string, T> {
20  const result = Object.create(null) as Record<string, T>
21  for (const [key, value] of entries) result[key] = value
22  return result
23}
24
25export const KINDS = ['login', 'claudeai', 'claudeai-token'] as const
26// Read legacy provider records so ordinary OAuth edits preserve them verbatim.
27const STORED_KINDS = [...KINDS, 'api-key', 'gateway', 'bedrock', 'vertex', 'foundry'] as const
28export type Kind = (typeof STORED_KINDS)[number]
29
30/** The keychain service a secret saved by name lives under, its account being the saved account's name. */
31export const SECRET_SERVICE = 'rice-session-accounts'
32
33export type SecretRef = { service: string; account: string }
34
35export type AccountConfig = {
36  kind: Kind
37  label?: string
38  /** claudeai: the config folder an isolated `claude auth login` signed in. */
39  loginDir?: string
40  /** claudeai-token, api-key, gateway, and optionally bedrock (bearer token) and foundry (API key). */
41  secret?: SecretRef
42  /** gateway: required. bedrock, vertex, foundry: optional endpoint override. */
43  baseUrl?: string
44  awsProfile?: string
45  region?: string
46  projectId?: string
47  resource?: string
48  /** Model ids this account calls by another name (a Bedrock inference profile, say). */
49  models?: Record<string, string>
50}
51
52export type Config = { default: string; accounts: Record<string, AccountConfig>; legacy?: Record<string, unknown> }
53
54export const LOGIN_NAME = 'login'
55
56export function defaultConfig(): Config {
57  return { default: LOGIN_NAME, accounts: dictionary<AccountConfig>([[LOGIN_NAME, { kind: 'login', label: "this machine's /login" }]]) }
58}
59
60/** The saved account by exactly this name, never an inherited object key. */
61export function savedAccount(config: Config, name: string): AccountConfig | undefined {
62  return Object.hasOwn(config.accounts, name) ? config.accounts[name] : undefined
63}
64
65export type Paths = { base: string; config: string; loginDir: (name: string) => string; lock: (name: string) => string }
66
67export function pathsFor(claudeDir: string): Paths {
68  const base = `${claudeDir.replace(/\/+$/, '')}/rice-session-accounts`
69
70  return {
71    base,
72    config: `${base}/accounts.json`,
73    loginDir: name => `${base}/logins/${name}`,
74    lock: name => `${base}/locks/${name}.lock`,
75  }
76}
77
78/**
79 * Names a new account may use: safe in a keychain account, a folder on macOS,
80 * Linux and Windows, and a command line, and never a command word or an
81 * inherited object key. Accounts saved under an older rule keep working.
82 */
83export function isAccountName(name: string): boolean {
84  return sharedIsAccountName(name)
85}
86
87function isKind(value: unknown): value is Kind {
88  return typeof value === 'string' && (STORED_KINDS as readonly string[]).includes(value)
89}
90
91function stringField(raw: Record<string, unknown>, key: string): string | undefined {
92  return typeof raw[key] === 'string' && raw[key] !== '' ? (raw[key] as string) : undefined
93}
94
95/** Checks one account; the problems name what is missing for its kind. */
96export function accountProblems(name: string, account: AccountConfig): string[] {
97  const problems: string[] = []
98  // Saved names keep the rule they were saved under; new names use isAccountName.
99  if (!isStoredAccountName(name)) problems.push(`"${name}" is not a usable name (letters, digits, . _ -, up to 40)`)
100  const needsSecret = account.kind === 'claudeai-token' || account.kind === 'api-key' || account.kind === 'gateway'
101  if (needsSecret && !account.secret) problems.push(`${name}: a ${account.kind} account needs "secret"`)
102  if (account.kind === 'claudeai' && !account.loginDir) problems.push(`${name}: a claudeai account needs "loginDir"`)
103  if (account.kind === 'gateway' && !account.baseUrl) problems.push(`${name}: a gateway account needs "baseUrl"`)
104  if (account.kind === 'vertex' && !account.projectId) problems.push(`${name}: a vertex account needs "projectId"`)
105  if (account.kind === 'foundry' && !account.resource && !account.baseUrl) problems.push(`${name}: a foundry account needs "resource" or "baseUrl"`)
106
107  return problems
108}
109
110/** The problem a file that does not parse reports, so writers can keep it for repair. */
111export const UNPARSED_CONFIG = 'accounts.json does not parse'
112
113function isRecord(value: unknown): value is Record<string, unknown> {
114  return typeof value === 'object' && value !== null && !Array.isArray(value)
115}
116
117/**
118 * The file's accounts, the bad ones left out and said in problems; a file that
119 * does not parse is all problem. Notes name saved accounts that keep working
120 * but deserve attention, such as a name new accounts can no longer use.
121 */
122export function parseConfig(text: string): { config: Config; problems: string[]; notes: string[] } {
123  const config = defaultConfig()
124  const problems: string[] = []
125  const notes: string[] = []
126  let raw: unknown
127  try {
128    raw = JSON.parse(text)
129  } catch (error) {
130    return { config, problems: [`${UNPARSED_CONFIG}: ${error instanceof Error ? error.message : String(error)}`], notes }
131  }
132  const top: Record<string, unknown> = isRecord(raw) ? raw : {}
133  if (isRecord(top.accounts)) {
134    for (const [name, value] of Object.entries(top.accounts)) {
135      const entry: Record<string, unknown> = isRecord(value) ? value : {}
136      if (!isKind(entry.kind)) {
137        problems.push(`${name}: unknown kind ${JSON.stringify(entry.kind)} (one of ${KINDS.join(', ')})`)
138        continue
139      }
140      if (!(KINDS as readonly string[]).includes(entry.kind)) {
141        config.legacy ??= dictionary<unknown>()
142        config.legacy[name] = value
143      }
144      const secret = isRecord(entry.secret) ? (entry.secret as { service?: unknown; account?: unknown }) : undefined
145      const models = isRecord(entry.models) ? entry.models : undefined
146      const account: AccountConfig = {
147        kind: entry.kind,
148        label: stringField(entry, 'label'),
149        loginDir: stringField(entry, 'loginDir'),
150        secret: typeof secret?.service === 'string' && typeof secret.account === 'string' ? { service: secret.service, account: secret.account } : undefined,
151        baseUrl: stringField(entry, 'baseUrl'),
152        awsProfile: stringField(entry, 'awsProfile'),
153        region: stringField(entry, 'region'),
154        projectId: stringField(entry, 'projectId'),
155        resource: stringField(entry, 'resource'),
156        models: models
157          ? dictionary<string>(Object.entries(models).filter((pair): pair is [string, string] => typeof pair[1] === 'string'))
158          : undefined,
159      }
160      const found = accountProblems(name, account)
161      if (found.length > 0) {
162        problems.push(...found)
163        continue
164      }
165      config.accounts[name] = account
166      if (name !== LOGIN_NAME && (KINDS as readonly string[]).includes(account.kind)) {
167        const note = legacyNameNote(name)
168        if (note) notes.push(note)
169      }
170    }
171  }
172  const names = [...Object.keys(config.accounts), ...Object.keys(config.legacy ?? {})]
173  const reported = new Set<string>()
174  for (const name of names) {
175    const other = caseConflict(names, name)
176    if (!other || reported.has(name.toLowerCase())) continue
177    reported.add(name.toLowerCase())
178    notes.push(`${other} and ${name} differ only in letter case; macOS and Windows treat them as one login folder. Remove one of them.`)
179  }
180  if (typeof top.default === 'string') {
181    if (savedAccount(config, top.default)) config.default = top.default
182    else problems.push(`default names no saved account: ${top.default}`)
183  }
184
185  return { config, problems, notes }
186}
187
188export function serializeConfig(config: Config): string {
189  return `${JSON.stringify({ default: config.default, accounts: { ...config.accounts, ...config.legacy } }, null, 2)}\n`
190}
191
192/** The options `/rice-account add` takes, as `key=value` words. */
193export const ADD_OPTIONS = ['label', 'service'] as const
194
195/**
196 * A new account and what the person still does once, in a terminal, before
197 * switching to it. Nothing secret is asked here: a secret is typed into the
198 * keychain prompt, never into the session.
199 */
200export function addAccount(
201  config: Config,
202  name: string,
203  kind: Kind,
204  options: Record<string, string>,
205  paths: Paths,
206): { config: Config; steps: string[] } {
207  if (!isStoredAccountName(name)) throw new Error(accountNameProblem(name))
208  if (!(KINDS as readonly string[]).includes(kind)) throw new Error('Rice Accounts supports Anthropic OAuth accounts only. Use rice-multi-models for provider accounts.')
209  if (config.legacy && Object.hasOwn(config.legacy, name)) throw new Error(`${name} is a preserved provider entry. Use another name for an OAuth account.`)
210  for (const option of Object.keys(options)) {
211    if (!(ADD_OPTIONS as readonly string[]).includes(option)) throw new Error(`Unknown option: ${option}`)
212  }
213  const allowed: Record<Kind, readonly string[]> = {
214    login: [], claudeai: ['label'], 'claudeai-token': ['label', 'service'], 'api-key': ['label', 'service'],
215    gateway: ['label', 'service', 'base_url'], bedrock: ['label', 'aws_profile', 'region', 'base_url', 'secret', 'service'],
216    vertex: ['label', 'project', 'region', 'base_url'], foundry: ['label', 'resource', 'base_url', 'secret', 'service'],
217  }
218  for (const option of Object.keys(options)) {
219    if (!allowed[kind].includes(option)) throw new Error(`Option ${option} does not apply to ${kind}`)
220  }
221  if (options.secret && !((kind === 'bedrock' && options.secret === 'bearer') || (kind === 'foundry' && options.secret === 'key'))) {
222    throw new Error('Use secret=bearer for Bedrock or secret=key for Foundry.')
223  }
224  if (options.service && (kind === 'bedrock' || kind === 'foundry') && !options.secret) throw new Error('service= requires secret=bearer for Bedrock or secret=key for Foundry.')
225  const existing = savedAccount(config, name)
226  if (existing) {
227    if (existing.kind !== kind || Object.keys(options).length > 0) {
228      throw new Error(`${name} is already saved as ${existing.kind}; use /rice-account setup ${name} to finish it. Existing settings were kept.`)
229    }
230    return { config, steps: [] }
231  }
232  // An account saved under an older rule stays usable above; a new one meets the current rule.
233  const problem = accountNameProblem(name)
234  if (problem) throw new Error(problem)
235  const other = caseConflict([...Object.keys(config.accounts), ...Object.keys(config.legacy ?? {})], name)
236  if (other) throw new Error(`${name} differs from the saved account ${other} only in letter case; macOS and Windows would store both in one login folder. Choose another name.`)
237  const service = options.service ?? SECRET_SERVICE
238  const secret: SecretRef = { service, account: name }
239  const storeSecret = (what: string) => `The terminal setup helper will ask for the ${what} without echoing it.`
240  const account: AccountConfig = { kind, label: options.label }
241  const steps: string[] = []
242  switch (kind) {
243    case 'login':
244      throw new Error("the machine's /login is saved already as \"login\"")
245    case 'claudeai': {
246      account.loginDir = paths.loginDir(name)
247      steps.push('The terminal setup helper signs in this isolated account using Claude Code.')
248      break
249    }
250    case 'claudeai-token':
251      account.secret = secret
252      steps.push('claude setup-token   # sign in as that account; it prints a one-year token')
253      steps.push(storeSecret('token'))
254      break
255    default:
256      throw new Error('Rice Accounts supports Anthropic OAuth accounts only.')
257  }
258  const problems = accountProblems(name, account)
259  if (problems.length > 0) throw new Error(problems.join('; '))
260
261  return { config: { ...config, accounts: dictionary<AccountConfig>([...Object.entries(config.accounts), [name, account] as const]) }, steps: [...steps, `then: /rice-account ${name}`] }
262}
263
264/** The config without an account; the default goes back to the machine login when it named it. */
265export function removeAccount(config: Config, name: string): Config {
266  if (name === LOGIN_NAME) throw new Error("the machine's /login cannot be removed")
267  if (!savedAccount(config, name)) throw new Error(`no account named ${name}`)
268  const accounts = dictionary<AccountConfig>(Object.entries(config.accounts).filter(([saved]) => saved !== name))
269
270  return { ...config, default: config.default === name ? LOGIN_NAME : config.default, accounts }
271}
272
273export function describeAccount(name: string, account: AccountConfig): string {
274  const where =
275    account.kind === 'bedrock'
276      ? [account.awsProfile && `profile ${account.awsProfile}`, account.region].filter(Boolean).join(', ')
277      : account.kind === 'vertex'
278        ? [account.projectId, account.region].filter(Boolean).join(', ')
279        : account.kind === 'foundry'
280          ? (account.resource ?? account.baseUrl ?? '')
281          : account.kind === 'gateway'
282            ? (account.baseUrl ?? '')
283            : ''
284
285  return `${name}  ${account.kind}${account.label ? `  "${account.label}"` : ''}${where ? `  (${where})` : ''}`
286}
287
hooks/credentials.ts 1130 lines
1import type { SecretRef } from './config'
2import type { Io, RunFailure } from './io'
3import { message, runFailure, trustedRun } from './io'
4import { fitCredential, KeychainError, keychainAccountName, liveServiceName, readItem, resolveKeychainAccount, writeItem } from './keychain'
5import type { Credential, StorageVariables } from './keychain'
6import { WINDOWS_CREDENTIAL_STORE } from '../scripts/windows-store-payloads.mjs'
7
8export type HostPlatform = 'darwin' | 'linux' | 'win32'
9export type LoginLocation = { storage: StorageVariables; defaultConfigDir: string; user?: string }
10
11/** Appended to the native credential path: the renewed login written ahead of the store. */
12export const PENDING_SUFFIX = '.rice-pending'
13/** The pending file format this version writes and reads; a file of any other format is ignored. */
14export const PENDING_VERSION = 2
15/** A leftover temporary copy, or a pending file of another format, is removed only once it is older than this. */
16export const STALE_COPY_MS = 5 * 60 * 1000
17/** The largest pending or credentials file read on macOS; the Node program applies the same cap. */
18const PENDING_LIMIT = 1024 * 1024
19/** Set to exactly 1, it makes Claude Code on Windows keep logins in Credential Manager. */
20const CREDMAN_VARIABLE = 'CLAUDE_CODE_FORCE_WINDOWS_CREDMAN'
21/** The cached GrowthBook flag that does the same when it is true. */
22const CREDMAN_FLAG = 'tengu_windows_credman'
23/** How many spent refresh tokens a renewal kept in memory remembers it descends from. */
24const SPENT_KEPT = 32
25
26let platformCache: { key: string; platform: Promise<HostPlatform> } | undefined
27
28/**
29 * Detect the execution host, including Linux inside WSL. Native Windows is
30 * known from its environment without a process; otherwise `uname -s` runs
31 * once per process rather than once per Io (register.ts builds a new Io for
32 * every call), since the platform does not change. The cache is keyed by
33 * HOME only so tests that fake several hosts in one process still detect each
34 * one; HOME does not change within a session. A failed detection is retried.
35 */
36export async function hostPlatform(io: Io): Promise<HostPlatform> {
37  if (await io.env('OS') === 'Windows_NT') return 'win32'
38  const key = await io.env('HOME') ?? ''
39  if (platformCache?.key === key) return platformCache.platform
40  const platform = detectPosix(io)
41  platformCache = { key, platform }
42  platform.catch(() => { if (platformCache?.platform === platform) platformCache = undefined })
43
44  return platform
45}
46
47async function detectPosix(io: Io): Promise<HostPlatform> {
48  // Alpine and unmerged-/usr systems ship /bin/uname only; NixOS has neither path.
49  let system: string | undefined
50  for (const command of ['/usr/bin/uname', '/bin/uname', 'uname']) {
51    const result = await io.run([command, '-s'], trustedRun('/', { timeoutMs: 10_000 })).catch(() => undefined)
52    if (result?.exitCode === 0) { system = result.stdout.trim(); break }
53  }
54  if (system === undefined) throw new Error('Cannot detect the host OS: uname -s must be available.')
55  if (system === 'Darwin') return 'darwin'
56  if (system === 'Linux') return 'linux'
57  throw new Error('Account storage supports macOS, Linux (including WSL) and native Windows.')
58}
59
60/** Forget the detected platform; for tests that fake several hosts. */
61export function forgetHostPlatform(): void {
62  platformCache = undefined
63}
64
65/** Native file storage is independent of CLAUDE_CONFIG_DIR when overridden. */
66export function nativeCredentialPath(location: LoginLocation, home: string | undefined, platform: HostPlatform = 'linux'): string {
67  const { secureStorageDir, configDir } = location.storage
68  const folder = secureStorageDir === ''
69    ? home ? `${home}/.claude` : undefined
70    : secureStorageDir ?? configDir ?? location.defaultConfigDir
71  const absolute = folder && (platform === 'win32' ? /^(?:[A-Za-z]:[\\/]|\\\\[^\\]+\\[^\\]+)/.test(folder) : folder.startsWith('/'))
72  if (!absolute || /[\0\r\n]/.test(folder)) throw new Error('The native credential directory must be an absolute path; the machine home is required for an empty secure-storage override.')
73
74  return `${folder.normalize('NFC').replace(/[\\/]+$/, '')}/.credentials.json`
75}
76
77/**
78 * The static program Node runs for native file storage. Paths and the program
79 * are argv; secrets use stdin/stdout only. It is ES5 (var, function, no
80 * optional chaining, nullish coalescing, arrow functions or `node:`
81 * specifiers) so that an old Node, such as Ubuntu 22.04's Node 12, parses it
82 * and reaches the version guard instead of failing with a syntax error.
83 *
84 * The `.rice-pending` file beside the store holds
85 * `{"version":2,"base":B,"credential":{"claudeAiOauth":G}}`: G is the newest
86 * renewed grant not saved to the store yet, and B the refresh token the store
87 * held when the first unsaved renewal began. A pending renewal is usable only
88 * while the store still holds B (rule B in `pendingState`); expiry times never
89 * decide which login is newer.
90 *
91 * Operations: `read` prints the store, or the store with a usable pending
92 * grant, and never writes or removes anything; `examine` prints
93 * `{"stored":document or null,"pending":{"base":B,"credential":...} or null}`
94 * (null for a missing store; otherwise its exit codes are `read`'s), also
95 * without writing; `write` replaces only the OAuth grant (the two tokens,
96 * `expiresAt`, and `refreshTokenExpiresAt` when the renewal has one; a stored
97 * one stays otherwise) when the stored refresh token is still the expected
98 * one, and leaves the pending file alone;
99 * `pending` writes `{base, credential}` from stdin as the pending file;
100 * `readpending` prints `{"pending":...}` alone, for a store that cannot be
101 * read; `clearpending` takes `{base, tokens}` and removes the pending file only
102 * when its base is that one and its refresh token is one of `tokens` (the
103 * caller's own renewals: another session's later renewal is left), or when it
104 * is not version 2 and older than five minutes. `write` and
105 * `pending` also remove temporary copies older than five minutes left by a
106 * killed write. Writes create an exclusive 0600 temporary file, fsync it,
107 * rename it over the target and fsync the folder on POSIX; a rename refused
108 * as busy is retried for about 3 seconds, and on Windows also one refused
109 * with EPERM or EACCES while Defender or an indexer holds the file. stdin is
110 * read in a loop that waits out EAGAIN from a non-blocking pipe.
111 *
112 * Exit codes: 43 a valid document without OAuth; 44 only ENOENT, never an
113 * unreadable store; 45 a symbolic link; 46 unreadable, malformed or not
114 * permitted; 47 the stored grant changed (another writer); 48 the file stayed
115 * held by another program; 49 no space or a read-only file system; 50 Node is
116 * older than 22; 51 a Windows node.exe reached from WSL (a POSIX path on win32).
117 */
118const NATIVE_FILE = String.raw`
119var fs = require('fs');
120var crypto = require('crypto');
121var paths = require('path');
122var operation = process.argv[1];
123var path = process.argv[2];
124var flags = fs.constants || {};
125var limit = 1024 * 1024;
126var staleMs = 5 * 60 * 1000;
127var retryDelays = [50, 100, 200, 400, 800, 1450];
128var pendingPath = path + '.rice-pending';
129var temporary;
130function Refusal(code) { this.exitCode = code; }
131function fail(code) { throw new Refusal(code); }
132function sleep(ms) {
133  try { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); }
134  catch (ignored) { var until = Date.now() + ms; while (Date.now() < until) {} }
135}
136function isObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
137function isOAuth(value) { return isObject(value) && typeof value.accessToken === 'string' && typeof value.refreshToken === 'string' && typeof value.expiresAt === 'number' && isFinite(value.expiresAt); }
138function grantOf(document) { return isObject(document) && isOAuth(document.claudeAiOauth) ? document.claudeAiOauth : null; }
139function copy(source) {
140  var target = {};
141  for (var key in source) {
142    if (Object.prototype.hasOwnProperty.call(source, key)) Object.defineProperty(target, key, { value: source[key], enumerable: true, writable: true, configurable: true });
143  }
144  return target;
145}
146function grantOnly(oauth) {
147  var grant = { accessToken: oauth.accessToken, refreshToken: oauth.refreshToken, expiresAt: oauth.expiresAt };
148  if (typeof oauth.refreshTokenExpiresAt === 'number' && isFinite(oauth.refreshTokenExpiresAt)) grant.refreshTokenExpiresAt = oauth.refreshTokenExpiresAt;
149  return grant;
150}
151function merged(document, oauth) {
152  var next = copy(document);
153  var inner = copy(document.claudeAiOauth);
154  var grant = grantOnly(oauth);
155  inner.accessToken = grant.accessToken;
156  inner.refreshToken = grant.refreshToken;
157  inner.expiresAt = grant.expiresAt;
158  if (grant.refreshTokenExpiresAt !== undefined) inner.refreshTokenExpiresAt = grant.refreshTokenExpiresAt;
159  next.claudeAiOauth = inner;
160  return next;
161}
162function remove(file) { try { fs.unlinkSync(file); } catch (ignored) {} }
163function readJson(file, strict) {
164  var fd;
165  try {
166    var link = fs.lstatSync(file, { bigint: true });
167    if (link.isSymbolicLink()) fail(45);
168    if (!link.isFile() || link.size > limit) fail(46);
169    fd = fs.openSync(file, flags.O_RDONLY | (flags.O_NOFOLLOW || 0) | (flags.O_NONBLOCK || 0));
170    var identity = fs.fstatSync(fd, { bigint: true });
171    if (!identity.isFile() || identity.size > limit) fail(46);
172    if (identity.ino !== link.ino || identity.dev !== link.dev) fail(45);
173    var bytes = Buffer.alloc(limit + 1);
174    var size = 0;
175    while (size < bytes.length) {
176      var count = fs.readSync(fd, bytes, size, bytes.length - size, null);
177      if (count === 0) break;
178      size += count;
179    }
180    if (size > limit) fail(46);
181    return JSON.parse(bytes.toString('utf8', 0, size));
182  } catch (error) {
183    if (strict) throw error;
184    return undefined;
185  } finally {
186    if (fd !== undefined) { try { fs.closeSync(fd); } catch (ignored) {} }
187  }
188}
189function readStored() {
190  var document = readJson(path, true);
191  if (!isObject(document)) fail(46);
192  if (document.claudeAiOauth === undefined || document.claudeAiOauth === null) fail(43);
193  if (!isOAuth(document.claudeAiOauth)) fail(46);
194  return document;
195}
196function readStoredOrNull() {
197  try { return readStored(); } catch (error) {
198    if (error && error.code === 'ENOENT') return null;
199    throw error;
200  }
201}
202function pendingOf(document) {
203  if (!isObject(document) || document.version !== 2 || typeof document.base !== 'string' || document.base === '') return null;
204  var grant = grantOf(document.credential);
205  return grant === null ? null : { base: document.base, credential: { claudeAiOauth: grantOnly(grant) } };
206}
207function readPending() { return pendingOf(readJson(pendingPath, false)); }
208function bestOf(stored, pending) {
209  return pending !== null && stored.claudeAiOauth.refreshToken === pending.base ? merged(stored, pending.credential.claudeAiOauth) : stored;
210}
211function isStale(file) {
212  var stat = null;
213  try { stat = fs.lstatSync(file); } catch (ignored) {}
214  return stat !== null && stat.isFile() && Date.now() - stat.mtimeMs >= staleMs;
215}
216function removeStaleCopies() {
217  var folder = paths.dirname(path);
218  var prefix = paths.basename(path) + '.rice-';
219  var names = [];
220  try { names = fs.readdirSync(folder); } catch (ignored) {}
221  for (var index = 0; index < names.length; index += 1) {
222    var name = names[index];
223    if (name.indexOf(prefix) !== 0 || !/^[0-9]+-[0-9a-f-]{16,64}$/.test(name.slice(prefix.length))) continue;
224    var file = paths.join(folder, name);
225    if (file !== temporary && isStale(file)) remove(file);
226  }
227}
228function isRetryable(code) {
229  if (code === 'EBUSY') return true;
230  return process.platform === 'win32' && (code === 'EPERM' || code === 'EACCES');
231}
232function renameWithRetry(from, to) {
233  for (var attempt = 0; ; attempt += 1) {
234    try { fs.renameSync(from, to); return; } catch (error) {
235      if (!isRetryable(error && error.code)) throw error;
236      if (attempt >= retryDelays.length) fail(48);
237      sleep(retryDelays[attempt]);
238    }
239  }
240}
241function syncFolder(folder) {
242  if (process.platform === 'win32') return;
243  var fd;
244  try { fd = fs.openSync(folder, 'r'); fs.fsyncSync(fd); } catch (ignored) {} finally {
245    if (fd !== undefined) { try { fs.closeSync(fd); } catch (ignored) {} }
246  }
247}
248function writeAtomic(target, document) {
249  var encoded = JSON.stringify(document);
250  if (Buffer.byteLength(encoded) > limit) fail(46);
251  temporary = path + '.rice-' + process.pid + '-' + crypto.randomBytes(16).toString('hex');
252  var fd = fs.openSync(temporary, flags.O_WRONLY | flags.O_CREAT | flags.O_EXCL | (flags.O_NOFOLLOW || 0), 384);
253  try { fs.writeFileSync(fd, encoded, 'utf8'); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
254  renameWithRetry(temporary, target);
255  temporary = undefined;
256  syncFolder(paths.dirname(target));
257}
258function readInput() {
259  var chunk = Buffer.alloc(65536);
260  var chunks = [];
261  var size = 0;
262  var deadline = Date.now() + 10000;
263  for (;;) {
264    var count;
265    try { count = fs.readSync(0, chunk, 0, chunk.length, null); } catch (error) {
266      var code = error && error.code;
267      if (code === 'EAGAIN' && Date.now() < deadline) { sleep(5); continue; }
268      if (code === 'EOF') break;
269      throw error;
270    }
271    if (count === 0) break;
272    size += count;
273    if (size > limit) fail(46);
274    chunks.push(Buffer.from(chunk.subarray(0, count)));
275  }
276  return Buffer.concat(chunks, size).toString('utf8');
277}
278function input() {
279  var value = JSON.parse(readInput());
280  if (!isObject(value)) fail(46);
281  return value;
282}
283try {
284  if (process.platform === 'win32' && typeof path === 'string' && /^\/(?!\/)/.test(path)) fail(51);
285  if (Number(String(process.versions.node).split('.')[0]) < 22) fail(50);
286  if (!path || !paths.isAbsolute(path) || /[\0\r\n]/.test(path) || process.platform === 'win32' && !/^(?:[A-Za-z]:[\\/]|\\\\[^\\]+\\[^\\]+)/.test(path)) fail(46);
287  var output = null;
288  if (operation === 'read') {
289    output = bestOf(readStored(), readPending());
290  } else if (operation === 'examine') {
291    output = { stored: readStoredOrNull(), pending: readPending() };
292  } else if (operation === 'write') {
293    var request = input();
294    var oauth = request.oauth;
295    if (!isOAuth(oauth) || typeof request.expectedRefreshToken !== 'string') fail(46);
296    var current = readStored();
297    if (current.claudeAiOauth.refreshToken !== request.expectedRefreshToken) fail(47);
298    output = merged(current, oauth);
299    writeAtomic(path, output);
300    removeStaleCopies();
301  } else if (operation === 'pending') {
302    var renewal = input();
303    var grant = grantOf(renewal.credential);
304    if (typeof renewal.base !== 'string' || renewal.base === '' || grant === null) fail(46);
305    removeStaleCopies();
306    writeAtomic(pendingPath, { version: 2, base: renewal.base, credential: { claudeAiOauth: grantOnly(grant) } });
307  } else if (operation === 'readpending') {
308    output = { pending: readPending() };
309  } else if (operation === 'clearpending') {
310    var request = input();
311    var expected = request.base;
312    var owned = request.tokens;
313    if (typeof expected !== 'string' || expected === '' || !Array.isArray(owned)) fail(46);
314    var held = readPending();
315    var mine = held !== null && held.base === expected && owned.indexOf(held.credential.claudeAiOauth.refreshToken) >= 0;
316    if (held !== null ? mine : isStale(pendingPath)) remove(pendingPath);
317  } else fail(46);
318  if (output !== null) process.stdout.write(JSON.stringify(output));
319} catch (error) {
320  var code = error && error.code;
321  process.exitCode = error instanceof Refusal ? error.exitCode
322    : code === 'ENOENT' ? 44
323    : code === 'ELOOP' ? 45
324    : code === 'ENOSPC' || code === 'EDQUOT' || code === 'EROFS' ? 49
325    : 46;
326} finally {
327  if (temporary) remove(temporary);
328}
329`
330
331/** The native file program's documented exit codes. */
332export const FILE_EXIT = { noOAuth: 43, missing: 44, link: 45, invalid: 46, changed: 47, busy: 48, full: 49, oldNode: 50, windowsNode: 51 } as const
333
334/**
335 * The darwin pending writer: no Node there, so a POSIX shell writes the
336 * owner-only (umask 077) copy. It first removes its own temporary copies
337 * older than five minutes (`<pending>.tmp.<pid>.<random>`, and the fixed
338 * `<pending>.tmp` of earlier versions), then creates a temporary file named
339 * with its process id and a random suffix exclusively (noclobber), so
340 * concurrent writers never share or delete one another's copy, flushes it
341 * (`sync`), renames it into place and flushes again. stdin is the document.
342 */
343const PENDING_SH = String.raw`umask 077
344d=$(/usr/bin/dirname "$0") && b=$(/usr/bin/basename "$0") || exit 1
345/usr/bin/find "$d" -maxdepth 1 -type f \( -name "$b.tmp" -o -name "$b.tmp.[0-9]*" \) -mmin +5 -exec /bin/rm -f {} + 2>/dev/null
346r=$(/usr/bin/od -An -N8 -tx1 /dev/urandom 2>/dev/null | /usr/bin/tr -d ' \n')
347t="$0.tmp.$$.$r"
348set -C
349: > "$t" || exit 1
350if /bin/cat >> "$t" && /bin/sync && /bin/mv -f "$t" "$0"; then /bin/sync; exit 0; fi
351/bin/rm -f "$t"
352exit 1
353`
354
355/** What a renewal changes in a stored login; `refreshTokenExpiresAt` only when the server gave one. */
356type OAuthGrant = Pick<Credential['claudeAiOauth'], 'accessToken' | 'refreshToken' | 'expiresAt' | 'refreshTokenExpiresAt'>
357/** `filePath` is the credentials file Claude Code falls back to when the keychain cannot store a login. */
358type KeychainStore = { kind: 'keychain'; key: string; service: string; account: string | undefined; writeAccount: string; filePath: string | undefined; pendingPath: string | undefined; cwd: string }
359type FileStore = { kind: 'file'; key: string; path: string; pendingPath: string; cwd: string; platform: HostPlatform }
360type Store = KeychainStore | FileStore
361// Never name an operation `inspect` (or `debug`): Node runs a first program argument with that name as its debugger client, even after -e.
362type FileOperation = 'read' | 'examine' | 'readpending' | 'write' | 'pending' | 'clearpending'
363type RunResult = Awaited<ReturnType<Io['run']>>
364
365/**
366 * A renewal not saved to the store yet. `base` is the refresh token the store
367 * held when the first unsaved renewal began; that renewal spent it, so it no
368 * longer works. It stays the same across further unsaved renewals while
369 * `credential` advances to the newest renewed login.
370 */
371export type PendingLogin = { base: string; credential: Credential }
372
373/**
374 * How a pending renewal relates to the stored login: `usable` while the store
375 * still holds its base, `redundant` once the store holds its refresh token
376 * (saved), `obsolete` when the store holds neither (it moved past the
377 * renewal, or was signed in again: the store is authoritative), `orphaned`
378 * when there is no stored login to compare with.
379 */
380export type PendingState = 'usable' | 'redundant' | 'obsolete' | 'orphaned'
381
382/** Where the login to use came from. */
383export type CandidateSource = 'store' | 'pending' | 'memory'
384
385/** The store, its pending renewal and the login to use by rule B, as read at one moment. */
386export type LoginState = {
387  /** The stored login; null when there is none, or it could not be read and memory answered. */
388  stored: Credential | null
389  pending: PendingLogin | null
390  /** The login to use: the stored one, or it with a usable renewal's grant. */
391  login: Credential | null
392  source: CandidateSource
393  /** The usable renewal `login` came from, when it did not come from the store. */
394  candidate: PendingLogin | null
395  /** The refresh token the store holds: what a store write must find (compare-and-swap). */
396  onDisk: string | undefined
397  /** Spent refresh tokens `login` is known to descend from (from this process's memory). */
398  spent: readonly string[]
399}
400
401/** The store's login changed while it was renewed: another sign-in or another writer. */
402class LoginChangedError extends Error {}
403
404/** The store holds no login any more: a renewal cannot be saved there, nor used without one. */
405class StoreGoneError extends Error {}
406
407/** A renewal the server granted that could not be saved; the message says where it was kept. */
408export class LoginNotSavedError extends Error {}
409
410function invalidStore(): Error {
411  return new Error('The credential store contains no valid Claude OAuth login. Run account setup again.')
412}
413
414function grantOf(value: unknown): OAuthGrant | null {
415  const oauth = (value as { claudeAiOauth?: Partial<OAuthGrant> } | null)?.claudeAiOauth
416  return typeof oauth?.accessToken === 'string' && typeof oauth.refreshToken === 'string' && typeof oauth.expiresAt === 'number' && Number.isFinite(oauth.expiresAt)
417    ? grantOnly(oauth as OAuthGrant)
418    : null
419}
420
421/** A stored credential document: null when it is valid but holds no OAuth login. */
422function documentOf(value: unknown): Credential | null {
423  if (value === null || typeof value !== 'object' || Array.isArray(value)) throw invalidStore()
424  const oauth = (value as { claudeAiOauth?: unknown }).claudeAiOauth
425  if (oauth === undefined || oauth === null) return null
426  if (grantOf(value) === null) throw invalidStore()
427
428  return value as Credential
429}
430
431function credential(text: string): Credential | null {
432  let value: unknown
433  try { value = JSON.parse(text) } catch { throw invalidStore() }
434
435  return documentOf(value)
436}
437
438function pendingOf(value: unknown): PendingLogin | null {
439  const fields = value as { base?: unknown; credential?: unknown } | null
440  if (fields === null || typeof fields !== 'object' || Array.isArray(fields) || typeof fields.base !== 'string' || fields.base === '') return null
441  const oauth = grantOf(fields.credential)
442
443  return oauth === null ? null : { base: fields.base, credential: { claudeAiOauth: oauth } }
444}
445
446/** A pending file's text as a renewal; null for any other version, a malformed file or one without a grant. */
447export function parsePendingLogin(text: string): PendingLogin | null {
448  let value: unknown
449  try { value = JSON.parse(text) } catch { return null }
450  if ((value as { version?: unknown } | null)?.version !== PENDING_VERSION) return null
451
452  return pendingOf(value)
453}
454
455/**
456 * Rule B, shared by the file and keychain stores: lineage is decided by the
457 * refresh tokens, never by expiry times (a salvaged login has `expiresAt` 0
458 * and is still the newest one).
459 */
460export function pendingState(stored: Credential | null, pending: PendingLogin): PendingState {
461  if (stored === null) return 'orphaned'
462  const held = stored.claudeAiOauth.refreshToken
463  if (held === pending.base) return 'usable'
464  if (held === pending.credential.claudeAiOauth.refreshToken) return 'redundant'
465
466  return 'obsolete'
467}
468
469/** The stored document with a renewal's grant; a stored `refreshTokenExpiresAt` stays when the renewal gave none, as in Claude Code. */
470function merged(document: Credential, oauth: OAuthGrant): Credential {
471  return { ...document, claudeAiOauth: { ...document.claudeAiOauth, ...grantOnly(oauth) } }
472}
473
474function grantOnly(oauth: OAuthGrant): OAuthGrant {
475  const expiry = oauth.refreshTokenExpiresAt
476  return { accessToken: oauth.accessToken, refreshToken: oauth.refreshToken, expiresAt: oauth.expiresAt, ...(typeof expiry === 'number' && Number.isFinite(expiry) ? { refreshTokenExpiresAt: expiry } : {}) }
477}
478
479/** Whether a usable pending renewal is later than a usable memory one: memory does not descend from it. */
480function pendingIsLater(memory: PendingLogin & { spent?: readonly string[] }, pending: PendingLogin): boolean {
481  const held = pending.credential.claudeAiOauth.refreshToken
482  return held !== memory.credential.claudeAiOauth.refreshToken && !(memory.spent ?? []).includes(held)
483}
484
485/**
486 * The login to use (rule B): the best usable candidate, the in-memory renewal
487 * `memory` before the pending file, else the store. Usable candidates share
488 * the store's refresh token as their base, so they lie on one chain of
489 * renewals; the later one is the one whose credential is not an ancestor of
490 * the other. Memory knows the spent tokens it descends from, so the pending
491 * renewal wins only when memory does not descend from it (another session
492 * renewed further). The login keeps the stored document's other fields.
493 */
494export function bestLogin(stored: Credential | null, pending: PendingLogin | null, memory?: (PendingLogin & { spent?: readonly string[] }) | null): { login: Credential | null; source: CandidateSource; candidate: PendingLogin | null } {
495  const fromMemory = memory && pendingState(stored, memory) === 'usable' ? memory : null
496  const fromPending = pending && pendingState(stored, pending) === 'usable' ? pending : null
497  const candidate = fromMemory && fromPending ? (pendingIsLater(fromMemory, fromPending) ? fromPending : fromMemory) : fromMemory ?? fromPending
498  if (candidate === null || stored === null) return { login: stored, source: 'store', candidate: null }
499
500  return { login: merged(stored, candidate.credential.claudeAiOauth), source: candidate === fromMemory ? 'memory' : 'pending', candidate }
501}
502
503/** A config file's text: '' when there is none (or a folder stands there), undefined when it cannot be read. */
504async function configText(io: Io, path: string): Promise<string | undefined> {
505  const stat = await io.stat(path).catch(() => null)
506  if (stat === null || stat.kind === 'dir') return ''
507  if (stat.kind !== 'file') return undefined
508  return io.read(path).catch(() => undefined)
509}
510
511/**
512 * Why Claude Code on Windows keeps the login at `location` in Credential
513 * Manager (read before the credentials file), or undefined when it uses the
514 * file alone. Its rule, read in the 2.1.302 binary: CLAUDE_CODE_FORCE_WINDOWS_CREDMAN
515 * is exactly 1, or the cached GrowthBook flag tengu_windows_credman is true in
516 * `<config folder>/.config.json` when that file is present and not empty, else
517 * in `<CLAUDE_CONFIG_DIR or home>/.claude.json`. A config that cannot be read
518 * or parsed counts as off, as it does there.
519 */
520async function credentialManagerCause(io: Io, location: LoginLocation, home: string | undefined): Promise<string | undefined> {
521  if (await io.env(CREDMAN_VARIABLE) === '1') return `${CREDMAN_VARIABLE} is 1`
522  const { configDir } = location.storage
523  const folder = (path: string) => path.replace(/[\\/]+$/, '')
524  let file: string | undefined = `${folder(configDir ?? location.defaultConfigDir)}/.config.json`
525  let text = await configText(io, file)
526  if (text === '') {
527    file = configDir ? `${folder(configDir)}/.claude.json` : home ? `${folder(home)}/.claude.json` : undefined
528    text = file === undefined ? undefined : await configText(io, file)
529  }
530  if (!text) return undefined
531  let flag: unknown
532  try { flag = (JSON.parse(text) as { cachedGrowthBookFeatures?: Record<string, unknown> }).cachedGrowthBookFeatures?.[CREDMAN_FLAG] } catch { return undefined }
533
534  return flag === true ? `its cached setting ${CREDMAN_FLAG} is on in ${file}` : undefined
535}
536
537/** Refuse a Windows login Claude Code keeps in Credential Manager: this module reads browser logins from the credentials file only. */
538async function refuseCredentialManager(io: Io, location: LoginLocation, home: string | undefined, path: string): Promise<void> {
539  const cause = await credentialManagerCause(io, location, home)
540  if (cause === undefined) return
541  const variable = cause.startsWith(CREDMAN_VARIABLE) ? `, or start this session and account setup without ${CREDMAN_VARIABLE}` : ''
542  throw new Error(`Claude Code keeps the login for ${path.replace(/[\\/]\.credentials\.json$/, '')} in Windows Credential Manager (${cause}), and Rice Accounts reads browser logins only from the credentials file ${path}. Use a claudeai-token account instead (/rice-account add <name> claudeai-token), whose token Rice Accounts keeps in Windows Credential Manager itself${variable}.`)
543}
544
545/**
546 * Claude Code on macOS keeps a login in its plaintext credentials file only
547 * when the keychain could not store it, and reads that file when the keychain
548 * holds no item. Whether `path` holds such a login; the grant is not kept.
549 */
550async function fileHoldsLogin(io: Io, path: string): Promise<boolean> {
551  const stat = await io.stat(path).catch(() => null)
552  if (stat === null || stat.kind !== 'file' || stat.size > PENDING_LIMIT) return false
553  const text = await io.read(path).catch(() => null)
554  if (text === null) return false
555  try { return grantOf(JSON.parse(text)) !== null } catch { return false }
556}
557
558/** Windows paths name one file whatever their case or separators. */
559function fileKey(path: string, platform: HostPlatform): string {
560  return `file\0${platform === 'win32' ? path.replace(/\\/g, '/').toLowerCase() : path}`
561}
562
563async function storeOf(io: Io, location: LoginLocation): Promise<Store> {
564  const platform = await hostPlatform(io)
565  if (platform === 'darwin') {
566    const service = await liveServiceName(location.storage, location.defaultConfigDir)
567    const account = await resolveKeychainAccount(io, location.user)
568    let filePath: string | undefined
569    try { filePath = nativeCredentialPath(location, await io.env('HOME'), platform) } catch { filePath = undefined }
570    const pendingPath = filePath === undefined ? undefined : `${filePath}${PENDING_SUFFIX}`
571
572    return { kind: 'keychain', key: `keychain\0${service}\0${account ?? ''}`, service, account, writeAccount: account ?? keychainAccountName(undefined), filePath, pendingPath, cwd: '/' }
573  }
574  const home = platform === 'win32' ? await io.env('USERPROFILE') ?? await io.env('HOME') : await io.env('HOME')
575  const path = nativeCredentialPath(location, home, platform)
576  if (platform === 'win32') await refuseCredentialManager(io, location, home, path)
577  // POSIX never searches the working folder for a program; Windows does, so
578  // there it is the Claude config folder, which only this user writes.
579  const cwd = platform === 'win32' ? location.defaultConfigDir : '/'
580
581  return { kind: 'file', key: fileKey(path, platform), path, pendingPath: `${path}${PENDING_SUFFIX}`, cwd, platform }
582}
583
584async function isFolder(io: Io, path: string): Promise<boolean> {
585  const stat = await io.stat(path).catch(() => null)
586  return stat !== null && stat.kind === 'dir'
587}
588
589async function nodeStartProblem(io: Io, failure: RunFailure, store: FileStore, operation: FileOperation): Promise<string> {
590  const doing = operation === 'read' || operation === 'examine' || operation === 'readpending' ? 'reading' : 'writing'
591  switch (failure) {
592    case 'timeout':
593      return `Node.js did not finish ${doing} the native Claude credential file at ${store.path} within 15 seconds; another program (for example antivirus or a search indexer) may be holding it. Retry in a moment.`
594    case 'missing':
595      // Windows starts Node in the Claude config folder: a missing folder fails the start with ENOENT too.
596      if (store.platform === 'win32' && !(await isFolder(io, store.cwd))) {
597        return `The Claude configuration folder ${store.cwd} does not exist, so Node.js could not be started there for native file account storage. Start Claude Code once so it creates that folder (or check CLAUDE_CONFIG_DIR), then retry.`
598      }
599      return `Native file account storage needs Node.js 22 or later, and no node program could be started from PATH${store.platform === 'win32' ? ` (working folder ${store.cwd})` : ''}. Install Node.js 22 or later, then run account setup again.`
600    case 'denied':
601      return 'The node program on PATH could not be executed for native file account storage. Check that Node.js 22 or later is installed and executable, then run account setup again.'
602    default:
603      return 'Node.js could not be started for native file account storage. Check that Node.js 22 or later is on PATH, then run account setup again.'
604  }
605}
606
607function nodeExitProblem(code: number, store: FileStore, operation: FileOperation): string {
608  const reading = operation === 'read' || operation === 'examine' || operation === 'readpending'
609  const target = operation === 'pending' || operation === 'clearpending' || operation === 'readpending' ? `the pending copy ${store.pendingPath}` : `the native Claude credential file at ${store.path}`
610  const verb = reading ? 'read' : operation === 'clearpending' ? 'remove' : 'write'
611  switch (code) {
612    case FILE_EXIT.noOAuth:
613      return `The native Claude credential file at ${store.path} no longer holds a Claude OAuth login: it was signed out or replaced while the login was renewed.`
614    case FILE_EXIT.missing:
615      return operation === 'pending'
616        ? `Cannot keep the renewed login in ${store.pendingPath}: the login folder does not exist.`
617        : `The native Claude credential file at ${store.path} disappeared while the login was renewed.`
618    case FILE_EXIT.link:
619      return 'Refused a symbolic link at the native credential file. Run account setup with its own login directory.'
620    case FILE_EXIT.invalid:
621      return reading
622        ? `Cannot read the native Claude credential file at ${store.path}: it is unreadable, malformed or not permitted. Check its permissions and run account setup again.`
623        : `Cannot ${verb} ${target}: permission was denied, or the file is unreadable or malformed. Check the permissions of the file and its folder.`
624    case FILE_EXIT.busy:
625      return `Another program (for example antivirus or a search indexer) kept ${target} open, so it could not be replaced after retrying for 3 seconds.`
626    case FILE_EXIT.full:
627      return `Cannot write ${target}: no space is left on its disk, or the file system is read-only.`
628    case FILE_EXIT.oldNode:
629      return 'Native file account storage requires Node.js 22 or later on PATH; the node program found there is older. Install Node.js 22 or later, then run account setup again.'
630    case FILE_EXIT.windowsNode:
631      return 'This WSL session found a Windows node.exe through Windows interop. Install Linux Node.js 22 or later inside WSL so node on PATH is the Linux build, then run account setup again.'
632    default:
633      return `Cannot ${verb} ${target}: Node.js exited with code ${code}.${reading ? ' Check its permissions and run account setup again.' : ''}`
634  }
635}
636
637async function runFile(io: Io, store: FileStore, operation: FileOperation, stdin?: string): Promise<RunResult> {
638  const init = trustedRun(store.cwd, stdin === undefined ? { timeoutMs: 15_000 } : { stdin, timeoutMs: 15_000 })
639  try {
640    return await io.run(['node', '-e', NATIVE_FILE, operation, store.path], init)
641  } catch (error) {
642    throw new Error(await nodeStartProblem(io, runFailure(error), store, operation))
643  }
644}
645
646/** The program's `read`: the store, or the store with a usable pending grant. Nothing is written. */
647async function fileRead(io: Io, store: FileStore): Promise<Credential | null> {
648  const result = await runFile(io, store, 'read')
649  if (result.exitCode === FILE_EXIT.noOAuth || result.exitCode === FILE_EXIT.missing) return null
650  if (result.exitCode !== 0) throw new Error(nodeExitProblem(result.exitCode, store, 'read'))
651  if (result.isStdoutTruncated) throw new Error(nodeExitProblem(FILE_EXIT.invalid, store, 'read'))
652
653  return credential(result.stdout)
654}
655
656type StoreView = { stored: Credential | null; pending: PendingLogin | null }
657
658/**
659 * The program's `examine`: the store and its pending renewal as they are.
660 * Nothing is written. `examine` reports a missing store as null, so its exit
661 * 44 is not an answer: the login is not renewed on a guess (reading the store
662 * alone would also mix in a usable pending renewal and hide which token the
663 * store holds).
664 */
665async function fileInspect(io: Io, store: FileStore): Promise<StoreView> {
666  const result = await runFile(io, store, 'examine')
667  if (result.exitCode === FILE_EXIT.noOAuth) return { stored: null, pending: null }
668  if (result.exitCode !== 0) throw new Error(nodeExitProblem(result.exitCode, store, 'examine'))
669  if (result.isStdoutTruncated) throw new Error(nodeExitProblem(FILE_EXIT.invalid, store, 'examine'))
670  let value: { stored?: unknown; pending?: unknown } | null
671  try { value = JSON.parse(result.stdout) as { stored?: unknown; pending?: unknown } | null } catch { throw invalidStore() }
672  if (value === null || typeof value !== 'object') throw invalidStore()
673  const stored = value.stored === null || value.stored === undefined ? null : documentOf(value.stored)
674
675  return { stored, pending: pendingOf(value.pending) }
676}
677
678/** The program's `readpending`: the pending renewal alone, for a store that cannot be read. */
679async function filePendingOnly(io: Io, store: FileStore): Promise<PendingLogin | null> {
680  const result = await runFile(io, store, 'readpending')
681  if (result.exitCode !== 0 || result.isStdoutTruncated) return null
682  try { return pendingOf((JSON.parse(result.stdout) as { pending?: unknown } | null)?.pending) } catch { return null }
683}
684
685async function fileWrite(io: Io, store: FileStore, fresh: Credential, expected: string): Promise<Credential> {
686  const result = await runFile(io, store, 'write', JSON.stringify({ expectedRefreshToken: expected, oauth: grantOnly(fresh.claudeAiOauth) }))
687  if (result.exitCode === FILE_EXIT.changed) throw new LoginChangedError('The login changed while it was renewed.')
688  if (result.exitCode === FILE_EXIT.noOAuth || result.exitCode === FILE_EXIT.missing) throw new StoreGoneError(nodeExitProblem(result.exitCode, store, 'write'))
689  if (result.exitCode !== 0) throw new Error(nodeExitProblem(result.exitCode, store, 'write'))
690  if (result.isStdoutTruncated) throw new Error(nodeExitProblem(FILE_EXIT.invalid, store, 'write'))
691  const saved = credential(result.stdout)
692  if (saved === null) throw new StoreGoneError(nodeExitProblem(FILE_EXIT.noOAuth, store, 'write'))
693
694  return saved
695}
696
697async function fileChange(io: Io, store: FileStore, operation: 'pending' | 'clearpending', stdin: string): Promise<void> {
698  const result = await runFile(io, store, operation, stdin)
699  if (result.exitCode !== 0) throw new Error(nodeExitProblem(result.exitCode, store, operation))
700}
701
702/** Remove files by absolute path; only POSIX (darwin) needs this, the Node program removes its own. */
703async function removeFiles(io: Io, cwd: string, files: string[]): Promise<void> {
704  if (files.length === 0) return
705  await io.run(['/bin/rm', '-f', '--', ...files], trustedRun(cwd, { timeoutMs: 10_000 }))
706    .then(ran => { if (ran.exitCode !== 0) io.log(`could not remove ${files.join(', ')} (rm exit ${ran.exitCode})`) })
707    .catch((error: unknown) => io.log(`could not remove ${files.join(', ')}: ${message(error)}`))
708}
709
710type PendingFile = { pending: PendingLogin | null; regular: boolean; mtimeMs: number }
711
712/** The darwin pending file through Io, never following a symbolic link; null when there is none. */
713async function readPendingFile(io: Io, path: string): Promise<PendingFile | null> {
714  const stat = await io.stat(path).catch(() => null)
715  if (stat === null) return null
716  const regular = stat.kind === 'file' && !stat.isLink
717  if (!regular || stat.size > PENDING_LIMIT) return { pending: null, regular, mtimeMs: stat.mtimeMs }
718  const text = await io.read(path).catch(() => null)
719
720  return { pending: text === null ? null : parsePendingLogin(text), regular, mtimeMs: stat.mtimeMs }
721}
722
723/**
724 * The keychain item and the pending file. Reads, the compare before a write
725 * and the read-back after it all address the same item: the account when it
726 * is known, else none. Without an item, a login Claude Code kept in its
727 * plaintext credentials file instead is reported, never used.
728 */
729async function keychainView(io: Io, store: KeychainStore): Promise<StoreView> {
730  const text = await readItem(io, store.service, store.account)
731  if (text === null && store.filePath !== undefined && await fileHoldsLogin(io, store.filePath)) {
732    throw new StoreGoneError(`The Claude login for ${store.filePath.replace(/\/\.credentials\.json$/, '')} is in its plaintext credentials file ${store.filePath}, not in the macOS keychain item "${store.service}" that Rice Accounts reads: Claude Code keeps a login in that file only when the keychain could not store it, for example while the keychain was locked. Unlock the login keychain (security unlock-keychain), then sign in again in a terminal so Claude Code moves the login into the keychain: for a saved account, run the command /rice-account setup <name> prints, with --login added; for this machine's login, run claude auth login.`)
733  }
734  const stored = text === null ? null : credential(text)
735  if (stored === null || store.pendingPath === undefined) return { stored, pending: null }
736
737  return { stored, pending: (await readPendingFile(io, store.pendingPath))?.pending ?? null }
738}
739
740/** Store a login in the keychain within the line limit and read the same item back. */
741async function writeKeychain(io: Io, store: KeychainStore, document: Credential): Promise<Credential> {
742  const { text, dropped } = fitCredential(document, store.service, store.writeAccount)
743  if (dropped.length > 0) io.log(`the macOS keychain line limit left ${dropped.join(', ')} out of the stored login "${store.service}"; the OAuth login was kept whole`)
744  await writeItem(io, store.service, store.writeAccount, text)
745  const check = await readItem(io, store.service, store.account)
746  const written = check === null ? null : credential(check)
747  if (written === null || written.claudeAiOauth.refreshToken !== document.claudeAiOauth.refreshToken || written.claudeAiOauth.accessToken !== document.claudeAiOauth.accessToken) {
748    throw new KeychainError(`the keychain item "${store.service}" did not read back as written`)
749  }
750
751  return written
752}
753
754async function viewOf(io: Io, store: Store): Promise<StoreView> {
755  return store.kind === 'file' ? fileInspect(io, store) : keychainView(io, store)
756}
757
758/**
759 * Renewals the server granted that are not saved yet, by store: the store's
760 * refresh token when the first of them began, the newest renewed login, and
761 * the spent refresh tokens it descends from.
762 */
763const unsaved = new Map<string, PendingLogin & { spent: readonly string[] }>()
764
765/** The store each inspected state was read from. */
766const stores = new WeakMap<LoginState, Store>()
767
768/** Forget unsaved renewals; for tests. */
769export function forgetUnsavedLogins(): void {
770  unsaved.clear()
771}
772
773/** Rule B over a view and this process's memory; memory that is no longer usable, or older than the pending renewal, is forgotten. */
774function choose(key: string, view: StoreView): LoginState {
775  const entry = unsaved.get(key)
776  const picked = bestLogin(view.stored, view.pending, entry)
777  if (entry && view.stored !== null && picked.source !== 'memory') unsaved.delete(key)
778
779  return {
780    stored: view.stored,
781    pending: view.pending,
782    login: picked.login,
783    source: picked.source,
784    candidate: picked.candidate,
785    onDisk: view.stored?.claudeAiOauth.refreshToken,
786    spent: picked.source === 'memory' && entry ? entry.spent : [],
787  }
788}
789
790/**
791 * A pending renewal that is later than the one kept in memory, read without the
792 * store (which cannot be read): the same base, a login memory does not descend
793 * from. Another session renewed further while this one's store was unreadable.
794 */
795async function laterPending(io: Io, store: Store, entry: PendingLogin & { spent: readonly string[] }): Promise<(PendingLogin & { spent: readonly string[] }) | null> {
796  let pending: PendingLogin | null
797  try {
798    pending = store.kind === 'file' ? await filePendingOnly(io, store) : store.pendingPath === undefined ? null : (await readPendingFile(io, store.pendingPath))?.pending ?? null
799  } catch {
800    return null
801  }
802  if (pending === null || pending.base !== entry.base || !pendingIsLater(entry, pending)) return null
803
804  return { ...pending, spent: descent(entry.spent, entry.credential.claudeAiOauth.refreshToken, pending.credential) }
805}
806
807/** The state of `store`; when it cannot be read, the newest renewal kept in memory or in the pending file answers (with its base as the store's token). */
808async function stateOf(io: Io, store: Store): Promise<LoginState> {
809  let view: StoreView
810  try {
811    view = await viewOf(io, store)
812  } catch (error) {
813    const entry = unsaved.get(store.key)
814    if (!entry) throw error
815    io.log(`the credential store is unreadable (${message(error)}); using the renewed login kept in memory`)
816    const current = await laterPending(io, store, entry) ?? entry
817    if (current !== entry) unsaved.set(store.key, current)
818    return { stored: null, pending: null, login: current.credential, source: 'memory', candidate: current, onDisk: current.base, spent: current.spent }
819  }
820
821  return choose(store.key, view)
822}
823
824/**
825 * The login at `location`: the stored one, or a renewal not saved yet that
826 * is usable against it (rule B). A plain read: it never writes or removes
827 * anything, whatever it finds.
828 */
829export async function readLogin(io: Io, location: LoginLocation): Promise<Credential | null> {
830  const store = await storeOf(io, location)
831  if (store.kind === 'file' && !unsaved.has(store.key)) return fileRead(io, store)
832
833  return (await stateOf(io, store)).login
834}
835
836/**
837 * The store, its pending renewal and the login to use, for a renewal under
838 * the renewal lock. It reads only; `onDisk` is what the next store write must
839 * find there.
840 */
841export async function inspectLogin(io: Io, location: LoginLocation): Promise<LoginState> {
842  const store = await storeOf(io, location)
843  const state = await stateOf(io, store)
844  // Saving the renewal must not look the store up again (that can start a process) once the old token is spent.
845  stores.set(state, store)
846
847  return state
848}
849
850async function writePending(io: Io, store: Store, renewal: PendingLogin): Promise<string> {
851  const content = { base: renewal.base, credential: { claudeAiOauth: grantOnly(renewal.credential.claudeAiOauth) } }
852  if (store.kind === 'file') {
853    await fileChange(io, store, 'pending', JSON.stringify(content))
854    return store.pendingPath
855  }
856  if (store.pendingPath === undefined) throw new Error('the login has no folder to keep a pending copy in')
857  const ran = await io.run(['/bin/sh', '-c', PENDING_SH, store.pendingPath], trustedRun(store.cwd, { stdin: JSON.stringify({ version: PENDING_VERSION, ...content }), timeoutMs: 15_000 }))
858  if (ran.exitCode !== 0) throw new Error(`the pending copy ${store.pendingPath} could not be written (sh exit ${ran.exitCode})`)
859
860  return store.pendingPath
861}
862
863/**
864 * Remove the pending file when its base is `base` and its refresh token is one
865 * of `tokens` (this renewal's own and the ones it descends from), so another
866 * session's later renewal under the same base stays; or when it is not a
867 * version 2 file and older than five minutes. Failures are logged: a pending
868 * file left behind is redundant or obsolete by rule B and never used.
869 */
870async function clearPending(io: Io, store: Store, base: string, tokens: readonly string[]): Promise<void> {
871  try {
872    if (store.kind === 'file') {
873      await fileChange(io, store, 'clearpending', JSON.stringify({ base, tokens }))
874      return
875    }
876    if (store.pendingPath === undefined) return
877    const found = await readPendingFile(io, store.pendingPath)
878    if (found === null) return
879    const now = await io.now().catch(() => undefined)
880    const stale = found.regular && now !== undefined && now - found.mtimeMs >= STALE_COPY_MS
881    const mine = found.pending !== null && found.pending.base === base && tokens.includes(found.pending.credential.claudeAiOauth.refreshToken)
882    if (found.pending !== null ? mine : stale) await removeFiles(io, store.cwd, [store.pendingPath])
883  } catch (error) {
884    io.log(`could not remove the pending copy of a saved login: ${message(error)}`)
885  }
886}
887
888/** Save `fresh` when the store still holds `expected` (compare-and-swap); `LoginChangedError` when it holds another login. */
889async function saveToStore(io: Io, store: Store, fresh: Credential, expected: string): Promise<Credential> {
890  if (store.kind === 'file') return fileWrite(io, store, fresh, expected)
891  // The keychain has no compare-and-swap: read the same item again immediately before writing.
892  const text = await readItem(io, store.service, store.account)
893  const stored = text === null ? null : credential(text)
894  if (stored === null) throw new StoreGoneError(`The keychain login "${store.service}" disappeared while the login was renewed.`)
895  const held = stored.claudeAiOauth.refreshToken
896  if (held !== expected) {
897    if (held === fresh.claudeAiOauth.refreshToken) return stored
898    throw new LoginChangedError('The login changed while it was renewed.')
899  }
900
901  return writeKeychain(io, store, merged(stored, fresh.claudeAiOauth))
902}
903
904function notSaved(error: unknown, kept: string | undefined): LoginNotSavedError {
905  const where = kept === undefined ? 'in this session\'s memory only' : `in ${kept} (owner-only) and in this session's memory`
906  const text = message(error).replace(/\.?$/, '.')
907  if (error instanceof StoreGoneError) return new LoginNotSavedError(`${text} The renewed login was kept ${where}, but it cannot be used without a stored login: sign this account in again with account setup.`)
908
909  return new LoginNotSavedError(`${text} The renewed login was kept ${where}; it is saved automatically the next time this account is used.`)
910}
911
912/**
913 * The store changed under the lock (an interactive sign-in, or a session
914 * without the lock). When it holds `fresh` it was saved; otherwise the store
915 * is authoritative: its login (with a renewal usable against it) is used,
916 * this process's renewal is forgotten, and a pending file is removed only
917 * when it is obsolete against the new store.
918 */
919async function settleChanged(io: Io, store: Store, fresh: Credential, onDisk: string, kept: string | undefined, spent: readonly string[], hops: number): Promise<Credential> {
920  let view: StoreView
921  try {
922    view = await viewOf(io, store)
923  } catch (error) {
924    throw notSaved(error, kept)
925  }
926  if (view.stored === null) throw notSaved(new StoreGoneError('The stored login disappeared while it was renewed.'), kept)
927  const held = view.stored.claudeAiOauth.refreshToken
928  // The store advanced along this renewal's own ancestry (a stalled session saved
929  // its older renewal after this one began): `fresh` is the later login, and it is
930  // saved over that one. Taking the store's login instead would drop the newest.
931  if (held !== fresh.claudeAiOauth.refreshToken && spent.includes(held) && hops < SPENT_KEPT) {
932    io.log('an older renewal of this login was saved while a newer one was being renewed; saving the newer one over it')
933    return persist(io, store, fresh, held, spent, undefined, hops + 1)
934  }
935  unsaved.delete(store.key)
936  if (held === fresh.claudeAiOauth.refreshToken) {
937    await clearPending(io, store, onDisk, ownedTokens(spent, fresh))
938    return view.stored
939  }
940  if (view.pending !== null && pendingState(view.stored, view.pending) === 'obsolete') await clearPending(io, store, view.pending.base, [view.pending.credential.claudeAiOauth.refreshToken])
941  io.log('another session or sign-in saved a different login while this one renewed; kept that login')
942
943  return bestLogin(view.stored, view.pending).login ?? view.stored
944}
945
946/**
947 * Persist a renewal: kept in memory, then written ahead to the owner-only
948 * pending file as `{base: onDisk, credential: fresh}`, then saved to the store
949 * only if it still holds `onDisk`, and the pending file cleared. A failed
950 * store write keeps both and throws `LoginNotSavedError` naming where.
951 */
952async function persist(io: Io, store: Store, fresh: Credential, onDisk: string, spent: readonly string[], afterKept?: () => Promise<void>, hops = 0): Promise<Credential> {
953  const renewal: PendingLogin = { base: onDisk, credential: fresh }
954  unsaved.set(store.key, { ...renewal, spent })
955  let kept: string | undefined
956  try {
957    kept = await writePending(io, store, renewal)
958  } catch (error) {
959    io.log(`could not keep the renewed login in a pending file: ${message(error)}`)
960  }
961  // The only copy that could be lost is in memory until now; whatever extends the lock for the save comes after it.
962  if (afterKept) await afterKept().catch((error: unknown) => io.log(`could not prepare saving the renewed login: ${message(error)}`))
963  let saved: Credential
964  try {
965    saved = await saveToStore(io, store, fresh, onDisk)
966  } catch (error) {
967    if (error instanceof LoginChangedError) return settleChanged(io, store, fresh, onDisk, kept, spent, hops)
968    throw notSaved(error, kept)
969  }
970  unsaved.delete(store.key)
971  await clearPending(io, store, onDisk, ownedTokens(spent, fresh))
972
973  return saved
974}
975
976/** The refresh tokens a renewal owns: its own and the spent ones it descends from. */
977function ownedTokens(spent: readonly string[], fresh: Credential): string[] {
978  return [...spent, fresh.claudeAiOauth.refreshToken]
979}
980
981/** The spent tokens a renewal of `renewed` into `fresh` descends from. */
982function descent(spent: readonly string[], renewed: string, fresh: Credential): string[] {
983  const all = renewed === fresh.claudeAiOauth.refreshToken || spent.includes(renewed) ? [...spent] : [...spent, renewed]
984  return all.slice(-SPENT_KEPT)
985}
986
987/**
988 * Persist a rotated grant renewed from `from.login` (read with
989 * `inspectLogin`), comparing the store against `from.onDisk`. The server
990 * already spent the previous refresh token, so the renewal is kept in memory
991 * and written ahead to the pending file before the store write; a failed
992 * store write throws `LoginNotSavedError`, and the renewal stays usable.
993 * `afterKept` runs once the pending copy is written (or failed) and before the
994 * store write.
995 */
996export async function saveRenewal(io: Io, location: LoginLocation, fresh: Credential, from: LoginState, afterKept?: () => Promise<void>): Promise<Credential> {
997  const store = stores.get(from) ?? await storeOf(io, location)
998  const renewed = from.login?.claudeAiOauth.refreshToken
999  const onDisk = from.onDisk ?? renewed
1000  if (renewed === undefined || onDisk === undefined) throw new Error('There is no stored login to save this renewal over. Run account setup again.')
1001
1002  return persist(io, store, fresh, onDisk, descent(from.spent, renewed, fresh), afterKept)
1003}
1004
1005/**
1006 * Persist a rotated grant without replacing unrelated native credential
1007 * fields; `previous` is the login that was renewed. The store write compares
1008 * against the refresh token the store held when `previous`'s lineage began.
1009 */
1010export async function writeLogin(io: Io, location: LoginLocation, fresh: Credential, previous: Credential): Promise<Credential> {
1011  const store = await storeOf(io, location)
1012  const renewed = previous.claudeAiOauth.refreshToken
1013  const entry = unsaved.get(store.key)
1014  const remembered = entry?.credential.claudeAiOauth.refreshToken === renewed ? entry : undefined
1015  let onDisk = remembered?.base ?? renewed
1016  let spent: readonly string[] = remembered?.spent ?? []
1017  try {
1018    const state = await stateOf(io, store)
1019    if (state.stored?.claudeAiOauth.refreshToken === renewed) {
1020      onDisk = renewed
1021      spent = []
1022    } else if (state.candidate !== null && state.login?.claudeAiOauth.refreshToken === renewed && state.onDisk !== undefined) {
1023      onDisk = state.onDisk
1024      spent = state.spent
1025    }
1026  } catch {
1027    // Unreadable now: the store write below reports it, and the renewal is still kept.
1028  }
1029
1030  return persist(io, store, fresh, onDisk, descent(spent, renewed, fresh))
1031}
1032
1033/**
1034 * Save a usable renewal that `state` found unsaved (opportunistically, under
1035 * the renewal lock). Resolves the login to use: the saved one, the store's
1036 * when it changed meanwhile, or the renewal itself when the store still
1037 * refuses it (logged only: the renewal works).
1038 */
1039export async function promoteLogin(io: Io, location: LoginLocation, state: LoginState): Promise<Credential | null> {
1040  if (state.source === 'store' || state.login === null || state.stored === null) return state.login
1041  const store = stores.get(state) ?? await storeOf(io, location)
1042  const login = state.login
1043  const onDisk = state.stored.claudeAiOauth.refreshToken
1044  try {
1045    const saved = await saveToStore(io, store, login, onDisk)
1046    unsaved.delete(store.key)
1047    await clearPending(io, store, onDisk, ownedTokens(state.spent, login))
1048    io.log('saved a renewed login that had been kept unsaved')
1049    return saved
1050  } catch (error) {
1051    if (error instanceof LoginChangedError) {
1052      try { return await settleChanged(io, store, login, onDisk, undefined, state.spent, 0) } catch { return login }
1053    }
1054    io.log(`a renewed login is still unsaved and is used as it is: ${message(error)}`)
1055    return login
1056  }
1057}
1058
1059/** Whether this process holds a renewal for `location` that is not saved yet. */
1060export async function hasUnsavedLogin(io: Io, location: LoginLocation): Promise<boolean> {
1061  if (unsaved.size === 0) return false
1062  return unsaved.has((await storeOf(io, location)).key)
1063}
1064
1065/**
1066 * Try again to save a renewal this process holds for `location`. Resolves the
1067 * login to use, as `promoteLogin` does; null when there is none.
1068 */
1069export async function saveUnsavedLogin(io: Io, location: LoginLocation): Promise<Credential | null> {
1070  const store = await storeOf(io, location)
1071  if (!unsaved.has(store.key)) return null
1072  const state = await stateOf(io, store)
1073
1074  return promoteLogin(io, location, state)
1075}
1076
1077/** Placeholder growth for a token whose renewed length is not known yet. */
1078function grown(token: string): string {
1079  return 'x'.repeat(Math.max(token.length * 2, token.length + 512))
1080}
1081
1082/**
1083 * Refuse, before the token endpoint spends the refresh token, a renewal whose
1084 * result could not be stored. Only the macOS keychain has a limit this small:
1085 * `security -i` takes about 4 KB per line. The check projects longer tokens
1086 * than the current ones and counts on optional fields being left out.
1087 */
1088export async function checkRenewable(io: Io, location: LoginLocation, current: Credential): Promise<void> {
1089  const store = await storeOf(io, location)
1090  if (store.kind !== 'keychain') return
1091  const oauth = current.claudeAiOauth
1092  try {
1093    fitCredential(merged(current, { accessToken: grown(oauth.accessToken), refreshToken: grown(oauth.refreshToken), expiresAt: Number.MAX_SAFE_INTEGER, refreshTokenExpiresAt: Number.MAX_SAFE_INTEGER }), store.service, store.writeAccount)
1094  } catch (error) {
1095    throw new Error(`This login is too large to store in the macOS keychain (${message(error)}). It was not renewed, so its refresh token was not spent; sign it in again with account setup.`)
1096  }
1097}
1098
1099function secretStartProblem(failure: RunFailure, platform: 'win32' | 'linux', command: string): string {
1100  if (platform === 'win32') {
1101    if (failure === 'timeout') return 'Windows Credential Manager did not answer within 15 seconds. Sign into an interactive Windows session (a sign-in prompt may be waiting), then retry.'
1102    if (failure === 'missing' || failure === 'denied') return `Windows account secrets require Windows PowerShell; ${command} could not be started. Restore Windows PowerShell, then run account setup again.`
1103    return 'Windows account secrets require Windows PowerShell and an interactive Windows sign-in with Credential Manager available.'
1104  }
1105  if (failure === 'timeout') return 'The Linux Secret Service keyring did not answer within 15 seconds. Unlock the keyring (a prompt may be waiting) or start its service, then retry.'
1106  if (failure === 'missing' || failure === 'denied') return 'Named account secrets on Linux require secret-tool (libsecret), and it could not be started. Install it (for example the libsecret-tools package) and enable an unlocked Secret Service keyring, then run account setup again.'
1107  return 'Named account secrets on Linux require secret-tool (libsecret) and an unlocked Secret Service keyring. Install or enable them, then run account setup again.'
1108}
1109
1110/** Named keys and tokens use the OS keyring, separate from native OAuth files. */
1111export async function readSecret(io: Io, reference: SecretRef): Promise<string | null> {
1112  const platform = await hostPlatform(io)
1113  if (platform === 'darwin') return readItem(io, reference.service, reference.account)
1114  if (platform === 'win32') {
1115    const root = await io.env('SystemRoot') ?? await io.env('WINDIR')
1116    const command = root ? `${root.replace(/[\\/]+$/, '')}/System32/WindowsPowerShell/v1.0/powershell.exe` : 'powershell.exe'
1117    const cwd = root ?? await io.env('USERPROFILE') ?? 'C:\\'
1118    const result = await io.run([command, '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', WINDOWS_CREDENTIAL_STORE], trustedRun(cwd, { stdin: JSON.stringify({ operation: 'read', service: reference.service, account: reference.account }), timeoutMs: 15_000 }))
1119      .catch((error: unknown) => { throw new Error(secretStartProblem(runFailure(error), 'win32', command)) })
1120    if (result.exitCode === 44) return null
1121    if (result.exitCode !== 0 || result.isStdoutTruncated) throw new Error(`Cannot read Windows Credential Manager (exit ${result.exitCode}). Sign into an interactive Windows session and run account setup again.`)
1122    return result.stdout
1123  }
1124  const result = await io.run(['secret-tool', 'lookup', 'service', reference.service, 'account', reference.account], trustedRun('/', { timeoutMs: 15_000 }))
1125    .catch((error: unknown) => { throw new Error(secretStartProblem(runFailure(error), 'linux', 'secret-tool')) })
1126  if (result.exitCode === 1 && result.stderr.trim() === '') return null
1127  if (result.exitCode !== 0 || result.isStdoutTruncated) throw new Error(`Cannot read the Linux account keyring (secret-tool exit ${result.exitCode}). Check that secret-tool (libsecret) and an unlocked Secret Service keyring are available, then run account setup again.`)
1128  return result.stdout.replace(/\n$/, '')
1129}
1130
hooks/descendants.ts 159 lines
1/**
2 * Children keep native behavior: Bash and `$.process.*` children inherit the
3 * session's `ANTHROPIC_CUSTOM_HEADERS` (the selected bearer) the way Claude
4 * passes its environment on, and no command text or child environment is
5 * rewritten. The one thing added here is a lockout: while the session account
6 * is unconfirmed, a child `claude` is refused so it cannot start on an account
7 * nobody confirmed.
8 */
9
10const CLAUDE_PROGRAMS = new Set(['claude', 'claude.exe', 'claude.cmd', 'claude.ps1', 'claude-code', 'claude-code.exe', 'claude-code.cmd'])
11/** Claude Code's own versioned binaries, which have a version number for a name. */
12const VERSIONED_CLAUDE = /(?:^|[\\/])claude[\\/]versions[\\/][^\\/]+$/i
13const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish', 'sh.exe', 'bash.exe', 'cmd', 'cmd.exe', 'powershell', 'powershell.exe', 'pwsh', 'pwsh.exe'])
14/** Programs that run the command after their own options, assignments or a duration. */
15const WRAPPERS = new Set(['env', 'exec', 'command', 'builtin', 'nohup', 'time', 'sudo', 'doas', 'nice', 'timeout', 'xargs', 'stdbuf', 'setsid', 'caffeinate', 'npx', 'bunx', 'pnpx', 'call'])
16/** Shell keywords after which a command word follows. */
17const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', 'time', 'function', 'coproc'])
18/** Wrapper options whose value is the next word, so that word is not the command. */
19const OPTION_VALUES = new Set(['-u', '-g', '-C', '-S', '-n', '-s', '-k', '-P', '-I', '-L', '-a', '--user', '--group', '--chdir', '--signal', '--kill-after', '--package'])
20
21export const GUARD_FAILED = 'Rice Accounts could not confirm the session account before starting claude, so it was not started. Run /rice-account login or select a saved account again, then retry.'
22
23/** One shell word without its quotes and escapes: "c\laude" and 'claude' both read as claude. */
24function word(text: string): string {
25  return text.replace(/\\(.)/g, '$1').replace(/["']/g, '')
26}
27
28function basename(text: string): string {
29  return (word(text).split(/[\\/]/).pop() ?? '').toLowerCase()
30}
31
32/** A Windows path keeps its backslashes, and a POSIX word may escape a letter with one (c\laude): either reading counts. */
33function isClaude(text: string): boolean {
34  const plain = word(text)
35  const asPath = (text.replace(/["']/g, '').split(/[\\/]/).pop() ?? '').toLowerCase()
36  return CLAUDE_PROGRAMS.has(basename(plain)) || CLAUDE_PROGRAMS.has(asPath) || VERSIONED_CLAUDE.test(plain)
37}
38
39/**
40 * Splits a command line into command segments and their words, honoring
41 * quotes and backslash escapes: separators and spaces inside quotes belong to a
42 * word. Words keep their quotes for `word` to remove.
43 */
44function segments(command: string): string[][] {
45  const out: string[][] = []
46  let words: string[] = []
47  let current = ''
48  let quote: '"' | "'" | undefined
49  const endWord = () => { if (current !== '') words.push(current); current = '' }
50  const endSegment = () => { endWord(); if (words.length > 0) out.push(words); words = [] }
51  for (let i = 0; i < command.length; i += 1) {
52    const char = command[i]!
53    if (quote) {
54      current += char
55      if (char === '\\' && quote === '"' && i + 1 < command.length) { i += 1; current += command[i]! }
56      else if (char === quote) quote = undefined
57      continue
58    }
59    if (char === '\\' && i + 1 < command.length) { current += char + command[i + 1]!; i += 1; continue }
60    if (char === '"' || char === "'") { quote = char; current += char; continue }
61    if (/\s/.test(char) && char !== '\n' && char !== '\r') { endWord(); continue }
62    // ">&", "<&" and "&>" are redirections, not command separators.
63    if (char === '&' && (command[i - 1] === '>' || command[i - 1] === '<' || command[i + 1] === '>')) { current += char; continue }
64    if (';|&\n\r(){}`'.includes(char)) { endSegment(); continue }
65    current += char
66  }
67  endSegment()
68  return out
69}
70
71/** Leading redirections (">f", "2>&1", ">" "file") do not make a word the command. */
72function afterRedirections(words: readonly string[], start: number): number {
73  let index = start
74  while (index < words.length) {
75    const current = word(words[index] ?? '')
76    const operator = /^\d*(?:>>|<<|>&|<&|>\|?|<)/.exec(current)
77    if (!operator) return index
78    index += operator[0].length === current.length && !/&$/.test(operator[0]) ? 2 : 1
79  }
80  return index
81}
82
83/** The index of the command a wrapper at `index` runs: past keywords, redirections, options, their values, assignments and a duration. */
84function afterWrappers(words: readonly string[], start: number): number {
85  let index = afterRedirections(words, start)
86  while (index < words.length) {
87    const current = word(words[index] ?? '')
88    if (KEYWORDS.has(current)) { index = afterRedirections(words, index + 1); continue }
89    if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(current)) { index = afterRedirections(words, index + 1); continue }
90    if (!WRAPPERS.has(basename(current))) return index
91    index += 1
92    while (index < words.length) {
93      const option = word(words[index] ?? '')
94      if (option === '--') { index += 1; break }
95      // `sudo -n claude` and `nice -n 5 claude` differ only by meaning: a claude value is taken as the command.
96      if (OPTION_VALUES.has(option)) {
97        if (isClaude(words[index + 1] ?? '')) return index + 1
98        index += 2
99        continue
100      }
101      if (option.startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(option) || /^\d+(?:\.\d+)?[smhd]?$/.test(option)) { index += 1; continue }
102      break
103    }
104  }
105  return index
106}
107
108/**
109 * Whether a shell command line runs `claude` as a command word: in any list,
110 * pipeline, group or substitution, after keywords, redirections, assignments and
111 * wrapper programs, including the text of `eval` and `env -S`. Words inside
112 * quotes that hold separators belong to their word. A line this cannot read
113 * fully may be over-matched; a refusal then names the lockout rather than
114 * starting an unconfirmed account.
115 */
116export function commandInvokesClaude(command: string): boolean {
117  for (const words of segments(command)) {
118    // env -S and --split-string take a whole command line.
119    if (basename(words[0] ?? '') === 'env') {
120      for (let at = 1; at < words.length; at += 1) {
121        const option = word(words[at] ?? '')
122        const value = option === '-S' || option === '--split-string' ? word(words[at + 1] ?? '') : /^--split-string=/.test(option) ? option.slice('--split-string='.length) : undefined
123        if (value !== undefined && commandInvokesClaude(value)) return true
124      }
125    }
126    const index = afterWrappers(words, 0)
127    const program = words[index]
128    if (program === undefined) continue
129    if (isClaude(program)) return true
130    const name = basename(program)
131    if (name === 'eval' && commandInvokesClaude(words.slice(index + 1).map(word).join(' '))) return true
132    // A shell started on the line runs its own command text (sh -c, cmd /c, powershell -Command).
133    if (SHELLS.has(name) && argvInvokesClaude(words.slice(index).map(word))) return true
134  }
135  return false
136}
137
138/** Whether an argument vector starts `claude`, directly, through a wrapper, or as a shell's `-c` command. */
139export function argvInvokesClaude(argv: readonly string[]): boolean {
140  for (let at = 0; at < argv.length; at += 1) {
141    const option = argv[at] ?? ''
142    const split = option === '-S' || option === '--split-string' ? argv[at + 1] : /^--split-string=/.test(option) ? option.slice('--split-string='.length) : /^-S./.test(option) && basename(argv[0] ?? '') === 'env' ? option.slice(2) : undefined
143    if (split !== undefined && commandInvokesClaude(split)) return true
144  }
145  const index = afterWrappers(argv, 0)
146  const program = argv[index]
147  if (program === undefined) return false
148  if (isClaude(program)) return true
149  if (!SHELLS.has(basename(program))) return false
150  for (let at = index + 1; at < argv.length; at += 1) {
151    const option = argv[at] ?? ''
152    // cmd /c and PowerShell -Command run the rest of the line; a POSIX -c runs
153    // its next argument, the ones after it being positional parameters.
154    if (/^\/c$/i.test(option) || /^-command$/i.test(option)) return commandInvokesClaude(argv.slice(at + 1).join(' '))
155    if (/^-[A-Za-z]*c$/.test(option)) return commandInvokesClaude(argv[at + 1] ?? '')
156  }
157  return false
158}
159
hooks/env.ts 183 lines
1import type { AccountConfig } from './config'
2import type { EnvName } from './io'
3
4/**
5 * The environment variables a switch owns. Native OAuth credentials are
6 * memoized, while the supported custom request headers are read when a client
7 * is created. Keep the original native credential source available for its
8 * own refresh lifecycle and select another account through request headers.
9 */
10export const MANAGED = [
11  'ANTHROPIC_API_KEY',
12  'ANTHROPIC_AUTH_TOKEN',
13  'ANTHROPIC_CUSTOM_HEADERS',
14  'CLAUDE_CODE_OAUTH_TOKEN',
15  'CLAUDE_SECURESTORAGE_CONFIG_DIR',
16  'ANTHROPIC_BASE_URL',
17  'CLAUDE_CODE_USE_BEDROCK',
18  'CLAUDE_CODE_USE_VERTEX',
19  'CLAUDE_CODE_USE_FOUNDRY',
20  'CLAUDE_CODE_USE_ANTHROPIC_AWS',
21  'CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD',
22  'CLAUDE_CODE_USE_MANTLE',
23  'CLAUDE_CODE_USE_GATEWAY',
24  'CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR',
25  'CLAUDE_CODE_GATEWAY_TOKEN_FILE_DESCRIPTOR',
26  'CLAUDE_BG_AUTH_SNAPSHOT_PATH',
27  'CLAUDE_CODE_HOST_CREDS_FILE',
28  'CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST',
29  'CLAUDE_CODE_HOST_AUTH_ENV_VAR',
30  'AWS_PROFILE',
31  'AWS_REGION',
32  'AWS_BEARER_TOKEN_BEDROCK',
33  'ANTHROPIC_BEDROCK_BASE_URL',
34  'ANTHROPIC_VERTEX_PROJECT_ID',
35  'CLOUD_ML_REGION',
36  'ANTHROPIC_VERTEX_BASE_URL',
37  'ANTHROPIC_FOUNDRY_RESOURCE',
38  'ANTHROPIC_FOUNDRY_BASE_URL',
39  'ANTHROPIC_FOUNDRY_API_KEY',
40] as const
41
42export type Managed = (typeof MANAGED)[number]
43
44/** Each managed variable as the process started: a value, or null for unset. */
45export type Originals = Record<Managed, string | null>
46
47/** What a switch sets: a value, or undefined to unset. */
48export type EnvPlan = Record<Managed, string | undefined>
49
50/** The variables that pick a credential or a provider; a switch to any other account clears them first. */
51const AUTH: readonly Managed[] = [
52  'ANTHROPIC_API_KEY',
53  'ANTHROPIC_AUTH_TOKEN',
54  'CLAUDE_CODE_USE_BEDROCK',
55  'CLAUDE_CODE_USE_VERTEX',
56  'CLAUDE_CODE_USE_FOUNDRY',
57  'CLAUDE_CODE_USE_ANTHROPIC_AWS',
58  'CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD',
59  'CLAUDE_CODE_USE_MANTLE',
60  'CLAUDE_CODE_USE_GATEWAY',
61  'CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR',
62  'CLAUDE_CODE_GATEWAY_TOKEN_FILE_DESCRIPTOR',
63  'CLAUDE_BG_AUTH_SNAPSHOT_PATH',
64  'CLAUDE_CODE_HOST_CREDS_FILE',
65  'CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST',
66  'CLAUDE_CODE_HOST_AUTH_ENV_VAR',
67  'AWS_BEARER_TOKEN_BEDROCK',
68  'ANTHROPIC_FOUNDRY_API_KEY',
69]
70
71/** Keep unrelated custom headers, replacing only competing authentication. */
72export function withoutAuthHeaders(headers: string | undefined): string | undefined {
73  const kept = headers?.split(/\r?\n/).filter(line => !/^\s*(?:authorization|x-api-key)\s*:/i.test(line)).join('\n')
74  return kept || undefined
75}
76
77/** A session-local native SDK override. Credential bytes stay in process memory. */
78export function oauthHeaders(headers: string | undefined, token: string): string {
79  if (!token || /[\r\n\0]/.test(token)) throw new Error('The OAuth access token cannot be used as an HTTP header.')
80  const lines = (withoutAuthHeaders(headers) ?? '').split('\n').filter(Boolean)
81  const betas: string[] = []
82  const kept = lines.filter(line => {
83    const beta = /^\s*anthropic-beta\s*:(.*)$/i.exec(line)
84    if (!beta) return true
85    betas.push(...beta[1]!.split(',').map(value => value.trim()).filter(Boolean))
86    return false
87  })
88  kept.push(`anthropic-beta: ${[...new Set([...betas, 'oauth-2025-04-20'])].join(',')}`, `Authorization: Bearer ${token}`)
89  return kept.join('\n')
90}
91
92/** Reads only the generated bearer line, never arbitrary prose or another scheme. */
93export function headerToken(headers: string | undefined): string | undefined {
94  const values = headers?.split(/\r?\n/).flatMap(line => /^\s*authorization\s*:\s*Bearer ([^\r\n\0]+)\s*$/i.exec(line)?.[1]?.trim() ?? []) ?? []
95  return values.length === 1 ? values[0] : undefined
96}
97
98/**
99 * The environment for an OAuth account. `secret` is its access token.
100 * The machine login restores the
101 * process's own values; any other kind starts from them with every
102 * credential and provider switch cleared, then sets its own.
103 */
104export function planEnv(account: AccountConfig, secret: string | undefined, originals: Originals): EnvPlan {
105  const plan = Object.fromEntries(MANAGED.map(name => [name, originals[name] ?? undefined])) as EnvPlan
106  if (account.kind === 'login') return plan
107  for (const name of AUTH) plan[name] = undefined
108  switch (account.kind) {
109    case 'claudeai':
110      if (!account.loginDir) throw new Error('The browser account has no native login directory.')
111      if (!secret) throw new Error('The browser account has no OAuth access token.')
112      plan.ANTHROPIC_CUSTOM_HEADERS = oauthHeaders(originals.ANTHROPIC_CUSTOM_HEADERS ?? undefined, secret)
113      break
114    case 'claudeai-token':
115      if (!secret) throw new Error('The setup-token account has no OAuth access token.')
116      plan.ANTHROPIC_CUSTOM_HEADERS = oauthHeaders(originals.ANTHROPIC_CUSTOM_HEADERS ?? undefined, secret)
117      break
118    default:
119      throw new Error('Rice Accounts supports Anthropic OAuth accounts only.')
120  }
121
122  return plan
123}
124
125/**
126 * What a switch is checked against before anything changes: the settings
127 * merged over every source, the variables the blockers name, and whether
128 * Claude Code itself signs in with a Claude subscription. A read that failed
129 * leaves `settings` or `isOAuthLogin` undefined.
130 */
131export type SwitchContext = {
132  settings: Readonly<Record<string, unknown>> | undefined
133  variables: Readonly<Partial<Record<EnvName, string>>>
134  isOAuthLogin: boolean | undefined
135}
136
137/** A credential source, how it is detected, and what to change; `message` names the cause and the fix. */
138export type SwitchBlocker =
139  | { setting: string; message: string }
140  | { variables: readonly EnvName[]; message: string }
141  | { login: 'not-oauth'; message: string }
142
143/**
144 * The sources that beat or break the selected account's bearer on the wire,
145 * as measured against Claude Code 2.1.302: Claude Code's own credential wins
146 * over the request header, or its requests drop the OAuth beta header the
147 * bearer needs. An API key, an auth token or a provider selector does
148 * neither: the switch clears them. The first that applies is reported.
149 */
150export const SWITCH_BLOCKERS: readonly SwitchBlocker[] = [
151  { setting: 'apiKeyHelper', message: "Claude Code sends the key from the apiKeyHelper setting in place of the selected account's token. Remove apiKeyHelper from your settings, then restart Claude Code." },
152  { variables: ['CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR'], message: "Claude Code sends the API key it read through CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR along with the selected account's token. Start Claude Code without CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR." },
153  { variables: ['ANTHROPIC_FEDERATION_RULE_ID', 'ANTHROPIC_ORGANIZATION_ID'], message: "Claude Code signs in through workload identity federation (ANTHROPIC_FEDERATION_RULE_ID and ANTHROPIC_ORGANIZATION_ID) and sends that token in place of the selected account's. Start Claude Code without them." },
154  { login: 'not-oauth', message: "Claude Code was not started signed in with a Claude subscription, so its requests drop the OAuth beta header the selected account's token needs. Start Claude Code signed in with your Claude subscription (claude auth login, or CLAUDE_CODE_OAUTH_TOKEN)." },
155]
156
157/** The variables the blockers name, for the switch to read by their literal names. */
158export const BLOCKING_VARIABLES: readonly EnvName[] = [...new Set(SWITCH_BLOCKERS.flatMap(blocker => 'variables' in blocker ? blocker.variables : []))]
159
160/**
161 * Why a switch to an account other than the login cannot work in this session, or undefined. Settings that
162 * could not be read refuse the switch (it could not be told whether one replaces the token); a machine login
163 * that could not be read refuses nothing, since the stores it would be read from are the ones a switch needs anyway.
164 */
165export function switchBlocker(context: SwitchContext): string | undefined {
166  if (context.settings === undefined) return 'This session cannot switch accounts: your Claude Code settings could not be read, so it cannot be told whether one of them (apiKeyHelper) would replace the selected account\'s token. Try again.'
167  const found = SWITCH_BLOCKERS.find(blocker => {
168    if ('setting' in blocker) {
169      // Set as Claude Code reads it: any non-empty text.
170      const value = context.settings?.[blocker.setting]
171      return typeof value === 'string' && value !== ''
172    }
173    if ('variables' in blocker) return blocker.variables.every(name => Boolean(context.variables[name]))
174    return context.isOAuthLogin === false
175  })
176  return found && `This session cannot switch accounts: ${found.message}`
177}
178
179/** The names a plan changes from what the process holds now, for the switch to set. */
180export function changedNames(plan: EnvPlan, current: Record<Managed, string | undefined>): Managed[] {
181  return MANAGED.filter(name => plan[name] !== current[name])
182}
183
hooks/identity.ts 100 lines
1import type { Machine } from './accounts'
2import type { AccountConfig } from './config'
3import { readLogin } from './credentials'
4import type { LoginLocation } from './credentials'
5import type { Io } from './io'
6import type { Credential } from './keychain'
7import type { LoginSource } from './login'
8
9export type AccountIdentity = { email: string; tier: string }
10
11const UNKNOWN: AccountIdentity = { email: 'Unknown', tier: 'Unknown' }
12const UNSIGNED: AccountIdentity = { email: 'Not signed in', tier: 'Unknown' }
13const PLANS: Record<string, string> = {
14  free: 'Free', pro: 'Pro', max: 'Max', team: 'Team', enterprise: 'Enterprise',
15}
16
17function plan(credential: Credential): string {
18  const { subscriptionType, rateLimitTier } = credential.claudeAiOauth
19  if (typeof subscriptionType !== 'string') return 'Unknown'
20  const subscription = subscriptionType.trim().toLowerCase()
21  if (subscription === 'max') {
22    if (rateLimitTier === 'default_claude_max_5x') return 'Max (5x)'
23    if (rateLimitTier === 'default_claude_max_20x') return 'Max (20x)'
24  }
25
26  return Object.hasOwn(PLANS, subscription) ? PLANS[subscription] ?? 'Unknown' : 'Unknown'
27}
28
29/** Native account metadata only. Never infer an identity from a saved label. */
30async function emailAt(io: Io, path: string): Promise<string | undefined> {
31  try {
32    const raw: unknown = JSON.parse(await io.read(path))
33    const email = (raw as { oauthAccount?: { emailAddress?: unknown } } | null)?.oauthAccount?.emailAddress
34    if (typeof email !== 'string') return undefined
35    const value = email.trim()
36
37    return value.length > 0 && value.length <= 320 && !/[\u0000-\u001f\u007f]/.test(value) ? value : undefined
38  } catch {
39    return undefined
40  }
41}
42
43function metadataPath(folder: string): string {
44  return `${folder.replace(/\/+$/, '')}/.claude.json`
45}
46
47/**
48 * Read cached email and plan for account rows without refreshing the login or
49 * making provider requests. Credential bytes are never returned or logged.
50 * The machine login's `source` says what the session launched with: a launch
51 * token or an API key is not the stored /login, so that login is not read.
52 */
53export async function accountIdentity(io: Io, account: AccountConfig, machine: Machine, source: LoginSource = { kind: 'stored' }): Promise<AccountIdentity> {
54  if (account.kind === 'login' && source.kind === 'launch-token') return { email: 'Set by CLAUDE_CODE_OAUTH_TOKEN', tier: 'Unknown' }
55  if (account.kind === 'login' && source.kind === 'not-oauth') return { email: 'Not available', tier: 'API or provider' }
56  if (account.kind !== 'login' && account.kind !== 'claudeai') {
57    const provider = {
58      'claudeai-token': 'Unknown', 'api-key': 'API', gateway: 'Gateway',
59      bedrock: 'AWS Bedrock', vertex: 'Google Vertex', foundry: 'Azure Foundry',
60    }
61
62    return { email: 'Not available', tier: provider[account.kind] }
63  }
64  if (account.kind === 'claudeai' && !account.loginDir) return { ...UNSIGNED }
65  const location: LoginLocation = {
66    storage: account.kind === 'claudeai'
67      ? { configDir: account.loginDir, secureStorageDir: account.loginDir }
68      : machine.storage,
69    defaultConfigDir: machine.claudeDir,
70    user: machine.user,
71  }
72  let credential: Credential | null
73  try {
74    credential = await readLogin(io, location)
75  } catch {
76    return { ...UNKNOWN }
77  }
78  if (credential === null) return { ...UNSIGNED }
79
80  const paths: string[] = []
81  if (account.kind === 'claudeai') {
82    paths.push(metadataPath(account.loginDir!))
83  } else if (machine.storage.configDir) {
84    paths.push(metadataPath(machine.storage.configDir))
85  } else {
86    // Native Windows keeps ~/.claude.json under USERPROFILE, which HOME rarely names.
87    const windows = await io.env('OS').catch(() => undefined) === 'Windows_NT'
88    const home = (windows ? await io.env('USERPROFILE').catch(() => undefined) : undefined) ?? await io.env('HOME').catch(() => undefined)
89    if (home) paths.push(metadataPath(home))
90    const fallback = metadataPath(machine.claudeDir)
91    if (!paths.includes(fallback)) paths.push(fallback)
92  }
93  for (const path of paths) {
94    const email = await emailAt(io, path)
95    if (email) return { email, tier: plan(credential) }
96  }
97
98  return { email: 'Unknown', tier: plan(credential) }
99}
100
hooks/io.ts 66 lines
1// Adapted from simplecore-inc/claude-mods mods/accounts/hooks/io.ts at 722763c
2// (MIT, Copyright (c) 2026 SimpleCORE Inc., see LICENSES/simplecore-claude-mods.MIT.txt).
3// Modified: trimmed to what rice-session-accounts uses; no store or listing; trusted
4// process options and process-failure classification added.
5import type { FsStat, HttpInit, HttpResponse, ProcessRunInit, ProcessRunResult } from 'claude-code'
6
7/** The environment variables the modules read, each read by its literal name in register.ts. */
8export type EnvName = 'HOME' | 'USER' | 'OS' | 'USERPROFILE' | 'USERNAME' | 'SystemRoot' | 'WINDIR' | 'CLAUDE_CODE_FORCE_WINDOWS_CREDMAN' | 'CLAUDE_CONFIG_DIR' | 'CLAUDE_SECURESTORAGE_CONFIG_DIR'
9  | 'CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR' | 'ANTHROPIC_FEDERATION_RULE_ID' | 'ANTHROPIC_ORGANIZATION_ID'
10
11/**
12 * What the modules reach the machine through; register.ts builds it over `$`.
13 * `run` takes the host's `{ cwd, env, stdin, timeoutMs }`: `cwd` replaces the
14 * session's working directory and `env` is set over the host environment.
15 */
16export type Io = {
17  run: (argv: readonly string[], init?: ProcessRunInit) => Promise<ProcessRunResult>
18  read: (path: string) => Promise<string>
19  write: (path: string, text: string) => Promise<void>
20  exists: (path: string) => Promise<boolean>
21  stat: (path: string) => Promise<FsStat>
22  env: (name: EnvName) => Promise<string | undefined>
23  now: () => Promise<number>
24  sleep: (ms: number) => Promise<void>
25  fetch: (url: string, init?: HttpInit) => Promise<HttpResponse>
26  /** A line for the debug log; never a secret. */
27  log: (text: string) => void
28}
29
30export function message(error: unknown): string {
31  return error instanceof Error ? error.message : String(error)
32}
33
34/**
35 * Variables set on every credential-related child. Windows searches the
36 * current directory before PATH unless NoDefaultCurrentDirectoryInExePath is
37 * set, and NODE_OPTIONS could preload code into the Node credential program.
38 */
39export const TRUSTED_ENV: Readonly<Record<string, string>> = { NoDefaultCurrentDirectoryInExePath: '1', NODE_OPTIONS: '' }
40
41/**
42 * Options for a credential-related child: a trusted working directory (never
43 * the session's project folder, which may be a cloned repository holding a
44 * planted program) and the trusted environment above.
45 */
46export function trustedRun(cwd: string, init: { stdin?: string; timeoutMs?: number } = {}): ProcessRunInit {
47  return { ...init, cwd, env: { ...TRUSTED_ENV } }
48}
49
50/** Why `io.run` rejected: it ran out of time, its program was not found, could not be executed, or something else. */
51export type RunFailure = 'timeout' | 'missing' | 'denied' | 'failed'
52
53/**
54 * Classifies an `io.run` rejection. The host rejects with "still running
55 * after N ms" when the timeout kills the child, and with the spawn error
56 * (ENOENT, EACCES) when the program cannot start.
57 */
58export function runFailure(error: unknown): RunFailure {
59  const code = typeof error === 'object' && error !== null && 'code' in error ? String((error as { code?: unknown }).code) : ''
60  const text = `${code} ${message(error)}`
61  if (/still running after|timed? ?out|ETIMEDOUT/i.test(text)) return 'timeout'
62  if (/ENOENT|not found|no such file|cannot find/i.test(text)) return 'missing'
63  if (/EACCES|EPERM|ENOEXEC|permission denied|not executable/i.test(text)) return 'denied'
64  return 'failed'
65}
66
hooks/lock.ts 183 lines
1// Adapted from simplecore-inc/claude-mods mods/accounts/hooks/lock.ts at 722763c
2// (MIT, Copyright (c) 2026 SimpleCORE Inc., see LICENSES/simplecore-claude-mods.MIT.txt).
3// Modified: the Windows PowerShell paths removed; native Windows uses a static Node program;
4// a heartbeat keeps a long critical section from being taken over as stale; a failed stat
5// is asked again, and a lock whose time stays unknown is owned only while it is young.
6import { hostPlatform } from './credentials'
7import type { Io } from './io'
8import { runFailure, trustedRun } from './io'
9
10/**
11 * Locks held across processes, laid out as proper-lockfile lays them: a
12 * directory only one process can make, taken as abandoned once its
13 * modification time is older than the lock's stale time. `heartbeat` renews
14 * that time, and fails with `LockLostError` when another process already took
15 * the lock over.
16 */
17export type Lock = { release: () => Promise<void>; heartbeat: () => Promise<void> }
18
19export class LockBusyError extends Error {}
20
21/** The lock was taken over as stale by another process. */
22export class LockLostError extends Error {}
23
24/** `cwd`: a trusted working folder for the lock programs on native Windows (the Claude config folder). */
25export type LockOptions = { staleMs: number; tries: number; cwd?: string }
26
27export function retryDelay(attempt: number): number {
28  return Math.min(1000, 100 * 2 ** attempt)
29}
30
31const MAKE = ['/bin/sh', '-c', 'mkdir -p "$(dirname "$0")" && mkdir "$0"']
32const REMOVE = ['/bin/sh', '-c', '[ ! -d "$0" ] || rmdir "$0"']
33const TOUCH = ['/bin/sh', '-c', '[ -d "$0" ] && touch -c "$0"']
34
35/**
36 * Native Windows has no /bin/sh. Node 22+ is already its credential-file
37 * prerequisite, so the same mkdir, rmdir and touch semantics run as a static
38 * program, written in ES5 like the credential program.
39 */
40const NODE_LOCK = String.raw`
41var fs = require('fs');
42var paths = require('path');
43var operation = process.argv[1];
44var path = process.argv[2];
45function codeOf(error) { return error && error.code ? String(error.code) : 'lock operation failed'; }
46function invalid(text) { var error = new Error(text); error.code = 'EINVAL'; return error; }
47try {
48  if (!path || !paths.isAbsolute(path)) throw invalid('invalid lock path');
49  if (operation === 'make') {
50    fs.mkdirSync(paths.dirname(path), { recursive: true });
51    fs.mkdirSync(path);
52  } else if (operation === 'remove') {
53    try { fs.rmdirSync(path); } catch (error) { if (codeOf(error) !== 'ENOENT') throw error; }
54  } else if (operation === 'touch') {
55    var now = new Date();
56    fs.utimesSync(path, now, now);
57  } else throw invalid('invalid lock operation');
58} catch (error) {
59  process.stderr.write(codeOf(error));
60  process.exitCode = 1;
61}
62`
63
64type Commands = { make: string[]; remove: string[]; touch: string[]; cwd: string }
65
66async function lockCommands(io: Io, options: LockOptions): Promise<Commands> {
67  if (await hostPlatform(io) !== 'win32') return { make: MAKE, remove: REMOVE, touch: TOUCH, cwd: '/' }
68  const cwd = options.cwd ?? await io.env('USERPROFILE') ?? 'C:\\'
69
70  return { make: ['node', '-e', NODE_LOCK, 'make'], remove: ['node', '-e', NODE_LOCK, 'remove'], touch: ['node', '-e', NODE_LOCK, 'touch'], cwd }
71}
72
73/** How many times a lock's modification time is asked for before it counts as unknown. */
74export const STAT_TRIES = 3
75
76/**
77 * The lock's modification time, asked up to `STAT_TRIES` times: one failed
78 * stat must not make a held lock look taken over, nor leave its holder unable
79 * to release it. The attempts follow one another without a `$.clock` pause,
80 * which a test clock would hold until it is moved. Undefined when it stays
81 * unknown.
82 */
83async function mtimeOf(io: Io, path: string): Promise<number | undefined> {
84  for (let attempt = 0; attempt < STAT_TRIES; attempt += 1) {
85    const stat = await io.stat(path).catch(() => null)
86    if (stat !== null) return stat.mtimeMs
87  }
88
89  return undefined
90}
91
92/**
93 * The lock this session made at `path`. With its modification time known, the
94 * lock is this session's while that time is the one it set: another session
95 * that took it over as stale made it again with another time. When the time
96 * cannot be read (now, or when the lock was made), the lock is this session's
97 * only while it is far too young for anyone to take it over (half the stale
98 * time since this session last made or renewed it, measured from before it
99 * did), so a release still removes it and nobody is locked out for the whole
100 * stale time.
101 */
102function held(io: Io, path: string, options: LockOptions, commands: Commands, init: ReturnType<typeof trustedRun>, madeAt: number | undefined, since: number): Lock {
103  let mtimeMs = madeAt
104  let renewedAt = since
105  const lost = () => new LockLostError(`the lock ${path} was taken over by another session`)
106  // Both times known: the lock is this session's while it is the one set. Either unknown (a failed stat is not a takeover): the youth rule.
107  const isOwn = async (current: number | undefined): Promise<boolean> => mtimeMs !== undefined && current !== undefined
108    ? current === mtimeMs
109    : (await io.now()) - renewedAt < options.staleMs / 2
110
111  return {
112    release: async () => {
113      // Taken over as stale and made again by another process: that lock is not this one's to remove.
114      if (!(await isOwn(await mtimeOf(io, path)))) return
115      await io.run([...commands.remove, path], init)
116    },
117    heartbeat: async () => {
118      if (!(await isOwn(await mtimeOf(io, path)))) throw lost()
119      const touching = await io.now()
120      const touched = await io.run([...commands.touch, path], init)
121      if (touched.exitCode !== 0) throw lost()
122      mtimeMs = await mtimeOf(io, path)
123      renewedAt = touching
124    },
125  }
126}
127
128async function startProblem(io: Io, commands: Commands, path: string, error: unknown): Promise<string> {
129  const windows = commands.make[0] === 'node'
130  const program = windows ? 'Node.js 22 or later (node on PATH)' : '/bin/sh'
131  const failure = runFailure(error)
132  if (failure === 'timeout') return `cannot take the renewal lock ${path}: ${program} did not finish within 10 seconds`
133  // Windows starts the lock program in the Claude config folder: a missing folder fails the start with ENOENT too.
134  if (failure === 'missing' && windows && (await io.stat(commands.cwd).catch(() => null))?.kind !== 'dir') {
135    return `cannot take the renewal lock ${path}: its working folder ${commands.cwd} (the Claude configuration folder) does not exist. Start Claude Code once so it creates that folder, then retry.`
136  }
137
138  return `cannot take the renewal lock ${path}: ${program} could not be started${failure === 'missing' ? ' (not found)' : ''}`
139}
140
141/** Takes the lock at `path`, taking over one abandoned past its stale time; `LockBusyError` when it stays held. */
142export async function acquire(io: Io, path: string, options: LockOptions): Promise<Lock> {
143  const commands = await lockCommands(io, options)
144  const init = trustedRun(commands.cwd, { timeoutMs: 10_000 })
145  // Why the last attempt could not make the lock when nobody held it.
146  let unmade: string | undefined
147  for (let attempt = 0; attempt < options.tries; attempt += 1) {
148    const before = await io.now()
149    let made: Awaited<ReturnType<Io['run']>>
150    try {
151      made = await io.run([...commands.make, path], init)
152    } catch (error) {
153      throw new Error(await startProblem(io, commands, path, error))
154    }
155    if (made.exitCode === 0) return held(io, path, options, commands, init, await mtimeOf(io, path), before)
156    const holder = await io.stat(path).catch(() => null)
157    if (holder === null) {
158      // The holder released it between the mkdir and the stat (or the mkdir failed for another reason): try again.
159      unmade = made.stderr.trim() || `exit ${made.exitCode}`
160      continue
161    }
162    unmade = undefined
163    if ((await io.now()) - holder.mtimeMs > options.staleMs) {
164      if ((await io.stat(path).catch(() => null))?.mtimeMs === holder.mtimeMs) await io.run([...commands.remove, path], init)
165      continue
166    }
167    if (attempt + 1 < options.tries) await io.sleep(retryDelay(attempt))
168  }
169  if (unmade !== undefined) throw new Error(`cannot make the lock ${path}: ${unmade}`)
170
171  throw new LockBusyError(`another session is renewing this login (the lock ${path} is held); retry in a moment`)
172}
173
174/** Runs `work` holding the lock at `path`, and gives the lock up after, whatever `work` did. */
175export async function withLock<T>(io: Io, path: string, options: LockOptions, work: (lock: Lock) => Promise<T>): Promise<T> {
176  const lock = await acquire(io, path, options)
177  try {
178    return await work(lock)
179  } finally {
180    await lock.release().catch((error: unknown) => io.log(`cannot release ${path}: ${error instanceof Error ? error.message : String(error)}`))
181  }
182}
183
hooks/login.ts 27 lines
1import type { Originals } from './env'
2
3/**
4 * How this session's machine login authenticates, decided from the launch
5 * environment in native precedence: a provider selector, an API key or an
6 * auth token comes before CLAUDE_CODE_OAUTH_TOKEN, which comes before the
7 * stored /login. Only the last two carry subscription usage.
8 */
9export type LoginSource =
10  | { kind: 'not-oauth' }
11  | { kind: 'launch-token'; token: string }
12  | { kind: 'stored' }
13
14const NOT_OAUTH: readonly (keyof Originals)[] = [
15  'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY',
16  'CLAUDE_CODE_USE_ANTHROPIC_AWS', 'CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD', 'CLAUDE_CODE_USE_MANTLE', 'CLAUDE_CODE_USE_GATEWAY',
17]
18
19export const NOT_OAUTH_LOGIN = "This session's machine login uses an API key or a cloud provider, which have no Claude subscription usage. Check limits on that provider's console."
20
21export function loginSourceOf(originals: Originals): LoginSource {
22  if (NOT_OAUTH.some(name => Boolean(originals[name]))) return { kind: 'not-oauth' }
23  const token = originals.CLAUDE_CODE_OAUTH_TOKEN
24  if (token) return { kind: 'launch-token', token }
25  return { kind: 'stored' }
26}
27
hooks/oauth.ts 283 lines
1// Adapted from simplecore-inc/claude-mods mods/accounts/hooks/anthropic.ts at 722763c
2// (MIT, Copyright (c) 2026 SimpleCORE Inc., see LICENSES/simplecore-claude-mods.MIT.txt).
3// Modified: kept the endpoint constants, refresh, usage and profile parsing; pane-specific
4// readings, spend and healing removed; LimitView declared here; refresh responses and
5// token-endpoint failures validated and classified without echoing bodies.
6import type { HttpInit, HttpResponse, SessionRateLimit } from 'claude-code'
7
8import type { Credential } from './keychain'
9
10export const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
11/** Claude Code 2.1.302's TOKEN_URL and CLIENT_ID constants, verified read-only in its binary. */
12export const TOKEN_URL = 'https://platform.claude.com/v1/oauth/token'
13export const PROFILE_URL = 'https://api.anthropic.com/api/oauth/profile'
14const CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e'
15const OAUTH_BETA = 'oauth-2025-04-20'
16/** Refresh this long before the access token expires, by the local clock; it also absorbs a few minutes of clock skew. */
17export const EXPIRY_MARGIN_MS = 5 * 60 * 1000
18/** The largest token-endpoint body parsed; a larger one is refused without being read or quoted. */
19export const MAX_TOKEN_BODY = 64 * 1024
20/** A longer `expires_in` is treated as this, so a login is still renewed in time if the value is wrong. */
21export const MAX_TOKEN_LIFETIME_S = 7 * 24 * 60 * 60
22/** The lifetime assumed when `expires_in` is missing or not a positive number: short, so the login is renewed again soon. */
23export const UNKNOWN_TOKEN_LIFETIME_S = 10 * 60
24const MAX_TOKEN_LENGTH = 16 * 1024
25/** OAuth and API error codes that may be shown; any other text of an error body is never echoed. */
26const KNOWN_ERRORS = new Set([
27  'invalid_grant', 'invalid_request', 'invalid_client', 'invalid_scope', 'unauthorized_client', 'unsupported_grant_type',
28  'invalid_request_error', 'authentication_error', 'permission_error', 'rate_limit_error', 'api_error', 'overloaded_error',
29])
30
31export class AnthropicError extends Error {
32  readonly status?: number
33
34  constructor(message: string, status?: number) {
35    super(message)
36    this.status = status
37  }
38}
39
40/**
41 * A successful refresh whose body cannot be used. When it still rotated the
42 * refresh token, `salvage` is the login holding that new refresh token (its
43 * access token expired), which must be saved: the old refresh token is spent.
44 */
45export class RefreshResponseError extends AnthropicError {
46  readonly salvage?: Credential
47
48  constructor(message: string, salvage?: Credential) {
49    super(message)
50    this.salvage = salvage
51  }
52}
53
54/** One usage window: `5h`, `wk`, or a model's own weekly limit. */
55export type LimitView = { label: string; percent: number; resetsAt?: string }
56
57type RawLimit = {
58  kind?: string
59  percent?: number
60  resets_at?: string | null
61  scope?: { model?: { display_name?: string | null } | null } | null
62}
63
64type RawWindow = { utilization?: number | null; resets_at?: string | null } | null
65
66type RawUsage = { limits?: RawLimit[]; five_hour?: RawWindow; seven_day?: RawWindow }
67
68function labelOf(limit: RawLimit): string {
69  if (limit.kind === 'session') return '5h'
70  if (limit.kind === 'weekly_all') return 'wk'
71
72  return limit.scope?.model?.display_name ?? limit.kind ?? '?'
73}
74
75/** The usage endpoint's body as windows. */
76export function parseUsage(body: unknown): LimitView[] {
77  const raw = (body ?? {}) as RawUsage
78  if (Array.isArray(raw.limits) && raw.limits.length > 0) {
79    return raw.limits
80      .filter(limit => typeof limit.percent === 'number')
81      .map(limit => ({ label: labelOf(limit), percent: limit.percent as number, resetsAt: limit.resets_at ?? undefined }))
82  }
83  const windows: [string, RawWindow | undefined][] = [
84    ['5h', raw.five_hour],
85    ['wk', raw.seven_day],
86  ]
87
88  return windows.flatMap(([label, window]) =>
89    typeof window?.utilization === 'number' ? [{ label, percent: window.utilization, resetsAt: window.resets_at ?? undefined }] : [],
90  )
91}
92
93/** The window kinds the engine's `SessionRateLimit` declares. */
94const ENGINE_LIMIT_KINDS = new Set(['five_hour', 'seven_day', 'spend_limit'])
95const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})$/
96
97/**
98 * Usage windows as the engine's `SessionRateLimit` declares them (2.1.302):
99 * kind `five_hour`, `seven_day` or `spend_limit`; `percentUsed` 0 to 100 with
100 * at most one decimal, past 100 only on an exceeded spend limit; `resetsAt` an
101 * ISO 8601 timestamp. A model's own weekly window has no engine kind and is
102 * left out here; this module's own text still shows it.
103 */
104export function sessionRateLimits(limits: readonly { kind: string; percentUsed: number; resetsAt?: string }[]): SessionRateLimit[] {
105  return limits.flatMap(limit => {
106    if (!ENGINE_LIMIT_KINDS.has(limit.kind) || !Number.isFinite(limit.percentUsed)) return []
107    const percent = Math.max(0, limit.kind === 'spend_limit' ? limit.percentUsed : Math.min(100, limit.percentUsed))
108    return [{ kind: limit.kind, percentUsed: Math.round(percent * 10) / 10, ...(limit.resetsAt !== undefined && ISO_TIME.test(limit.resetsAt) ? { resetsAt: limit.resetsAt } : {}) }]
109  })
110}
111
112/**
113 * The User-Agent Claude Code 2.1.302 sends from its API client, which makes its
114 * GET /api/oauth/usage request: `claude-cli/<version> (external, cli)`, `cli`
115 * being its entry point in a terminal session. A version that is not one
116 * header token is sent as `unknown`.
117 */
118export function userAgent(version: string | undefined): string {
119  return `claude-cli/${version !== undefined && /^[\x21-\x7e]{1,128}$/.test(version) ? version : 'unknown'} (external, cli)`
120}
121
122/** `init` with that User-Agent, so usage, profile and token requests identify as Claude Code. */
123export function withUserAgent(init: HttpInit | undefined, version: string | undefined): HttpInit {
124  return { ...init, headers: { ...init?.headers, 'User-Agent': userAgent(version) } }
125}
126
127/** A usage or profile request: with a bearer token, or with the session's own credential handle. */
128export function oauthInit(auth: { token: string } | { handle: string }): HttpInit {
129  if ('handle' in auth) return { headers: { 'anthropic-beta': OAUTH_BETA }, auth: auth.handle }
130
131  return { headers: { 'anthropic-beta': OAUTH_BETA, Authorization: `Bearer ${auth.token}` } }
132}
133
134/** Whether a token expires within `marginMs` of the local clock: refreshed before it is used. A login without a usable expiry is renewed. */
135export function needsRefresh(credential: Credential, now: number, marginMs = EXPIRY_MARGIN_MS): boolean {
136  const expiresAt = credential.claudeAiOauth.expiresAt
137  return !Number.isFinite(expiresAt) || expiresAt - marginMs <= now
138}
139
140/**
141 * The refresh request Claude Code sends: grant type, refresh token, client id
142 * (the login's own `clientId` when it was signed in with another client, as
143 * Claude Code 2.1.302 sends it) and the login's scopes. A login without scopes
144 * omits `scope`, which keeps the scopes originally granted (RFC 6749 section
145 * 6); an empty `scope` would ask for none.
146 */
147export function refreshInit(credential: Credential): HttpInit {
148  const oauth = credential.claudeAiOauth
149  const scopes = Array.isArray(oauth.scopes) ? oauth.scopes.filter(scope => typeof scope === 'string' && scope !== '') : []
150  const clientId = typeof oauth.clientId === 'string' && /^[\x21-\x7e]{1,256}$/.test(oauth.clientId) ? oauth.clientId : CLIENT_ID
151
152  return {
153    method: 'POST',
154    headers: { 'Content-Type': 'application/json' },
155    body: JSON.stringify({
156      grant_type: 'refresh_token',
157      refresh_token: oauth.refreshToken,
158      client_id: clientId,
159      ...(scopes.length > 0 ? { scope: scopes.join(' ') } : {}),
160    }),
161  }
162}
163
164function isToken(value: unknown): value is string {
165  return typeof value === 'string' && value.length > 0 && value.length <= MAX_TOKEN_LENGTH && !/[\s\u0000-\u001f\u007f]/.test(value)
166}
167
168function lifetimeOf(value: unknown): number {
169  const seconds = typeof value === 'number' ? value : typeof value === 'string' && /^\d{1,10}$/.test(value) ? Number(value) : Number.NaN
170  if (!Number.isFinite(seconds) || seconds <= 0) return UNKNOWN_TOKEN_LIFETIME_S
171
172  return Math.min(seconds, MAX_TOKEN_LIFETIME_S)
173}
174
175/**
176 * When the refresh token of a response expires, as Claude Code 2.1.302 records
177 * it (`refreshTokenExpiresAt`, which its signed-in check reads): from a
178 * numeric `refresh_token_expires_in`, else not given, and the stored one stays.
179 */
180function refreshExpiryOf(fields: Record<string, unknown>, now: number): { refreshTokenExpiresAt?: number } {
181  const seconds = fields.refresh_token_expires_in
182  return typeof seconds === 'number' && Number.isFinite(seconds) ? { refreshTokenExpiresAt: now + seconds * 1000 } : {}
183}
184
185/**
186 * The credential after a refresh; the server rotates the refresh token, so it
187 * must be saved. An absent `refresh_token` means the server did not rotate it
188 * and the current one stays. A missing, negative or non-numeric `expires_in`
189 * counts as ten minutes, and one over seven days as seven days. Errors never
190 * quote the body: it carries grants.
191 */
192export function applyRefresh(credential: Credential, responseText: string, now: number): Credential {
193  if (responseText.length > MAX_TOKEN_BODY) throw new RefreshResponseError('the token refresh returned an oversized response')
194  let body: unknown
195  // A JSON syntax error quotes the text it read, and this response carries grants.
196  try { body = JSON.parse(responseText) } catch { throw new RefreshResponseError('the token refresh returned an unreadable response') }
197  if (body === null || typeof body !== 'object' || Array.isArray(body)) throw new RefreshResponseError('the token refresh returned an unreadable response')
198  const fields = body as Record<string, unknown>
199  const oauth = credential.claudeAiOauth
200  const refreshToken = fields.refresh_token
201  const rotated = isToken(refreshToken) ? refreshToken : undefined
202  const accessToken = fields.access_token
203  if (!isToken(accessToken)) {
204    const salvage = rotated !== undefined && rotated !== oauth.refreshToken
205      ? { ...credential, claudeAiOauth: { ...oauth, refreshToken: rotated, expiresAt: 0, ...refreshExpiryOf(fields, now) } }
206      : undefined
207    throw new RefreshResponseError('the token refresh returned no access token', salvage)
208  }
209
210  return {
211    ...credential,
212    claudeAiOauth: {
213      ...oauth,
214      accessToken,
215      refreshToken: rotated ?? oauth.refreshToken,
216      expiresAt: now + lifetimeOf(fields.expires_in) * 1000,
217      ...refreshExpiryOf(fields, now),
218    },
219  }
220}
221
222/** The error code of a token-endpoint error body, only when it is a known code; the body itself is never returned. */
223export function tokenErrorCode(text: string): string | undefined {
224  if (text.length > MAX_TOKEN_BODY) return undefined
225  try {
226    const body: unknown = JSON.parse(text)
227    const error = (body as { error?: unknown } | null)?.error
228    const code = typeof error === 'string' ? error : (error as { type?: unknown } | null | undefined)?.type
229    return typeof code === 'string' && KNOWN_ERRORS.has(code) ? code : undefined
230  } catch {
231    return undefined
232  }
233}
234
235function retryAfterSeconds(headers: Record<string, string> | undefined): number | undefined {
236  for (const [name, value] of Object.entries(headers ?? {})) {
237    if (name.toLowerCase() === 'retry-after' && /^\d{1,6}$/.test(value.trim())) return Number(value.trim())
238  }
239
240  return undefined
241}
242
243/**
244 * Why the token endpoint refused a renewal, for the account `name`. Only
245 * `invalid_grant` means the login itself is gone and must be signed in again;
246 * rate limits and server failures keep the saved login for a retry. The body
247 * is never echoed, only a known error code.
248 */
249export function refreshFailure(name: string, response: Pick<HttpResponse, 'status' | 'text'> & { headers?: Record<string, string> }): AnthropicError {
250  const { status } = response
251  const code = tokenErrorCode(response.text)
252  if (code === 'invalid_grant') {
253    return new AnthropicError(`the ${name} login was revoked or has expired (HTTP ${status}, invalid_grant); sign it in again: /rice-account setup ${name}`, status)
254  }
255  if (status === 429) {
256    const wait = retryAfterSeconds(response.headers)
257    return new AnthropicError(`the Anthropic sign-in service is rate limiting renewals (HTTP 429); the saved ${name} login was kept, retry ${wait === undefined ? 'in a few minutes' : `in ${wait} seconds`}`, status)
258  }
259  if (status >= 500) {
260    return new AnthropicError(`the Anthropic sign-in service failed (HTTP ${status}); the saved ${name} login was kept, retry later`, status)
261  }
262
263  return new AnthropicError(`the token endpoint refused to renew the ${name} login (HTTP ${status}${code ? `, ${code}` : ''}); the saved login was kept. Retry, and update Rice Accounts if this persists`, status)
264}
265
266/** A short, secret-free reason a token request could not be sent: its error code or kind, never its text. */
267export function networkProblem(error: unknown): string {
268  const text = error instanceof Error ? error.message : String(error)
269  if (/timed? ?out|ETIMEDOUT|still running after/i.test(text)) return 'the request timed out'
270  const code = /\b(E[A-Z]{3,}|UND_ERR_[A-Z_]+|CERT_[A-Z_]+)\b/.exec(text)?.[1]
271  return code ? `the network request failed (${code})` : 'the network request failed'
272}
273
274/** Whose a token is, as the profile endpoint answers. */
275export type TokenOwner = { email: string; organizationName?: string }
276
277export function parseProfile(text: string): TokenOwner {
278  const body = JSON.parse(text) as { account?: { email?: string }; organization?: { name?: string } }
279  if (typeof body.account?.email !== 'string') throw new AnthropicError('the profile endpoint named no account')
280
281  return { email: body.account.email, organizationName: body.organization?.name }
282}
283