Skip to content

feat(runtimes): sign claude and codex in through their own login - #94

Merged
xxchan merged 7 commits into
mainfrom
runtime-login
Oct 5, 2026
Merged

xxchan merged 7 commits into
mainfrom
runtime-login

Conversation

@xxchan

@xxchan xxchan commented Oct 3, 2026 •

Copy link
Copy Markdown
Member

A host that finds a runtime logged out could only send the person to a terminal; every runtime page said "Login management is not exposed". A host whose UI is on another device (a phone, a browser tab) cannot even do that. This adds a headless sign-in: the login runs on the machine, and the person opens a URL and, for claude, pastes a code back.

The scope (API shape, hard rules, first runtimes) is the one agreed with @cindy. Her review changes are in the second commit: results after success, leaks, Windows tree kill, naming, and dropping busy.

Since the rebase onto main (v0.21.2)

  • refactor(cli): oar run moved verbatim to packages/cli/src/run.ts (registerRunCommand), as the upgrade, login and mcp commands are registered. With oar login next to main's new exit.js and runtimes.js imports, the CLI entry would otherwise import 11 modules, over the lint limit of 10.
  • fix(runtimes): antigravity has no login member, following main's capabilities rule that an operation a runtime can't do is an absent member. terms_of_service is gone from LoginUnsupportedReason; unsupported keeps the reasons the machine decides (unsupported_installation, version_unsupported). Why antigravity can't sign a person in (its terms; use an API key or Vertex) is on its runtime page, and oar list shows login: false for it.
  • fix(runtimes): a login whose executable is gone fails the same way everywhere. Before anything is spawned, the login looks the executable up as the installation probe does: a pinned path must exist, and a bare name must be on PATH. A missing one is failed / process_failed with <runtime> executable not found: <command>, for claude and codex alike. Before this, Windows started a missing command through a shell and codex reported codex app-server exited, while Linux and macOS said spawn … ENOENT.

API
Runtime gets two optional capabilities, beside checkUpdate/upgrade and separate from the session record stream. They are defined in contracts/login.ts:

login?(installation, interaction: ProviderLoginInteraction, options?: { timeoutMs? }): Promise<LoginResult>
authStatus?(installation, options?: { timeoutMs? }): Promise<AuthStatus>

type LoginResult =
  | { kind: "logged_in"; account?: { email?; plan?; method? } }
  | { kind: "failed"; reason: "timed_out" | "rejected" | "not_logged_in" | "interaction_failed" | "process_failed"; detail? }
  | { kind: "cancelled" }
  | { kind: "unsupported"; reason: "unsupported_installation" | "version_unsupported"; detail? }

type AuthStatus =
  | { kind: "logged_in"; account?; source }
  | { kind: "logged_out"; source }
  | { kind: "unknown"; detail?; source? }
  • interaction is the existing ProviderLoginInteraction that pi's provider login already uses. It has no new event format:
    • The auth_url, device_code and info events carry what a person opens or types.
    • prompt({ kind: "manual_code" }) asks for a pasted code.
  • One small extension: options.timeoutMs overrides each driver's default deadline, mirroring UpgradeOptions.
  • Logins are not serialized: whether two may run at once is the host's policy.
  • docs/spec/login.md is the contract page.

Per runtime

  • claude: runs claude auth login over pipes.
    • Output handling:
      • OAR strips ANSI and OSC 8 escapes from both streams.
      • It parses If the browser didn't open, visit: <url> and relays the URL as auth_url.
      • The paste prompt Paste code here if prompted > has no trailing newline. OAR detects it in the unterminated tail and asks a manual_code prompt.
    • The answer, code#state with whitespace removed, is written to stdin with a newline.
    • A stderr line that starts with Invalid code asks again; Login failed: Invalid code verifier does not.
    • Login successful. is confirmed with claude auth status --json, which also gives the account. This holds even if a deadline or abort arrives while claude flushes telemetry before exiting.
    • Login failed: … with exit 1 is rejected. A failure in claude's own words (a suspended account, an org or provider that disallows the login) reports its last stderr line.
    • Claude has no deadline of its own, so OAR stops it after 15 min.
    • Below 2.1.126, the version that reads a pasted code, the result is unsupported / version_unsupported.
    • authStatus reads claude auth status --json.
  • codex: never runs codex login, which calls clear_existing_auth_before_login (logout plus revoke) before the new sign-in completes.
    • It uses the app-server on its own process: account/login/start {type:"chatgptDeviceCode"} returns verificationUrl and userCode, relayed as device_code.
    • OAR then waits for the account/login/completed notification and reads account/read for the account. A completion that arrives before the start reply is held, not dropped.
    • After a success, an account/read that fails, or a deadline or abort, yields logged_in without an account; codex has already stored the login.
    • The login's app-server never inherits stderr (even with OAR_CHILD_STDERR=inherit). On Windows a stop kills its whole process tree, so an npm install's cmd.exe shim doesn't leave codex polling.
    • I checked upstream source (openai/codex b741e480): the app-server writes the store only after the token exchange and workspace check succeed. Failure, cancel and expiry leave the old sign-in untouched.
    • The deadline is 16 min, so codex reports its own 15 min expiry first.
    • The floor is 0.118.0.
    • An info event, and the docs, say that device code sign-in must be enabled in ChatGPT security settings (or by a workspace admin).
    • authStatus reads the exit code of codex login status:
      • exit 0 is logged in;
      • exit 1 with Not logged in is logged out;
      • anything else is unknown.
    • So oar login codex --status shows only logged in (chatgpt), without the account: codex login status reports the method, not the account. The account appears only in a login's own result, from account/read in the login flow. This is on purpose; parsing codex's credential file isn't worth it.
  • antigravity: no login member. Antigravity's terms don't allow signing a personal account in through third-party tools; its runtime page says so and points to an API key or Vertex.
  • Not in this PR:
    • Cursor waits for its adapter's move to @cursor/sdk, whose login (Cursor.auth.login / status) is separate from cursor-agent's. I dropped the cursor-agent CLI driver; it lands as a follow-up after that PR.
    • grok, kimi and pi follow separately. grok and kimi each need the same "never signs out first" check against vendor source that codex got here.

