Skip to content

Turn a ~$5 AliExpress clock into a physical AI usage dashboard (Claude, Codex, multi-account). No firmware flashing.

4.4 KB
Raw Blame
"""Sign in to one account's own CLI home, without changing defaults."""
import argparse
import os
import shutil
import subprocess
import sys
from pathlib import Path

from token_tv.private_files import private_dir
from token_tv.sources import exe, fetch_account, load_config, scoped_env

# provider: (everyday CLI home, file present after login)
DEFAULT_HOMES = {"claude": ("~/.claude", ".credentials.json"), "codex": ("~/.codex", "auth.json"),
                 "grok": ("~/.grok", "auth.json")}


def cli_command(rest):
    from token_tv import cli
    return cli.cmd(rest)


def login_command(account, browser=False):
    provider = account["provider"]
    if provider == "claude":
        return [exe("claude"), "auth", "login", "--claudeai", "--email", account["email"]]
    if provider == "codex":
        return [exe("codex"), "login"] if browser else [exe("codex"), "login", "--device-auth"]
    return [exe(os.environ.get("TOKEN_TV_GROK_BIN", "grok")), "login", "--device-auth"]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--config", help="Config file (default: the one `start` made)")
    parser.add_argument("--account", help="Stable account key; omit to choose interactively")
    parser.add_argument("--browser", action="store_true", help="Use Codex browser login (forward localhost:1455 when running over SSH)")
    args = parser.parse_args()
    if args.config is None:
        from token_tv.cli import default_config
        args.config = default_config()
    accounts = load_config(args.config)["accounts"]
    key = args.account
    if key is None:
        for index, account in enumerate(accounts, 1):
            print(f"{index}. {account['provider']} · {account['alias']}")
        try:
            choice = int(input("Choose account number: "))
            if not 1 <= choice <= len(accounts):
                raise ValueError("Out of range")
            key = accounts[choice - 1]["key"]
        except (ValueError, IndexError, EOFError):
            parser.error("Choose one of the listed accounts")
    account = next((a for a in accounts if a["key"] == key), None)
    if account is None:
        parser.error(f"There is no account {key} in {args.config}; the accounts there are: "
                     + ", ".join(a["key"] for a in accounts))
    if not account.get("source_home"):
        parser.error("An account with its own CLI home (source_home) is required")
    root = Path(account["source_home"]).expanduser()
    default, marker = DEFAULT_HOMES[account["provider"]]
    keychain = account["provider"] == "claude" and sys.platform == "darwin"  # Claude Code on macOS keeps it there
    if root == Path(default).expanduser() and ((root / marker).is_file() or keychain):
        state = "may already be signed in (macOS keeps it in the Keychain)" if keychain else "it is already signed in"
        print(f"{account['alias']} reuses your everyday {account['provider']} login in {default}; {state}.\n"
              "Logging in again replaces that login for every tool that uses it. To keep it,\n"
              f"just run {cli_command('doctor --live')}. For a separate login, point source_home elsewhere.", flush=True)
        if not sys.stdin.isatty() or input("Type REPLACE to log in again anyway: ").strip() != "REPLACE":
            print("Kept the existing login.", flush=True)
            return
    command = login_command(account, args.browser)
    if not shutil.which(command[0]):
        raise SystemExit(f"The {account['provider']} CLI is not installed on this computer ({command[0]} not found). "
                         "Install it, then run this again.")
    private_dir(root)  # this login's own folder, 0700 from the start
    print("Sign in as " + account["email"] + ". Enter login codes here, not in chat.", flush=True)
    result = subprocess.run(command, env=scoped_env(account["provider"], root))
    if result.returncode:
        raise SystemExit(result.returncode)
    # Verification must use the newly authenticated source, never its fallback.
    direct = {k: v for k, v in account.items() if k not in ("snapshot_file", "fallback_snapshot_file")}
    row = fetch_account(direct)
    print("Verification: " + row["status"], flush=True)
    if row["status"] not in ("ok", "quota_unavailable") or not row["identity_verified"]:
        raise SystemExit(1)
    print("Account verified. A running TokenTV picks up this login on its next poll.", flush=True)


if __name__ == "__main__":
    main()