Rewrite ccswitch as a cross-shell Rust CLI
Replaces the fish-only plugin with one portable binary — completions for bash/zsh/fish/PowerShell via `ccswitch completions <shell>`. Same UX (save/add/use/list/current/rm/isolate/seed/search + bare-name switch-and-launch). - Fixes the auth-loss bug: the OAuth token is per-account (org lives only in ~/.claude.json), so switching between same-login/different-org profiles left the sibling holding a rotated, dead refresh token. A switch now propagates the refreshed credential to every profile sharing the account. - Adds `save --force` / `add --force` to overwrite a profile without rm first. - macOS Keychain via `security` (shim); file-based creds on Linux/Windows. - Ports-and-adapters; 100% line / 98.86% region coverage; clippy + fmt clean. - Homebrew formula (auto-installs completions) + cask + release workflow. - Old fish plugin preserved under legacy-fish/ (also at lei-wego/ccswitch-fish). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
25 files changed
+6425
-106
No files matched your search
@@ -0,0 +1,219 @@
|
||||
name: release
|
||||
|
||||
# Cut a release by pushing a tag like v0.1.0.
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Existing tag to (re)build, e.g. v0.1.0"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
BIN: ccswitch
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: build ${{ matrix.target }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: macos-14
|
||||
target: aarch64-apple-darwin
|
||||
# x86_64 mac is cross-compiled on the Apple-Silicon runner — the
|
||||
# scarce macos-13 Intel runner was leaving releases stuck in queue.
|
||||
- os: macos-14
|
||||
target: x86_64-apple-darwin
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-unknown-linux-gnu
|
||||
- os: ubuntu-24.04-arm
|
||||
target: aarch64-unknown-linux-gnu
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Resolve tag
|
||||
id: tag
|
||||
shell: bash
|
||||
env:
|
||||
INPUT_TAG: ${{ github.event.inputs.tag }}
|
||||
REF_NAME: ${{ github.ref_name }}
|
||||
run: |
|
||||
tag="${INPUT_TAG:-$REF_NAME}"
|
||||
if ! printf '%s' "$tag" | grep -qE '^v[0-9A-Za-z.+-]+$'; then
|
||||
echo "::error::invalid tag '$tag'"; exit 1
|
||||
fi
|
||||
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: ${{ matrix.target }}
|
||||
- name: Build
|
||||
run: cargo build --release --locked --target ${{ matrix.target }}
|
||||
- name: Package
|
||||
id: pkg
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tag="${{ steps.tag.outputs.tag }}"
|
||||
name="${BIN}-${tag}-${{ matrix.target }}"
|
||||
dist="dist/$name"
|
||||
mkdir -p "$dist"
|
||||
cp "target/${{ matrix.target }}/release/${BIN}" "$dist/"
|
||||
cp README.md LICENSE "$dist/" 2>/dev/null || true
|
||||
tar -C "$dist" -czf "dist/$name.tar.gz" . # binary at archive root
|
||||
( cd dist && shasum -a 256 "$name.tar.gz" > "$name.tar.gz.sha256" )
|
||||
echo "artifact=dist/$name.tar.gz" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ matrix.target }}
|
||||
path: dist/*.tar.gz*
|
||||
if-no-files-found: error
|
||||
|
||||
release:
|
||||
name: publish release + bump cask
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Resolve tag
|
||||
id: tag
|
||||
shell: bash
|
||||
env:
|
||||
INPUT_TAG: ${{ github.event.inputs.tag }}
|
||||
REF_NAME: ${{ github.ref_name }}
|
||||
run: |
|
||||
tag="${INPUT_TAG:-$REF_NAME}"
|
||||
if ! printf '%s' "$tag" | grep -qE '^v[0-9A-Za-z.+-]+$'; then
|
||||
echo "::error::invalid tag '$tag'"; exit 1
|
||||
fi
|
||||
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
- name: Collect artifacts
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p dist
|
||||
find artifacts -type f \( -name '*.tar.gz' -o -name '*.sha256' \) -exec cp {} dist/ \;
|
||||
ls -l dist
|
||||
- name: Create GitHub release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.tag.outputs.tag }}
|
||||
generate_release_notes: true
|
||||
files: dist/*
|
||||
- name: Bump Homebrew cask
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tag="${{ steps.tag.outputs.tag }}"
|
||||
version="${tag#v}"
|
||||
sha() { cut -d' ' -f1 "dist/${BIN}-${tag}-$1.tar.gz.sha256"; }
|
||||
arm_mac=$(sha aarch64-apple-darwin)
|
||||
x86_mac=$(sha x86_64-apple-darwin)
|
||||
arm_lin=$(sha aarch64-unknown-linux-gnu)
|
||||
x86_lin=$(sha x86_64-unknown-linux-gnu)
|
||||
mkdir -p Casks
|
||||
cat > Casks/ccswitch.rb <<RUBY
|
||||
# Auto-generated by .github/workflows/release.yml on each tag. Do not edit by hand.
|
||||
cask "ccswitch" do
|
||||
version "${version}"
|
||||
|
||||
on_macos do
|
||||
on_arm do
|
||||
sha256 "${arm_mac}"
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-apple-darwin.tar.gz"
|
||||
end
|
||||
on_intel do
|
||||
sha256 "${x86_mac}"
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-apple-darwin.tar.gz"
|
||||
end
|
||||
end
|
||||
on_linux do
|
||||
on_arm do
|
||||
sha256 "${arm_lin}"
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-unknown-linux-gnu.tar.gz"
|
||||
end
|
||||
on_intel do
|
||||
sha256 "${x86_lin}"
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-unknown-linux-gnu.tar.gz"
|
||||
end
|
||||
end
|
||||
|
||||
livecheck do
|
||||
url :url
|
||||
strategy :github_latest
|
||||
end
|
||||
|
||||
name "ccswitch"
|
||||
desc "Switch between multiple Claude Code accounts"
|
||||
homepage "https://github.com/mysqto/ccswitch"
|
||||
|
||||
binary "ccswitch"
|
||||
end
|
||||
RUBY
|
||||
mkdir -p Formula
|
||||
cat > Formula/ccswitch.rb <<RUBY
|
||||
# Auto-generated by .github/workflows/release.yml on each tag. Do not edit by hand.
|
||||
class Ccswitch < Formula
|
||||
desc "Cross-shell switcher for multiple Claude Code accounts"
|
||||
homepage "https://github.com/mysqto/ccswitch"
|
||||
version "${version}"
|
||||
|
||||
on_macos do
|
||||
on_arm do
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-apple-darwin.tar.gz"
|
||||
sha256 "${arm_mac}"
|
||||
end
|
||||
on_intel do
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-apple-darwin.tar.gz"
|
||||
sha256 "${x86_mac}"
|
||||
end
|
||||
end
|
||||
on_linux do
|
||||
on_arm do
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-unknown-linux-gnu.tar.gz"
|
||||
sha256 "${arm_lin}"
|
||||
end
|
||||
on_intel do
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-unknown-linux-gnu.tar.gz"
|
||||
sha256 "${x86_lin}"
|
||||
end
|
||||
end
|
||||
|
||||
livecheck do
|
||||
url :url
|
||||
strategy :github_latest
|
||||
end
|
||||
|
||||
def install
|
||||
bin.install "ccswitch"
|
||||
generate_completions_from_executable(bin/"ccswitch", "completions")
|
||||
end
|
||||
|
||||
test do
|
||||
assert_match "ccswitch", shell_output("#{bin}/ccswitch --help")
|
||||
end
|
||||
end
|
||||
RUBY
|
||||
- name: Commit cask + formula
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git config user.name "mysqto"
|
||||
git config user.email "my@mysq.to"
|
||||
if ! git diff --quiet -- Casks/ccswitch.rb Formula/ccswitch.rb; then
|
||||
git add Casks/ccswitch.rb Formula/ccswitch.rb
|
||||
git commit -m "brew: bump cask + formula to ${{ steps.tag.outputs.tag }}"
|
||||
git push origin HEAD:main
|
||||
else
|
||||
echo "cask + formula unchanged"
|
||||
fi
|
||||
@@ -1,3 +1,5 @@
|
||||
/target
|
||||
|
||||
# ide related
|
||||
.idea
|
||||
.vscode
|
||||
@@ -0,0 +1,143 @@
|
||||
# AGENTS.md — working in the `ccswitch` repo
|
||||
|
||||
A guide for coding agents. Read it before touching this tree. `ccswitch` is a
|
||||
cross-shell CLI that switches between multiple Claude Code accounts by
|
||||
snapshotting and restoring each account's OAuth credential together with its
|
||||
`~/.claude.json` identity. The whole design exists to keep one invariant true:
|
||||
|
||||
> **Every real OS/network side effect sits behind a trait whose only real
|
||||
> implementation lives in a `*_shim.rs` file. All decision logic lives outside
|
||||
> shims and is unit-tested. Coverage target: ≥98% line AND region.**
|
||||
|
||||
If you internalize one thing, make it that.
|
||||
|
||||
---
|
||||
|
||||
## Build / test / lint
|
||||
|
||||
```sh
|
||||
cargo build
|
||||
cargo test
|
||||
cargo fmt
|
||||
cargo clippy --all-targets --all-features -- -D warnings
|
||||
```
|
||||
|
||||
All four must be green before you finish. `cargo fmt` and a clippy run with
|
||||
`-D warnings` are non-negotiable.
|
||||
|
||||
Dependencies are lean and pinned in `Cargo.toml`. The sanctioned set: `clap`
|
||||
(derive) + `clap_complete` for the CLI and completions, `serde`/`serde_json`
|
||||
for the JSON config and profile files, and `thiserror`/`anyhow` for errors. Do
|
||||
not add crates casually — there is no database, HTTP, or async runtime here.
|
||||
|
||||
---
|
||||
|
||||
## Coverage discipline (the important part)
|
||||
|
||||
Run coverage with Homebrew LLVM so `llvm-cov`/`llvm-profdata` match the
|
||||
toolchain:
|
||||
|
||||
```sh
|
||||
LLVM_COV="$(brew --prefix llvm)/bin/llvm-cov" \
|
||||
LLVM_PROFDATA="$(brew --prefix llvm)/bin/llvm-profdata" \
|
||||
cargo llvm-cov \
|
||||
--all-features \
|
||||
--ignore-filename-regex '(_shim\.rs$|/main\.rs$)' \
|
||||
--summary-only
|
||||
```
|
||||
|
||||
**Ignore regex:** `(_shim\.rs$|/main\.rs$)`. That is the coverage boundary — the
|
||||
`*_shim.rs` adapters plus the trivial `main.rs` entry point (which only
|
||||
delegates to `ccswitch::cli_shim::run`). Everything else must be covered to
|
||||
≥98% line **and** region.
|
||||
|
||||
Rules that keep coverage reachable:
|
||||
|
||||
- A `*_shim.rs` file holds a trait's **real** adapter and *nothing a test needs
|
||||
to reach*: no branching, no parsing, no decisions. If you find yourself
|
||||
writing an `if`/`match` that matters inside a shim, it belongs in a non-shim
|
||||
module behind the trait.
|
||||
- Reading and writing plain files under a **temp root** is testable — do it
|
||||
directly, no shim. Only spawning processes (`claude`, `csx`, `fzf`),
|
||||
creating symlinks, terminal prompting, the macOS Keychain (`security`
|
||||
binary), and replacing the process via `exec` need shims.
|
||||
- Every non-shim module carries its own `#[cfg(test)] mod tests` exercising all
|
||||
branches with fakes and `std::env::temp_dir()`-based temp directories.
|
||||
|
||||
---
|
||||
|
||||
## Architecture / module map
|
||||
|
||||
Ports (traits) are consumed by pure logic; the matching `*_shim.rs` supplies the
|
||||
one real adapter. Data flow: **`cli::parse_from` → `Command` → `App::dispatch`
|
||||
→ (`Switcher` over `CredentialStore` + `config` + `Store`) and/or the `System`
|
||||
port → output.**
|
||||
|
||||
| Module | Role | Port(s) → shim |
|
||||
| ---------------- | ------------------------------------------------------------------------------------------------ | -------------- |
|
||||
| `model.rs` | Domain types: `Account` (uuid/org/email/org-name) and `Profile` (persisted `account.json`). | — |
|
||||
| `error.rs` | `Error` / `Result` (`ProfileNotFound`, `ReservedName`, `Invalid`, wrapped `Io`/`Json`). | — |
|
||||
| `config.rs` | Read/splice `~/.claude.json`: extract + reinsert the `{oauthAccount, userID}` identity, leaving every other key untouched. Plain-file JSON, temp-tested. | — |
|
||||
| `creds.rs` | `CredentialStore` trait + the `FileStore` (`<config>/.credentials.json`) fallback used off macOS. Temp-tested. | `CredentialStore` |
|
||||
| `creds_shim.rs` | Real macOS Keychain adapter (`security` binary) + `platform_store` `cfg` selection. | `CredentialStore` → **shim** |
|
||||
| `store.rs` | The on-disk profile store under `$CCSWITCH_HOME`; `TokenScope` (`PerAccount` / `PerAccountOrg`) — the knob behind the auth-loss fix. Temp-tested. | — |
|
||||
| `switch.rs` | `Switcher` — save/activate orchestration over `creds` + `config` + `store`; re-snapshots the outgoing credential into every token-sharing sibling. | consumes `CredentialStore` |
|
||||
| `cli.rs` | clap types, the `Command` model, `App::dispatch` + every handler, `System` port, path resolution, symlink planning, `search`/`isolate`/`seed` logic, completion generation. | `System` |
|
||||
| `cli_shim.rs` | `RealSystem` (spawn `claude`/`csx`/`fzf`, symlinks, prompts, `exec`) + `run` — the one impure entry point (real env, `$HOME`/`$CCSWITCH_*`, stdio, platform stores). | `System` → **shim** |
|
||||
| `main.rs` | Binary entry point; delegates to `cli_shim::run`. | — (ignored) |
|
||||
|
||||
The `System` trait in `cli.rs` is the seam that keeps the whole command surface
|
||||
testable: handlers call `claude_login`, `command_exists`, `claude_is_running`,
|
||||
`make_symlink`, `confirm`, `csx_current`, `csx_sessions`, `fzf_pick`, and
|
||||
`exec` through it, and the tests drive a `FakeSystem` recording every call.
|
||||
|
||||
---
|
||||
|
||||
## The auth-loss fix (why `TokenScope` exists)
|
||||
|
||||
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 — so two profiles for the same login
|
||||
but different orgs each held a copy of the one shared token, and the first
|
||||
refresh under either org stranded the sibling with a dead one.
|
||||
|
||||
`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 `TokenScope`. Production wires `TokenScope::PerAccount` (group by
|
||||
`accountUuid` alone), so a rotation under any org keeps every sibling current.
|
||||
Preserve this behavior; it is the reason the Rust tool exists.
|
||||
|
||||
---
|
||||
|
||||
## Adding a feature
|
||||
|
||||
1. **Decide where the logic goes.** Any real side effect (a new process to
|
||||
spawn, a new prompt, a new file to watch) becomes a method on the `System`
|
||||
trait in `cli.rs`, implemented once in `RealSystem` (`cli_shim.rs`). Pure
|
||||
decision logic — parsing, validation, path math, JSON shaping — goes in the
|
||||
plain module and is unit-tested with a fake. Never put a decision in a
|
||||
`_shim.rs`.
|
||||
2. **A new subcommand:** add a variant to `Sub` (clap) and `Command` in
|
||||
`cli.rs`, map it in `From<Option<Sub>>`, add a handler on `App`, route it in
|
||||
`dispatch`, and extend `help_text()` and `RESERVED` if it introduces a new
|
||||
word. Cover the parse, the dispatch, and each error branch.
|
||||
3. **A new credential backend:** implement `CredentialStore` in `creds.rs` (if
|
||||
temp-testable) or add the real adapter to `creds_shim.rs` and select it in
|
||||
`platform_store`.
|
||||
4. **Run the gate:** `cargo build && cargo test`, then `cargo fmt`,
|
||||
`cargo clippy --all-targets --all-features -- -D warnings`, then the
|
||||
coverage command above — line and region must stay ≥98%.
|
||||
|
||||
---
|
||||
|
||||
## Distribution
|
||||
|
||||
`.github/workflows/release.yml` cuts a release on a `v*` tag (or manual
|
||||
`workflow_dispatch` with a validated `tag` input): it cross-compiles the four
|
||||
targets (`aarch64`/`x86_64` × macOS/Linux — the Intel mac is built on the
|
||||
Apple-Silicon `macos-14` runner), publishes per-arch `.tar.gz` + `.sha256`
|
||||
assets to a GitHub release, and regenerates `Casks/ccswitch.rb` with the real
|
||||
checksums (a `github_latest` livecheck keeps it tracking the latest tag). The
|
||||
binary name is `ccswitch`.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to ccswitch are documented here. The format follows
|
||||
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
|
||||
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
_Nothing yet._
|
||||
|
||||
## [0.1.0] — 2026-07-08
|
||||
|
||||
First release of the Rust CLI, superseding the original fish plugin (now under
|
||||
`legacy-fish/`).
|
||||
|
||||
### Added
|
||||
|
||||
- **Account switching** — `save`, `use`, and the bare `ccswitch <name>
|
||||
[args...]` form snapshot both halves of a Claude Code identity (the OAuth
|
||||
credential and the `~/.claude.json` `oauthAccount` + `userID`) into a plain
|
||||
profile directory and restore them as a unit, launching `claude` on the bare
|
||||
form.
|
||||
- **`add`** — sign in to a new account (`claude auth login`) and save it in one
|
||||
step; `--force` on `add`/`save` overwrites an existing profile.
|
||||
- **`list`, `current`, `rm`** — enumerate profiles (`*` marks the active one),
|
||||
show the active account, and delete a profile; with aliases `ls`, `whoami`,
|
||||
and `remove`/`delete`.
|
||||
- **Token-rotation fix** — on every switch the outgoing credential is
|
||||
re-snapshotted into **every** profile that shares its per-account refresh
|
||||
token (`TokenScope::PerAccount`), so an actively used account never strands a
|
||||
sibling profile with a rotated-out token.
|
||||
- **Concurrent sessions** — `isolate` runs a session under a per-profile
|
||||
`CLAUDE_CONFIG_DIR` with `projects/`, `history.jsonl`, and `CLAUDE.md`
|
||||
symlinked to a shared directory, and `seed` imports that shared memory from
|
||||
`~/.claude` (or a given dir). Empty shared memory triggers a confirm.
|
||||
- **`search`** — bridges to [`csx`](https://github.com/mysqto/csx) + `fzf` to
|
||||
fuzzy-pick and resume a past session, defaulting the scope to the active tool
|
||||
and resuming with the right command per tool (`claude`, `codex`).
|
||||
- **Cross-shell completions** — `completions <shell>` for bash, zsh, fish,
|
||||
PowerShell, and elvish.
|
||||
- **Cross-platform credentials** — macOS Keychain via the `security` binary,
|
||||
with a `~/.claude/.credentials.json` file store fallback elsewhere.
|
||||
- **Docs & distribution** — README, `AGENTS.md`, a GitHub release workflow with
|
||||
a cross-compile matrix, and an auto-bumped Homebrew cask.
|
||||
|
||||
### Notes
|
||||
|
||||
- Test suite covers decision logic to ≥98% line and region; OS/network I/O
|
||||
lives in `*_shim.rs` files behind traits (see `AGENTS.md`).
|
||||
|
||||
[Unreleased]: https://github.com/mysqto/ccswitch/compare/v0.1.0...HEAD
|
||||
[0.1.0]: https://github.com/mysqto/ccswitch/releases/tag/v0.1.0
|
||||
Generated
+287
@@ -0,0 +1,287 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse",
|
||||
"anstyle-query",
|
||||
"anstyle-wincon",
|
||||
"colorchoice",
|
||||
"is_terminal_polyfill",
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-query"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||
dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-wincon"
|
||||
version = "3.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.103"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
|
||||
|
||||
[[package]]
|
||||
name = "ccswitch"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"clap_complete",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
"strsim",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_complete"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db8b397918185f0161ff3d6fcaa9e4bfc09b8367caf6e1d4a2848e5477ed027b"
|
||||
dependencies = [
|
||||
"clap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.150"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "ccswitch"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Switch between multiple Claude Code accounts"
|
||||
license = "MIT"
|
||||
|
||||
[[bin]]
|
||||
name = "ccswitch"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lib]
|
||||
name = "ccswitch"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.5", features = ["derive"] }
|
||||
clap_complete = "4.5"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
anyhow = "1.0"
|
||||
thiserror = "2.0"
|
||||
@@ -0,0 +1,36 @@
|
||||
# Auto-generated by .github/workflows/release.yml on each tag. Do not edit by hand.
|
||||
cask "ccswitch" do
|
||||
version "0.1.0"
|
||||
|
||||
on_macos do
|
||||
on_arm do
|
||||
sha256 :no_check
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-apple-darwin.tar.gz"
|
||||
end
|
||||
on_intel do
|
||||
sha256 :no_check
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-apple-darwin.tar.gz"
|
||||
end
|
||||
end
|
||||
on_linux do
|
||||
on_arm do
|
||||
sha256 :no_check
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-unknown-linux-gnu.tar.gz"
|
||||
end
|
||||
on_intel do
|
||||
sha256 :no_check
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-unknown-linux-gnu.tar.gz"
|
||||
end
|
||||
end
|
||||
|
||||
livecheck do
|
||||
url :url
|
||||
strategy :github_latest
|
||||
end
|
||||
|
||||
name "ccswitch"
|
||||
desc "Switch between multiple Claude Code accounts"
|
||||
homepage "https://github.com/mysqto/ccswitch"
|
||||
|
||||
binary "ccswitch"
|
||||
end
|
||||
@@ -0,0 +1,44 @@
|
||||
# Auto-generated by .github/workflows/release.yml on each tag. Do not edit by hand.
|
||||
# This committed copy is a template until the first release fills in real checksums.
|
||||
class Ccswitch < Formula
|
||||
desc "Cross-shell switcher for multiple Claude Code accounts"
|
||||
homepage "https://github.com/mysqto/ccswitch"
|
||||
version "0.0.0"
|
||||
|
||||
on_macos do
|
||||
on_arm do
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-apple-darwin.tar.gz"
|
||||
sha256 "0000000000000000000000000000000000000000000000000000000000000000"
|
||||
end
|
||||
on_intel do
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-apple-darwin.tar.gz"
|
||||
sha256 "0000000000000000000000000000000000000000000000000000000000000000"
|
||||
end
|
||||
end
|
||||
on_linux do
|
||||
on_arm do
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-aarch64-unknown-linux-gnu.tar.gz"
|
||||
sha256 "0000000000000000000000000000000000000000000000000000000000000000"
|
||||
end
|
||||
on_intel do
|
||||
url "https://github.com/mysqto/ccswitch/releases/download/v#{version}/ccswitch-v#{version}-x86_64-unknown-linux-gnu.tar.gz"
|
||||
sha256 "0000000000000000000000000000000000000000000000000000000000000000"
|
||||
end
|
||||
end
|
||||
|
||||
livecheck do
|
||||
url :url
|
||||
strategy :github_latest
|
||||
end
|
||||
|
||||
def install
|
||||
bin.install "ccswitch"
|
||||
# Runs `ccswitch completions {bash,zsh,fish}` and installs each script so
|
||||
# tab-completion works immediately — the piece a cask can't do.
|
||||
generate_completions_from_executable(bin/"ccswitch", "completions")
|
||||
end
|
||||
|
||||
test do
|
||||
assert_match "ccswitch", shell_output("#{bin}/ccswitch --help")
|
||||
end
|
||||
end
|
||||
@@ -1,72 +1,155 @@
|
||||
# ccswitch
|
||||
|
||||
A tiny [fish](https://fishshell.com) plugin to switch between multiple
|
||||
[Claude Code](https://claude.com/claude-code) accounts — personal, work,
|
||||
different orgs — and jump straight into a session.
|
||||
**Switch between multiple Claude Code accounts — personal, work, different
|
||||
orgs — and jump straight into a session.**
|
||||
|
||||
```fish
|
||||
`ccswitch` is a small, fast, cross-shell command-line tool. An account is two
|
||||
things that must travel together: the OAuth credential (in the macOS Keychain,
|
||||
or `~/.claude/.credentials.json` elsewhere) and the identity Claude Code
|
||||
validates it against (`oauthAccount` + `userID` inside `~/.claude.json`).
|
||||
`ccswitch` snapshots both into a plain profile directory and restores them as a
|
||||
unit, so one command becomes an account and drops you into `claude`.
|
||||
|
||||
```sh
|
||||
ccswitch work # switch to the "work" account and start claude
|
||||
ccswitch personal -c # switch to "personal", launch claude with -c
|
||||
ccswitch use work # just switch, don't launch
|
||||
ccswitch list # see every saved profile (* = active)
|
||||
ccswitch list # every saved profile (* = active)
|
||||
```
|
||||
|
||||
## How it works
|
||||
- **One binary, every shell.** A single Rust binary with completions for bash,
|
||||
zsh, fish, and PowerShell.
|
||||
- **Token-rotation safe.** OAuth refresh tokens rotate per *login*, shared
|
||||
across every org that login can see; `ccswitch` re-snapshots the outgoing
|
||||
credential into every sibling profile on each switch, so an actively used
|
||||
account never goes stale.
|
||||
- **Concurrent sessions.** Run two accounts at once in separate terminals with
|
||||
isolated config dirs but shared project memory and history.
|
||||
- **Session recall.** `ccswitch search` bridges to
|
||||
[`csx`](https://github.com/mysqto/csx) + `fzf` to fuzzy-pick and resume any
|
||||
past session.
|
||||
|
||||
An account is two things that must travel together:
|
||||
> This Rust CLI supersedes the original fish plugin, now preserved under
|
||||
> [`legacy-fish/`](legacy-fish/). The commands are the same; the tool is now a
|
||||
> single portable binary rather than a fish-only function.
|
||||
|
||||
1. **OAuth tokens** — the real credential. On macOS these live in the login
|
||||
Keychain (`Claude Code-credentials`); on Linux/others in
|
||||
`~/.claude/.credentials.json`. `ccswitch` picks the right backend per platform.
|
||||
2. **Identity** — the `oauthAccount` object and `userID` inside `~/.claude.json`,
|
||||
which Claude Code validates the token against.
|
||||
|
||||
`ccswitch save <name>` snapshots both into a plain profile directory. Switching
|
||||
restores the credential into the platform store and splices only `oauthAccount`
|
||||
and `userID` back into `~/.claude.json` (backing it up first — the rest of that
|
||||
file is shared and left untouched). Because a profile is just two JSON files, it
|
||||
is portable across machines and operating systems.
|
||||
---
|
||||
|
||||
## Install
|
||||
|
||||
With [fisher](https://github.com/jorgebucaran/fisher):
|
||||
### Homebrew (macOS & Linux)
|
||||
|
||||
```fish
|
||||
fisher install mysqto/ccswitch
|
||||
```sh
|
||||
brew tap mysqto/ccswitch https://github.com/mysqto/ccswitch
|
||||
brew install ccswitch # formula (recommended) — also installs shell completions
|
||||
# or:
|
||||
brew install --cask ccswitch # cask — installs the binary only (no completions)
|
||||
```
|
||||
|
||||
Requires [`jq`](https://jqlang.github.io/jq/).
|
||||
The tap ships **both** a formula and a cask, auto-regenerated with real
|
||||
checksums on each release. Prefer `brew install ccswitch` (the **formula**): it
|
||||
runs `ccswitch completions {bash,zsh,fish}` during install and drops each script
|
||||
into Homebrew's completion directories, so tab-completion works right away. The
|
||||
`--cask` route installs just the binary — use it if you don't want the formula,
|
||||
and set up completions yourself (see [Shell completions](#shell-completions)). Install one,
|
||||
not both — they each provide a `ccswitch` binary.
|
||||
|
||||
## Usage
|
||||
### From source with Cargo
|
||||
|
||||
```sh
|
||||
cargo install --git https://github.com/mysqto/ccswitch # or, in a clone: cargo install --path .
|
||||
```
|
||||
|
||||
### Prebuilt binary
|
||||
|
||||
Download the tarball for your platform from the [latest release][releases],
|
||||
extract it, and put `ccswitch` on your `PATH`. Assets are named
|
||||
`ccswitch-<tag>-<target>.tar.gz`, each with a matching `.sha256`:
|
||||
|
||||
| Platform | Target |
|
||||
| --- | --- |
|
||||
| macOS Apple Silicon | `aarch64-apple-darwin` |
|
||||
| macOS Intel | `x86_64-apple-darwin` |
|
||||
| Linux x86_64 | `x86_64-unknown-linux-gnu` |
|
||||
| Linux ARM64 | `aarch64-unknown-linux-gnu` |
|
||||
|
||||
Every method produces a single `ccswitch` binary with no runtime dependencies
|
||||
(the optional `search` bridge aside).
|
||||
|
||||
[releases]: https://github.com/mysqto/ccswitch/releases/latest
|
||||
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
Run `ccswitch` (or `ccswitch help`) for usage. Every command is below.
|
||||
|
||||
| Command | Action |
|
||||
| --- | --- |
|
||||
| `ccswitch <name> [args...]` | Switch to `<name>`, then start `claude` (extra args passed through) |
|
||||
| `ccswitch use <name>` | Switch without launching |
|
||||
| `ccswitch add <name>` | Sign in to a new account (`claude auth login`) and save it as `<name>` |
|
||||
| `ccswitch isolate <name> [args...]` | Run a **concurrent** session isolated to `<name>` (own credential) with memory/history shared across profiles |
|
||||
| `ccswitch save <name>` | Save the current account as `<name>` |
|
||||
| `ccswitch list` / `ls` | List profiles (`*` marks the active one) |
|
||||
| `ccswitch current` / `whoami` | Show the active account |
|
||||
| `ccswitch search` / `s` `[scope…]` | Fuzzy-pick a past session (via [`csx`](https://github.com/mysqto/csx)) and resume it |
|
||||
| `ccswitch rm <name>` | Delete a profile |
|
||||
| `ccswitch add <name> [--force]` | Sign in to a new account (`claude auth login`) and save it as `<name>` |
|
||||
| `ccswitch save <name> [--force]` | Snapshot the current account as `<name>` |
|
||||
| `ccswitch isolate <name> [args...]` | Run a **concurrent** session isolated to `<name>` (own credential, shared memory) |
|
||||
| `ccswitch isolate` | With no name, list existing isolated profiles |
|
||||
| `ccswitch seed [dir]` | Seed the shared isolate memory from `~/.claude` (or `dir`) |
|
||||
| `ccswitch search [scope...]` | Fuzzy-pick a past session (via `csx` + `fzf`) and resume it |
|
||||
| `ccswitch list` | List saved profiles (`*` marks the active one) |
|
||||
| `ccswitch current` | Show the active account |
|
||||
| `ccswitch rm <name>` | Delete a saved profile |
|
||||
| `ccswitch completions <shell>` | Print a completion script to stdout |
|
||||
| `ccswitch help` | Show usage |
|
||||
|
||||
## Search past sessions
|
||||
**Aliases:** `iso` = `isolate`, `s` = `search`, `ls` = `list`, `whoami` =
|
||||
`current`, `remove`/`delete` = `rm`.
|
||||
|
||||
`ccswitch search` (alias `s`) is an optional bridge to
|
||||
[`csx`](https://github.com/mysqto/csx), a local index of your AI-coding
|
||||
sessions. It fuzzy-picks a session and resumes it in the tool that produced it:
|
||||
**`--force`** (on `add` and `save`) overwrites an existing profile of the same
|
||||
name; without it, saving over an existing profile is refused.
|
||||
|
||||
```fish
|
||||
ccswitch search # sessions for the active tool → fzf → resume
|
||||
ccswitch search --repo payments # any csx scope flag passes straight through
|
||||
Profile names may not collide with a reserved subcommand word (`save`, `add`,
|
||||
`isolate`, `iso`, `seed`, `search`, `s`, `list`, `ls`, `current`, `whoami`,
|
||||
`use`, `rm`, `remove`, `delete`, `help`).
|
||||
|
||||
### Environment
|
||||
|
||||
| Variable | Purpose | Default |
|
||||
| --- | --- | --- |
|
||||
| `CCSWITCH_HOME` | Where saved profiles live. | `~/.claude/accounts` |
|
||||
| `CCSWITCH_ISOLATE_HOME` | Where isolated profiles + shared memory live. | `~/.claude/profiles` |
|
||||
|
||||
---
|
||||
|
||||
## Shell completions
|
||||
|
||||
`ccswitch completions <shell>` prints a completion script to stdout for
|
||||
`bash`, `zsh`, `fish`, `powershell` (and `elvish`). Install it once for your
|
||||
shell:
|
||||
|
||||
**bash** — add to `~/.bashrc`:
|
||||
|
||||
```sh
|
||||
source <(ccswitch completions bash)
|
||||
```
|
||||
|
||||
It shells out to `csx sessions` (defaulting the scope to the active tool),
|
||||
previews each transcript with `csx show <id>` in `fzf`, and resumes the pick
|
||||
(`claude --resume <id>`, `codex resume <id>`, …). Requires `csx` and `fzf` on
|
||||
`PATH` (`jq` optional, for a nicer picker list). If `csx` isn't installed, every
|
||||
other `ccswitch` command still works — this subcommand just prints a hint.
|
||||
**zsh** — write into a directory on your `$fpath` (before `compinit`):
|
||||
|
||||
```sh
|
||||
ccswitch completions zsh > "${fpath[1]}/_ccswitch"
|
||||
```
|
||||
|
||||
**fish**:
|
||||
|
||||
```fish
|
||||
ccswitch completions fish > ~/.config/fish/completions/ccswitch.fish
|
||||
```
|
||||
|
||||
**PowerShell** — add to your `$PROFILE`:
|
||||
|
||||
```powershell
|
||||
ccswitch completions powershell | Out-String | Invoke-Expression
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Walkthrough
|
||||
|
||||
@@ -74,12 +157,9 @@ A complete run, from a fresh install to switching daily.
|
||||
|
||||
### 1. Save the account you're already signed into
|
||||
|
||||
```fish
|
||||
```sh
|
||||
claude auth status # confirm who you're logged in as
|
||||
ccswitch save personal # snapshot the active account as "personal"
|
||||
```
|
||||
|
||||
```fish
|
||||
ccswitch list
|
||||
# * personal you@gmail.com
|
||||
```
|
||||
@@ -90,22 +170,13 @@ The `*` marks the currently active account.
|
||||
|
||||
`ccswitch add` signs you in to another account and saves it in one step:
|
||||
|
||||
```fish
|
||||
```sh
|
||||
ccswitch add work # runs `claude auth login`, then saves it as "work"
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Prefer to do it by hand?</summary>
|
||||
|
||||
```fish
|
||||
claude auth login # sign in as the other account (or switch org via /login)
|
||||
ccswitch save work
|
||||
```
|
||||
</details>
|
||||
|
||||
Both are now saved:
|
||||
|
||||
```fish
|
||||
```sh
|
||||
ccswitch list
|
||||
# personal you@gmail.com
|
||||
# * work you@company.com (Acme)
|
||||
@@ -113,7 +184,7 @@ ccswitch list
|
||||
|
||||
### 3. Switch and work — the daily loop
|
||||
|
||||
```fish
|
||||
```sh
|
||||
ccswitch work # become "work" and start a claude session
|
||||
ccswitch personal -c # become "personal", continue the last conversation
|
||||
ccswitch use work # just switch, don't launch anything
|
||||
@@ -123,29 +194,13 @@ ccswitch current # you@company.com (Acme)
|
||||
One command becomes an account and drops you into a session. Switching also
|
||||
re-snapshots the account you're leaving, so rotating tokens never go stale.
|
||||
|
||||
### 4. Run two accounts at the same time
|
||||
|
||||
Steps 1–3 swap one machine-global account (sequential — one at a time). To keep
|
||||
**two live sessions as different accounts concurrently**, use isolated profiles
|
||||
with shared memory:
|
||||
|
||||
```fish
|
||||
ccswitch seed # once: copy your ~/.claude memory + history into shared/
|
||||
ccswitch isolate work # terminal 1 — sign in once as work
|
||||
ccswitch isolate personal # terminal 2 — sign in once as personal, at the same time
|
||||
```
|
||||
|
||||
Each isolated session has its own credential but shares project memory and
|
||||
history. Re-running `ccswitch isolate <name>` reuses the earlier login. (If you
|
||||
skip `seed`, the first `isolate` warns that memory is empty and asks to confirm.)
|
||||
|
||||
## Same login, multiple orgs
|
||||
### Same login, multiple orgs
|
||||
|
||||
If one login (e.g. a Claude Team account) belongs to several organizations,
|
||||
each org is a separate profile — Claude Code issues a distinct org-scoped token
|
||||
per org. Save one after switching org inside Claude Code (`/login`):
|
||||
|
||||
```fish
|
||||
```sh
|
||||
ccswitch save org-a # while the first org is active
|
||||
# switch org in Claude Code, then:
|
||||
ccswitch save org-b
|
||||
@@ -154,16 +209,19 @@ ccswitch save org-b
|
||||
`ccswitch list` distinguishes them by account **and** organization, so the same
|
||||
email can appear more than once with only the active org starred.
|
||||
|
||||
## Concurrent sessions (shared memory, separate accounts)
|
||||
---
|
||||
|
||||
`ccswitch <name>` swaps a single machine-global account, so it is sequential —
|
||||
one active account at a time. To run **two accounts at once** (two terminals),
|
||||
## Concurrent sessions (isolate + seed)
|
||||
|
||||
`ccswitch <name>` swaps a single machine-global account, so it is **sequential**
|
||||
— one active account at a time. To run **two accounts at once** (two terminals),
|
||||
use `ccswitch isolate`, which gives each profile its own
|
||||
[`CLAUDE_CONFIG_DIR`](https://code.claude.com/docs/en/settings):
|
||||
|
||||
```fish
|
||||
ccswitch isolate work # terminal 1 — signs in once, then reuses
|
||||
ccswitch isolate personal # terminal 2 — a different account, at the same time
|
||||
```sh
|
||||
ccswitch seed # once: copy your ~/.claude memory + history into shared/
|
||||
ccswitch isolate work # terminal 1 — sign in once as work
|
||||
ccswitch isolate personal # terminal 2 — sign in once as personal, at the same time
|
||||
```
|
||||
|
||||
Each profile keeps its **own credential and identity**, but memory and history
|
||||
@@ -172,7 +230,8 @@ are **shared** — `isolate` symlinks `projects/` (session transcripts + the
|
||||
`shared/` directory. So both accounts see the same project memory and past
|
||||
sessions while staying logged in as different users.
|
||||
|
||||
Layout (centralized under `~/.claude`, override with `$CCSWITCH_ISOLATE_HOME`):
|
||||
Layout (centralized under `~/.claude/profiles`, override with
|
||||
`$CCSWITCH_ISOLATE_HOME`):
|
||||
|
||||
```
|
||||
~/.claude/profiles/
|
||||
@@ -192,27 +251,47 @@ Layout (centralized under `~/.claude`, override with `$CCSWITCH_ISOLATE_HOME`):
|
||||
`ccswitch isolate` with no name lists existing isolated profiles. Existing
|
||||
non-symlink files in a profile dir are left untouched (never clobbered).
|
||||
|
||||
`shared/` starts **empty** — isolated profiles begin with fresh memory. To carry
|
||||
your existing memory/history over, seed it once from your default `~/.claude`:
|
||||
**Seeding.** `shared/` starts empty — isolated profiles begin with fresh
|
||||
memory. Carry your existing memory/history over once:
|
||||
|
||||
```fish
|
||||
```sh
|
||||
ccswitch seed # copies CLAUDE.md, history.jsonl and projects/ from ~/.claude
|
||||
ccswitch seed <dir> # ... or from another config dir
|
||||
```
|
||||
|
||||
Re-run `ccswitch seed` anytime to re-sync from the source (source wins on
|
||||
same-named files).
|
||||
same-named files). While `shared/` is empty, `ccswitch isolate` warns and asks
|
||||
for confirmation before launching, so you don't start with no memory by
|
||||
accident. The prompt stops once `shared/` has content.
|
||||
|
||||
While `shared/` is empty, `ccswitch isolate` warns and asks for confirmation
|
||||
before launching (so you don't start with no memory by accident). The prompt
|
||||
stops appearing once `shared/` has content — from `ccswitch seed` or from your
|
||||
first session.
|
||||
|
||||
> Note: this pattern relies on `CLAUDE_CONFIG_DIR` (supported) plus symlinking of
|
||||
> This pattern relies on `CLAUDE_CONFIG_DIR` (supported) plus symlinking of
|
||||
> account-agnostic paths (a community pattern, not officially documented). Auth
|
||||
> stays isolated; only memory/history is shared. Two sessions writing the same
|
||||
> project's memory simultaneously can race — low risk in practice.
|
||||
|
||||
---
|
||||
|
||||
## Search past sessions
|
||||
|
||||
`ccswitch search` (alias `s`) is an optional bridge to
|
||||
[`csx`](https://github.com/mysqto/csx), a local index of your AI-coding
|
||||
sessions. It fuzzy-picks a session and resumes it in the tool that produced it:
|
||||
|
||||
```sh
|
||||
ccswitch search # sessions for the active tool → fzf → resume
|
||||
ccswitch search --repo payments # any csx scope flag passes straight through
|
||||
ccswitch search --tool codex # pick from Codex sessions instead
|
||||
```
|
||||
|
||||
It shells out to `csx sessions --json` (defaulting the scope to the tool
|
||||
reported by `csx current`), previews each transcript with `csx show <id>` in
|
||||
`fzf`, and resumes the pick — `claude --resume <id>` for Claude Code, `codex
|
||||
resume <id>` for Codex. Requires `csx` and `fzf` on `PATH`. If either is
|
||||
missing, every other `ccswitch` command still works — this subcommand just
|
||||
prints a hint.
|
||||
|
||||
---
|
||||
|
||||
## Profile storage
|
||||
|
||||
Profiles live in `$CCSWITCH_HOME` (default `~/.claude/accounts`), one directory
|
||||
@@ -221,35 +300,48 @@ per profile:
|
||||
```
|
||||
~/.claude/accounts/work/
|
||||
├── credentials.json # OAuth blob
|
||||
└── account.json # oauthAccount + userID
|
||||
└── account.json # oauthAccount + userID (+ keychain account attr)
|
||||
```
|
||||
|
||||
Point `$CCSWITCH_HOME` at a synced folder or repo to move profiles between
|
||||
machines:
|
||||
machines.
|
||||
|
||||
```fish
|
||||
set -Ux CCSWITCH_HOME ~/vault/claude-accounts
|
||||
```
|
||||
|
||||
## ⚠️ These files are secrets
|
||||
### ⚠️ These files are secrets
|
||||
|
||||
`credentials.json` holds a live bearer token. If you sync `$CCSWITCH_HOME` with
|
||||
git or a cloud folder, **encrypt it** — use a private repo with
|
||||
[git-crypt](https://github.com/AGWA/git-crypt) / [age](https://github.com/FiloSottile/age) /
|
||||
[git-crypt](https://github.com/AGWA/git-crypt) /
|
||||
[age](https://github.com/FiloSottile/age) /
|
||||
[SOPS](https://github.com/getsops/sops), or a real secret manager. Never commit
|
||||
plaintext tokens to a shared or public repo.
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- 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.
|
||||
rewrite `~/.claude.json` on exit and clobber the swap. `ccswitch` warns when
|
||||
it detects one.
|
||||
- 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 its matching profile automatically on
|
||||
every switch — so an account you actively use won't go stale.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
cargo build
|
||||
cargo test
|
||||
cargo fmt
|
||||
cargo clippy --all-targets --all-features -- -D warnings
|
||||
```
|
||||
|
||||
Architecture, the ports-and-adapters layout, and the coverage discipline are
|
||||
documented in [`AGENTS.md`](AGENTS.md).
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
MIT — see [`LICENSE`](LICENSE). Copyright (c) 2026 Chen Lei.
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2026 Chen Lei
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,255 @@
|
||||
# ccswitch
|
||||
|
||||
A tiny [fish](https://fishshell.com) plugin to switch between multiple
|
||||
[Claude Code](https://claude.com/claude-code) accounts — personal, work,
|
||||
different orgs — and jump straight into a session.
|
||||
|
||||
```fish
|
||||
ccswitch work # switch to the "work" account and start claude
|
||||
ccswitch personal -c # switch to "personal", launch claude with -c
|
||||
ccswitch use work # just switch, don't launch
|
||||
ccswitch list # see every saved profile (* = active)
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
An account is two things that must travel together:
|
||||
|
||||
1. **OAuth tokens** — the real credential. On macOS these live in the login
|
||||
Keychain (`Claude Code-credentials`); on Linux/others in
|
||||
`~/.claude/.credentials.json`. `ccswitch` picks the right backend per platform.
|
||||
2. **Identity** — the `oauthAccount` object and `userID` inside `~/.claude.json`,
|
||||
which Claude Code validates the token against.
|
||||
|
||||
`ccswitch save <name>` snapshots both into a plain profile directory. Switching
|
||||
restores the credential into the platform store and splices only `oauthAccount`
|
||||
and `userID` back into `~/.claude.json` (backing it up first — the rest of that
|
||||
file is shared and left untouched). Because a profile is just two JSON files, it
|
||||
is portable across machines and operating systems.
|
||||
|
||||
## Install
|
||||
|
||||
With [fisher](https://github.com/jorgebucaran/fisher):
|
||||
|
||||
```fish
|
||||
fisher install mysqto/ccswitch
|
||||
```
|
||||
|
||||
Requires [`jq`](https://jqlang.github.io/jq/).
|
||||
|
||||
## Usage
|
||||
|
||||
| Command | Action |
|
||||
| --- | --- |
|
||||
| `ccswitch <name> [args...]` | Switch to `<name>`, then start `claude` (extra args passed through) |
|
||||
| `ccswitch use <name>` | Switch without launching |
|
||||
| `ccswitch add <name>` | Sign in to a new account (`claude auth login`) and save it as `<name>` |
|
||||
| `ccswitch isolate <name> [args...]` | Run a **concurrent** session isolated to `<name>` (own credential) with memory/history shared across profiles |
|
||||
| `ccswitch save <name>` | Save the current account as `<name>` |
|
||||
| `ccswitch list` / `ls` | List profiles (`*` marks the active one) |
|
||||
| `ccswitch current` / `whoami` | Show the active account |
|
||||
| `ccswitch search` / `s` `[scope…]` | Fuzzy-pick a past session (via [`csx`](https://github.com/mysqto/csx)) and resume it |
|
||||
| `ccswitch rm <name>` | Delete a profile |
|
||||
|
||||
## Search past sessions
|
||||
|
||||
`ccswitch search` (alias `s`) is an optional bridge to
|
||||
[`csx`](https://github.com/mysqto/csx), a local index of your AI-coding
|
||||
sessions. It fuzzy-picks a session and resumes it in the tool that produced it:
|
||||
|
||||
```fish
|
||||
ccswitch search # sessions for the active tool → fzf → resume
|
||||
ccswitch search --repo payments # any csx scope flag passes straight through
|
||||
```
|
||||
|
||||
It shells out to `csx sessions` (defaulting the scope to the active tool),
|
||||
previews each transcript with `csx show <id>` in `fzf`, and resumes the pick
|
||||
(`claude --resume <id>`, `codex resume <id>`, …). Requires `csx` and `fzf` on
|
||||
`PATH` (`jq` optional, for a nicer picker list). If `csx` isn't installed, every
|
||||
other `ccswitch` command still works — this subcommand just prints a hint.
|
||||
|
||||
## Walkthrough
|
||||
|
||||
A complete run, from a fresh install to switching daily.
|
||||
|
||||
### 1. Save the account you're already signed into
|
||||
|
||||
```fish
|
||||
claude auth status # confirm who you're logged in as
|
||||
ccswitch save personal # snapshot the active account as "personal"
|
||||
```
|
||||
|
||||
```fish
|
||||
ccswitch list
|
||||
# * personal you@gmail.com
|
||||
```
|
||||
|
||||
The `*` marks the currently active account.
|
||||
|
||||
### 2. Add a second account
|
||||
|
||||
`ccswitch add` signs you in to another account and saves it in one step:
|
||||
|
||||
```fish
|
||||
ccswitch add work # runs `claude auth login`, then saves it as "work"
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Prefer to do it by hand?</summary>
|
||||
|
||||
```fish
|
||||
claude auth login # sign in as the other account (or switch org via /login)
|
||||
ccswitch save work
|
||||
```
|
||||
</details>
|
||||
|
||||
Both are now saved:
|
||||
|
||||
```fish
|
||||
ccswitch list
|
||||
# personal you@gmail.com
|
||||
# * work you@company.com (Acme)
|
||||
```
|
||||
|
||||
### 3. Switch and work — the daily loop
|
||||
|
||||
```fish
|
||||
ccswitch work # become "work" and start a claude session
|
||||
ccswitch personal -c # become "personal", continue the last conversation
|
||||
ccswitch use work # just switch, don't launch anything
|
||||
ccswitch current # you@company.com (Acme)
|
||||
```
|
||||
|
||||
One command becomes an account and drops you into a session. Switching also
|
||||
re-snapshots the account you're leaving, so rotating tokens never go stale.
|
||||
|
||||
### 4. Run two accounts at the same time
|
||||
|
||||
Steps 1–3 swap one machine-global account (sequential — one at a time). To keep
|
||||
**two live sessions as different accounts concurrently**, use isolated profiles
|
||||
with shared memory:
|
||||
|
||||
```fish
|
||||
ccswitch seed # once: copy your ~/.claude memory + history into shared/
|
||||
ccswitch isolate work # terminal 1 — sign in once as work
|
||||
ccswitch isolate personal # terminal 2 — sign in once as personal, at the same time
|
||||
```
|
||||
|
||||
Each isolated session has its own credential but shares project memory and
|
||||
history. Re-running `ccswitch isolate <name>` reuses the earlier login. (If you
|
||||
skip `seed`, the first `isolate` warns that memory is empty and asks to confirm.)
|
||||
|
||||
## Same login, multiple orgs
|
||||
|
||||
If one login (e.g. a Claude Team account) belongs to several organizations,
|
||||
each org is a separate profile — Claude Code issues a distinct org-scoped token
|
||||
per org. Save one after switching org inside Claude Code (`/login`):
|
||||
|
||||
```fish
|
||||
ccswitch save org-a # while the first org is active
|
||||
# switch org in Claude Code, then:
|
||||
ccswitch save org-b
|
||||
```
|
||||
|
||||
`ccswitch list` distinguishes them by account **and** organization, so the same
|
||||
email can appear more than once with only the active org starred.
|
||||
|
||||
## Concurrent sessions (shared memory, separate accounts)
|
||||
|
||||
`ccswitch <name>` swaps a single machine-global account, so it is sequential —
|
||||
one active account at a time. To run **two accounts at once** (two terminals),
|
||||
use `ccswitch isolate`, which gives each profile its own
|
||||
[`CLAUDE_CONFIG_DIR`](https://code.claude.com/docs/en/settings):
|
||||
|
||||
```fish
|
||||
ccswitch isolate work # terminal 1 — signs in once, then reuses
|
||||
ccswitch isolate personal # terminal 2 — a different account, at the same time
|
||||
```
|
||||
|
||||
Each profile keeps its **own credential and identity**, but memory and history
|
||||
are **shared** — `isolate` symlinks `projects/` (session transcripts + the
|
||||
`memory/` files), `history.jsonl`, and `CLAUDE.md` from each profile to a common
|
||||
`shared/` directory. So both accounts see the same project memory and past
|
||||
sessions while staying logged in as different users.
|
||||
|
||||
Layout (centralized under `~/.claude`, override with `$CCSWITCH_ISOLATE_HOME`):
|
||||
|
||||
```
|
||||
~/.claude/profiles/
|
||||
├── shared/ # one real copy of the shared memory/history
|
||||
│ ├── projects/
|
||||
│ ├── history.jsonl
|
||||
│ └── CLAUDE.md
|
||||
├── work/ # CLAUDE_CONFIG_DIR for "work"
|
||||
│ ├── projects -> ../shared/projects
|
||||
│ ├── history.jsonl -> ../shared/history.jsonl
|
||||
│ ├── CLAUDE.md -> ../shared/CLAUDE.md
|
||||
│ ├── .claude.json # own account identity (NOT shared)
|
||||
│ └── settings.json # own settings
|
||||
└── personal/ # CLAUDE_CONFIG_DIR for "personal" (same shared links)
|
||||
```
|
||||
|
||||
`ccswitch isolate` with no name lists existing isolated profiles. Existing
|
||||
non-symlink files in a profile dir are left untouched (never clobbered).
|
||||
|
||||
`shared/` starts **empty** — isolated profiles begin with fresh memory. To carry
|
||||
your existing memory/history over, seed it once from your default `~/.claude`:
|
||||
|
||||
```fish
|
||||
ccswitch seed # copies CLAUDE.md, history.jsonl and projects/ from ~/.claude
|
||||
ccswitch seed <dir> # ... or from another config dir
|
||||
```
|
||||
|
||||
Re-run `ccswitch seed` anytime to re-sync from the source (source wins on
|
||||
same-named files).
|
||||
|
||||
While `shared/` is empty, `ccswitch isolate` warns and asks for confirmation
|
||||
before launching (so you don't start with no memory by accident). The prompt
|
||||
stops appearing once `shared/` has content — from `ccswitch seed` or from your
|
||||
first session.
|
||||
|
||||
> Note: this pattern relies on `CLAUDE_CONFIG_DIR` (supported) plus symlinking of
|
||||
> account-agnostic paths (a community pattern, not officially documented). Auth
|
||||
> stays isolated; only memory/history is shared. Two sessions writing the same
|
||||
> project's memory simultaneously can race — low risk in practice.
|
||||
|
||||
## Profile storage
|
||||
|
||||
Profiles live in `$CCSWITCH_HOME` (default `~/.claude/accounts`), one directory
|
||||
per profile:
|
||||
|
||||
```
|
||||
~/.claude/accounts/work/
|
||||
├── credentials.json # OAuth blob
|
||||
└── account.json # oauthAccount + userID
|
||||
```
|
||||
|
||||
Point `$CCSWITCH_HOME` at a synced folder or repo to move profiles between
|
||||
machines:
|
||||
|
||||
```fish
|
||||
set -Ux CCSWITCH_HOME ~/vault/claude-accounts
|
||||
```
|
||||
|
||||
## ⚠️ These files are secrets
|
||||
|
||||
`credentials.json` holds a live bearer token. If you sync `$CCSWITCH_HOME` with
|
||||
git or a cloud folder, **encrypt it** — use a private repo with
|
||||
[git-crypt](https://github.com/AGWA/git-crypt) / [age](https://github.com/FiloSottile/age) /
|
||||
[SOPS](https://github.com/getsops/sops), or a real secret manager. Never commit
|
||||
plaintext tokens to a shared or public repo.
|
||||
|
||||
## Notes
|
||||
|
||||
- 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.
|
||||
- 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 its matching profile automatically on
|
||||
every switch — so an account you actively use won't go stale.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
File renamed without changes.
File renamed without changes.
+2703
File diff suppressed because it is too large.
Load diff
+192
@@ -0,0 +1,192 @@
|
||||
//! Real process-spawning adapter and program entry point.
|
||||
//!
|
||||
//! Side-effecting implementation of the [`crate::cli::System`] port: launching
|
||||
//! `claude`, `csx`, and `fzf`, creating symlinks, prompting on the terminal,
|
||||
//! and replacing the current process via `exec`. This file also owns the
|
||||
//! real-environment wiring in [`run`] (argv parsing, `$HOME`/`$CCSWITCH_*`
|
||||
//! resolution, and building the platform stores). It contains no decision
|
||||
//! logic — every branch of behavior lives in [`crate::cli`] — and is excluded
|
||||
//! from coverage.
|
||||
|
||||
use crate::cli::{self, App, Io, Paths, System};
|
||||
use crate::creds_shim::platform_store;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::store::{Store, TokenScope};
|
||||
use std::io::{BufRead, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command as Proc, Stdio};
|
||||
|
||||
/// The real system adapter.
|
||||
struct RealSystem;
|
||||
|
||||
impl System for RealSystem {
|
||||
fn claude_login(&self) -> Result<bool> {
|
||||
Ok(Proc::new("claude")
|
||||
.args(["auth", "login"])
|
||||
.status()?
|
||||
.success())
|
||||
}
|
||||
|
||||
fn command_exists(&self, program: &str) -> bool {
|
||||
std::env::var_os("PATH").is_some_and(|paths| {
|
||||
std::env::split_paths(&paths).any(|dir| dir.join(program).is_file())
|
||||
})
|
||||
}
|
||||
|
||||
fn claude_is_running(&self) -> bool {
|
||||
Proc::new("pgrep")
|
||||
.args(["-x", "claude"])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn make_symlink(&self, target: &Path, link: &Path) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let _ = std::fs::remove_file(link);
|
||||
std::os::unix::fs::symlink(target, link)?;
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = (target, link);
|
||||
Err(Error::Invalid(
|
||||
"symlinks unsupported on this platform".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(&self, prompt: &str) -> Result<bool> {
|
||||
let mut stderr = std::io::stderr();
|
||||
write!(stderr, "{prompt}")?;
|
||||
stderr.flush()?;
|
||||
let mut line = String::new();
|
||||
std::io::stdin().lock().read_line(&mut line)?;
|
||||
let answer = line.trim().to_ascii_lowercase();
|
||||
Ok(answer == "y" || answer == "yes")
|
||||
}
|
||||
|
||||
fn csx_current(&self) -> Result<Vec<u8>> {
|
||||
Ok(Proc::new("csx")
|
||||
.args(["current", "--json"])
|
||||
.output()?
|
||||
.stdout)
|
||||
}
|
||||
|
||||
fn csx_sessions(&self, scope: &[String]) -> Result<Vec<u8>> {
|
||||
Ok(Proc::new("csx")
|
||||
.args(["sessions", "--json"])
|
||||
.args(scope)
|
||||
.output()?
|
||||
.stdout)
|
||||
}
|
||||
|
||||
fn fzf_pick(&self, rows: &str, preview: &str) -> Result<Option<String>> {
|
||||
let mut child = Proc::new("fzf")
|
||||
.args([
|
||||
"--with-nth=2..",
|
||||
"--delimiter=\t",
|
||||
"--preview",
|
||||
preview,
|
||||
"--preview-window=right,60%,wrap",
|
||||
"--prompt=session> ",
|
||||
])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()?;
|
||||
child
|
||||
.stdin
|
||||
.take()
|
||||
.ok_or_else(|| Error::Invalid("fzf stdin unavailable".to_string()))?
|
||||
.write_all(rows.as_bytes())?;
|
||||
let output = child.wait_with_output()?;
|
||||
if !output.status.success() {
|
||||
return Ok(None);
|
||||
}
|
||||
let picked = String::from_utf8_lossy(&output.stdout)
|
||||
.trim_end()
|
||||
.to_string();
|
||||
if picked.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(picked))
|
||||
}
|
||||
}
|
||||
|
||||
fn exec(&self, program: &str, args: &[String], envs: &[(String, String)]) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
let mut cmd = Proc::new(program);
|
||||
cmd.args(args);
|
||||
for (key, value) in envs {
|
||||
cmd.env(key, value);
|
||||
}
|
||||
Err(cmd.exec().into())
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let status = Proc::new(program)
|
||||
.args(args)
|
||||
.envs(envs.iter().cloned())
|
||||
.status()?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Invalid(format!("{program} exited with failure")))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The home directory, falling back to the current directory.
|
||||
fn home_dir() -> PathBuf {
|
||||
std::env::var_os("HOME").map_or_else(|| PathBuf::from("."), PathBuf::from)
|
||||
}
|
||||
|
||||
/// Program entry point: parse arguments, resolve the environment, and dispatch.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the selected subcommand fails.
|
||||
pub fn run() -> anyhow::Result<()> {
|
||||
let command = match cli::parse_from(std::env::args_os()) {
|
||||
Ok(command) => command,
|
||||
Err(err) => err.exit(),
|
||||
};
|
||||
|
||||
let home = home_dir();
|
||||
let claude = cli::claude_dir(&home);
|
||||
let store = Store::new(cli::ccswitch_home(
|
||||
std::env::var("CCSWITCH_HOME").ok(),
|
||||
&home,
|
||||
));
|
||||
let creds = platform_store(claude.clone());
|
||||
let paths = Paths {
|
||||
config: cli::config_path(&home),
|
||||
isolate_base: cli::isolate_home(std::env::var("CCSWITCH_ISOLATE_HOME").ok(), &home),
|
||||
seed_default: claude,
|
||||
};
|
||||
let system = RealSystem;
|
||||
let app = App::new(
|
||||
&system,
|
||||
creds.as_ref(),
|
||||
&store,
|
||||
paths,
|
||||
TokenScope::PerAccount,
|
||||
);
|
||||
|
||||
let stdout = std::io::stdout();
|
||||
let stderr = std::io::stderr();
|
||||
let mut out = stdout.lock();
|
||||
let mut err = stderr.lock();
|
||||
let mut io = Io {
|
||||
out: &mut out,
|
||||
err: &mut err,
|
||||
};
|
||||
app.dispatch(&mut io, command)?;
|
||||
Ok(())
|
||||
}
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
//! Reading and splicing the Claude Code `~/.claude.json` configuration file.
|
||||
//!
|
||||
//! Claude Code keeps a large amount of unrelated state in `~/.claude.json`
|
||||
//! alongside the signed-in identity (`oauthAccount` and `userID`). To switch
|
||||
//! accounts we must swap only that identity in and out while leaving every
|
||||
//! other key untouched. All of that is plain-file JSON manipulation under a
|
||||
//! caller-provided path, so it lives here and is unit-tested against a
|
||||
//! temporary file with no shim.
|
||||
|
||||
use crate::creds::set_permissions_600;
|
||||
use crate::error::Result;
|
||||
use crate::model::Account;
|
||||
use serde_json::{json, Value};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The two config keys that make up a Claude Code identity snapshot.
|
||||
const IDENTITY_KEYS: [&str; 2] = ["oauthAccount", "userID"];
|
||||
|
||||
/// Load `~/.claude.json` from `path` as a JSON value.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the file is missing or is not valid JSON.
|
||||
pub fn load(path: &Path) -> Result<Value> {
|
||||
let text = fs::read_to_string(path)?;
|
||||
let value = serde_json::from_str(&text)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Extract the identity snapshot (`{oauthAccount, userID}`) from a loaded
|
||||
/// config value. Missing keys are captured as JSON `null` so the shape is
|
||||
/// stable.
|
||||
#[must_use]
|
||||
pub fn extract_identity(config: &Value) -> Value {
|
||||
json!({
|
||||
"oauthAccount": config.get("oauthAccount").cloned().unwrap_or(Value::Null),
|
||||
"userID": config.get("userID").cloned().unwrap_or(Value::Null),
|
||||
})
|
||||
}
|
||||
|
||||
/// Splice a saved identity snapshot back into `config`, replacing only the
|
||||
/// identity keys and leaving every other key untouched. A key absent from
|
||||
/// `identity` leaves the corresponding config key unchanged; a non-object
|
||||
/// config is left as-is.
|
||||
pub fn splice_identity(config: &mut Value, identity: &Value) {
|
||||
let Some(obj) = config.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
for key in IDENTITY_KEYS {
|
||||
if let Some(value) = identity.get(key) {
|
||||
obj.insert(key.to_string(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the account identity (accountUuid, organizationUuid, emailAddress,
|
||||
/// organizationName) out of a loaded config value.
|
||||
#[must_use]
|
||||
pub fn account_of(config: &Value) -> Account {
|
||||
match config.get("oauthAccount") {
|
||||
Some(value) => serde_json::from_value(value.clone()).unwrap_or_default(),
|
||||
None => Account::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `.ccswitch.bak` backup path for a config file.
|
||||
#[must_use]
|
||||
fn backup_path(config_path: &Path) -> PathBuf {
|
||||
let mut name = config_path.as_os_str().to_owned();
|
||||
name.push(".ccswitch.bak");
|
||||
PathBuf::from(name)
|
||||
}
|
||||
|
||||
/// The `.ccswitch.tmp` scratch path used for atomic writes.
|
||||
#[must_use]
|
||||
fn temp_path(config_path: &Path) -> PathBuf {
|
||||
let mut name = config_path.as_os_str().to_owned();
|
||||
name.push(".ccswitch.tmp");
|
||||
PathBuf::from(name)
|
||||
}
|
||||
|
||||
/// Patch the identity in the config file at `config_path` with `identity`,
|
||||
/// preserving all other keys.
|
||||
///
|
||||
/// The existing file is backed up to `<path>.ccswitch.bak` first, and the new
|
||||
/// contents are written atomically via a sibling temp file that is renamed
|
||||
/// into place.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the config cannot be read, backed up, or written.
|
||||
pub fn patch(config_path: &Path, identity: &Value) -> Result<()> {
|
||||
let mut config = load(config_path)?;
|
||||
fs::copy(config_path, backup_path(config_path))?;
|
||||
splice_identity(&mut config, identity);
|
||||
let text = serde_json::to_string_pretty(&config)?;
|
||||
let tmp = temp_path(config_path);
|
||||
fs::write(&tmp, text.as_bytes())?;
|
||||
set_permissions_600(&tmp)?;
|
||||
fs::rename(&tmp, config_path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_dir() -> PathBuf {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let base = std::env::temp_dir().join(format!(
|
||||
"ccswitch-config-{}-{}",
|
||||
std::process::id(),
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(&base).unwrap();
|
||||
base
|
||||
}
|
||||
|
||||
fn sample_config() -> Value {
|
||||
json!({
|
||||
"numStartups": 7,
|
||||
"userID": "user-old",
|
||||
"oauthAccount": {
|
||||
"accountUuid": "acct-old",
|
||||
"organizationUuid": "org-old",
|
||||
"emailAddress": "old@example.com",
|
||||
"organizationName": "Old Org"
|
||||
},
|
||||
"projects": { "/tmp/foo": { "allowedTools": [] } }
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_reads_json() {
|
||||
let dir = temp_dir();
|
||||
let path = dir.join(".claude.json");
|
||||
fs::write(&path, sample_config().to_string()).unwrap();
|
||||
let loaded = load(&path).unwrap();
|
||||
assert_eq!(loaded["numStartups"], json!(7));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_missing_file_errors() {
|
||||
let dir = temp_dir();
|
||||
let path = dir.join(".claude.json");
|
||||
assert!(load(&path).is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_invalid_json_errors() {
|
||||
let dir = temp_dir();
|
||||
let path = dir.join(".claude.json");
|
||||
fs::write(&path, "{not json").unwrap();
|
||||
assert!(load(&path).is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_identity_pulls_both_keys() {
|
||||
let identity = extract_identity(&sample_config());
|
||||
assert_eq!(identity["userID"], json!("user-old"));
|
||||
assert_eq!(
|
||||
identity["oauthAccount"]["emailAddress"],
|
||||
json!("old@example.com")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_identity_defaults_missing_keys_to_null() {
|
||||
let identity = extract_identity(&json!({ "numStartups": 1 }));
|
||||
assert_eq!(identity["oauthAccount"], Value::Null);
|
||||
assert_eq!(identity["userID"], Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splice_replaces_identity_and_preserves_others() {
|
||||
let mut config = sample_config();
|
||||
let identity = json!({
|
||||
"userID": "user-new",
|
||||
"oauthAccount": {
|
||||
"accountUuid": "acct-new",
|
||||
"organizationUuid": "org-new",
|
||||
"emailAddress": "new@example.com",
|
||||
"organizationName": "New Org"
|
||||
}
|
||||
});
|
||||
splice_identity(&mut config, &identity);
|
||||
assert_eq!(config["userID"], json!("user-new"));
|
||||
assert_eq!(config["oauthAccount"]["accountUuid"], json!("acct-new"));
|
||||
// Unrelated keys survive untouched.
|
||||
assert_eq!(config["numStartups"], json!(7));
|
||||
assert_eq!(config["projects"]["/tmp/foo"]["allowedTools"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splice_leaves_config_key_when_identity_key_absent() {
|
||||
let mut config = sample_config();
|
||||
let identity = json!({ "userID": "user-new" });
|
||||
splice_identity(&mut config, &identity);
|
||||
assert_eq!(config["userID"], json!("user-new"));
|
||||
// oauthAccount was not in identity, so it is left as it was.
|
||||
assert_eq!(config["oauthAccount"]["accountUuid"], json!("acct-old"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splice_ignores_non_object_config() {
|
||||
let mut config = Value::Null;
|
||||
splice_identity(&mut config, &json!({ "userID": "x" }));
|
||||
assert_eq!(config, Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_of_reads_all_four_fields() {
|
||||
let account = account_of(&sample_config());
|
||||
assert_eq!(account.account_uuid, "acct-old");
|
||||
assert_eq!(account.org_uuid, "org-old");
|
||||
assert_eq!(account.email, "old@example.com");
|
||||
assert_eq!(account.org, "Old Org");
|
||||
assert_eq!(account.key(), "acct-old|org-old");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_of_missing_oauth_is_default() {
|
||||
let account = account_of(&json!({ "numStartups": 1 }));
|
||||
assert_eq!(account, Account::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_of_malformed_oauth_is_default() {
|
||||
let account = account_of(&json!({ "oauthAccount": "not-an-object" }));
|
||||
assert_eq!(account, Account::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patch_round_trips_identity_and_backs_up() {
|
||||
let dir = temp_dir();
|
||||
let path = dir.join(".claude.json");
|
||||
fs::write(&path, sample_config().to_string()).unwrap();
|
||||
|
||||
let identity = extract_identity(&json!({
|
||||
"userID": "user-new",
|
||||
"oauthAccount": {
|
||||
"accountUuid": "acct-new",
|
||||
"organizationUuid": "org-new",
|
||||
"emailAddress": "new@example.com",
|
||||
"organizationName": "New Org"
|
||||
}
|
||||
}));
|
||||
patch(&path, &identity).unwrap();
|
||||
|
||||
let patched = load(&path).unwrap();
|
||||
assert_eq!(patched["userID"], json!("user-new"));
|
||||
assert_eq!(
|
||||
patched["oauthAccount"]["emailAddress"],
|
||||
json!("new@example.com")
|
||||
);
|
||||
// Unrelated keys preserved through the atomic rewrite.
|
||||
assert_eq!(patched["numStartups"], json!(7));
|
||||
|
||||
// A backup of the pre-patch file exists and holds the old identity.
|
||||
let backup = load(&backup_path(&path)).unwrap();
|
||||
assert_eq!(backup["userID"], json!("user-old"));
|
||||
|
||||
// The temp scratch file was renamed away, not left behind.
|
||||
assert!(!temp_path(&path).exists());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patch_missing_file_errors_before_backup() {
|
||||
let dir = temp_dir();
|
||||
let path = dir.join(".claude.json");
|
||||
assert!(patch(&path, &json!({ "userID": "x" })).is_err());
|
||||
assert!(!backup_path(&path).exists());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn patch_sets_owner_only_permissions() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = temp_dir();
|
||||
let path = dir.join(".claude.json");
|
||||
fs::write(&path, sample_config().to_string()).unwrap();
|
||||
patch(&path, &extract_identity(&sample_config())).unwrap();
|
||||
let mode = fs::metadata(&path).unwrap().permissions().mode();
|
||||
assert_eq!(mode & 0o777, 0o600);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
//! Credential port: reading and writing the Claude Code OAuth credential
|
||||
//! blob from the platform store.
|
||||
//!
|
||||
//! The [`CredentialStore`] trait and all decision logic (path selection,
|
||||
//! empty handling) live here, together with the file-based implementation
|
||||
//! used on Linux and Windows. The real macOS Keychain adapter, which shells
|
||||
//! out to the `security` binary, lives in [`crate::creds_shim`] and is
|
||||
//! excluded from coverage.
|
||||
|
||||
use crate::error::Result;
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Abstraction over the platform credential store holding the Claude Code
|
||||
/// OAuth credential blob.
|
||||
pub trait CredentialStore {
|
||||
/// Return the stored credential blob, or `None` when no credential is
|
||||
/// present (missing or empty).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the store cannot be read.
|
||||
fn read(&self) -> Result<Option<String>>;
|
||||
|
||||
/// Write `blob` into the store under account attribute `acct`.
|
||||
///
|
||||
/// The `acct` attribute is only meaningful for the macOS Keychain; the
|
||||
/// file store ignores it.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the store cannot be written.
|
||||
fn write(&self, blob: &str, acct: &str) -> Result<()>;
|
||||
|
||||
/// Return the account attribute the credential is stored under, or
|
||||
/// `None` when the store does not track one (the file store).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the store cannot be queried.
|
||||
fn account_attr(&self) -> Result<Option<String>>;
|
||||
}
|
||||
|
||||
/// File-based credential store: keeps the blob in
|
||||
/// `<config_dir>/.credentials.json`.
|
||||
///
|
||||
/// This is the fallback used on every platform other than macOS. It is pure
|
||||
/// filesystem I/O under a configurable directory, so it is unit-testable
|
||||
/// against a temporary directory without a shim.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FileStore {
|
||||
dir: PathBuf,
|
||||
}
|
||||
|
||||
impl FileStore {
|
||||
/// Create a store rooted at `config_dir`.
|
||||
pub fn new(config_dir: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
dir: config_dir.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of the credential file this store reads and writes.
|
||||
#[must_use]
|
||||
pub fn path(&self) -> PathBuf {
|
||||
self.dir.join(".credentials.json")
|
||||
}
|
||||
}
|
||||
|
||||
impl CredentialStore for FileStore {
|
||||
fn read(&self) -> Result<Option<String>> {
|
||||
match fs::read_to_string(self.path()) {
|
||||
Ok(blob) if blob.trim().is_empty() => Ok(None),
|
||||
Ok(blob) => Ok(Some(blob)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&self, blob: &str, _acct: &str) -> Result<()> {
|
||||
fs::create_dir_all(&self.dir)?;
|
||||
let path = self.path();
|
||||
fs::write(&path, blob)?;
|
||||
set_permissions_600(&path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn account_attr(&self) -> Result<Option<String>> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Tighten a file's permissions to owner read/write only.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn set_permissions_600(path: &Path) -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// No-op on platforms without Unix permission bits.
|
||||
#[cfg(not(unix))]
|
||||
pub(crate) fn set_permissions_600(_path: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tighten a directory's permissions to owner access only.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn set_permissions_700(path: &Path) -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// No-op on platforms without Unix permission bits.
|
||||
#[cfg(not(unix))]
|
||||
pub(crate) fn set_permissions_700(_path: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_dir() -> PathBuf {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let base = std::env::temp_dir().join(format!(
|
||||
"ccswitch-creds-{}-{}",
|
||||
std::process::id(),
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(&base).unwrap();
|
||||
base
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_is_credentials_json_under_dir() {
|
||||
let store = FileStore::new("/some/config/dir");
|
||||
assert_eq!(
|
||||
store.path(),
|
||||
PathBuf::from("/some/config/dir/.credentials.json")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_missing_file_is_none() {
|
||||
let dir = temp_dir();
|
||||
let store = FileStore::new(&dir);
|
||||
assert_eq!(store.read().unwrap(), None);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_empty_file_is_none() {
|
||||
let dir = temp_dir();
|
||||
let store = FileStore::new(&dir);
|
||||
fs::write(store.path(), " \n").unwrap();
|
||||
assert_eq!(store.read().unwrap(), None);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_then_read_round_trips() {
|
||||
let dir = temp_dir();
|
||||
let store = FileStore::new(&dir);
|
||||
store.write("{\"token\":\"abc\"}", "ignored").unwrap();
|
||||
assert_eq!(
|
||||
store.read().unwrap().as_deref(),
|
||||
Some("{\"token\":\"abc\"}")
|
||||
);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_creates_missing_parent_directory() {
|
||||
let dir = temp_dir();
|
||||
let nested = dir.join("deep/nested/config");
|
||||
let store = FileStore::new(&nested);
|
||||
store.write("blob", "").unwrap();
|
||||
assert!(nested.join(".credentials.json").exists());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn write_sets_owner_only_permissions() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = temp_dir();
|
||||
let store = FileStore::new(&dir);
|
||||
store.write("blob", "").unwrap();
|
||||
let mode = fs::metadata(store.path()).unwrap().permissions().mode();
|
||||
assert_eq!(mode & 0o777, 0o600);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_propagates_unexpected_error() {
|
||||
let dir = temp_dir();
|
||||
let store = FileStore::new(&dir);
|
||||
// Make the credential path a directory so reading it as a string
|
||||
// fails with an error other than "not found".
|
||||
fs::create_dir_all(store.path()).unwrap();
|
||||
assert!(store.read().is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_fails_when_dir_uncreatable() {
|
||||
// A directory nested under a regular file cannot be created.
|
||||
let dir = temp_dir();
|
||||
let blocker = dir.join("blocker");
|
||||
fs::write(&blocker, "x").unwrap();
|
||||
let store = FileStore::new(blocker.join("sub"));
|
||||
assert!(store.write("blob", "").is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_fails_when_target_is_directory() {
|
||||
let dir = temp_dir();
|
||||
let store = FileStore::new(&dir);
|
||||
// The credential path is a directory, so writing the blob fails.
|
||||
fs::create_dir_all(store.path()).unwrap();
|
||||
assert!(store.write("blob", "").is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn set_permissions_error_on_missing_path() {
|
||||
let dir = temp_dir();
|
||||
let missing = dir.join("nope");
|
||||
assert!(set_permissions_600(&missing).is_err());
|
||||
assert!(set_permissions_700(&missing).is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_attr_is_none_for_file_store() {
|
||||
let store = FileStore::new("/anywhere");
|
||||
assert_eq!(store.account_attr().unwrap(), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn set_permissions_700_tightens_directory() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = temp_dir();
|
||||
let nested = dir.join("locked");
|
||||
fs::create_dir_all(&nested).unwrap();
|
||||
set_permissions_700(&nested).unwrap();
|
||||
let mode = fs::metadata(&nested).unwrap().permissions().mode();
|
||||
assert_eq!(mode & 0o777, 0o700);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_is_debuggable_and_cloneable() {
|
||||
let store = FileStore::new("/x");
|
||||
let cloned = store.clone();
|
||||
assert_eq!(store.path(), cloned.path());
|
||||
assert!(format!("{store:?}").contains("FileStore"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Real credential-store adapter (macOS `security` binary).
|
||||
//!
|
||||
//! Side-effecting implementation of the [`crate::creds`] port. This is the
|
||||
//! only place in the crate that runs the `security` binary, and it is
|
||||
//! excluded from coverage. It contains no decision logic: platform selection
|
||||
//! is a single `cfg` switch and each method is a thin wrapper over one
|
||||
//! `security` invocation.
|
||||
|
||||
use crate::creds::CredentialStore;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use crate::creds::FileStore;
|
||||
#[cfg(target_os = "macos")]
|
||||
use crate::error::Error;
|
||||
use crate::error::Result;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Service name under which Claude Code stores its OAuth credential.
|
||||
#[cfg(target_os = "macos")]
|
||||
const SERVICE: &str = "Claude Code-credentials";
|
||||
|
||||
/// Select the credential store for the current platform: the macOS Keychain
|
||||
/// when available, otherwise the file-based fallback rooted at `config_dir`.
|
||||
#[must_use]
|
||||
pub fn platform_store(config_dir: PathBuf) -> Box<dyn CredentialStore> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let _ = config_dir;
|
||||
Box::new(KeychainStore)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
Box::new(FileStore::new(config_dir))
|
||||
}
|
||||
}
|
||||
|
||||
/// macOS Keychain credential store backed by the `security` binary.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub struct KeychainStore;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl CredentialStore for KeychainStore {
|
||||
fn read(&self) -> Result<Option<String>> {
|
||||
use std::process::Command;
|
||||
let output = Command::new("security")
|
||||
.args(["find-generic-password", "-s", SERVICE, "-w"])
|
||||
.output()?;
|
||||
if !output.status.success() {
|
||||
return Ok(None);
|
||||
}
|
||||
let blob = String::from_utf8_lossy(&output.stdout)
|
||||
.trim_end_matches('\n')
|
||||
.to_string();
|
||||
if blob.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(blob))
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&self, blob: &str, acct: &str) -> Result<()> {
|
||||
use std::process::Command;
|
||||
let acct = if acct.is_empty() {
|
||||
std::env::var("USER").unwrap_or_default()
|
||||
} else {
|
||||
acct.to_string()
|
||||
};
|
||||
let _ = Command::new("security")
|
||||
.args(["delete-generic-password", "-s", SERVICE])
|
||||
.output();
|
||||
let status = Command::new("security")
|
||||
.args([
|
||||
"add-generic-password",
|
||||
"-U",
|
||||
"-a",
|
||||
&acct,
|
||||
"-s",
|
||||
SERVICE,
|
||||
"-w",
|
||||
blob,
|
||||
])
|
||||
.status()?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Invalid("failed to write credential".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
fn account_attr(&self) -> Result<Option<String>> {
|
||||
use std::process::Command;
|
||||
let output = Command::new("security")
|
||||
.args(["find-generic-password", "-s", SERVICE, "-g"])
|
||||
.output()?;
|
||||
let text = String::from_utf8_lossy(&output.stderr);
|
||||
for line in text.lines() {
|
||||
if let Some(rest) = line.trim().strip_prefix("\"acct\"<blob>=\"") {
|
||||
if let Some(acct) = rest.strip_suffix('"') {
|
||||
return Ok(Some(acct.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! Error types shared across the crate.
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
/// Errors produced by `ccswitch` operations.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
/// A profile name was not found in the store.
|
||||
#[error("profile '{0}' not found")]
|
||||
ProfileNotFound(String),
|
||||
|
||||
/// A profile name collides with a reserved subcommand word.
|
||||
#[error("'{0}' is a reserved word, pick another profile name")]
|
||||
ReservedName(String),
|
||||
|
||||
/// A required input was missing or empty.
|
||||
#[error("{0}")]
|
||||
Invalid(String),
|
||||
|
||||
/// A wrapped I/O error.
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
|
||||
/// A wrapped JSON (de)serialization error.
|
||||
#[error(transparent)]
|
||||
Json(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
/// Convenience result alias used throughout the crate.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn displays_domain_variants() {
|
||||
assert_eq!(
|
||||
Error::ProfileNotFound("dev".to_string()).to_string(),
|
||||
"profile 'dev' not found"
|
||||
);
|
||||
assert_eq!(
|
||||
Error::ReservedName("list".to_string()).to_string(),
|
||||
"'list' is a reserved word, pick another profile name"
|
||||
);
|
||||
assert_eq!(
|
||||
Error::Invalid("bad input".to_string()).to_string(),
|
||||
"bad input"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wraps_io_errors() {
|
||||
let io = std::io::Error::new(std::io::ErrorKind::NotFound, "missing");
|
||||
let err: Error = io.into();
|
||||
assert!(format!("{err:?}").starts_with("Io"));
|
||||
assert!(err.to_string().contains("missing"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wraps_json_errors() {
|
||||
let json_err = serde_json::from_str::<i32>("not json").unwrap_err();
|
||||
let err: Error = json_err.into();
|
||||
assert!(format!("{err:?}").starts_with("Json"));
|
||||
assert!(!err.to_string().is_empty());
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
//! `ccswitch` — switch between multiple Claude Code accounts.
|
||||
//!
|
||||
//! This crate is organized with a ports-and-adapters layout: every real
|
||||
//! operating-system or network side effect lives behind a trait whose
|
||||
//! concrete implementation is in a `*_shim.rs` file (excluded from coverage),
|
||||
//! while all decision logic lives in the plain modules and is unit-tested
|
||||
//! with fakes.
|
||||
|
||||
pub mod cli;
|
||||
pub mod cli_shim;
|
||||
pub mod config;
|
||||
pub mod creds;
|
||||
pub mod creds_shim;
|
||||
pub mod error;
|
||||
pub mod model;
|
||||
pub mod store;
|
||||
pub mod switch;
|
||||
|
||||
pub use error::{Error, Result};
|
||||
pub use model::{Account, Profile};
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Thin binary entry point that delegates to the CLI adapter.
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
ccswitch::cli_shim::run()
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
//! Core data types describing Claude Code accounts and saved profiles.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Identity of a single Claude Code account within an organization.
|
||||
///
|
||||
/// A login can span multiple organizations, so an account is uniquely
|
||||
/// identified by the pair (`account_uuid`, `org_uuid`).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Account {
|
||||
/// Stable per-user account identifier (`oauthAccount.accountUuid`).
|
||||
#[serde(rename = "accountUuid", default)]
|
||||
pub account_uuid: String,
|
||||
|
||||
/// Organization identifier (`oauthAccount.organizationUuid`).
|
||||
#[serde(rename = "organizationUuid", default)]
|
||||
pub org_uuid: String,
|
||||
|
||||
/// Account email address (`oauthAccount.emailAddress`).
|
||||
#[serde(rename = "emailAddress", default)]
|
||||
pub email: String,
|
||||
|
||||
/// Human-readable organization name (`oauthAccount.organizationName`).
|
||||
#[serde(rename = "organizationName", default)]
|
||||
pub org: String,
|
||||
}
|
||||
|
||||
impl Account {
|
||||
/// The identity key used to compare two accounts for equality when
|
||||
/// deciding whether a profile is the currently active one.
|
||||
#[must_use]
|
||||
pub fn key(&self) -> String {
|
||||
format!("{}|{}", self.account_uuid, self.org_uuid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata persisted alongside a saved profile's credentials.
|
||||
///
|
||||
/// Mirrors the `account.json` file written for each profile: the account
|
||||
/// identity, the Claude Code `userID`, and the keychain account attribute
|
||||
/// used to restore the credential on macOS.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Profile {
|
||||
/// The account identity for this profile.
|
||||
#[serde(rename = "oauthAccount")]
|
||||
pub account: Account,
|
||||
|
||||
/// Claude Code's opaque user identifier.
|
||||
#[serde(rename = "userID", default, skip_serializing_if = "Option::is_none")]
|
||||
pub user_id: Option<String>,
|
||||
|
||||
/// The macOS keychain account attribute the credential was stored under.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub keychain_account: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_account() -> Account {
|
||||
Account {
|
||||
account_uuid: "acct-123".to_string(),
|
||||
org_uuid: "org-456".to_string(),
|
||||
email: "person@example.com".to_string(),
|
||||
org: "Example Org".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_key_joins_identity() {
|
||||
assert_eq!(sample_account().key(), "acct-123|org-456");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_round_trips_via_claude_field_names() {
|
||||
let json = r#"{
|
||||
"accountUuid": "acct-123",
|
||||
"organizationUuid": "org-456",
|
||||
"emailAddress": "person@example.com",
|
||||
"organizationName": "Example Org"
|
||||
}"#;
|
||||
let parsed: Account = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(parsed, sample_account());
|
||||
|
||||
let reserialized = serde_json::to_string(&parsed).unwrap();
|
||||
let reparsed: Account = serde_json::from_str(&reserialized).unwrap();
|
||||
assert_eq!(reparsed, parsed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_defaults_missing_fields() {
|
||||
let parsed: Account = serde_json::from_str("{}").unwrap();
|
||||
assert_eq!(parsed.key(), "|");
|
||||
assert!(parsed.email.is_empty());
|
||||
assert!(parsed.org.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_is_debuggable_and_cloneable() {
|
||||
let account = sample_account();
|
||||
let cloned = account.clone();
|
||||
assert_eq!(account, cloned);
|
||||
assert!(format!("{account:?}").contains("acct-123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_round_trips() {
|
||||
let profile = Profile {
|
||||
account: sample_account(),
|
||||
user_id: Some("user-789".to_string()),
|
||||
keychain_account: Some("login".to_string()),
|
||||
};
|
||||
let json = serde_json::to_string(&profile).unwrap();
|
||||
let parsed: Profile = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(parsed, profile);
|
||||
assert!(format!("{profile:?}").contains("user-789"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_omits_absent_optionals() {
|
||||
let profile = Profile {
|
||||
account: sample_account(),
|
||||
user_id: None,
|
||||
keychain_account: None,
|
||||
};
|
||||
let json = serde_json::to_string(&profile).unwrap();
|
||||
assert!(!json.contains("userID"));
|
||||
assert!(!json.contains("keychain_account"));
|
||||
|
||||
let parsed: Profile = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(parsed, profile);
|
||||
}
|
||||
}
|
||||
+715
@@ -0,0 +1,715 @@
|
||||
//! The on-disk profile store: enumerating, saving, and removing profiles
|
||||
//! under the accounts directory (`$CCSWITCH_HOME`, default
|
||||
//! `~/.claude/accounts`).
|
||||
//!
|
||||
//! Each profile is a directory holding two files:
|
||||
//!
|
||||
//! * `credentials.json` — the raw Claude Code OAuth credential blob, exactly
|
||||
//! as read from the platform credential store.
|
||||
//! * `account.json` — the identity snapshot `{oauthAccount, userID,
|
||||
//! keychain_account}` spliced out of `~/.claude.json`. The full
|
||||
//! `oauthAccount` object is preserved verbatim as JSON so that restoring a
|
||||
//! profile carries back every field (organizationUuid, tiers, onboarding
|
||||
//! flags, …), not just the handful this crate keys on.
|
||||
//!
|
||||
//! This is plain-file I/O under a configurable root, so it is unit-tested
|
||||
//! against a temporary directory with no shim.
|
||||
|
||||
use crate::config;
|
||||
use crate::creds::{set_permissions_600, set_permissions_700};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::model::Account;
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// File name of the credential blob within a profile directory.
|
||||
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.
|
||||
///
|
||||
/// 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.
|
||||
#[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.
|
||||
PerAccount,
|
||||
/// One credential per `(accountUuid, organizationUuid)` pair.
|
||||
PerAccountOrg,
|
||||
}
|
||||
|
||||
impl TokenScope {
|
||||
/// The key grouping profiles that share one credential under this scope.
|
||||
#[must_use]
|
||||
pub fn token_key(self, account: &Account) -> String {
|
||||
match self {
|
||||
TokenScope::PerAccount => account.account_uuid.clone(),
|
||||
TokenScope::PerAccountOrg => account.key(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `account` carries enough identity to select a token group.
|
||||
///
|
||||
/// An all-empty identity (no `accountUuid`, no `organizationUuid`) matches
|
||||
/// nothing, so credential propagation is skipped rather than blindly
|
||||
/// overwriting every profile.
|
||||
#[must_use]
|
||||
pub fn identifies(self, account: &Account) -> bool {
|
||||
match self {
|
||||
TokenScope::PerAccount => !account.account_uuid.is_empty(),
|
||||
TokenScope::PerAccountOrg => {
|
||||
!account.account_uuid.is_empty() || !account.org_uuid.is_empty()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A profile loaded from disk: its credential blob and identity snapshot.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StoredProfile {
|
||||
/// The raw OAuth credential blob (`credentials.json`).
|
||||
pub credentials: String,
|
||||
/// The identity snapshot object (`account.json`).
|
||||
pub account: Value,
|
||||
}
|
||||
|
||||
impl StoredProfile {
|
||||
/// The account identity keyed on, parsed out of the snapshot.
|
||||
#[must_use]
|
||||
pub fn account(&self) -> Account {
|
||||
config::account_of(&self.account)
|
||||
}
|
||||
|
||||
/// The `{oauthAccount, userID}` slice to splice back into `~/.claude.json`.
|
||||
#[must_use]
|
||||
pub fn identity(&self) -> Value {
|
||||
config::extract_identity(&self.account)
|
||||
}
|
||||
|
||||
/// The keychain account attribute the credential should be restored under.
|
||||
#[must_use]
|
||||
pub fn keychain_account(&self) -> String {
|
||||
self.account
|
||||
.get("keychain_account")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// A profile listed by name alongside its parsed identity.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProfileSummary {
|
||||
/// The profile's directory name.
|
||||
pub name: String,
|
||||
/// The account identity read from its `account.json`.
|
||||
pub account: Account,
|
||||
}
|
||||
|
||||
/// The profile store rooted at a single directory.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Store {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
/// Create a store rooted at `root` (the `$CCSWITCH_HOME` directory).
|
||||
pub fn new(root: impl Into<PathBuf>) -> Self {
|
||||
Self { root: root.into() }
|
||||
}
|
||||
|
||||
/// The store's root directory.
|
||||
#[must_use]
|
||||
pub fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// The directory holding profile `name`.
|
||||
#[must_use]
|
||||
pub fn profile_dir(&self, name: &str) -> PathBuf {
|
||||
self.root.join(name)
|
||||
}
|
||||
|
||||
fn credentials_path(&self, name: &str) -> PathBuf {
|
||||
self.profile_dir(name).join(CREDENTIALS_FILE)
|
||||
}
|
||||
|
||||
fn account_path(&self, name: &str) -> PathBuf {
|
||||
self.profile_dir(name).join(ACCOUNT_FILE)
|
||||
}
|
||||
|
||||
/// Whether a profile directory named `name` already exists.
|
||||
#[must_use]
|
||||
pub fn contains(&self, name: &str) -> bool {
|
||||
self.profile_dir(name).exists()
|
||||
}
|
||||
|
||||
/// Create the profile directory (and the root) with owner-only perms.
|
||||
fn ensure_dir(&self, name: &str) -> Result<PathBuf> {
|
||||
let dir = self.profile_dir(name);
|
||||
fs::create_dir_all(&dir)?;
|
||||
set_permissions_700(&self.root)?;
|
||||
set_permissions_700(&dir)?;
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// Write only the credential blob of profile `name`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the directory or file cannot be created/written.
|
||||
pub fn write_credentials(&self, name: &str, blob: &str) -> Result<()> {
|
||||
self.ensure_dir(name)?;
|
||||
let path = self.credentials_path(name);
|
||||
fs::write(&path, blob)?;
|
||||
set_permissions_600(&path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write only the identity snapshot of profile `name`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the directory or file cannot be created/written.
|
||||
pub fn write_account(&self, name: &str, account: &Value) -> Result<()> {
|
||||
self.ensure_dir(name)?;
|
||||
let path = self.account_path(name);
|
||||
let text = serde_json::to_string_pretty(account)?;
|
||||
fs::write(&path, text)?;
|
||||
set_permissions_600(&path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Save both files of a profile in one step.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if either file cannot be written.
|
||||
pub fn save_profile(&self, name: &str, blob: &str, account: &Value) -> Result<()> {
|
||||
self.write_credentials(name, blob)?;
|
||||
self.write_account(name, account)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Load profile `name`, both files.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::ProfileNotFound`] when no such directory exists, or
|
||||
/// [`Error::Invalid`] when the directory is missing one of its two files.
|
||||
pub fn load(&self, name: &str) -> Result<StoredProfile> {
|
||||
if !self.contains(name) {
|
||||
return Err(Error::ProfileNotFound(name.to_string()));
|
||||
}
|
||||
let credentials = self.load_credentials(name)?;
|
||||
let account_text = read_required(&self.account_path(name), name)?;
|
||||
let account = serde_json::from_str(&account_text)?;
|
||||
Ok(StoredProfile {
|
||||
credentials,
|
||||
account,
|
||||
})
|
||||
}
|
||||
|
||||
/// Load just the credential blob of profile `name`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::ProfileNotFound`] when the directory is absent, or
|
||||
/// [`Error::Invalid`] when the directory exists without a credential file.
|
||||
pub fn load_credentials(&self, name: &str) -> Result<String> {
|
||||
if !self.contains(name) {
|
||||
return Err(Error::ProfileNotFound(name.to_string()));
|
||||
}
|
||||
read_required(&self.credentials_path(name), name)
|
||||
}
|
||||
|
||||
/// List every saved profile (directories with an `account.json`), sorted
|
||||
/// by name.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the root cannot be read (other than being absent,
|
||||
/// which yields an empty list) or a snapshot is not valid JSON.
|
||||
pub fn list(&self) -> Result<Vec<ProfileSummary>> {
|
||||
let entries = match fs::read_dir(&self.root) {
|
||||
Ok(entries) => entries,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(err) => return Err(err.into()),
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
if !entry.file_type()?.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let account_text = match fs::read_to_string(self.account_path(&name)) {
|
||||
Ok(text) => text,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err.into()),
|
||||
};
|
||||
let snapshot: Value = serde_json::from_str(&account_text)?;
|
||||
out.push(ProfileSummary {
|
||||
name,
|
||||
account: config::account_of(&snapshot),
|
||||
});
|
||||
}
|
||||
out.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Every profile that shares a rotating credential with `active` under
|
||||
/// `scope`.
|
||||
///
|
||||
/// With [`TokenScope::PerAccount`] this returns *all* profiles of the same
|
||||
/// login regardless of org — the set that must be kept in lockstep so a
|
||||
/// rotation under one org does not strand the others. An identity that
|
||||
/// does not [`TokenScope::identifies`] anything yields an empty list.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the store cannot be listed.
|
||||
pub fn profiles_sharing_token(
|
||||
&self,
|
||||
active: &Account,
|
||||
scope: TokenScope,
|
||||
) -> Result<Vec<ProfileSummary>> {
|
||||
if !scope.identifies(active) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let key = scope.token_key(active);
|
||||
Ok(self
|
||||
.list()?
|
||||
.into_iter()
|
||||
.filter(|summary| {
|
||||
scope.identifies(&summary.account) && scope.token_key(&summary.account) == key
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Remove profile `name` and all of its files.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::ProfileNotFound`] when no such directory exists.
|
||||
pub fn remove(&self, name: &str) -> Result<()> {
|
||||
if !self.contains(name) {
|
||||
return Err(Error::ProfileNotFound(name.to_string()));
|
||||
}
|
||||
fs::remove_dir_all(self.profile_dir(name))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a file that a profile is required to have, mapping a missing file to
|
||||
/// an "incomplete profile" error rather than a bare I/O error.
|
||||
fn read_required(path: &Path, name: &str) -> Result<String> {
|
||||
match fs::read_to_string(path) {
|
||||
Ok(text) => Ok(text),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => {
|
||||
Err(Error::Invalid(format!("profile '{name}' is incomplete")))
|
||||
}
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn temp_dir() -> PathBuf {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let base = std::env::temp_dir().join(format!(
|
||||
"ccswitch-store-{}-{}",
|
||||
std::process::id(),
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(&base).unwrap();
|
||||
base
|
||||
}
|
||||
|
||||
fn account_snapshot(acct: &str, org: &str, email: &str) -> Value {
|
||||
json!({
|
||||
"oauthAccount": {
|
||||
"accountUuid": acct,
|
||||
"organizationUuid": org,
|
||||
"emailAddress": email,
|
||||
"organizationName": "Org",
|
||||
"organizationRole": "admin"
|
||||
},
|
||||
"userID": "user-hash",
|
||||
"keychain_account": "login-attr"
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_scope_keys_group_by_scope() {
|
||||
let account = Account {
|
||||
account_uuid: "A".to_string(),
|
||||
org_uuid: "O".to_string(),
|
||||
..Account::default()
|
||||
};
|
||||
assert_eq!(TokenScope::PerAccount.token_key(&account), "A");
|
||||
assert_eq!(TokenScope::PerAccountOrg.token_key(&account), "A|O");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_scope_identifies_requires_identity() {
|
||||
let empty = Account::default();
|
||||
assert!(!TokenScope::PerAccount.identifies(&empty));
|
||||
assert!(!TokenScope::PerAccountOrg.identifies(&empty));
|
||||
|
||||
let only_org = Account {
|
||||
org_uuid: "O".to_string(),
|
||||
..Account::default()
|
||||
};
|
||||
assert!(!TokenScope::PerAccount.identifies(&only_org));
|
||||
assert!(TokenScope::PerAccountOrg.identifies(&only_org));
|
||||
|
||||
let with_acct = Account {
|
||||
account_uuid: "A".to_string(),
|
||||
..Account::default()
|
||||
};
|
||||
assert!(TokenScope::PerAccount.identifies(&with_acct));
|
||||
assert!(TokenScope::PerAccountOrg.identifies(&with_acct));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_scope_is_copy_and_debuggable() {
|
||||
let scope = TokenScope::PerAccount;
|
||||
let copied = scope;
|
||||
assert_eq!(scope, copied);
|
||||
assert!(format!("{scope:?}").contains("PerAccount"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_are_under_root() {
|
||||
let store = Store::new("/root");
|
||||
assert_eq!(store.root(), Path::new("/root"));
|
||||
assert_eq!(store.profile_dir("dev"), PathBuf::from("/root/dev"));
|
||||
assert_eq!(
|
||||
store.credentials_path("dev"),
|
||||
PathBuf::from("/root/dev/credentials.json")
|
||||
);
|
||||
assert_eq!(
|
||||
store.account_path("dev"),
|
||||
PathBuf::from("/root/dev/account.json")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_is_cloneable_and_debuggable() {
|
||||
let store = Store::new("/root");
|
||||
let cloned = store.clone();
|
||||
assert_eq!(store.root(), cloned.root());
|
||||
assert!(format!("{store:?}").contains("Store"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_then_load_round_trips_both_files() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
let snapshot = account_snapshot("A", "O", "a@example.com");
|
||||
store.save_profile("dev", "BLOB", &snapshot).unwrap();
|
||||
|
||||
assert!(store.contains("dev"));
|
||||
let loaded = store.load("dev").unwrap();
|
||||
assert_eq!(loaded.credentials, "BLOB");
|
||||
assert_eq!(loaded.account, snapshot);
|
||||
// The full oauthAccount object is preserved, not just keyed fields.
|
||||
assert_eq!(
|
||||
loaded.account["oauthAccount"]["organizationRole"],
|
||||
json!("admin")
|
||||
);
|
||||
assert_eq!(loaded.account().account_uuid, "A");
|
||||
assert_eq!(loaded.identity()["userID"], json!("user-hash"));
|
||||
assert_eq!(loaded.keychain_account(), "login-attr");
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_profile_keychain_account_defaults_empty() {
|
||||
let profile = StoredProfile {
|
||||
credentials: "x".to_string(),
|
||||
account: json!({ "oauthAccount": {} }),
|
||||
};
|
||||
assert_eq!(profile.keychain_account(), "");
|
||||
assert_eq!(
|
||||
profile,
|
||||
StoredProfile {
|
||||
credentials: "x".to_string(),
|
||||
account: json!({ "oauthAccount": {} }),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn saved_files_and_dirs_have_tight_permissions() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
store
|
||||
.save_profile("dev", "BLOB", &account_snapshot("A", "O", "a@x"))
|
||||
.unwrap();
|
||||
let mode = |p: PathBuf| fs::metadata(p).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode(store.profile_dir("dev")), 0o700);
|
||||
assert_eq!(mode(store.credentials_path("dev")), 0o600);
|
||||
assert_eq!(mode(store.account_path("dev")), 0o600);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_missing_profile_is_not_found() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
assert!(matches!(
|
||||
store.load("ghost"),
|
||||
Err(Error::ProfileNotFound(name)) if name == "ghost"
|
||||
));
|
||||
assert!(matches!(
|
||||
store.load_credentials("ghost"),
|
||||
Err(Error::ProfileNotFound(_))
|
||||
));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_unreadable_root_errors() {
|
||||
// A root that is a file (not a directory) surfaces a read_dir error
|
||||
// other than "not found".
|
||||
let dir = temp_dir();
|
||||
let file_root = dir.join("iam-a-file");
|
||||
fs::write(&file_root, "x").unwrap();
|
||||
let store = Store::new(&file_root);
|
||||
assert!(store.list().is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_unreadable_account_errors() {
|
||||
// An account.json that is a directory fails to read as a string with
|
||||
// an error other than "not found".
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
fs::create_dir_all(store.account_path("dev")).unwrap();
|
||||
assert!(store.list().is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_credentials_unreadable_file_errors() {
|
||||
// A credentials.json that is a directory hits the non-NotFound arm of
|
||||
// the required-file reader.
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
fs::create_dir_all(store.credentials_path("dev")).unwrap();
|
||||
// Give it an account.json so the directory counts as a profile.
|
||||
store
|
||||
.write_account("dev", &account_snapshot("A", "O", "a@x"))
|
||||
.unwrap();
|
||||
assert!(store.load_credentials("dev").is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_incomplete_profile_errors() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
// Directory exists with only the account file, no credentials.
|
||||
store
|
||||
.write_account("dev", &account_snapshot("A", "O", "a@x"))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
store.load_credentials("dev"),
|
||||
Err(Error::Invalid(msg)) if msg.contains("incomplete")
|
||||
));
|
||||
assert!(matches!(store.load("dev"), Err(Error::Invalid(_))));
|
||||
|
||||
// And with only credentials, no account file.
|
||||
let store2 = Store::new(dir.join("other"));
|
||||
store2.write_credentials("dev", "BLOB").unwrap();
|
||||
assert!(matches!(store2.load("dev"), Err(Error::Invalid(_))));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_malformed_account_json_errors() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
store.write_credentials("dev", "blob").unwrap();
|
||||
fs::write(store.account_path("dev"), "{not json").unwrap();
|
||||
assert!(store.load("dev").is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_fails_when_directory_uncreatable() {
|
||||
// Rooting the store under a regular file makes the profile directory
|
||||
// impossible to create.
|
||||
let dir = temp_dir();
|
||||
let blocker = dir.join("blocker");
|
||||
fs::write(&blocker, "x").unwrap();
|
||||
let store = Store::new(&blocker);
|
||||
assert!(store.write_credentials("dev", "blob").is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_credentials_fails_when_target_is_directory() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
fs::create_dir_all(store.credentials_path("dev")).unwrap();
|
||||
assert!(store.write_credentials("dev", "blob").is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_account_fails_when_target_is_directory() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
fs::create_dir_all(store.account_path("dev")).unwrap();
|
||||
assert!(store.write_account("dev", &json!({})).is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_empty_root_is_empty() {
|
||||
let dir = temp_dir();
|
||||
let missing = dir.join("nope");
|
||||
let store = Store::new(&missing);
|
||||
assert!(store.list().unwrap().is_empty());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_skips_non_dirs_and_dirs_without_account() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
store
|
||||
.save_profile("bravo", "b", &account_snapshot("B", "O", "b@x"))
|
||||
.unwrap();
|
||||
store
|
||||
.save_profile("alpha", "a", &account_snapshot("A", "O", "a@x"))
|
||||
.unwrap();
|
||||
// A stray file at the root is not a profile.
|
||||
fs::write(dir.join("loose.txt"), "junk").unwrap();
|
||||
// A directory without an account.json is not a profile.
|
||||
fs::create_dir_all(dir.join("half")).unwrap();
|
||||
|
||||
let names: Vec<String> = store.list().unwrap().into_iter().map(|s| s.name).collect();
|
||||
assert_eq!(names, vec!["alpha".to_string(), "bravo".to_string()]);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_malformed_account_json_errors() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
fs::create_dir_all(store.profile_dir("dev")).unwrap();
|
||||
fs::write(store.account_path("dev"), "{not json").unwrap();
|
||||
assert!(store.list().is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profiles_sharing_token_groups_by_account_under_per_account() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
// Two orgs of one login, plus an unrelated account.
|
||||
store
|
||||
.save_profile("orga", "t", &account_snapshot("A", "O1", "a@x"))
|
||||
.unwrap();
|
||||
store
|
||||
.save_profile("orgb", "t", &account_snapshot("A", "O2", "a@x"))
|
||||
.unwrap();
|
||||
store
|
||||
.save_profile("other", "t", &account_snapshot("Z", "O9", "z@x"))
|
||||
.unwrap();
|
||||
|
||||
let active = Account {
|
||||
account_uuid: "A".to_string(),
|
||||
org_uuid: "O1".to_string(),
|
||||
..Account::default()
|
||||
};
|
||||
|
||||
let per_account: Vec<String> = store
|
||||
.profiles_sharing_token(&active, TokenScope::PerAccount)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|s| s.name)
|
||||
.collect();
|
||||
assert_eq!(per_account, vec!["orga".to_string(), "orgb".to_string()]);
|
||||
|
||||
let per_org: Vec<String> = store
|
||||
.profiles_sharing_token(&active, TokenScope::PerAccountOrg)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|s| s.name)
|
||||
.collect();
|
||||
assert_eq!(per_org, vec!["orga".to_string()]);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profiles_sharing_token_empty_identity_matches_nothing() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
store
|
||||
.save_profile("orga", "t", &account_snapshot("A", "O1", "a@x"))
|
||||
.unwrap();
|
||||
let empty = Account::default();
|
||||
assert!(store
|
||||
.profiles_sharing_token(&empty, TokenScope::PerAccount)
|
||||
.unwrap()
|
||||
.is_empty());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_deletes_profile() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
store
|
||||
.save_profile("dev", "t", &account_snapshot("A", "O", "a@x"))
|
||||
.unwrap();
|
||||
assert!(store.contains("dev"));
|
||||
store.remove("dev").unwrap();
|
||||
assert!(!store.contains("dev"));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_missing_profile_is_not_found() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(&dir);
|
||||
assert!(matches!(
|
||||
store.remove("ghost"),
|
||||
Err(Error::ProfileNotFound(_))
|
||||
));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_summary_is_debuggable_and_cloneable() {
|
||||
let summary = ProfileSummary {
|
||||
name: "dev".to_string(),
|
||||
account: Account::default(),
|
||||
};
|
||||
let cloned = summary.clone();
|
||||
assert_eq!(summary, cloned);
|
||||
assert!(format!("{summary:?}").contains("dev"));
|
||||
}
|
||||
}
|
||||
+625
@@ -0,0 +1,625 @@
|
||||
//! Account-switching orchestration: tying the credential store, the
|
||||
//! `~/.claude.json` config, and the profile store together to save and
|
||||
//! activate profiles.
|
||||
//!
|
||||
//! This is pure decision logic composed over the [`crate::creds`],
|
||||
//! [`crate::config`], and [`crate::store`] ports, so it is unit-tested with a
|
||||
//! fake credential store and temp directories — no real Keychain or process
|
||||
//! spawning involved.
|
||||
//!
|
||||
//! ## The auth-loss fix
|
||||
//!
|
||||
//! 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.
|
||||
//!
|
||||
//! [`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.
|
||||
|
||||
use crate::config;
|
||||
use crate::creds::CredentialStore;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::model::Account;
|
||||
use crate::store::{Store, TokenScope};
|
||||
use serde_json::{json, Value};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Orchestrates saving and activating profiles over the three ports.
|
||||
pub struct Switcher<'a> {
|
||||
creds: &'a dyn CredentialStore,
|
||||
store: &'a Store,
|
||||
config_path: PathBuf,
|
||||
scope: TokenScope,
|
||||
}
|
||||
|
||||
impl<'a> Switcher<'a> {
|
||||
/// Build a switcher over a credential store, a profile store, the path to
|
||||
/// `~/.claude.json`, and the token-sharing scope that drives the fix.
|
||||
pub fn new(
|
||||
creds: &'a dyn CredentialStore,
|
||||
store: &'a Store,
|
||||
config_path: impl Into<PathBuf>,
|
||||
scope: TokenScope,
|
||||
) -> Self {
|
||||
Self {
|
||||
creds,
|
||||
store,
|
||||
config_path: config_path.into(),
|
||||
scope,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `~/.claude.json` path this switcher operates on.
|
||||
#[must_use]
|
||||
pub fn config_path(&self) -> &Path {
|
||||
&self.config_path
|
||||
}
|
||||
|
||||
/// Snapshot the live account into profile `name`.
|
||||
///
|
||||
/// Reads the active credential blob, the keychain account attribute, and
|
||||
/// the `{oauthAccount, userID}` identity out of `~/.claude.json`, and
|
||||
/// writes them into the profile.
|
||||
///
|
||||
/// If a profile of that name already exists this errors unless `force` is
|
||||
/// set, in which case it is overwritten (the `--force` behavior).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::Invalid`] when the profile exists and `force` is
|
||||
/// false, or when there is no active credential to snapshot; propagates
|
||||
/// config-read and store-write errors otherwise.
|
||||
pub fn save(&self, name: &str, force: bool) -> Result<Account> {
|
||||
if self.store.contains(name) && !force {
|
||||
return Err(Error::Invalid(format!(
|
||||
"profile '{name}' already exists (pass --force to overwrite)"
|
||||
)));
|
||||
}
|
||||
let blob = self.creds.read()?.ok_or_else(|| {
|
||||
Error::Invalid("no active credential found — sign in with 'claude' first".to_string())
|
||||
})?;
|
||||
let config = config::load(&self.config_path)?;
|
||||
let snapshot = self.identity_snapshot(&config)?;
|
||||
self.store.save_profile(name, &blob, &snapshot)?;
|
||||
Ok(config::account_of(&config))
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::ProfileNotFound`] / [`Error::Invalid`] when the target
|
||||
/// profile is missing or incomplete; propagates credential, config, and
|
||||
/// store errors otherwise.
|
||||
pub fn activate(&self, name: &str) -> Result<Account> {
|
||||
// Validate the target up front so a missing/incomplete profile fails
|
||||
// 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.
|
||||
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.
|
||||
let blob = self.store.load_credentials(name)?;
|
||||
self.creds.write(&blob, &target.keychain_account())?;
|
||||
|
||||
// Splice this profile's identity (incl. organizationUuid) into
|
||||
// ~/.claude.json, preserving all unrelated keys.
|
||||
config::patch(&self.config_path, &target.identity())?;
|
||||
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.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Propagates store-write errors.
|
||||
pub fn sync_current(&self) -> Result<()> {
|
||||
let Ok(config) = config::load(&self.config_path) else {
|
||||
return Ok(());
|
||||
};
|
||||
let active = config::account_of(&config);
|
||||
if !self.scope.identifies(&active) {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(blob) = self.creds.read()? else {
|
||||
return Ok(());
|
||||
};
|
||||
let live_snapshot = self.identity_snapshot(&config)?;
|
||||
let active_key = active.key();
|
||||
|
||||
for shared in self.store.profiles_sharing_token(&active, self.scope)? {
|
||||
// Every sibling gets the freshly rotated credential...
|
||||
self.store.write_credentials(&shared.name, &blob)?;
|
||||
// ...but only the profile whose (account, org) *is* the live one
|
||||
// gets its identity snapshot refreshed. A sibling for a different
|
||||
// org must keep its own organizationUuid.
|
||||
if shared.account.key() == active_key {
|
||||
self.store.write_account(&shared.name, &live_snapshot)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build the `{oauthAccount, userID, keychain_account}` snapshot stored in
|
||||
/// a profile's `account.json` from a loaded config and the current
|
||||
/// keychain account attribute.
|
||||
fn identity_snapshot(&self, config: &Value) -> Result<Value> {
|
||||
let keychain_account = self.creds.account_attr()?.unwrap_or_default();
|
||||
let mut snapshot = config::extract_identity(config);
|
||||
if let Some(obj) = snapshot.as_object_mut() {
|
||||
obj.insert("keychain_account".to_string(), json!(keychain_account));
|
||||
}
|
||||
Ok(snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// In-memory fake of the platform credential store.
|
||||
struct FakeCredentialStore {
|
||||
blob: RefCell<Option<String>>,
|
||||
acct: Option<String>,
|
||||
fail_read: bool,
|
||||
fail_write: bool,
|
||||
fail_acct: bool,
|
||||
}
|
||||
|
||||
impl FakeCredentialStore {
|
||||
fn with(blob: Option<&str>, acct: Option<&str>) -> Self {
|
||||
Self {
|
||||
blob: RefCell::new(blob.map(str::to_string)),
|
||||
acct: acct.map(str::to_string),
|
||||
fail_read: false,
|
||||
fail_write: false,
|
||||
fail_acct: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CredentialStore for FakeCredentialStore {
|
||||
fn read(&self) -> Result<Option<String>> {
|
||||
if self.fail_read {
|
||||
return Err(Error::Invalid("read failed".to_string()));
|
||||
}
|
||||
Ok(self.blob.borrow().clone())
|
||||
}
|
||||
|
||||
fn write(&self, blob: &str, _acct: &str) -> Result<()> {
|
||||
if self.fail_write {
|
||||
return Err(Error::Invalid("write failed".to_string()));
|
||||
}
|
||||
*self.blob.borrow_mut() = Some(blob.to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn account_attr(&self) -> Result<Option<String>> {
|
||||
if self.fail_acct {
|
||||
return Err(Error::Invalid("account_attr failed".to_string()));
|
||||
}
|
||||
Ok(self.acct.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir() -> PathBuf {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let base = std::env::temp_dir().join(format!(
|
||||
"ccswitch-switch-{}-{}",
|
||||
std::process::id(),
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(&base).unwrap();
|
||||
base
|
||||
}
|
||||
|
||||
fn config_json(acct: &str, org: &str, email: &str, user: &str) -> Value {
|
||||
json!({
|
||||
"numStartups": 3,
|
||||
"userID": user,
|
||||
"oauthAccount": {
|
||||
"accountUuid": acct,
|
||||
"organizationUuid": org,
|
||||
"emailAddress": email,
|
||||
"organizationName": "Org",
|
||||
"organizationRole": "admin",
|
||||
"profileFetchedAt": "yesterday"
|
||||
},
|
||||
"projects": { "/x": { "allowedTools": [] } }
|
||||
})
|
||||
}
|
||||
|
||||
fn write_config(dir: &Path, value: &Value) -> PathBuf {
|
||||
let path = dir.join(".claude.json");
|
||||
fs::write(&path, serde_json::to_string_pretty(value).unwrap()).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
// ---- save --------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn save_new_profile_snapshots_live_state() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &config_json("A", "O1", "a@example.com", "uid-1"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let creds = FakeCredentialStore::with(Some("BLOB-1"), Some("login-attr"));
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
|
||||
let account = switcher.save("orga", false).unwrap();
|
||||
assert_eq!(account.email, "a@example.com");
|
||||
assert_eq!(switcher.config_path(), config);
|
||||
|
||||
let loaded = store.load("orga").unwrap();
|
||||
assert_eq!(loaded.credentials, "BLOB-1");
|
||||
assert_eq!(loaded.keychain_account(), "login-attr");
|
||||
assert_eq!(loaded.account().org_uuid, "O1");
|
||||
assert_eq!(loaded.account.get("userID").unwrap(), &json!("uid-1"));
|
||||
// The full oauthAccount is preserved, not just keyed fields.
|
||||
assert_eq!(
|
||||
loaded.account["oauthAccount"]["profileFetchedAt"],
|
||||
json!("yesterday")
|
||||
);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_existing_without_force_errors() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-1"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let creds = FakeCredentialStore::with(Some("BLOB-1"), None);
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
|
||||
switcher.save("orga", false).unwrap();
|
||||
let err = switcher.save("orga", false).unwrap_err();
|
||||
assert!(matches!(err, Error::Invalid(msg) if msg.contains("already exists")));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_existing_with_force_overwrites() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-1"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let creds = FakeCredentialStore::with(Some("BLOB-1"), None);
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
switcher.save("orga", false).unwrap();
|
||||
|
||||
// A newer credential arrives; force overwrites the stored snapshot.
|
||||
*creds.blob.borrow_mut() = Some("BLOB-2".to_string());
|
||||
switcher.save("orga", true).unwrap();
|
||||
assert_eq!(store.load("orga").unwrap().credentials, "BLOB-2");
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_without_credential_errors() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-1"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let creds = FakeCredentialStore::with(None, None);
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
let err = switcher.save("orga", false).unwrap_err();
|
||||
assert!(matches!(err, Error::Invalid(msg) if msg.contains("no active credential")));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_propagates_credential_read_error() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-1"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let mut creds = FakeCredentialStore::with(Some("BLOB"), None);
|
||||
creds.fail_read = true;
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
assert!(switcher.save("orga", false).is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_propagates_account_attr_error() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-1"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let mut creds = FakeCredentialStore::with(Some("BLOB"), None);
|
||||
creds.fail_acct = true;
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
assert!(switcher.save("orga", false).is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_missing_config_errors() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let creds = FakeCredentialStore::with(Some("BLOB"), None);
|
||||
let switcher = Switcher::new(
|
||||
&creds,
|
||||
&store,
|
||||
dir.join(".claude.json"),
|
||||
TokenScope::PerAccount,
|
||||
);
|
||||
assert!(switcher.save("orga", false).is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
// ---- activate ----------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn activate_restores_credential_and_identity() {
|
||||
let dir = temp_dir();
|
||||
// Live account is B/OB; we switch to a saved A/OA profile.
|
||||
let config = write_config(&dir, &config_json("B", "OB", "b@example.com", "uid-b"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let creds = FakeCredentialStore::with(Some("LIVE-B"), Some("attr-b"));
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
|
||||
// Seed a saved profile for a different account.
|
||||
store
|
||||
.save_profile(
|
||||
"orga",
|
||||
"TOKEN-A",
|
||||
&json!({
|
||||
"oauthAccount": {
|
||||
"accountUuid": "A",
|
||||
"organizationUuid": "OA",
|
||||
"emailAddress": "a@example.com",
|
||||
"organizationName": "Org A"
|
||||
},
|
||||
"userID": "uid-a",
|
||||
"keychain_account": "attr-a"
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let account = switcher.activate("orga").unwrap();
|
||||
assert_eq!(account.email, "a@example.com");
|
||||
|
||||
// Credential store now holds profile A's token.
|
||||
assert_eq!(creds.blob.borrow().as_deref(), Some("TOKEN-A"));
|
||||
// Config identity was spliced to A/OA, unrelated keys preserved.
|
||||
let patched = config::load(&config).unwrap();
|
||||
assert_eq!(patched["oauthAccount"]["accountUuid"], json!("A"));
|
||||
assert_eq!(patched["oauthAccount"]["organizationUuid"], json!("OA"));
|
||||
assert_eq!(patched["userID"], json!("uid-a"));
|
||||
assert_eq!(patched["numStartups"], json!(3));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn activate_missing_profile_errors_without_touching_state() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &config_json("A", "OA", "a@x", "uid-a"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let creds = FakeCredentialStore::with(Some("LIVE"), None);
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
assert!(matches!(
|
||||
switcher.activate("ghost"),
|
||||
Err(Error::ProfileNotFound(_))
|
||||
));
|
||||
// Live credential untouched.
|
||||
assert_eq!(creds.blob.borrow().as_deref(), Some("LIVE"));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn activate_propagates_credential_write_error() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &config_json("B", "OB", "b@x", "uid-b"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
store
|
||||
.save_profile(
|
||||
"orga",
|
||||
"TOKEN-A",
|
||||
&json!({
|
||||
"oauthAccount": { "accountUuid": "A", "organizationUuid": "OA" },
|
||||
"userID": "uid-a",
|
||||
"keychain_account": "attr-a"
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
let mut creds = FakeCredentialStore::with(Some("LIVE-B"), Some("attr-b"));
|
||||
creds.fail_write = true;
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
assert!(switcher.activate("orga").is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
// ---- the rotation fix --------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn rotated_token_propagates_to_all_sibling_org_profiles() {
|
||||
let dir = temp_dir();
|
||||
// Two profiles: same account A, different orgs O1 and O2.
|
||||
// Active account is A/O1; both were saved with the same original token.
|
||||
let config = write_config(&dir, &config_json("A", "O1", "a@example.com", "uid-a"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
|
||||
let snap = |org: &str| {
|
||||
json!({
|
||||
"oauthAccount": {
|
||||
"accountUuid": "A",
|
||||
"organizationUuid": org,
|
||||
"emailAddress": "a@example.com",
|
||||
"organizationName": org
|
||||
},
|
||||
"userID": "uid-a",
|
||||
"keychain_account": "attr-a"
|
||||
})
|
||||
};
|
||||
store.save_profile("orga", "R-OLD", &snap("O1")).unwrap();
|
||||
store.save_profile("orgb", "R-OLD", &snap("O2")).unwrap();
|
||||
|
||||
// The live credential has since rotated (claude ran under O1).
|
||||
let creds = FakeCredentialStore::with(Some("R-NEW"), Some("attr-a"));
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
|
||||
// Switch to the sibling org profile.
|
||||
switcher.activate("orgb").unwrap();
|
||||
|
||||
// THE FIX: both same-account profiles now hold the rotated token, not
|
||||
// just the one matching the live (account, org) key.
|
||||
assert_eq!(store.load_credentials("orga").unwrap(), "R-NEW");
|
||||
assert_eq!(store.load_credentials("orgb").unwrap(), "R-NEW");
|
||||
|
||||
// orga keeps its own org identity (not overwritten with O2's live one).
|
||||
assert_eq!(store.load("orga").unwrap().account().org_uuid, "O1");
|
||||
|
||||
// The credential restored into the live store is the current token, so
|
||||
// switching to orgb does not force a re-login.
|
||||
assert_eq!(creds.blob.borrow().as_deref(), Some("R-NEW"));
|
||||
|
||||
// And switching back to orga also restores the live token — no
|
||||
// re-login there either.
|
||||
switcher.activate("orga").unwrap();
|
||||
assert_eq!(creds.blob.borrow().as_deref(), Some("R-NEW"));
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_account_org_scope_isolates_credential_to_exact_profile() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-a"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let snap = |org: &str| {
|
||||
json!({
|
||||
"oauthAccount": { "accountUuid": "A", "organizationUuid": org },
|
||||
"userID": "uid-a",
|
||||
"keychain_account": "attr-a"
|
||||
})
|
||||
};
|
||||
store.save_profile("orga", "R-OLD", &snap("O1")).unwrap();
|
||||
store.save_profile("orgb", "R-OLD", &snap("O2")).unwrap();
|
||||
|
||||
let creds = FakeCredentialStore::with(Some("R-NEW"), Some("attr-a"));
|
||||
// Under the stricter (buggy) scope, only the exact match is synced.
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccountOrg);
|
||||
switcher.sync_current().unwrap();
|
||||
|
||||
assert_eq!(store.load_credentials("orga").unwrap(), "R-NEW");
|
||||
// orgb is NOT updated — this is the stranding the PerAccount fix cures.
|
||||
assert_eq!(store.load_credentials("orgb").unwrap(), "R-OLD");
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_current_refreshes_identity_of_exact_match() {
|
||||
let dir = temp_dir();
|
||||
// Live identity has advanced (new profileFetchedAt) vs the snapshot.
|
||||
let config = write_config(&dir, &config_json("A", "O1", "a@example.com", "uid-a"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
store
|
||||
.save_profile(
|
||||
"orga",
|
||||
"R-OLD",
|
||||
&json!({
|
||||
"oauthAccount": {
|
||||
"accountUuid": "A",
|
||||
"organizationUuid": "O1",
|
||||
"profileFetchedAt": "stale"
|
||||
},
|
||||
"userID": "uid-a",
|
||||
"keychain_account": "attr-a"
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
let creds = FakeCredentialStore::with(Some("R-NEW"), Some("attr-a"));
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
switcher.sync_current().unwrap();
|
||||
|
||||
let refreshed = store.load("orga").unwrap();
|
||||
assert_eq!(refreshed.credentials, "R-NEW");
|
||||
assert_eq!(
|
||||
refreshed.account["oauthAccount"]["profileFetchedAt"],
|
||||
json!("yesterday")
|
||||
);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_current_no_config_is_noop() {
|
||||
let dir = temp_dir();
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let creds = FakeCredentialStore::with(Some("R-NEW"), None);
|
||||
let switcher = Switcher::new(
|
||||
&creds,
|
||||
&store,
|
||||
dir.join(".claude.json"),
|
||||
TokenScope::PerAccount,
|
||||
);
|
||||
switcher.sync_current().unwrap();
|
||||
assert!(store.list().unwrap().is_empty());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_current_empty_identity_is_noop() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &json!({ "numStartups": 1 }));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
store
|
||||
.save_profile("orga", "R-OLD", &json!({ "oauthAccount": {} }))
|
||||
.unwrap();
|
||||
let creds = FakeCredentialStore::with(Some("R-NEW"), None);
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
switcher.sync_current().unwrap();
|
||||
assert_eq!(store.load_credentials("orga").unwrap(), "R-OLD");
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_current_no_live_credential_is_noop() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-a"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
store
|
||||
.save_profile(
|
||||
"orga",
|
||||
"R-OLD",
|
||||
&json!({ "oauthAccount": { "accountUuid": "A", "organizationUuid": "O1" } }),
|
||||
)
|
||||
.unwrap();
|
||||
let creds = FakeCredentialStore::with(None, None);
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
switcher.sync_current().unwrap();
|
||||
assert_eq!(store.load_credentials("orga").unwrap(), "R-OLD");
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_current_propagates_credential_read_error() {
|
||||
let dir = temp_dir();
|
||||
let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-a"));
|
||||
let store = Store::new(dir.join("accounts"));
|
||||
let mut creds = FakeCredentialStore::with(Some("R-NEW"), None);
|
||||
creds.fail_read = true;
|
||||
let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount);
|
||||
assert!(switcher.sync_current().is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//! Smoke test: the crate's public pure helpers behave as documented.
|
||||
|
||||
use ccswitch::cli;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn help_text_and_reserved_words_are_public() {
|
||||
assert!(cli::help_text().contains("ccswitch <name>"));
|
||||
assert!(cli::is_reserved("list"));
|
||||
assert!(!cli::is_reserved("dev"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_paths_resolve_under_home() {
|
||||
let home = Path::new("/home/example");
|
||||
assert_eq!(
|
||||
cli::ccswitch_home(None, home),
|
||||
home.join(".claude").join("accounts")
|
||||
);
|
||||
assert_eq!(cli::config_path(home), home.join(".claude.json"));
|
||||
}
|
||||
Reference in new issue
Block a user