Safety properties

  • No secrets leave the login:
    • Tokens and the pasted code never appear in events, results, errors or logs. The pasted value and its authorization code go to the runtime's stdin only.
    • A detail is one line in the runtime's own words, or an exit code; never a stderr tail. It is redacted for pasted values plus sk-… and JWT shapes, and capped at 500 chars.
    • No login process forwards its output to the host, whatever OAR_CHILD_STDERR says.
    • oar login reads the pasted code without echoing it.
  • No logout first: claude's auth login and codex's app-server keep the old credentials until the new ones are saved. timed_out and cancelled therefore mean the old login is untouched.
  • Success is final: once the runtime reports success, a later deadline or abort is never reported as timed_out or cancelled. The status query decides; when it can't answer, the result is logged_in without an account.
  • Cancellable: aborting interaction.signal stops the login process and everything it started. On POSIX that is SIGTERM to its process group, then SIGKILL after the grace period; on Windows it is taskkill /T for both drivers. The result is cancelled.
  • Bounded: each driver has its own deadline. A command that can't be spawned fails at once, without leaving a timer behind.
  • Confirmed: a reported success is checked with the runtime's own status query, which honours the abort. A login that still reads logged out is failed / not_logged_in.

CLI
oar login <runtime> mirrors oar upgrade:

  • It prints the URL or device code, and reads a pasted code from stdin when the runtime asks.
  • Ctrl-C cancels, and input that ends fails the open prompt. A pasted code is not echoed; I checked this under a pseudo-terminal.
  • Exit codes: 0 logged in, 130 cancelled, 1 otherwise.
  • oar login [runtime] --status reports login status; --json and --timeout are supported.
  • oar list shows login and authStatus.

Tests

  • Fake executables mimic each CLI, with no real logins:
    • fake-claude-login.mjs prints claude 2.1.288's strings, including the OSC 8 hyperlink and the paste prompt with no newline.
    • fake-codex-login.mjs answers with the 0.160.0 app-server shapes.
  • claude cases:
    • success;
    • an invalid code, then success;
    • rejection whose message echoes the pasted code (redacted);
    • a failure in claude's own words, and Login failed: Invalid code verifier (no second prompt);
    • sign-in finished in the browser while the prompt is open;
    • unverified success;
    • a deadline, and an abort, after Login successful. (the status decides);
    • deadline and cancel, each checking that the process tree is gone (these now also run on Windows);
    • a throwing prompt or onEvent;
    • a command that can't be spawned;
    • version floor;
    • a signal that was already aborted;
    • authStatus logged in, logged out and unknown.
    • A leak check asserts that the pasted code is absent from events, prompts and results.
  • codex cases:
    • success (and that codex login never ran);
    • codex's own failure, a refused start, a crash (exit code only, no stderr tail) and unverified success;
    • stderr not forwarded under OAR_CHILD_STDERR=inherit; this test fails without the fix;
    • an account/read error after success, and a completion before the start reply;
    • a deadline, and an abort, after success;
    • deadline and cancel, each checking that the process tree is gone (also on Windows);
    • a command that can't be spawned;
    • version floor;
    • authStatus.
  • Shared mechanisms: escape stripping, redaction, the one-line detail.
  • CLI rendering, exit codes, select answers and the echo gate.
  • I also drove oar login claude and oar login codex end to end against the fakes through OAR_CLAUDE_BIN / OAR_CODEX_BIN. oar login --status against real installations is read only.
  • pnpm run check passes, and the tests also pass with CI=1, which enforces snapshots: 649 tests passed, 31 skipped; mock sea-trial 19/19.
  • The process-layer options touch shared runtime machinery, so I also ran pnpm tsx sea-trial/all.ts mock codex-aimock claude-aimock: all three backends clean (19/19 each after the rebase).

Manual real-login verification: all five checklist steps passed on a test machine (cindytest) at f7e6428: steps 1, 3 and 5 by Cindy, steps 2 and 4 by the account owner. Both runtimes were logged out afterwards.

  • oar login claude --status and oar login codex --status: note the current accounts.
  • oar login claude: open the URL on another device, sign in, paste the code#state the page shows. Expect a logged-in result with the account; the code must not echo.
  • oar login claude again, and press Ctrl-C at the paste prompt. Expect login cancelled (exit 130). Then claude auth status shows the previous account, unchanged.
  • oar login codex: enter the device code at the URL on another device. Expect a logged-in result with the account. If device code sign-in isn't enabled for the account, expect codex's error as rejected.
  • oar login codex again, and press Ctrl-C while the device code is shown. Expect login cancelled, then codex login status still logged in with the previous account.
  • Optional: a wrong paste for claude (expect a second prompt), and oar login codex on Windows with an npm install (no codex process left after Ctrl-C).

🤖 Generated with Claude Code

xxchan and others added 4 commits October 5, 2026 15:37
A host that finds a runtime signed out could only send the person to a
terminal: every runtime page said "Login management is not exposed". A
host whose UI runs on another device (a phone, a browser tab) cannot
even do that, so the sign-in has to run headless on the machine while
the person only opens a URL and, for claude, pastes a code back.

Runtime gains two optional capabilities beside checkUpdate/upgrade,
separate from the session record stream:

