Last active
September 14, 2026 12:52
-
-
Save StarpTech/e84e8918f8db7a974c119d616ca5e31a to your computer and use it in GitHub Desktop.
Switch between codex accounts seamlessly and keep projects, sessions, and archives (automatic backups)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Keep local work in one place when account credentials change. | |
| set -euo pipefail | |
| umask 077 | |
| usage() { | |
| cat <<'HELP' | |
| Usage: codex-accounts.sh [--home DIR] [--store DIR] [--dry-run] COMMAND [NAME] | |
| save NAME Save the current ChatGPT credentials under a new name. | |
| login NAME Log into a new named account without changing the active account. | |
| switch NAME Back up local data, save refreshed credentials, and activate NAME. | |
| logout Back up local data and remove the active file credentials. | |
| list List saved account names (never tokens or email addresses). | |
| status Report file credentials and local project/session counts. | |
| backup Save a verified local-data archive. | |
| restore NAME Extract backup NAME into a new recovery directory for inspection. | |
| Quit the desktop app, CLI sessions, and IDE Codex extensions before any write. | |
| Run this script from a separate terminal. Keep Codex closed until it finishes. | |
| Defaults: --home uses CODEX_HOME or ~/.codex; --store uses ~/.codex-accounts. | |
| Only file-based ChatGPT credentials are supported. Keyring/auto/ephemeral modes | |
| are rejected. Login uses the installed codex CLI and its normal browser flow. | |
| Projects, session links, active/archived transcripts, worktrees, attachments, | |
| SQLite databases, hidden state, and shared configuration stay at the same paths. | |
| Backups exclude global skills/plugins/packages/cache and transient runtime data. | |
| External repositories and symlink targets are not copied. Cloud data is not moved. | |
| Restore never overwrites live data. Saved credentials and backups are sensitive. | |
| Expired credentials require a new login; offline validation cannot prove validity. | |
| Example: switch between personal and work accounts | |
| Quit Codex first, then run these commands in a separate terminal: | |
| cd ~/Documents | |
| ./codex-accounts.sh save personal | |
| ./codex-accounts.sh login work | |
| ./codex-accounts.sh switch work | |
| Select your work account in the browser during login. Reopen Codex after switch. | |
| To return to your personal account, quit Codex again, then run: | |
| ./codex-accounts.sh switch personal | |
| Reopen Codex. Your local projects and sessions stay in place. | |
| Run save and login once per named login; use switch for later changes. | |
| HELP | |
| } | |
| fail() { printf 'Error: %s\n' "$*" >&2; exit 1; } | |
| name_ok() { [[ "$1" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$ ]] || fail 'Use 1-64 letters, digits, underscores, or hyphens for a name.'; } | |
| root=${CODEX_HOME:-"$HOME/.codex"} | |
| vault=$HOME/.codex-accounts | |
| dry=0 | |
| while [[ $# -gt 0 ]]; do | |
| case "$1" in | |
| --home|--store) [[ $# -ge 2 ]] || fail "Missing value for $1"; if [[ $1 == --home ]]; then root=$2; else vault=$2; fi; shift 2 ;; | |
| --dry-run) dry=1; shift ;; | |
| -h|--help) usage; exit 0 ;; | |
| --*) fail "Unknown option: $1" ;; | |
| *) break ;; | |
| esac | |
| done | |
| cmd=${1:-help}; [[ $# -eq 0 ]] || shift | |
| case "$cmd" in | |
| help) usage; exit 0 ;; | |
| save|login|switch|restore) [[ $# -eq 1 ]] || fail "$cmd needs one name"; name=$1; name_ok "$name" ;; | |
| status|list|backup|logout) [[ $# -eq 0 ]] || fail "$cmd takes no arguments" ;; | |
| *) fail "Unknown command: $cmd" ;; | |
| esac | |
| for tool in sqlite3 tar shasum openssl ps awk od cmp mktemp; do command -v "$tool" >/dev/null || fail "Missing command: $tool"; done | |
| [[ -d "$root" && ! -L "$root" ]] || fail 'Codex home must be an existing directory, not a symlink.' | |
| root=$(cd "$root" && pwd -P) | |
| [[ -O "$root" && "$root" != / && "$root" != "$HOME" ]] || fail 'Use a dedicated Codex home owned by you.' | |
| [[ "$vault" = /* && "$vault" != *$'\n'* && "$root" != *$'\n'* ]] || fail 'Use absolute paths without newlines.' | |
| [[ "$(basename "$vault")" != . && "$(basename "$vault")" != .. ]] || fail 'Invalid account store path.' | |
| [[ ! -L "$vault" ]] || fail 'Account store must not be a symlink.' | |
| [[ -d "$(dirname "$vault")" ]] || fail 'Account store parent must exist.' | |
| vault=$(cd "$(dirname "$vault")" && printf '%s/%s' "$(pwd -P)" "$(basename "$vault")") | |
| if [[ -d "$vault" ]]; then vault=$(cd "$vault" && pwd -P); fi | |
| case "$vault/" in "$root/"*) fail 'Account store must be outside Codex home.' ;; esac | |
| case "$root/" in "$vault/"*) fail 'Codex home must be outside the account store.' ;; esac | |
| [[ "$vault" != / && "$vault" != "$HOME" ]] || fail 'Use a dedicated account store.' | |
| [[ ! -L "$root/auth.json" ]] || fail 'Symlinked credentials are unsupported.' | |
| sql_path() { printf '%s' "${1//\'/\'\'}"; } | |
| json_field() { | |
| sqlite3 :memory: "SELECT json_extract(CAST(readfile('$(sql_path "$1")') AS TEXT), '$2');" 2>/dev/null | |
| } | |
| identity() { | |
| local file=$1 account jwt payload subject hex | |
| [[ -f "$file" && ! -L "$file" ]] || return 1 | |
| [[ -z "$(json_field "$file" '$.OPENAI_API_KEY')" ]] || return 1 | |
| case "$(json_field "$file" '$.auth_mode')" in ""|chatgpt) ;; *) return 1 ;; esac | |
| account=$(json_field "$file" '$.tokens.account_id') || return 1 | |
| jwt=$(json_field "$file" '$.tokens.id_token') || return 1 | |
| [[ -n "$account" && "$jwt" == *.*.* ]] || return 1 | |
| [[ -n "$(json_field "$file" '$.tokens.access_token')" && -n "$(json_field "$file" '$.tokens.refresh_token')" ]] || return 1 | |
| payload=${jwt#*.}; payload=${payload%%.*} | |
| [[ "$payload" =~ ^[A-Za-z0-9_-]+$ ]] || return 1 | |
| payload=${payload//-/+}; payload=${payload//_/\/} | |
| case $((${#payload} % 4)) in 2) payload=$payload== ;; 3) payload=$payload= ;; 1) return 1 ;; esac | |
| hex=$(printf '%s' "$payload" | openssl base64 -d -A | od -An -v -tx1 | tr -d ' \n') || return 1 | |
| subject=$(sqlite3 :memory: "SELECT json_extract(CAST(X'$hex' AS TEXT), '$.sub');" 2>/dev/null) || return 1 | |
| [[ -n "$subject" ]] || return 1 | |
| printf '%s\n%s\n' "$account" "$subject" | shasum -a 256 | awk '{print $1}' | |
| } | |
| file_mode() { | |
| local config | |
| for config in "$root/config.toml" "$root/managed_config.toml" /etc/codex/managed_config.toml /etc/codex/config.toml /Library/Preferences/com.openai.codex.plist; do | |
| [[ -f "$config" ]] || continue | |
| # Unknown credential settings need an explicit review before a switch. | |
| if LC_ALL=C awk '/^[[:space:]]*#/ {next} /cli_auth_credentials_store/ {print}' "$config" | LC_ALL=C grep -q .; then | |
| LC_ALL=C awk '/^[[:space:]]*#/ {next} /cli_auth_credentials_store/ {print}' "$config" | | |
| LC_ALL=C grep -Ev '^[[:space:]]*cli_auth_credentials_store[[:space:]]*=[[:space:]]*"file"[[:space:]]*(#.*)?$' >/dev/null && | |
| fail "Unsupported credential setting in $config. This script requires file storage." | |
| fi | |
| done | |
| return 0 | |
| } | |
| quiet_required() { | |
| local running blockers | |
| running=$(ps -axo pid=,comm=) || fail 'Cannot inspect running processes.' | |
| blockers=$(printf '%s\n' "$running" | awk ' | |
| { | |
| pid=$1 | |
| sub(/^[[:space:]]*[0-9]+[[:space:]]+/, "") | |
| } | |
| # Crash reporters can remain after the app quits. | |
| /(^|\/)(browser_crashpad_handler|chrome_crashpad_handler|crashpad_handler)$/ {next} | |
| /(^|\/)(codex|codex-app-server|codex-exec|codex_chronicle|codex-code-mode-host)([[:space:]]|$)/ || | |
| /\/(Codex|ChatGPT)\.app\// || | |
| /^(Codex|ChatGPT)( Helper.*)?$/ {printf " PID %s: %s\n", pid, $0} | |
| ') || fail 'Cannot filter running processes.' | |
| if [[ -n "$blockers" ]]; then | |
| printf 'Processes still running:\n%s\n' "$blockers" >&2 | |
| fail 'Quit Codex/ChatGPT, CLI sessions, and IDE Codex extensions first. Use a separate terminal.' | |
| fi | |
| } | |
| counts() { | |
| local db | |
| for db in "$root"/state_*.sqlite; do | |
| [[ -f "$db" ]] || continue | |
| printf '%s: ' "$(basename "$db")" | |
| sqlite3 -readonly "$db" "SELECT 'projects=' || (SELECT count(*) FROM projects) || ', sessions=' || count(*) || ', archived=' || coalesce(sum(archived != 0),0) FROM threads;" || fail 'Cannot inspect project/session schema.' | |
| done | |
| } | |
| if [[ "$cmd" == status ]]; then | |
| if identity "$root/auth.json" >/dev/null; then echo 'Local ChatGPT file credentials present (server validity not checked).'; else echo 'No supported ChatGPT file credentials.'; fi | |
| counts | |
| exit 0 | |
| fi | |
| if [[ "$cmd" == list ]]; then | |
| for entry in "$vault"/accounts/*; do [[ ! -d "$entry" ]] || basename "$entry"; done | |
| exit 0 | |
| fi | |
| file_mode | |
| quiet_required | |
| if [[ "$dry" == 1 ]]; then | |
| printf 'Dry run: %s%s\nHome: %s\nStore: %s\nNo files changed.\n' "$cmd" "${name:+ $name}" "$root" "$vault" | |
| exit 0 | |
| fi | |
| if [[ -d "$vault" && ! -f "$vault/home" ]]; then | |
| [[ -z "$(ls -A "$vault")" ]] || fail 'Existing store is not empty and has no home marker.' | |
| fi | |
| mkdir -p "$vault" | |
| [[ -O "$vault" && ! -L "$vault" ]] || fail 'Account store must be owned by you.' | |
| chmod 700 "$vault" | |
| for dir in accounts backups; do | |
| [[ ! -L "$vault/$dir" ]] || fail 'Account store contains a symlink.' | |
| mkdir -p "$vault/$dir"; chmod 700 "$vault/$dir" | |
| done | |
| lock=$vault/lock | |
| mkdir "$lock" 2>/dev/null || fail "Store is locked. After confirming no script is running, remove $lock." | |
| stage= | |
| auth_tmp= | |
| marker_tmp= | |
| home_lock= | |
| cleanup() { | |
| [[ -z "$auth_tmp" ]] || rm -f "$auth_tmp" | |
| [[ -z "$marker_tmp" ]] || rm -f "$marker_tmp" | |
| [[ -z "$stage" ]] || rm -rf "$stage" | |
| [[ -z "$home_lock" ]] || rmdir "$home_lock" 2>/dev/null || true | |
| rmdir "$lock" 2>/dev/null || true | |
| } | |
| trap cleanup EXIT | |
| trap 'exit 130' INT | |
| trap 'exit 143' TERM | |
| mkdir "$root/.codex-accounts.lock" 2>/dev/null || fail "Codex home is locked: $root/.codex-accounts.lock" | |
| home_lock=$root/.codex-accounts.lock | |
| stage=$(mktemp -d "$vault/.stage.XXXXXXXX") | |
| printf '%s\n' "$root" > "$stage/home" | |
| if [[ -e "$vault/home" ]]; then | |
| [[ ! -L "$vault/home" ]] && cmp -s "$stage/home" "$vault/home" || fail 'This store belongs to a different Codex home.' | |
| else cp "$stage/home" "$vault/home"; fi | |
| active_marker=$root/.codex-accounts-active | |
| [[ ! -L "$active_marker" && ( ! -e "$active_marker" || -f "$active_marker" ) ]] || fail 'Active account marker is unsafe.' | |
| check_account() { | |
| [[ -d "$vault/accounts/$1" && ! -L "$vault/accounts/$1" ]] || fail 'Saved account not found or unsafe.' | |
| identity "$vault/accounts/$1/auth.json" || fail 'Saved credentials are invalid.' | |
| } | |
| mark_active() { | |
| marker_tmp=$(mktemp "$root/.account-marker.XXXXXXXX") | |
| printf '%s\n%s\n' "$vault" "$1" > "$marker_tmp" | |
| mv -f "$marker_tmp" "$active_marker" | |
| marker_tmp= | |
| } | |
| save_current() { | |
| local current entry saved selected= tracked= tracked_store= matches=0 candidate= | |
| [[ -e "$root/auth.json" ]] || return 0 | |
| current=$(identity "$root/auth.json") || fail 'Current credentials are unsupported. Nothing switched.' | |
| if [[ -f "$active_marker" ]]; then | |
| { IFS= read -r tracked_store && IFS= read -r tracked; } < "$active_marker" || fail 'Invalid active account marker.' | |
| name_ok "$tracked" | |
| [[ "$tracked_store" == "$vault" ]] || tracked= | |
| fi | |
| for entry in "$vault"/accounts/*; do | |
| [[ -d "$entry" && ! -L "$entry" ]] || continue | |
| saved=$(identity "$entry/auth.json") || continue | |
| [[ "$current" == "$saved" ]] || continue | |
| matches=$((matches + 1)) | |
| candidate=$entry | |
| if [[ "${entry##*/}" == "$tracked" ]]; then | |
| selected=$entry | |
| break | |
| fi | |
| if [[ -z "$selected" ]] && cmp -s "$root/auth.json" "$entry/auth.json"; then | |
| selected=$entry | |
| fi | |
| done | |
| # Older stores have no active name. Do not guess between separate logins. | |
| if [[ -z "$selected" && "$matches" == 1 && ! -e "$candidate/login" ]]; then selected=$candidate; fi | |
| [[ -n "$selected" ]] || fail 'Save the current account with save NAME before switching or logging out.' | |
| cp "$root/auth.json" "$stage/refreshed" | |
| chmod 600 "$stage/refreshed" | |
| mv -f "$stage/refreshed" "$selected/auth.json" | |
| mark_active "${selected##*/}" | |
| } | |
| backup() { | |
| local id db result | |
| id=$(date -u +%Y%m%dT%H%M%SZ)-$$ | |
| mkdir "$stage/snapshot" | |
| echo 'Backing up local data; this can take several minutes.' >&2 | |
| # Keep databases and their journals together while all writers are closed. | |
| COPYFILE_DISABLE=1 tar -cf "$stage/snapshot/data.tar" \ | |
| --exclude='./packages' --exclude='./skills' --exclude='./plugins' --exclude='./cache' \ | |
| --exclude='./.codex-accounts-active' --exclude='./.codex-accounts.lock' --exclude='./tmp' --exclude='./.tmp' --exclude='./ipc' --exclude='./thread-writer-locks' \ | |
| --exclude='./browser' --exclude='./computer-use' --exclude='./node_repl' \ | |
| -C "$root" . | |
| quiet_required | |
| mkdir "$stage/verify" | |
| tar -xf "$stage/snapshot/data.tar" -C "$stage/verify" | |
| for db in "$stage/verify"/*.sqlite "$stage/verify/sqlite"/*.db; do | |
| [[ -f "$db" ]] || continue | |
| result=$(sqlite3 "$db" 'PRAGMA quick_check;') || fail 'Backup database check failed.' | |
| [[ "$result" == ok ]] || fail 'Backup database integrity check failed.' | |
| done | |
| cp "$stage/home" "$stage/snapshot/home" | |
| (cd "$stage/snapshot" && shasum -a 256 data.tar > SHA256) | |
| (cd "$stage/snapshot" && shasum -a 256 -c SHA256 >/dev/null) | |
| mv "$stage/snapshot" "$vault/backups/$id" | |
| printf 'Backup: %s\n' "$id" | |
| } | |
| activate() { | |
| quiet_required | |
| auth_tmp=$(mktemp "$root/.account-auth.XXXXXXXX") | |
| cp "$1" "$auth_tmp" | |
| chmod 600 "$auth_tmp" | |
| cmp -s "$1" "$auth_tmp" || fail 'Credential copy verification failed.' | |
| mv -f "$auth_tmp" "$root/auth.json" | |
| auth_tmp= | |
| } | |
| case "$cmd" in | |
| save|login) | |
| [[ ! -e "$vault/accounts/$name" && ! -L "$vault/accounts/$name" ]] || fail 'That name already exists. Use a new name for a fresh login.' | |
| mkdir "$stage/account" | |
| if [[ "$cmd" == login ]]; then | |
| command -v codex >/dev/null || fail 'codex CLI is required for login.' | |
| mkdir "$stage/login" | |
| (cd "$stage/login" && env CODEX_HOME="$stage/login" codex -c 'cli_auth_credentials_store="file"' login) | |
| source_auth=$stage/login/auth.json | |
| else source_auth=$root/auth.json; fi | |
| identity "$source_auth" >/dev/null || fail 'Expected valid ChatGPT file credentials.' | |
| cp "$source_auth" "$stage/account/auth.json" | |
| chmod 600 "$stage/account/auth.json" | |
| if [[ "$cmd" == login ]]; then touch "$stage/account/login"; fi | |
| mv "$stage/account" "$vault/accounts/$name" | |
| if [[ "$cmd" == save ]]; then mark_active "$name"; fi | |
| printf 'Saved %s. Active credentials unchanged.\n' "$name" | |
| ;; | |
| switch) | |
| check_account "$name" >/dev/null | |
| save_current | |
| backup | |
| # A missing marker permits recovery if activation stops between file writes. | |
| rm -f "$active_marker" | |
| activate "$vault/accounts/$name/auth.json" | |
| mark_active "$name" | |
| printf 'Activated %s. Reopen Codex. Local projects and sessions remain in place.\n' "$name" | |
| ;; | |
| logout) | |
| save_current | |
| backup | |
| quiet_required | |
| rm -f "$root/auth.json" | |
| rm -f "$active_marker" | |
| echo 'Removed active file credentials. Local data and saved accounts remain.' | |
| ;; | |
| backup) backup ;; | |
| restore) | |
| snapshot=$vault/backups/$name | |
| [[ -d "$snapshot" && ! -L "$snapshot" && ! -L "$snapshot/data.tar" && ! -L "$snapshot/SHA256" ]] || fail 'Backup is missing or unsafe.' | |
| (cd "$snapshot" && shasum -a 256 -c SHA256 >/dev/null) || fail 'Backup checksum failed.' | |
| [[ "$(cat "$snapshot/home")" == "$root" ]] || fail 'Backup belongs to another Codex home.' | |
| recovery=$(mktemp -d "$vault/recovery-$name.XXXXXXXX") | |
| tar -xf "$snapshot/data.tar" -C "$recovery" | |
| printf 'Recovered files: %s\nLive data was not overwritten.\n' "$recovery" | |
| ;; | |
| esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment