diff --git a/CHANGELOG.md b/CHANGELOG.md index a87efc2..fc70d7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,30 @@ All notable changes to ccswitch are documented here. The format follows _Nothing yet._ +## [0.1.3] — 2026-07-16 + +### Fixed + +- **Same-login, multi-org switching is no longer cosmetic.** The default token + scope is now `PerAccountOrg` (one credential per `(account, org)`), not + `PerAccount`. A Claude Code OAuth token is bound **server-side to the org it + was minted under** — it is opaque and the server re-derives the org from it at + session start, overwriting `~/.claude.json`. The old `PerAccount` scope shared + one token across a login's orgs, so `sync_current` propagated one org's token + into the sibling profile; every "switch" then only relabelled `~/.claude.json` + while real sessions ran under the token's minting org. Each profile now keeps + its own org-scoped token, and `sync_current` re-snapshots **only the outgoing + profile**. (Existing profiles saved before this release share one token and + must be re-provisioned: `claude /login` into the right org, then + `ccswitch save --force`.) + +### Removed + +- **The daemon-stop on switch (v0.1.1/v0.1.2).** It addressed a misdiagnosis: + there is no persistent Claude Code daemon holding auth, and stopping it never + affected switching. v0.1.2's worker-kill also needlessly ended background + sessions. Removed entirely. + ## [0.1.2] — 2026-07-08 ### Changed diff --git a/Cargo.lock b/Cargo.lock index 9b88f29..e13b335 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -60,7 +60,7 @@ checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" [[package]] name = "ccswitch" -version = "0.1.2" +version = "0.1.3" dependencies = [ "anyhow", "clap", diff --git a/Cargo.toml b/Cargo.toml index 2eca7e7..dea3351 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ccswitch" -version = "0.1.2" +version = "0.1.3" edition = "2021" description = "Switch between multiple Claude Code accounts" license = "MIT" diff --git a/README.md b/README.md index aedb1ab..05578c3 100644 --- a/README.md +++ b/README.md @@ -327,20 +327,19 @@ plaintext tokens to a shared or public repo. - Quit any running `claude` session before switching — an open session can rewrite `~/.claude.json` on exit and clobber the swap. `ccswitch` warns when it detects one. -- Recent Claude Code releases keep a background **daemon** (and per-session - workers) that cache each account's auth in memory. On every switch `ccswitch` - stops the daemon and its workers (`claude daemon stop --any`) so the next - session re-reads the restored credentials. Workers are stopped too because a - kept worker holds the account it was started under, so a `claude --resume` - would reattach to it and ignore the switch. This is best-effort: on an older - Claude Code, or when no daemon is running, it is a no-op and the switch - proceeds regardless. **Note:** this ends any detached background Claude Code - sessions when you switch. - Access tokens expire, but the refresh token is restored too, so Claude Code re-refreshes automatically after a switch. - OAuth refresh tokens rotate on every use. To keep snapshots valid, `ccswitch` - re-captures the outgoing account into **every** profile that shares its token - on each switch — so an account you actively use won't go stale. + re-captures the **outgoing profile** (its own credential only) on each switch, + so an account you actively use won't go stale. +- **Same login, multiple orgs:** a Claude Code OAuth token is bound + server-side to the organization it was minted under — org selection is *not* + purely client-side. Each org profile therefore needs its own token: run + `claude /login` and pick the org, then `ccswitch save `. `ccswitch` + keeps each `(account, org)` profile's token separate and never copies one + org's token onto another. (If you use two orgs of the same login heavily, note + that Anthropic may rotate/invalidate the shared account's refresh token; if a + profile's token goes dead, re-`save` it after a fresh `claude /login`.) --- diff --git a/src/cli.rs b/src/cli.rs index 2964e89..9e83246 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -248,17 +248,6 @@ pub trait System { /// Whether a `claude` process is currently running. fn claude_is_running(&self) -> bool; - /// Stop the Claude Code daemon and its session workers so the next session - /// re-reads the restored credentials (`claude daemon stop --any`). A kept - /// worker would hold its original account in memory and a resumed session - /// would reattach to it, ignoring the switch — so workers are stopped too. - /// Best-effort. - /// - /// # Errors - /// - /// Returns an error if the daemon control command could not be run. - fn stop_daemon(&self) -> Result<()>; - /// Create (or replace) a symlink at `link` pointing to `target`. /// /// # Errors @@ -547,12 +536,6 @@ impl<'a> App<'a> { "warning: a running 'claude' may overwrite ~/.claude.json on exit; quit it first" )?; } - // A running daemon (and its session workers) cache the account's auth; - // stop them so the next session — including a `claude --resume` — picks - // up the restored credentials. Best-effort — never block the switch. - if let Err(e) = self.system.stop_daemon() { - writeln!(io.err, "warning: could not stop the claude daemon: {e}")?; - } let account = self.switcher().activate(name)?; writeln!(io.out, "switched to '{name}' ({})", email_of(&account))?; Ok(()) @@ -946,11 +929,9 @@ mod tests { pick_err: bool, symlink_err: bool, exec_err: bool, - daemon_stop_err: bool, links: RefCell>, execs: RefCell>, sessions_scope: RefCell>, - daemon_stops: RefCell, } impl System for FakeSystem { @@ -966,13 +947,6 @@ mod tests { fn claude_is_running(&self) -> bool { self.running } - fn stop_daemon(&self) -> Result<()> { - *self.daemon_stops.borrow_mut() += 1; - if self.daemon_stop_err { - return Err(Error::Invalid("daemon".to_string())); - } - Ok(()) - } fn make_symlink(&self, target: &Path, link: &Path) -> Result<()> { if self.symlink_err { return Err(Error::Invalid("symlink".to_string())); @@ -1441,7 +1415,13 @@ mod tests { store: &'a Store, dir: &Path, ) -> App<'a> { - App::new(system, creds, store, paths_for(dir), TokenScope::PerAccount) + App::new( + system, + creds, + store, + paths_for(dir), + TokenScope::PerAccountOrg, + ) } #[test] @@ -1691,34 +1671,6 @@ mod tests { .unwrap(); assert!(bufs.err().contains("warning: a running 'claude'")); assert!(bufs.out().contains("switched to 'dev' (a@example.com)")); - // The daemon supervisor is stopped as part of the switch. - assert_eq!(*system.daemon_stops.borrow(), 1); - fs::remove_dir_all(&dir).unwrap(); - } - - #[test] - fn use_warns_but_still_switches_when_daemon_stop_fails() { - let dir = temp_dir(); - write_config(&dir, &config_json("B", "OB", "b@x", "Org B")); - let store = Store::new(dir.join("accounts")); - seed_profile(&store, "dev", "A", "OA", "a@example.com"); - let creds = FakeCreds::with(Some("LIVE"), Some("attr")); - let system = FakeSystem { - daemon_stop_err: true, - ..Default::default() - }; - let app = app_env(&system, &creds, &store, &dir); - let mut bufs = Bufs::new(); - app.dispatch( - &mut bufs.io(), - Command::Use { - name: "dev".to_string(), - }, - ) - .unwrap(); - assert!(bufs.err().contains("could not stop the claude daemon")); - assert!(bufs.out().contains("switched to 'dev' (a@example.com)")); - assert_eq!(*system.daemon_stops.borrow(), 1); fs::remove_dir_all(&dir).unwrap(); } diff --git a/src/cli_shim.rs b/src/cli_shim.rs index 47cf35c..03ab95f 100644 --- a/src/cli_shim.rs +++ b/src/cli_shim.rs @@ -43,20 +43,6 @@ impl System for RealSystem { .unwrap_or(false) } - fn stop_daemon(&self) -> Result<()> { - // Stop the supervisor AND its session workers: a kept worker holds the - // account it was started under in memory, so `claude --resume` would - // reattach to it and ignore the switch. Killing workers makes every - // switch take effect. Best-effort: an old Claude Code without the - // daemon, a missing binary, or no daemon running never fail the switch. - let _ = Proc::new("claude") - .args(["daemon", "stop", "--any"]) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status(); - Ok(()) - } - fn make_symlink(&self, target: &Path, link: &Path) -> Result<()> { #[cfg(unix)] { @@ -185,12 +171,16 @@ pub fn run() -> anyhow::Result<()> { seed_default: claude, }; let system = RealSystem; + // Each (account, org) profile owns its own credential. Claude Code's OAuth + // token is bound server-side to the org it was minted under, so sharing one + // token across a login's orgs (PerAccount) makes a "switch" cosmetic — the + // server re-derives the token's real org and reverts ~/.claude.json. let app = App::new( &system, creds.as_ref(), &store, paths, - TokenScope::PerAccount, + TokenScope::PerAccountOrg, ); let stdout = std::io::stdout(); diff --git a/src/store.rs b/src/store.rs index d9da9fa..8859c8a 100644 --- a/src/store.rs +++ b/src/store.rs @@ -30,21 +30,27 @@ pub const CREDENTIALS_FILE: &str = "credentials.json"; /// File name of the identity snapshot within a profile directory. pub const ACCOUNT_FILE: &str = "account.json"; -/// How broadly a single, rotating OAuth credential is shared. +/// How a stored OAuth credential maps to profiles. /// -/// This is the knob that fixes the auth-loss bug: the Claude Code refresh -/// token rotates per *account*, shared across every organization a login can -/// see. Keying a stored credential by the full `(account, org)` pair — as the -/// original tool did — means two profiles for the same login but different -/// orgs each believe they own a separate token, when in truth there is one. -/// The first refresh under either org rotates the shared token and strands the -/// sibling with a dead one. +/// A Claude Code OAuth token is bound **server-side to the organization it was +/// minted under**: it is opaque, carries no client-readable org, and the server +/// re-derives the org from it at session start. So each `(account, org)` needs +/// its own token, minted by that org's own `claude /login` +/// ([`PerAccountOrg`](TokenScope::PerAccountOrg), the correct and default +/// scope). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TokenScope { - /// One rotating credential per login, shared across all of its orgs. - /// Profiles are grouped by `accountUuid` alone. + /// One credential per login, treated as shared across all of its orgs + /// (profiles grouped by `accountUuid` alone). + /// + /// **Do not use for org switching.** This encodes the mistaken belief that + /// org selection is purely client-side. In reality it fuses two same-login + /// org profiles onto one org-bound token, so "switching" only relabels + /// `~/.claude.json` while every real session runs under the token's minting + /// org. Retained only for the grouping unit tests. PerAccount, - /// One credential per `(accountUuid, organizationUuid)` pair. + /// One credential per `(accountUuid, organizationUuid)` pair. The token is + /// org-bound, so this is the only correct scope for multi-org logins. PerAccountOrg, } diff --git a/src/switch.rs b/src/switch.rs index 5031d94..e3b86c9 100644 --- a/src/switch.rs +++ b/src/switch.rs @@ -7,23 +7,21 @@ //! fake credential store and temp directories — no real Keychain or process //! spawning involved. //! -//! ## The auth-loss fix +//! ## Token scope: one credential per (account, org) //! -//! The Claude Code OAuth refresh token rotates per **account**, shared across -//! every organization a single login can operate in (org selection is -//! client-side state in `~/.claude.json`, not part of the credential). The -//! original tool re-snapshotted the live credential into only the one profile -//! whose `(accountUuid, organizationUuid)` matched the live config. So two -//! profiles for the same login but different orgs each held their own copy of -//! the one shared token; the first refresh under either org rotated the shared -//! token and left the sibling profile holding a dead one — a delayed forced -//! re-login. +//! A Claude Code OAuth token is bound **server-side to the organization it was +//! minted under** — it is opaque (`sk-ant-oat…`), carries no client-readable +//! org, and the server re-derives the org from the token at session start, +//! overwriting `~/.claude.json`'s `oauthAccount`. So org selection is *not* +//! merely client-side state: to operate in a different org you need a token +//! minted for that org (its own `claude /login`). //! -//! [`Switcher`] closes that gap: before switching away it re-snapshots the -//! live credential into **every** profile that shares the outgoing account's -//! token, as selected by the configured [`TokenScope`]. Under -//! [`TokenScope::PerAccount`] that is all same-login profiles regardless of -//! org, so a rotation under any org keeps every sibling current. +//! Therefore a profile is keyed by the full `(accountUuid, organizationUuid)` +//! pair ([`TokenScope::PerAccountOrg`]) and owns its own token. Before +//! switching away, [`Switcher`] re-snapshots the live credential back into +//! **only the outgoing profile** (whose key matches the live config), so a +//! token rotated while it was active is captured before we move on — without +//! ever overwriting a sibling profile that belongs to a different org. use crate::config; use crate::creds::CredentialStore; @@ -95,10 +93,9 @@ impl<'a> Switcher<'a> { /// Activate profile `name` as the current account. /// - /// First re-snapshots the outgoing account (its token may have rotated) - /// into every profile that shares its token, then restores `name`'s - /// credential into the platform store and splices its identity into - /// `~/.claude.json`. + /// First re-snapshots the outgoing profile (its token may have rotated), + /// then restores `name`'s credential into the platform store and splices + /// its identity into `~/.claude.json`. /// /// # Errors /// @@ -110,13 +107,13 @@ impl<'a> Switcher<'a> { // before we touch any live state. let target = self.store.load(name)?; - // Re-snapshot the outgoing account before overwriting it. This may - // update `name`'s own credential file too, when it shares the outgoing - // account's token — which is exactly what we want. + // Re-snapshot the outgoing profile before overwriting it, in case its + // token rotated while it was active. Under PerAccountOrg this touches + // only the profile whose (account, org) is the live one — never a + // sibling profile for a different org. self.sync_current()?; - // Restore the credential. Re-read it from the store so we pick up any - // rotation `sync_current` just propagated into this profile. + // Restore the target's credential from the store. let blob = self.store.load_credentials(name)?; self.creds.write(&blob, &target.keychain_account())?; @@ -126,10 +123,12 @@ impl<'a> Switcher<'a> { Ok(target.account()) } - /// Re-snapshot the live account's credential into every profile that - /// shares its token, and refresh the identity of the exact profile it maps - /// to. Silently does nothing when there is no config, no live identity, or - /// no active credential. + /// Re-snapshot the live account's credential (and identity) into the + /// profile that matches it under the configured [`TokenScope`]. Under + /// [`TokenScope::PerAccountOrg`] that is exactly the outgoing profile — + /// the one whose `(account, org)` equals the live config. Silently does + /// nothing when there is no config, no live identity, or no active + /// credential. /// /// # Errors ///