- login(installation, interaction, options?) drives the runtime's own
  login over pipes and reports through the existing
  ProviderLoginInteraction (auth_url, device_code, info events; a
  manual_code prompt when a code must be pasted back). It resolves
  logged_in (with the account the runtime's status names), failed (a
  reason code), cancelled or unsupported.
- authStatus(installation) runs the runtime's local status query, so a
  host can decide whether to offer a sign-in.

The contract's hard rules: a pasted code goes to the runtime's stdin
only and is redacted, with token shapes, from every reported detail;
the current sign-in is never cleared before the new one exists; the
signal stops the login with its whole process group; each driver reads
stdout and stderr, strips terminal escapes, enforces its own deadline,
and runs one at a time per runtime. A reported success is confirmed
with the runtime's status query.

- claude: `claude auth login`, relaying the printed URL and writing the
  pasted code#state to stdin; an invalid code asks again; 15 minute
  deadline (claude has none); 2.1.126+ reads a pasted code.
- codex: the app-server's chatgptDeviceCode flow (0.118.0+), never
  `codex login`, which signs out and revokes before the new sign-in
  completes; account/read names the account.
- antigravity: unsupported, its terms do not allow a personal account
  through third-party tools.

Cursor waits for its adapter's move to the Cursor SDK, whose login is
its own; grok, kimi and pi follow separately.

`oar login <runtime>` drives a login in the terminal (Ctrl-C cancels,
exit 0/130/1) and `oar login --status` reports every runtime. Fake
claude and codex executables cover success, an invalid code then
success, rejection, crash, unverified success, deadline and cancel
(process group gone), and that the pasted code never appears in events,
prompts, results or errors. docs/spec/login.md is the contract page;
the claude, codex and antigravity pages record each path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of the login capability found results that could contradict what the
runtime had stored, output that could leave oar, and a Windows stop that
missed the real process.

Results:
- Once the runtime reports success (`Login successful.`, codex's completed
  notification) the login is stored, so a later deadline or abort no longer
  reports timed_out or cancelled: the status query decides, and when it
  cannot answer (it failed, or the caller aborted) the result is logged_in
  without an account. A codex account/read that fails after success is
  logged_in, as claude's unknown status already was. The post-success query
  honours the abort.
- claude failures in its own words (a suspended account, an organization
  that disallows the login) report its last stderr line instead of just
  the exit code; `Invalid code` asks again only at the start of a stderr
  line, so `Login failed: Invalid code verifier` is a failure.
- A codex completion read before the start reply is held, not dropped.
- A command that cannot be spawned fails at once; the deadline is created
  after the spawn and never keeps a process alive on its own.

Leaks:
- The login's codex app-server never inherits stderr, whatever
  OAR_CHILD_STDERR says (spawnLineProcess gains `inheritStderr`), and a
  failure detail is one line in the runtime's own words or the exit code,
  never the stderr tail.
- `oar login` reads a pasted code without echoing it.

Windows: spawnLineProcess gains `killTree`, used by the login's app-server,
so a stop ends codex itself, not only an npm shim's cmd.exe. The shared
taskkill walk is one helper now. The cancel and deadline tests run on
Windows too.

Naming and scope: AuthStatus kinds are logged_in / logged_out / unknown, the
failure reason not_logged_in. The busy result and the one-login-per-runtime
guard are gone: they could not stop another process or a terminal login,
and serializing logins is the host's policy. Login is not listed as shipped
in the roadmap until a real-device verification.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Re-review: a completion that came before the start reply still showed the
device code, so a caller whose onEvent threw turned a stored login into
interaction_failed; it now returns the confirmation at once. A missing
executable reports the spawn error (ENOENT), as claude's driver does. The
spec says the status query and the stop grace can take a call past
timeoutMs, and LineProcess.kill's comment matches killTree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `oar login` beside main's exit and runtime-registry modules, the CLI
entry imported eleven modules, one over the lint limit. The run command
moves to run.ts verbatim (its recorder version is now passed in, as mcp's
is); the entry keeps the small commands and registers the rest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
exe.dev user and others added 3 commits October 5, 2026 16:00
An operation a runtime cannot do is an absent member (design/capabilities),
and antigravity's login was `unsupported` / `terms_of_service` on every
machine. Its `login` goes, and with it the `terms_of_service` reason;
`unsupported` keeps the machine-dependent reasons (`unsupported_installation`,
`version_unsupported`). Why it cannot sign a person in (its terms; use an API
key or Vertex) is on its runtime page, and `oar list` shows `login: false`.

The codex page also says why `--status` shows the method without the
account: `codex login status` does not name it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The runtime pages said no real login through OAR was recorded. On
2026-10-05 a fresh Linux test machine with claude 2.1.289 and codex 0.160.0
passed all five manual checklist steps at f7e6428: status reads, a real
login (claude's code pasted back, codex's device code), and a cancel while
waiting for input (`login cancelled`, exit 130, no process left over, the
previous login unchanged).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On Windows a missing command is started through a shell, so codex's login
reported `codex app-server exited` where Linux and macOS said
`spawn … ENOENT`. Before a login spawns anything it now looks the
executable up as the installation probe does (a pinned path must exist, a
bare name must be on PATH), and a missing one is `failed` /
`process_failed` with `<runtime> executable not found: <command>` on every
platform, for claude and codex alike. The probe's lookup is shared as
`locateExecutable`; `loginExecutable`'s early answer is now `settled`, as it
is no longer only `unsupported`.

The tests take the missing executable through that lookup (a removed
pinned path, a bare name on no PATH), so they no longer depend on how each
OS spawns a nonexistent path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@xxchan
xxchan merged commit 93bcc43 into main Oct 5, 2026
13 checks passed
@xxchan
xxchan deleted the runtime-login branch October 5, 2026 16:14
@xxchan xxchan mentioned this pull request Oct 5, 2026
xxchan added a commit that referenced this pull request Oct 6, 2026
Minor release: #94 (Ferryman) adds `Runtime.login` and
`Runtime.authStatus`, signing claude and codex in through their own
login commands, and `oar login` in the CLI. Verified on a real machine
(claude 2.1.289, codex 0.160.0). Version bump only.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: exe.dev user <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
xxchan added a commit that referenced this pull request Oct 7, 2026
Adds `login` and `authStatus` to the **cursor** runtime, under the
contract #94 introduced for claude and codex (`contracts/login.ts`,
`docs/spec/login.md`). #94 left cursor until its adapter moved to
`@cursor/sdk`. The SDK has a login of its own (`Cursor.auth.login` /
`status`), and OAR now uses it. So a host that finds cursor logged out
can sign it in without a terminal, from another device.

**The real login passed on a real account** (2026-10-06 and 2026-10-07,
fresh Linux test machine, `@cursor/sdk` 1.0.36, commit `d6ece22`): the
checklist below, steps 1 to 4. The optional race step was not run by
hand; #150 pins that window against the real SDK with a mock backend.

## What

- `runtimes/cursor/login.ts` (`cursorLoginWith(load)`) and
`runtimes/cursor/auth-status.ts` (`cursorAuthStatusWith(load)`) follow
claude's split. `createCursorRuntime` wires both in, and `CursorRuntime`
now guarantees `login` and `authStatus`.
- **login:** calls `Cursor.auth.login({ openBrowser: false, onLoginUrl,
signal, store })`. The URL from `onLoginUrl` goes out as one `auth_url`
event ("Open this URL on any device and sign in to Cursor; the login
completes on its own."). There is no prompt: the SDK polls on the server
side.
  - A resolved login is confirmed with `Cursor.auth.status`.
- Deadline: 15 min. The SDK's own poll gives up after about 24 min, so
OAR's deadline comes first.
- **authStatus:** reads only `Cursor.auth.status()`, with `source:
"Cursor.auth.status"`.
- `logged-in` maps to `logged_in` with `account: { email?, expiresAt?
}`.
  - `logged-out` maps to `logged_out`.
- A throw, a timeout (20 s default) or an unreadable shape is `unknown`
with a redacted detail.
- **Installation:** cursor's installation is `{ via: "bundled" }`. The
login checks for exactly that and does not use `loginExecutable`, which
would wrongly answer `unsupported_installation`.
  - Any other installation is `unsupported_installation`.
- An SDK without `Cursor.auth` or `FileCredentialStore` is
`version_unsupported` (`@cursor/sdk 1.0.35 is required`).
  - A failed SDK load is `process_failed`.
- **`CursorSdk` (sdk.ts):** gains `Cursor.auth?` (`login`, `status`) and
`FileCredentialStore?`, narrowed to what is used.
- Both are optional, so a host's own stand-in for the SDK keeps
compiling.
- When they are present, the host's compile still checks their shape
against the real SDK. I checked that a wrong `status` or
`FileCredentialStore` shape fails `sea-trial/harness/runtimes.ts`
against the real module.
- **CLI:** `oar login cursor` works through the existing command. `oar
list` shows `login: true, authStatus: true` for cursor, and `--status`
prints the expiry: `logged in as [email protected] (expires
2027-01-04T12:00:00.000Z)`.

### Contract addition: `LoginAccount.expiresAt?: UtcInstant`

The SDK's `apiKeyExpiresAtMs` is carried as `LoginAccount.expiresAt`.
The change is additive and documented on the field and in
`docs/spec/login.md`. Why this place and this form:

- **Why `LoginAccount`:** both `LoginResult.logged_in.account` and
`AuthStatus.logged_in.account` already carry it. A login's result and
the status both show the expiry, and no union variant changes shape.
`LoginAccount` already describes the sign-in, not only the person: see
`method`. A field on the `logged_in` AuthStatus variant only would have
left it out of a login's result.
- **Why `UtcInstant` and not raw ms:** the contracts already carry a
runtime-reported instant as the branded ISO string `UtcInstant`
(`AccountUsageWindow.resetsAt`). Converting the epoch ms is lossless (ms
precision).
- **Meaning:** the field is set only where the runtime reports an expiry
for a credential it does not renew itself. Today that is only cursor's
minted key, which lasts 90 days with no refresh.

## Reviewer rules and how each holds (evidence: `@cursor/sdk`
**1.0.35**)

The SDK ships minified with no public source. I read the installed
bundle `dist/esm/index.js`, in the modules `Ne.auth`,
`./src/agent/auth/login-flow.ts` and
`./src/agent/auth/credential-store.ts`, together with their
`dist/esm/auth/*.d.ts`. `dist/cjs` and `dist/bundled` contain the same
code.

**1. `openBrowser: false`; the URL reaches the host only through
`onLoginUrl`; no paste-back prompt.**
- `Cursor.auth.login` builds the handshake and calls
`t.onLoginUrl?.(n.loginUrl)` first. Then `let s = void 0 !==
t.onLoginUrl`, and with `openBrowser` false it skips the opener. The
`process.stderr.write("Could not open a browser…")` runs only when `!s`,
so with `onLoginUrl` set the SDK prints no URL.
- OAR relays the URL as `auth_url` and asks no prompt. Test: `the URL
reaches the host through onLoginUrl only…` asserts `openBrowser ===
false` and that no prompts were asked.

**2. Cancel through `interaction.signal`; after a cancel, timeout or
failure, `~/.cursor/sdk/auth.json` is not written.**

What the SDK does:
- **Poll:** `pollForLoginTokens({ signal })` checks `signal.aborted`
before each attempt, passes `signal` to each `fetch`, and wakes the
backoff sleep on abort. It then returns `null`, and `login` throws
`AuthenticationError("Login was cancelled.")`. That is 150 attempts with
a delay of `min(1000·1.2^n, 10000)` ms, about 24 min.
- **Mint:** after the poll returns tokens, `mintUserApiKey`
(`createUserApiKey`, then `getMe`) runs without the signal.
- **Save:** then `if (null !== t.store) { const e = t.store ?? ut(); …;
await e.save(n); clearStoredLoginCache() }` runs unconditionally. `ut()`
is `new FileCredentialStore()`, and `FileCredentialStore.save` opens the
file with `"w"`, mode 0600.
- Nothing is written before that `save`, and login never calls `clear`.
- **So the SDK alone does not meet the rule:** an abort that lands after
the browser sign-in, during the mint, is ignored, and the file is
written.

How OAR guarantees it:
- OAR passes its own `store`. Its `save` hands the SDK's credential
object, unread, to the SDK's own `new sdk.FileCredentialStore()`: the
same default path that `status()` reads. It does so only while the login
is `waiting`.
- Once OAR has ended the login (abort, deadline, or a throwing
`onEvent`), `save` throws and writes nothing. OAR also aborts the signal
it gave the SDK, which ends the poll.
- The check-and-set is synchronous on both sides, so whichever comes
first decides:
- The save began first: the login stands. A later abort or deadline
waits for the save and yields `logged_in`, as the contract's "success is
final" requires.
- The end came first: every later save is refused, so `cancelled` and
`timed_out` always mean auth.json was not touched.
- The gate's `clear` always throws (never log out first), and `load`
returns nothing (login never reads its store).
- Tests: a cancel while polling; a cancel while minting, where the fake
ignores the signal like the SDK, and its late save is refused; the
deadline in both phases; a stop while the save is held (`logged_in`).

**3. `authStatus` only reads `Cursor.auth.status`; no key anywhere;
expiry carried; `source` named.**
- `status()` is `store.load()` on the file, then `logged-out` (missing,
corrupt or expired) or `{ "logged-in", backendUrl, email,
apiKeyExpiresAtMs }`. It never returns the key.
- OAR reads that and nothing else (`source: "Cursor.auth.status"`).
- A test feeds a status object that carries an `apiKey` and asserts the
key appears nowhere in the result.

**4. No token or code in an event, result, error or log; `detail`
redacted.**
- OAR types the SDK's login result as `unknown` and drops it unread.
- Every `detail` is `LoginSecrets.line()`: the first line, with the
`sk-…` and JWT shapes redacted, capped at 500 characters.
- Tests: a mint error carrying a JWT gives `[redacted]`; a status error
carrying an `sk-` token gives `[redacted]`; a leak check confirms the
minted key is absent from events and results.

**5. Contract semantics.**
- Success is final (above).
- A resolved login is confirmed via status:
  - `logged-out` is `failed / not_logged_in`.
- A status that fails, or an aborted caller, gives `logged_in` without
an account, per the contract text.
- `failed` reasons come from the existing union:
- Any SDK rejection is `rejected`: its own poll failing or running out,
a refused key ("Login succeeded, but creating an SDK API key failed:
…"), or a save that failed.
  - A failed load is `process_failed`.
  - A throwing `onEvent` is `interaction_failed`.
- `unsupported` appears only for a non-bundled installation or an SDK
without `Cursor.auth`.
- **`CURSOR_API_KEY`:** the SDK's precedence (`resolveDefaultApiKey`) is
an explicit key, then `process.env.CURSOR_API_KEY`, then the stored key,
and `status()` ignores the variable. OAR does not guess. `authStatus`
reports the stored login only. A login started with the variable set
adds an `info` event: "CURSOR_API_KEY is set in this environment: cursor
uses it, not the stored login, until it is unset." Only the variable's
presence is checked; its value is never read. Documented on the runtime
page.

## Not guaranteed / for the reviewer to decide

- **A minted key can be left unsaved.** If a stop lands after the
browser sign-in but before the save (the mint RPCs), the SDK has already
minted a key on Cursor's side. OAR refuses to store it, so it stays in
the dashboard's API-key list as `Cursor SDK login (<hostname>)` until it
expires (90 days) or is revoked. The SDK has no revoke call. auth.json
is untouched. This is documented.
- **OAR returns at once on a stop.** An SDK mint already in flight
finishes in the background, and its save is refused. OAR does not wait
for it, because the mint takes no signal.
- **One SDK warning reaches stderr.** When a backend has no `POST
/auth/poll`, the SDK falls back to `GET` and writes a warning to stderr.
It names the backend, not the verifier. OAR cannot suppress it
(`onWarning` is not an option), and against production it should not
occur.
- **Cursor's key format is not redacted by shape.** The SDK does not
document it, so there is no token shape for it in `LoginSecrets`. No
path I found carries the key into a `detail`.
- **Decisions:**
- `expiresAt` as `UtcInstant` on `LoginAccount`, rather than raw ms or a
field on `AuthStatus`.
- `Cursor.auth` and `FileCredentialStore` as optional members of
`CursorSdk` (doesn't break a host's stand-ins), rather than required
(stricter drift check).
- `authStatus` ignores `CURSOR_API_KEY`, and the login adds an `info`
event about it.
- A key stored against another `CURSOR_BACKEND_URL` reads `logged_in`
from the SDK's status even though the SDK only uses it against that
backend; OAR passes this through.
- **Possible stronger evidence, not done (rule 8):** run the real SDK's
`Cursor.auth.login` against a local mock backend (`CURSOR_BACKEND_URL`)
with a temporary `HOME`, as an experiment pinning the cancel-during-mint
window on the real code. It needs no account and touches no real
credentials. Say if you want it.

## Tests

`tests/login/cursor-login.test.ts`,
`tests/login/cursor-auth-status.test.ts`, with a stand-in SDK
(`tests/fixtures/fake-cursor-auth.ts`) that runs 1.0.35's order:
`onLoginUrl`, a poll that honours the signal, a mint that ignores it,
then `store.save`. Its `FileCredentialStore` writes what `status()`
reads. No network, no real SDK.
- the URL relayed; `openBrowser: false`; no prompt; success gives
`logged_in` with `{ email, expiresAt }` from status; the key is written
once and leaks nowhere
- a cancel while polling gives `cancelled`: the SDK's signal is aborted,
it throws `Login was cancelled.`, and nothing is written
- a cancel while minting gives `cancelled`: the late save is refused,
nothing is written, and the status still shows the previous login
- the deadline, while polling and while minting, gives `timed_out` and
nothing is written
- a cancel or deadline while the save is held gives `logged_in` (without
an account after an abort; with the account after a deadline)
- SDK rejections (poll failure, mint failure with a JWT, save EACCES)
give `rejected` with a redacted first line
- the status after save reads logged out (`not_logged_in`) or throws
(`logged_in` without an account)
- a throwing `onEvent` gives `interaction_failed`, with the SDK aborted
and nothing written
- `CURSOR_API_KEY` set gives the `info` event, and its value appears
nowhere
- an already-aborted signal (SDK not even loaded), a non-bundled
installation, an SDK without `Cursor.auth`, a failed load
- the status: logged in with and without fields, logged out, a throw
(redacted), no answer within `timeoutMs`, a non-bundled installation, no
`Cursor.auth`, a failed load, unreadable shapes; never the key
- CLI: `--status` renders the expiry

`pnpm run check` passes: typecheck (including the CLI against the real
`@cursor/sdk` 1.0.35), lint, 672 tests passed / 31 skipped, and mock
sea-trial 19/19. `CI=1 pnpm vitest run` passes with snapshots enforced,
and `pnpm run build` passes. Rebased on main `6386132` (v0.23.0,
opencode).

## Real-login checklist (passed 2026-10-07)

Don't print auth.json's contents: compare a hash prefix and the mtime
only. Linux: `sha256sum ~/.cursor/sdk/auth.json | cut -c1-16; stat -c %Y
~/.cursor/sdk/auth.json`. macOS: `shasum -a 256 … | cut -c1-16; stat -f
%m …`. Run in a shell where `CURSOR_API_KEY` is unset (`[ -z
"${CURSOR_API_KEY+x}" ] && echo unset`).

- [x] `oar login cursor --status`: note the state (and the expiry, if
logged in). Note auth.json's hash prefix and mtime, if the file exists.
- [x] `oar login cursor`: no browser opens on the machine and no paste
prompt appears. Open the printed URL on another device and sign in.
Expect `cursor logged in as <email> (expires <about 90 days from now>)`,
exit 0. Then `--status` shows the same account and expiry, and the hash
and mtime changed.
- [x] `oar login cursor` again, and press Ctrl-C while it waits, before
signing in. Expect `cursor login cancelled`, exit 130. auth.json's hash
and mtime are unchanged, and `--status` is unchanged.
- [x] `oar login cursor --timeout 30000` without signing in. Expect
`login failed: timed_out (no sign-in within 30000 ms)`, with auth.json
unchanged.
- [ ] Optional (the window the store guards, hard to hit by hand): sign
in on the other device and press Ctrl-C right as the page confirms.
Expect either `login cancelled` with auth.json unchanged, or `logged in`
with it changed; never `cancelled` with a changed file. A cancelled run
may leave a `Cursor SDK login (<host>)` key in the dashboard: revoke it.
- [x] (auth.json removed from the test machine; the minted `Cursor SDK
login (cindytest)` key stays in the dashboard until revoked) Afterwards,
if wanted: OAR has no logout. Remove `~/.cursor/sdk/auth.json` and
revoke the test key in the dashboard.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: exe.dev user <[email protected]>
xxchan added a commit that referenced this pull request Oct 7, 2026
…ogout (#196)

Implements #192: a host can sign a runtime out the way it signs it in.
This follows the shape @cindy decided in [the
issue](#192 (comment))
("Shape decided by @cindy"), and the patterns of #94 (claude, codex) and
#146 (cursor).

**API** (`contracts/login.ts`, beside `login` and `authStatus`)

```ts
// Runtime, optional member: absent on runtimes without a native logout
readonly logout?: RuntimeLogout;
type RuntimeLogout = (installation: AvailableInstallation, options?: { timeoutMs?: number }) => Promise<LogoutResult>;

type LogoutResult =
  | { kind: "logged_out" }
  | { kind: "failed"; reason: LogoutFailureReason; detail?: string }
  | { kind: "unsupported"; reason: LoginUnsupportedReason; detail?: string };

type LogoutFailureReason = "timed_out" | "rejected" | "process_failed" | "still_logged_in";
```

- **Only the runtime's own logout.** OAR never deletes a credential file
or a Keychain entry.
- **`authStatus` decides afterwards.** The result is `logged_out` only
when the status reads logged out after the logout ran. That includes a
runtime that was logged out already: it answers in its own words, and
the status decides.
- **`still_logged_in`:** the logout succeeded, yet the status still
reads logged in. `detail` says what the status read. The result is never
`logged_out` in this case.
- **The environment is not touched.** `ANTHROPIC_API_KEY`,
`CURSOR_API_KEY` and the like stay as they are.
- **`failed` reasons** reuse login's (`process_failed`, `timed_out`,
`rejected`) and add only `still_logged_in`.
- **`unsupported`** is only for the installation or the version.
- **Details** are redacted the same way as a login's
(`LoginSecrets.line`).
- **Scope:** claude, codex and cursor. pi keeps its logout in
`createPiProviderAuth`. antigravity, grok, kimi and opencode have no
`logout` member.
- **Docs:** `docs/spec/login.md#logout` is the contract page.

**Per runtime**

- **claude**: runs `claude auth logout` over pipes, through the login's
process machinery: its own process group, nothing forwarded, stdin
closed, `CLAUDECODE` cleared. `claude auth status --json` then decides.
- **Server side** (bundle 2.1.292, `authLogout` → `performLogout`):
claude revokes the stored claude.ai OAuth refresh token (`POST <token
URL>/revoke`, 5 s, best effort: a failed revoke is only logged). It then
deletes `~/.claude/.credentials.json` (the Keychain on macOS) and the
account in `~/.claude.json`.
- **Failure:** `Logout failed: <msg>` with exit 1 is `rejected` with
`<msg>`.
- **Observed** in a temporary HOME, in a network namespace with no
network, with claude 2.1.292:
- Already logged out: claude prints `Successfully logged out from your
Anthropic account.` and exits 0. The result is `logged_out`.
- With `ANTHROPIC_API_KEY` (a fake value) set: the status reads
`loggedIn: true`, `authMethod: "api_key"`, `apiKeySource:
"ANTHROPIC_API_KEY"` before and after the logout, so the result is
`still_logged_in` (`… still reads logged in (api_key, from
ANTHROPIC_API_KEY)`).
- With `CLAUDE_CODE_OAUTH_TOKEN` set: the status reads `oauth_token`.
  - **Floor:** 2.1.41, where `auth logout` arrived (changelog).
  - **Deadline:** 60 s.
- **codex**: runs `codex logout` the same way. `codex login status` then
decides.
- **Server side** (`openai/codex` `rust-v0.160.1`: `run_logout`,
`logout_with_revoke`, `revoke.rs`): codex revokes a ChatGPT login's
refresh token, or its access token, at `auth.openai.com/oauth/revoke`
(10 s, best effort; since 0.122.0, openai/codex#17825). It then deletes
`auth.json` and the keyring entry. A stored API key is only deleted.
  - **Failure:** `Error logging out: …` with exit 1 is `rejected`.
- **Observed** in a temporary `CODEX_HOME` with no network, codex
0.160.1:
- Empty home: `Not logged in`, exit 0, so the result is `logged_out`.
- A stored fake API key: `Successfully logged out`; `auth.json` is gone
and the status reads logged out.
- `OPENAI_API_KEY` and `CODEX_API_KEY` are invisible to `codex login
status`, so a logout with either set is `logged_out`. codex therefore
never produces `still_logged_in` from the environment.
  - **Floor:** 0.15.0, where `codex logout` arrived (openai/codex#1932).
  - **Deadline:** 60 s.
- **cursor**: calls `Cursor.auth.logout()` with no options, so the SDK
clears its own default store. `Cursor.auth.status` then decides.
- **Signature** (1.0.36 `stubs.d.ts` / `auth/login.d.ts`; 1.0.35 has the
same): `logout(options?: SdkLogoutOptions): Promise<void>`, with
`SdkLogoutOptions { store?: SdkCredentialStore }`.
- **Implementation:** `(store ?? new FileCredentialStore()).clear()`,
which is `rm(~/.cursor/sdk/auth.json, { force: true })`, then
`clearStoredLoginCache()`. It makes no request.
- **The minted key is not revoked.** It stays valid in the dashboard
(`Cursor SDK login (<host>)`) until it expires (90 days) or is revoked
there. The SDK has no revoke call; its own `.d.ts` says "Local-only".
The cursor page says so.
- **`CURSOR_API_KEY`:** untouched. The status ignores it (#146), so the
result is `logged_out` while the SDK keeps using the variable.
Documented.
- **Errors:** a throw is `rejected`. An SDK without `Cursor.auth.logout`
is `version_unsupported`; `CursorAuth.logout?` is optional, like `auth`,
so hosts' stand-ins keep compiling.
- **Deadline:** 20 s. The removal is local and can't be stopped; past
the deadline OAR stops waiting.

**CLI**
- `oar logout <runtime>` takes `--json` and `--timeout <ms>`.
- Exit codes follow login: 0 logged out, 1 otherwise. Ctrl-C ends the
command with 130.
- `oar logout all` is refused: it takes one runtime.
- `oar list` shows `logout`.

**Decisions beyond the spec (for review)**
1. **Status `unknown` after a successful logout** is `logged_out` on the
runtime's own report, as a login's success is `logged_in` (changed in
review; was `process_failed`). A status that reads logged in is still
`still_logged_in`.
2. **The status decides even when the logout failed or timed out:** if
it reads logged out, the result is `logged_out`. Example: claude cleared
the credentials, then failed writing its config. A logout's own failure
is reported only when the status doesn't read logged out.
3. **A logout that never started** (executable missing, spawn error) is
`process_failed` without a status read.
4. **No abort signal**, since the spec has only `timeoutMs`. Logouts are
short.
5. **Version floors:** claude 2.1.41 and codex 0.15.0, so older versions
are `version_unsupported` rather than an "unknown subcommand" failure.
6. **The `still_logged_in` detail names claude's `apiKeySource`.** An
internal `readClaudeAuthStatus` returns it next to the `AuthStatus`;
`AuthStatus` is unchanged.
7. **Plumbing:**
   - `LoginProcess.closeInput()` closes a logout command's stdin.
- `loginExecutable` now returns an `ExecutableRefusal` type that is
valid for both results.
- `registerLogoutCommand` and `claudeAuthStatus` are re-exported from
`login.ts`, to stay within the lint's import limit of 10.

**Tests**
- **claude, against `fake-claude-login.mjs`** (new `auth logout` modes):
  - logout, and logout again when already logged out;
  - stdin closed (a negative control without it times out);
  - `ANTHROPIC_API_KEY` gives `still_logged_in`;
  - `Logout failed:` gives `rejected`;
  - a failure after the credentials were cleared gives `logged_out`;
  - a crash gives `process_failed`, redacted;
- a status that cannot tell (`logged_out` after a success, the failure
after a failure);
- the deadline, with the process tree checked gone (also on Windows),
and the status deciding;
- the version floor, a bundled installation, a missing executable, and a
command that can't be spawned.
- **codex, against `fake-codex-login.mjs`:**
  - logout, then `Not logged in`;
  - `codex login` never runs;
  - `Error logging out:` gives `rejected`;
  - a status that still reads logged in gives `still_logged_in`;
  - a broken status after a success gives `logged_out`;
  - the deadline, with the tree checked gone;
  - the floor, bundled, and missing.
- **cursor, against the stand-in SDK:**
  - logout with no options (the SDK's own store), and logout again;
  - `CURSOR_API_KEY` untouched;
  - `still_logged_in`;
  - a throw gives `rejected`, redacted;
  - the deadline, and the status deciding;
- no `Cursor.auth.logout`, a non-bundled installation, and a failed
load.
- **CLI:** rendering and exit codes.
- **Real SDK:** `experiments/cursor-login/probe.ts` gained two scenarios
against the real `@cursor/sdk` 1.0.36, in temporary homes:
- a logout over a previous login removes `auth.json`, reads logged out,
and a second logout is `logged_out`;
  - with `CURSOR_API_KEY` set, the variable is left as it was.

Neither makes a request or prints anything. The run passed 11/11, inside
a network namespace with only loopback up.
- **End to end:** `oar logout claude` / `oar logout codex` against the
fakes through `OAR_CLAUDE_BIN` / `OAR_CODEX_BIN`, in a temporary HOME
with no network.
- **Gate:** `pnpm run check` and `CI=1 pnpm run check` pass (797 passed
/ 53 skipped, mock sea-trial 19/19), rebased on main `e1f9177`
(v0.33.1).

No real login or logout ran anywhere for this PR.

## Real-login checklist for cindytest (not run yet)

**Setup:**
- Check out this branch, then run `pnpm install && pnpm run build &&
alias oar="node $PWD/packages/cli/dist/index.js"`.
- Use a shell with `ANTHROPIC_API_KEY`, `CLAUDE_CODE_OAUTH_TOKEN`,
`CODEX_API_KEY`, `OPENAI_API_KEY` and `CURSOR_API_KEY` unset: `env |
grep -E
'ANTHROPIC_API_KEY|CLAUDE_CODE_OAUTH_TOKEN|CODEX_API_KEY|OPENAI_API_KEY|CURSOR_API_KEY'
| cut -d= -f1` prints nothing.
- Never print the credential files.
- `oar list`: `logout: true` for claude, codex and cursor.

**claude**
- [ ] `oar login claude` (the account owner pastes the code). Expect
`claude logged in as <email> (claude.ai, <plan>)`.
- [ ] `oar logout claude; echo $?`. Expect `claude logged out` and `0`.
Then `oar login claude --status` shows `claude logged out`, and `claude
auth status` says `Not logged in`. Linux: `ls
~/.claude/.credentials.json` reports no such file.
- [ ] `oar logout claude; echo $?` again. Expect `claude logged out` and
`0`.
- [ ] `ANTHROPIC_API_KEY=sk-ant-api03-not-a-real-key oar logout claude;
echo $?`. Expect `claude logout failed: still_logged_in (claude auth
logout succeeded, yet claude auth status --json still reads logged in
(api_key, from ANTHROPIC_API_KEY))` and `1`. The key isn't validated,
and no request uses it.

**codex**
- [ ] `oar login codex` (the account owner enters the device code).
Expect `codex logged in as <email> (chatgpt, <plan>)`.
- [ ] `oar logout codex; echo $?`. Expect `codex logged out` and `0`.
Then `codex login status` says `Not logged in`, and `ls
~/.codex/auth.json` reports no such file.
- [ ] `oar logout codex; echo $?` again (codex itself answers `Not
logged in`). Expect `codex logged out` and `0`.
- [ ] `CODEX_API_KEY=sk-not-a-real-key oar logout codex; echo $?`.
Expect `codex logged out` and `0`: `codex login status` ignores the
variable, so codex has no `still_logged_in` from the environment.

**cursor**
- [ ] `oar login cursor` (the account owner opens the URL on another
device). Expect `cursor logged in as <email> (expires <~90 days>)`.
- [ ] `oar logout cursor; echo $?`. Expect `cursor logged out` and `0`.
Then `ls ~/.cursor/sdk/auth.json` reports no such file, and `oar login
cursor --status` shows `cursor logged out`.
- [ ] In the Cursor dashboard's API keys, `Cursor SDK login (cindytest)`
is **still listed**: the logout is local only. Revoke it there by hand.
- [ ] `oar logout cursor; echo $?` again. Expect `cursor logged out` and
`0`.
- [ ] `CURSOR_API_KEY=crsr-not-a-real-key oar logout cursor; echo $?`.
Expect `cursor logged out` and `0`; the status ignores the variable.

**Optional:** server-side revocation for claude and codex is best
effort. A login's token that was revoked shows up as the vendor's
"revoked" error if it is reused; the checklist doesn't try that.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: exe.dev user <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant