diff --git a/README.md b/README.md index 4f97ea2..f988bfb 100644 --- a/README.md +++ b/README.md @@ -123,16 +123,17 @@ npx @expo/code-review-cli doctor The scaffolded default is **Anthropic via the Claude Code CLI**: locally your `claude` login is enough, and for CI it helps you mint a token with `claude setup-token`. It also handles the alternatives (an OpenAI **API key**, -a **ChatGPT/Codex subscription** sign-in, or a Meta Model API key for **Muse -Spark**). `doctor` offers to run it whenever a credential is missing. +a **ChatGPT/Codex subscription** sign-in, a **SuperGrok subscription** sign-in, +or a Meta Model API key for **Muse Spark**). `doctor` offers to run it whenever a +credential is missing. In CI, store the credential as the repo secret the scaffolded workflow forwards (`CLAUDE_CODE_REVIEW_SHARED_API_TOKEN` by default — an `sk-ant-oat…` token from `claude setup-token`, or an `sk-ant-api…` Console key; the CLI reads either). Prefer **Muse Spark**, **OpenAI** (API key, or a ChatGPT/Codex subscription, or -both mixed), or another provider? See [Other providers & auth modes](#other-providers) -below. +both mixed), **Grok** (SuperGrok or an xAI API key), or another provider? See +[Other providers & auth modes](#other-providers) below. ### Reviewing (already configured) @@ -997,6 +998,42 @@ fallback key; `ecr doctor` diagnoses setup. `$0` cost — OpenCode can't price config-declared aliases; the OpenAI dashboard is the source of truth for spend). +- **xAI / Grok.** Models stay `xai/` (for example `xai/grok-4.7`) on the + OpenCode engine. A SuperGrok subscription and a console API key are different + credentials. + + ```jsonc + "auth": { "providers": { + "xai": { "mode": "oauth", "tokenEnv": "XAI_OAUTH_ACCESS_TOKEN" } + } } + ``` + + ```jsonc + "auth": { "providers": { + "xai": { "mode": "api-key", "tokenEnv": "XAI_API_KEY" } + } } + ``` + + `ecr setup-auth` runs the bundled + `opencode auth login -p xai -m "SuperGrok Subscription"`. That prints a device + code for . The command then exports the + **access** token from OpenCode's store. The refresh token stays there. Reviews + copy that access token into an isolated `auth.json` (empty `refresh`) and do + not set `XAI_API_KEY` from it. An API key is created at + and exported as `XAI_API_KEY`. `mode: "oauth"` caps + concurrency at 3. An API key stays at 6. + + The access token lasts 6 hours, and a review cannot renew it. So the SuperGrok + mode suits local runs: a CI secret goes stale the same day unless a job + re-mints it. + `ecr doctor` and the review both warn when under two hours are left. The + review stops before any pass when 120 seconds or less are left. Run + `ecr setup-auth` again for a new token. It signs in again unless a review + would take the current token without a warning. + + `XAI_OAUTH_ACCESS_TOKEN` needs `"mode": "oauth"`. An entry that names it + without that mode is refused. + - **Another provider** — `opencode auth login` once, then run with e.g. `REVIEWER_MODEL=google/gemini-3-pro`. No `auth` block needed. diff --git a/llp/0001-trust-model.principles.md b/llp/0001-trust-model.principles.md index bb343ee..3bc650f 100644 --- a/llp/0001-trust-model.principles.md +++ b/llp/0001-trust-model.principles.md @@ -104,7 +104,16 @@ in the deny-list — an anthropic entry may legitimately name them — but a cross-provider guard refuses a non-anthropic entry that names one. Without it, `{provider:"openai", tokenEnv:"CLAUDE_CODE_OAUTH_TOKEN"}` would slip past (neither a forbidden secret nor a provider key) and forward the Anthropic subscription -token to a foreign provider [observed] (`src/core/auth.ts:19-33`, commit 93aaf30). +token to a foreign provider [observed] (`src/core/auth.ts` `ANTHROPIC_TOKEN_ENVS`, commit 93aaf30). +`XAI_OAUTH_ACCESS_TOKEN` belongs to `xai` the same way (`XAI_TOKEN_ENVS`). +`XAI_API_KEY` belongs to `xai` through `PROVIDER_KEY_ENV`. A non-xai entry that +names either is refused, and `upstream: "xai"` does not make another provider id +an owner. `CODEX_OAUTH_ACCESS_TOKEN` and `CODEX_OAUTH_REFRESH_TOKEN` belong to +`openai` (`CODEX_OAUTH_TOKEN_ENVS`): a ChatGPT access token is a JWT, so the xAI +shape check alone would accept it. Only an api-key alias may borrow its +upstream's key. An oauth entry never does, because it is staged under its own +`provider` [observed] (`src/core/auth.ts` `checkAuthEntry`; tests in +`src/__tests__/auth.test.ts`). The credential must never reach logs, error messages, or `.expo-code-review/.runs/`. This is a named cross-cutting invariant, not an incidental property [observed] diff --git a/llp/0003-model-runtimes-and-credentials.explainer.md b/llp/0003-model-runtimes-and-credentials.explainer.md index 13fd661..b81c4c8 100644 --- a/llp/0003-model-runtimes-and-credentials.explainer.md +++ b/llp/0003-model-runtimes-and-credentials.explainer.md @@ -354,7 +354,14 @@ auto-review path it can be PR-controlled. ownership guard: a non-anthropic entry naming an Anthropic token env is refused. Without that guard, `{provider:"openai", tokenEnv:"CLAUDE_CODE_OAUTH_TOKEN"}` passes both other checks and forwards the Anthropic subscription token to a foreign provider -([observed] `auth.ts:20-34`; commit `93aaf30`). +([observed] `auth.ts` `ANTHROPIC_TOKEN_ENVS`; commit `93aaf30`). The same guard +covers `XAI_TOKEN_ENVS`: a non-xai entry that names `XAI_OAUTH_ACCESS_TOKEN` is +refused, and `XAI_API_KEY` is owned through `PROVIDER_KEY_ENV`. +`CODEX_OAUTH_TOKEN_ENVS` gives both Codex names to `openai`. `upstream` counts as +the owner only for an api-key alias. An oauth entry is staged under its own +`provider`, so `upstream` decides nothing there. An xAI credential never passes +through an alias: an `xai` alias is synthesized with the openai-compatible SDK and +no host ([observed] `auth.ts` `checkAuthEntry`; `opencode.ts` `buildOpencodeConfig`). **Scoped to providers in use.** Auth checks (`checkProviderAuth`) and credential forwarding are scoped to only the providers a resolved model actually routes to. A dead @@ -366,12 +373,42 @@ secret-forwarding the guard prevents ([observed] `auth.ts:378-392`). **Isolated staging, engines kept separate.** `prepareAuth` writes all OAuth credentials into one **isolated** OpenCode `auth.json` under a temp dir pointed to by `XDG_DATA_HOME`, so a run's injected credentials never touch the developer's real -`auth.json` ([observed] `auth.ts:557-560`). It must run and complete before the server +`auth.json` ([observed] `auth.ts` `prepareAuth`). It must run and complete before the server starts, because it mutates env the spawned server reads — documented as a precondition, -not a convenience ([observed] `auth.ts:479-482`). Anthropic credentials **never** pass +not a convenience ([observed] `auth.ts` `prepareAuth`). Anthropic credentials **never** pass through this path at all: anthropic is Claude-engine-only, so its credential is injected per-invocation into the Claude CLI child env by `startClaudeCode`, keeping the two -engines' credential plumbing fully separate ([observed] `auth.ts:527-532`). +engines' credential plumbing fully separate ([observed] `auth.ts` `prepareAuth`; +`claude-code.ts` `claudeTokenCredential`). + +**xAI follows the Codex file, not the Claude child env.** A `xai` oauth review writes +the SuperGrok access token into that same isolated `auth.json`: `type` `oauth`, `access` +set, `refresh` empty, `expires` from the JWT `exp` claim. `prepareAuth` does not copy +that token into `XAI_API_KEY`. An api-key entry that names `XAI_OAUTH_ACCESS_TOKEN` is +refused: `api-key` is the schema default, and it would send the token as a key with no +expiry check. An opaque xAI value is refused before any pass, and the +message names `ecr setup-auth`. A JWT that is expired, or that has 120 seconds or less +left, fails the same way, because the isolated entry has no refresh token. 120 seconds +is the point where OpenCode would refresh on the first request. Under about +two hours left, `doctor` and the run both warn and continue: `prepareAuth` returns the +warnings of the tokens it staged, and `runReview` prints them. The hard failure stays +at 120 seconds on purpose. A token that lapses later still fails the passes that run +then, and the warning says so. The token is short-lived: an access token from the +pinned OpenCode's SuperGrok login had `exp − iat` = 21600 seconds, and OpenCode stored +the same deadline in `expires` ([observed] 2026-11-27). The pinned OpenCode sends the +staged token as a bearer to `https://api.x.ai/v1/responses`, because no `provider.xai` +block changes the SDK's default host ([observed] 2026-11-27 with a placeholder token, +which that host refused with 400). With a real token staged the same way, one direct +request and one local review on `xai/grok-4.7` completed ([observed] 2026-11-27; the +token's scope held `grok-cli:access` and `api:access`). The user's +`~/.local/share/opencode/auth.json` is written by OpenCode during +`opencode auth login` and is only read by setup-auth, which exports the access token. +API-key mode copies the configured env into `XAI_API_KEY` (`PROVIDER_KEY_ENV`) and +writes no oauth entry. An `xai` api-key entry with no `tokenEnv` and no `XAI_API_KEY` +still passes and relies on OpenCode's own login, as it did before `XAI_API_KEY` had an +owner. `XAI_OAUTH_ACCESS_TOKEN` belongs to `xai` the same way +`CLAUDE_CODE_OAUTH_TOKEN` belongs to `anthropic` ([observed] `auth.ts` +`checkOauthTokenShape`, `XAI_TOKEN_ENVS`, `oauthAuthJsonEntry`, `prepareAuth`). **A deliberate re-check at the forwarding site.** The deny-list check (`checkAuthEntry`) is re-run at the Claude CLI credential-forwarding site inside `startClaudeCode`, in @@ -388,16 +425,20 @@ not a hole, because it requires an explicit env var the CI workflow never sets credential by what the token **is**: a JWT access token (three base64url segments) is used as-is with its own `exp` claim and never refreshed; an opaque OpenAI value is stored with `expires: 0` so OpenCode's codex plugin mints access tokens via its refresh -flow. Mixing the two breaks because refresh tokens are **single-use** — the +flow. That opaque-as-refresh branch is **openai-only**. A JWT for any other provider, +including xAI, is staged as the access token with an empty `refresh`. Mixing the two +breaks because refresh tokens are **single-use** — the refresh-token-as-static-secret strategy died in production (every pass "Token refresh failed: 401"; the shared copy was spent by its first use). The opaque strategy is only safe when the run is the token's **sole** consumer; a value shared across runs or repos -dies on first rotation ([observed] `auth.ts:452-477`; commit `188f852`, euxy#8). The -hard-fail bar for `checkOauthTokenShape` is deliberately narrow — "this cannot be a +dies on first rotation ([observed] `auth.ts` `oauthAuthJsonEntry`; commit `188f852`, euxy#8). The +hard-fail bar for `checkOauthTokenShape` is deliberately narrow for providers whose +format we do not know — "this cannot be a valid credential" (whitespace, absurd length, an API key in OAuth mode, a provably-mangled `sk-` prefix), not "this looks odd" — because a false rejection blocks a working setup, which is judged worse than the failure being prevented ([observed] -`auth.ts:88-101`). +`auth.ts` `checkOauthTokenShape`). xAI is judged more strictly: the value must be a +JWT access token, because the isolated entry cannot refresh. ## Subprocess Spawning Rules diff --git a/llp/0007-cli-commands-and-ci.explainer.md b/llp/0007-cli-commands-and-ci.explainer.md index 6640986..ef818f6 100644 --- a/llp/0007-cli-commands-and-ci.explainer.md +++ b/llp/0007-cli-commands-and-ci.explainer.md @@ -137,10 +137,11 @@ doctor resolves auth the way real reviews do: a `routing.jsonc` `defaults.auth` `ecr setup-auth` derives a plan from the repo's auth config via a pure `planFromAuth`, then guides local credential acquisition. Its decisions: - It hands out only ACCESS tokens; the refresh token never leaves OpenCode's store, because OpenCode's refresh tokens are SINGLE-USE (rotation) and OpenCode is their sole legitimate consumer — a copy in a shell config or CI secret dies on the next rotation and can take the whole sign-in down with it [observed: `src/commands/setup-auth.ts:87-93`]. -- The exported shell line single-quotes the token value so a token containing shell metacharacters (`$HOME`, `!`) is never expanded when sourced [observed: `src/commands/setup-auth.ts:127-131`; test in `src/__tests__/setup-auth.test.ts`]. +- The exported shell line single-quotes the token value so a token containing shell metacharacters (`$HOME`, `!`) is never expanded when sourced [observed: `src/commands/setup-auth.ts:127-131`; test in `src/__tests__/setup-auth.test.ts`]. A single quote in the value is escaped. The env name is printed unquoted, and the config that names it comes from the repo, so the schema refuses an `auth` `tokenEnv` that is not an env var name. That check sits on the `auth` union, not on the field: a field error in the map shape would fall through to the legacy shape and load the default auth [observed: `src/commands/setup-auth.ts` `exportLine`; `src/config/schema.ts` `ENV_VAR_NAME`; test in `src/__tests__/config-load.test.ts`]. - `anthropic` auth is always satisfied by the Claude Code CLI subscription-login flow regardless of the declared `mode` (oauth vs api-key) — mode is irrelevant for that provider [observed: `src/commands/setup-auth.ts:50-59`]. - A `meta` API-key entry is a manual-key plan: setup-auth points to the Meta AI developer portal and prints the configured `META_API_KEY` export, while doctor uses the same generic provider readiness check as the real review [observed: `src/commands/setup-auth.ts` `planFromAuth` / manual-key guidance; `src/core/auth.ts` `PROVIDER_KEY_ENV`]. -- The two interactive logins run via `spawnSync` with `stdio: "inherit"` and `cwd: os.tmpdir()` — the tmpdir cwd keeps a possibly-untrusted checkout from becoming the login subprocess's working directory, and the `inherit` stdio is why these two calls cannot be converted to `exec.ts`'s capturing `run()` [observed: `src/commands/setup-auth.ts:200-203,256-259`]. `ecr attach` is interactive too, but it stays inside `exec.ts` via `spawnInherited` because the opened session needs the terminal (see [Session archive](#session-archive)). +- A `xai` oauth entry is a SuperGrok login. setup-auth runs the bundled CLI as `opencode auth login -p xai -m "SuperGrok Subscription"` (`SUPERGROK_LOGIN_ARGS`), with cwd `os.tmpdir()`. OpenCode prints a device code for `https://accounts.x.ai/oauth2/device`. setup-auth then reads `xai.access` from OpenCode's own auth.json and exports that access token. The refresh token stays in the store. A stored token, or one already in the token env, is reused only when a review would take it with no error and no expiry warning. Otherwise setup-auth signs in again, because the review names this command as the fix for both. setup-auth cannot refresh: after the token lapses, it runs the device login again. An xAI api-key entry stays manual and points at `https://console.x.ai` [observed: `src/commands/setup-auth.ts` `planFromAuth`, `accessTokenFromStore`, `superGrokTokenComplaint`]. +- The two interactive logins run via `spawnSync` with `stdio: "inherit"` and `cwd: os.tmpdir()` — the tmpdir cwd keeps a possibly-untrusted checkout from becoming the login subprocess's working directory, and the `inherit` stdio is why these two calls cannot be converted to `exec.ts`'s capturing `run()` [observed: `src/commands/setup-auth.ts:200-203,256-259`]. The temp dir alone is not enough for OpenCode, which also reads `opencode.json` and `.opencode/` from every parent of its cwd, and the temp dir is the shared `/tmp` on Linux. So the OpenCode logins set `OPENCODE_DISABLE_PROJECT_CONFIG=1` [observed: `src/commands/setup-auth.ts` `opencodeLoginEnv`; the pinned `opencode debug config` loads a parent directory's `opencode.json` without the flag and not with it]. `ecr attach` is interactive too, but it stays inside `exec.ts` via `spawnInherited` because the opened session needs the terminal (see [Session archive](#session-archive)). ## init and dismiss diff --git a/src/__tests__/auth.test.ts b/src/__tests__/auth.test.ts index 8591182..8be6f9b 100644 --- a/src/__tests__/auth.test.ts +++ b/src/__tests__/auth.test.ts @@ -1,3 +1,5 @@ +import { tmpdir } from "node:os"; + import { test, expect } from "bun:test"; import { @@ -589,3 +591,280 @@ test("jwtExpiryMs decodes exp and tolerates garbage", () => { const jwt = `eyJ.${Buffer.from(JSON.stringify({ exp: 1000 })).toString("base64url")}.s`; expect(jwtExpiryMs(jwt)).toBe(1000_000); }); + +function xaiJwt(secondsFromNow: number): string { + const exp = Math.floor(Date.now() / 1000) + secondsFromNow; + return `eyJhbGciOiJSUzI1NiJ9.${Buffer.from(JSON.stringify({ exp })).toString("base64url")}.sig`; +} + +test("xAI oauth accepts a live JWT and refuses an opaque token", () => { + const live = checkOauthTokenShape("xai", xaiJwt(5 * 24 * 3600), "XAI_OAUTH_ACCESS_TOKEN"); + expect(live.ok).toBe(true); + expect(live.warning).toBeUndefined(); + + const opaque = checkOauthTokenShape("xai", "x".repeat(80), "XAI_OAUTH_ACCESS_TOKEN"); + expect(opaque.ok).toBe(false); + expect(opaque.detail).toContain("opaque"); + expect(opaque.detail).toContain("setup-auth"); +}); + +test("an expired xAI JWT fails before any pass", () => { + const r = checkOauthTokenShape("xai", xaiJwt(-120), "XAI_OAUTH_ACCESS_TOKEN"); + expect(r.ok).toBe(false); + expect(r.detail).toContain("EXPIRED"); + expect(r.detail).toContain("setup-auth"); +}); + +test("an xAI JWT inside 120 seconds fails", () => { + const r = checkOauthTokenShape("xai", xaiJwt(60), "XAI_OAUTH_ACCESS_TOKEN"); + expect(r.ok).toBe(false); + expect(r.detail).toContain("120"); + expect(r.detail).toContain("setup-auth"); +}); + +test("an xAI JWT with a couple of hours left warns and still runs", () => { + const r = checkOauthTokenShape("xai", xaiJwt(90 * 60), "XAI_OAUTH_ACCESS_TOKEN"); + expect(r.ok).toBe(true); + expect(r.warning).toContain("expires in"); +}); + +test("XAI_API_KEY and XAI_OAUTH_ACCESS_TOKEN belong to xai", () => { + const key = checkProviderAuth( + cfg({ mode: "api-key", provider: "openai", tokenEnv: "XAI_API_KEY" }), + { XAI_API_KEY: "xai-key-" + "k".repeat(40) }, + ); + expect(key.ok).toBe(false); + expect(key.detail).toContain("xai's"); + + const oauth = checkProviderAuth( + cfg({ mode: "oauth", provider: "openai", tokenEnv: "XAI_OAUTH_ACCESS_TOKEN" }), + { XAI_OAUTH_ACCESS_TOKEN: xaiJwt(5 * 24 * 3600) }, + ); + expect(oauth.ok).toBe(false); + expect(oauth.detail).toContain("xai's"); + + expect( + checkProviderAuth(cfg({ mode: "api-key", provider: "xai", tokenEnv: "XAI_API_KEY" }), { + XAI_API_KEY: "xai-key-" + "k".repeat(40), + }).ok, + ).toBe(true); + expect( + checkProviderAuth(cfg({ mode: "oauth", provider: "xai", tokenEnv: "XAI_OAUTH_ACCESS_TOKEN" }), { + XAI_OAUTH_ACCESS_TOKEN: xaiJwt(5 * 24 * 3600), + }).ok, + ).toBe(true); +}); + +test("prepareAuth stages an xAI access token and leaves the API key unset", async () => { + const prevModel = process.env.REVIEWER_MODEL; + const prevXdg = process.env.XDG_DATA_HOME; + const prevKey = process.env.XAI_API_KEY; + delete process.env.REVIEWER_MODEL; + delete process.env.XAI_API_KEY; + process.env.ECR_TEST_XAI = xaiJwt(5 * 24 * 3600); + process.env.ECR_TEST_CODEX = "r".repeat(80); + process.env.ECR_TEST_ANTHROPIC = OAUTH; + try { + const prepared = await prepareAuth( + cfg([ + { mode: "oauth", provider: "xai", tokenEnv: "ECR_TEST_XAI" }, + { mode: "oauth", provider: "openai", tokenEnv: "ECR_TEST_CODEX" }, + { mode: "oauth", provider: "anthropic", tokenEnv: "ECR_TEST_ANTHROPIC" }, + ]), + ); + expect(process.env.XDG_DATA_HOME?.startsWith(tmpdir())).toBe(true); + expect(process.env.XDG_DATA_HOME).toContain("ecr-auth-"); + expect(process.env.XAI_API_KEY).toBeUndefined(); + const written = JSON.parse( + await Bun.file(`${process.env.XDG_DATA_HOME}/opencode/auth.json`).text(), + ); + expect(written.xai).toEqual({ + type: "oauth", + access: process.env.ECR_TEST_XAI, + refresh: "", + expires: jwtExpiryMs(process.env.ECR_TEST_XAI!)!, + }); + expect(written.openai).toEqual({ + type: "oauth", + access: "", + refresh: process.env.ECR_TEST_CODEX, + expires: 0, + }); + expect(written.anthropic).toBeUndefined(); + await prepared.cleanup(); + } finally { + delete process.env.ECR_TEST_XAI; + delete process.env.ECR_TEST_CODEX; + delete process.env.ECR_TEST_ANTHROPIC; + if (prevModel === undefined) delete process.env.REVIEWER_MODEL; + else process.env.REVIEWER_MODEL = prevModel; + if (prevXdg === undefined) delete process.env.XDG_DATA_HOME; + else process.env.XDG_DATA_HOME = prevXdg; + if (prevKey === undefined) delete process.env.XAI_API_KEY; + else process.env.XAI_API_KEY = prevKey; + } +}); + +test("prepareAuth copies an xAI API key and writes no auth.json", async () => { + const prevModel = process.env.REVIEWER_MODEL; + const prevXdg = process.env.XDG_DATA_HOME; + const prevKey = process.env.XAI_API_KEY; + delete process.env.REVIEWER_MODEL; + delete process.env.XAI_API_KEY; + process.env.ECR_TEST_XAI_KEY = "xai-" + "k".repeat(40); + try { + const prepared = await prepareAuth( + cfg({ mode: "api-key", provider: "xai", tokenEnv: "ECR_TEST_XAI_KEY" }), + ); + expect(process.env.XAI_API_KEY).toBe(process.env.ECR_TEST_XAI_KEY); + expect(process.env.XDG_DATA_HOME).toBe(prevXdg); + await prepared.cleanup(); + } finally { + delete process.env.ECR_TEST_XAI_KEY; + if (prevModel === undefined) delete process.env.REVIEWER_MODEL; + else process.env.REVIEWER_MODEL = prevModel; + if (prevXdg === undefined) delete process.env.XDG_DATA_HOME; + else process.env.XDG_DATA_HOME = prevXdg; + if (prevKey === undefined) delete process.env.XAI_API_KEY; + else process.env.XAI_API_KEY = prevKey; + } +}); + +test("prepareAuth refuses an opaque xAI oauth token before staging", async () => { + const prevModel = process.env.REVIEWER_MODEL; + const prevXdg = process.env.XDG_DATA_HOME; + delete process.env.REVIEWER_MODEL; + process.env.ECR_TEST_XAI = "x".repeat(80); + try { + await expect( + prepareAuth(cfg({ mode: "oauth", provider: "xai", tokenEnv: "ECR_TEST_XAI" })), + ).rejects.toThrow(/setup-auth/); + expect(process.env.XDG_DATA_HOME).toBe(prevXdg); + } finally { + delete process.env.ECR_TEST_XAI; + if (prevModel === undefined) delete process.env.REVIEWER_MODEL; + else process.env.REVIEWER_MODEL = prevModel; + if (prevXdg === undefined) delete process.env.XDG_DATA_HOME; + else process.env.XDG_DATA_HOME = prevXdg; + } +}); + +test("a Codex token env belongs to openai", () => { + // A ChatGPT access token is a JWT too, so the xAI shape check alone would take it. + const stolen = checkProviderAuth( + cfg({ mode: "oauth", provider: "xai", tokenEnv: "CODEX_OAUTH_ACCESS_TOKEN" }), + { CODEX_OAUTH_ACCESS_TOKEN: xaiJwt(5 * 24 * 3600) }, + ); + expect(stolen.ok).toBe(false); + expect(stolen.detail).toContain("openai's"); + + expect( + checkProviderAuth( + cfg({ mode: "oauth", provider: "openai", tokenEnv: "CODEX_OAUTH_ACCESS_TOKEN" }), + { CODEX_OAUTH_ACCESS_TOKEN: xaiJwt(5 * 24 * 3600) }, + ).ok, + ).toBe(true); +}); + +test("an alias cannot borrow an xAI credential", () => { + const oauthAlias = checkProviderAuth( + cfg({ mode: "oauth", provider: "openai", upstream: "xai", tokenEnv: "XAI_OAUTH_ACCESS_TOKEN" }), + { XAI_OAUTH_ACCESS_TOKEN: xaiJwt(5 * 24 * 3600) }, + ); + expect(oauthAlias.ok).toBe(false); + expect(oauthAlias.detail).toContain("xai's"); + + const keyAlias = checkProviderAuth( + cfg({ mode: "api-key", provider: "openrouter", upstream: "xai", tokenEnv: "XAI_API_KEY" }), + { XAI_API_KEY: "xai-key-" + "k".repeat(40) }, + ); + expect(keyAlias.ok).toBe(false); + expect(keyAlias.detail).toContain("xai's"); +}); + +test("an oauth entry cannot borrow a credential through upstream", () => { + const r = checkProviderAuth( + cfg({ + mode: "oauth", + provider: "openai", + upstream: "anthropic", + tokenEnv: "CLAUDE_CODE_OAUTH_TOKEN", + }), + { CLAUDE_CODE_OAUTH_TOKEN: OAUTH }, + ); + expect(r.ok).toBe(false); + expect(r.detail).toContain("anthropic's"); +}); + +test("an api-key alias still carries its upstream's key", () => { + const r = checkProviderAuth( + cfg({ + mode: "api-key", + provider: "openai-api", + upstream: "openai", + tokenEnv: "OPENAI_API_KEY", + }), + { OPENAI_API_KEY: "sk-" + "k".repeat(40) }, + ); + expect(r.ok).toBe(true); +}); + +test("api-key mode refuses the SuperGrok token env and copies nothing", async () => { + const entry = { mode: "api-key", provider: "xai", tokenEnv: "XAI_OAUTH_ACCESS_TOKEN" }; + const r = checkProviderAuth(cfg(entry), { XAI_OAUTH_ACCESS_TOKEN: xaiJwt(5 * 24 * 3600) }); + expect(r.ok).toBe(false); + expect(r.detail).toContain('"mode": "oauth"'); + + const prevModel = process.env.REVIEWER_MODEL; + const prevKey = process.env.XAI_API_KEY; + const prevToken = process.env.XAI_OAUTH_ACCESS_TOKEN; + delete process.env.REVIEWER_MODEL; + delete process.env.XAI_API_KEY; + process.env.XAI_OAUTH_ACCESS_TOKEN = xaiJwt(5 * 24 * 3600); + try { + await expect(prepareAuth(cfg(entry))).rejects.toThrow(/"mode": "oauth"/); + expect(process.env.XAI_API_KEY).toBeUndefined(); + } finally { + if (prevModel === undefined) delete process.env.REVIEWER_MODEL; + else process.env.REVIEWER_MODEL = prevModel; + if (prevKey === undefined) delete process.env.XAI_API_KEY; + else process.env.XAI_API_KEY = prevKey; + if (prevToken === undefined) delete process.env.XAI_OAUTH_ACCESS_TOKEN; + else process.env.XAI_OAUTH_ACCESS_TOKEN = prevToken; + } +}); + +test("an xai api-key entry with no tokenEnv still relies on OpenCode's login", () => { + const xai = checkProviderAuth(cfg({ mode: "api-key", provider: "xai" }), {}); + expect(xai.ok).toBe(true); + expect(xai.detail).toContain("OpenCode's own login"); + + // Other providers with a known key env keep failing fast. + expect(checkProviderAuth(cfg({ mode: "api-key", provider: "openai" }), {}).ok).toBe(false); +}); + +test("prepareAuth hands the run the expiry warning of a staged token", async () => { + const prevModel = process.env.REVIEWER_MODEL; + const prevXdg = process.env.XDG_DATA_HOME; + delete process.env.REVIEWER_MODEL; + const entry = { mode: "oauth", provider: "xai", tokenEnv: "ECR_TEST_XAI" }; + try { + process.env.ECR_TEST_XAI = xaiJwt(90 * 60); + const lapsing = await prepareAuth(cfg(entry)); + expect(lapsing.warnings).toHaveLength(1); + expect(lapsing.warnings[0]).toContain("expires in 90 minute(s)"); + expect(lapsing.warnings[0]).toContain("setup-auth"); + await lapsing.cleanup(); + + process.env.ECR_TEST_XAI = xaiJwt(5 * 24 * 3600); + const live = await prepareAuth(cfg(entry)); + expect(live.warnings).toEqual([]); + await live.cleanup(); + } finally { + delete process.env.ECR_TEST_XAI; + if (prevModel === undefined) delete process.env.REVIEWER_MODEL; + else process.env.REVIEWER_MODEL = prevModel; + if (prevXdg === undefined) delete process.env.XDG_DATA_HOME; + else process.env.XDG_DATA_HOME = prevXdg; + } +}); diff --git a/src/__tests__/config-load.test.ts b/src/__tests__/config-load.test.ts index 9bcc841..54ae6c5 100644 --- a/src/__tests__/config-load.test.ts +++ b/src/__tests__/config-load.test.ts @@ -367,3 +367,32 @@ test("loadReviewConfig: reads the PR template comments from the repository root" await rm(root, { recursive: true, force: true }); } }); + +test("loadReviewConfig: an auth tokenEnv with shell syntax fails at load", async () => { + const root = await configDirWithAgent("IOS"); + const configPath = path.join(root, CONFIG_DIRNAME, "config.jsonc"); + const hostile = "X=1; touch /tmp/pwned; Y"; + try { + // setup-auth prints the name into an `export NAME='…'` line, so both shapes must refuse it. + await writeFile( + configPath, + JSON.stringify({ auth: { providers: { xai: { mode: "oauth", tokenEnv: hostile } } } }), + ); + await expect(loadReviewConfig(root)).rejects.toThrow(/tokenEnv must be an env var name/); + await writeFile( + configPath, + JSON.stringify({ auth: { mode: "oauth", provider: "xai", tokenEnv: hostile } }), + ); + await expect(loadReviewConfig(root)).rejects.toThrow(/tokenEnv must be an env var name/); + + await writeFile( + configPath, + JSON.stringify({ auth: { providers: { xai: { mode: "oauth", tokenEnv: "my_Token_2" } } } }), + ); + expect((await loadReviewConfig(root)).auth).toEqual([ + { provider: "xai", mode: "oauth", tokenEnv: "my_Token_2", upstream: undefined }, + ]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/src/__tests__/mcp-servers.test.ts b/src/__tests__/mcp-servers.test.ts index 637ea35..7f558fd 100644 --- a/src/__tests__/mcp-servers.test.ts +++ b/src/__tests__/mcp-servers.test.ts @@ -198,6 +198,8 @@ test("refuses a token env that holds another secret or the model credential", as "MODEL_TOKEN", "CODEX_OAUTH_ACCESS_TOKEN", "CODEX_OAUTH_REFRESH_TOKEN", + "XAI_API_KEY", + "XAI_OAUTH_ACCESS_TOKEN", ]) { await writeRootConfig({ auth: { mode: "api-key", provider: "anthropic", tokenEnv: "MODEL_TOKEN" }, diff --git a/src/__tests__/opencode.test.ts b/src/__tests__/opencode.test.ts index 791f153..1519175 100644 --- a/src/__tests__/opencode.test.ts +++ b/src/__tests__/opencode.test.ts @@ -436,6 +436,22 @@ test("Meta provider registers future model families neutrally and only for the m }); }); +test("xAI auth does not synthesize a provider block", () => { + for (const auth of [ + [{ mode: "oauth" as const, provider: "xai", tokenEnv: "XAI_OAUTH_ACCESS_TOKEN" }], + [{ mode: "api-key" as const, provider: "xai", tokenEnv: "XAI_API_KEY" }], + ]) { + const opencode = buildOpencodeConfig( + configWith({ + agents: [{ id: "correctness", model: "xai/grok-4.7" }], + coordinatorModel: "xai/grok-4.7", + auth, + }), + ) as { provider?: Record }; + expect(opencode.provider?.xai).toBeUndefined(); + } +}); + test("buildOpencodeConfig registers the no-tools stack verifier (empty tool list)", () => { const opencode = buildOpencodeConfig(configWith({})) as { agent: Record }>; diff --git a/src/__tests__/review-internals.test.ts b/src/__tests__/review-internals.test.ts index 0d4275c..5baf547 100644 --- a/src/__tests__/review-internals.test.ts +++ b/src/__tests__/review-internals.test.ts @@ -611,6 +611,13 @@ test("effectiveConcurrency: explicit config wins; subscription defaults lower", ).toBe(3); // Pure API-key runs keep the full default. expect(effectiveConcurrency(cfg({}, [{ mode: "api-key", provider: "openai" }]))).toBe(6); + // SuperGrok is an oauth entry, so it takes the same subscription cap. + expect(effectiveConcurrency(cfg({}, [{ mode: "oauth", provider: "xai" }], "xai/grok-4.7"))).toBe( + 3, + ); + expect( + effectiveConcurrency(cfg({}, [{ mode: "api-key", provider: "xai" }], "xai/grok-4.7")), + ).toBe(6); }); test("effectiveConcurrency: the claude engine caps on an OAUTH credential, not an api-key one", () => { diff --git a/src/__tests__/setup-auth.test.ts b/src/__tests__/setup-auth.test.ts index f25ebdc..1029c10 100644 --- a/src/__tests__/setup-auth.test.ts +++ b/src/__tests__/setup-auth.test.ts @@ -1,6 +1,15 @@ import { test, expect } from "bun:test"; -import { planFromAuth, exportLine, opencodeAuthJsonPath } from "../commands/setup-auth.js"; +import { + planFromAuth, + exportLine, + opencodeAuthJsonPath, + accessTokenFromStore, + opencodeLoginEnv, + remainingLabel, + superGrokTokenComplaint, + SUPERGROK_LOGIN_ARGS, +} from "../commands/setup-auth.js"; test("plan: the mixed setup needs one ChatGPT login and one manual key", () => { const plan = planFromAuth([ @@ -58,12 +67,95 @@ test("plan: an anthropic/… model triggers claudeLogin even with no anthropic a expect(plan.unsupported).toEqual([]); }); +test("plan: xAI oauth is a SuperGrok login and an xAI API key stays manual", () => { + const oauth = planFromAuth([ + { provider: "xai", mode: "oauth", tokenEnv: "XAI_OAUTH_ACCESS_TOKEN" }, + ]); + expect(oauth.grokLogin).toEqual({ tokenEnv: "XAI_OAUTH_ACCESS_TOKEN" }); + expect(oauth.chatgptLogin).toBeUndefined(); + expect(oauth.manualKeys).toEqual([]); + expect(oauth.unsupported).toEqual([]); + + // No tokenEnv: the review rejects this config, so setup-auth must not pretend + // the export line is enough. Same rule as the openai oauth branch. + const missing = planFromAuth([{ provider: "xai", mode: "oauth" }]); + expect(missing.grokLogin).toBeUndefined(); + expect(missing.unsupported).toEqual([{ provider: "xai", mode: "oauth" }]); + + const key = planFromAuth([{ provider: "xai", mode: "api-key", tokenEnv: "XAI_API_KEY" }]); + expect(key.grokLogin).toBeUndefined(); + expect(key.manualKeys).toEqual([ + { provider: "xai", tokenEnv: "XAI_API_KEY", upstream: undefined }, + ]); + expect(key.unsupported).toEqual([]); +}); + +test("SuperGrok login args select the device method and skip the menus", () => { + expect(SUPERGROK_LOGIN_ARGS).toEqual([ + "auth", + "login", + "-p", + "xai", + "-m", + "SuperGrok Subscription", + ]); +}); + +test("the xAI export line is the access token and never the refresh token", () => { + const exp = Math.floor(Date.now() / 1000) + 5 * 3600; + const access = `eyJhbGciOiJSUzI1NiJ9.${Buffer.from(JSON.stringify({ exp })).toString("base64url")}.sig`; + const refresh = "refresh-secret-not-for-export"; + const stored = accessTokenFromStore({ xai: { type: "oauth", access, refresh } }, "xai"); + expect(stored?.token).toBe(access); + const line = exportLine("XAI_OAUTH_ACCESS_TOKEN", stored!.token); + expect(line).toContain(access); + expect(line).not.toContain(refresh); + expect(accessTokenFromStore({ xai: { type: "oauth", refresh } }, "xai")).toBeNull(); +}); + +function superGrokJwt(secondsFromNow: number): string { + const exp = Math.floor(Date.now() / 1000) + secondsFromNow; + return `eyJhbGciOiJSUzI1NiJ9.${Buffer.from(JSON.stringify({ exp })).toString("base64url")}.sig`; +} + +test("a SuperGrok token is reused only when a review takes it without complaint", () => { + const env = "XAI_OAUTH_ACCESS_TOKEN"; + expect(superGrokTokenComplaint(superGrokJwt(5 * 3600), env)).toBeNull(); + // The review names `ecr setup-auth` as the fix for each of these, so none may skip the sign-in. + expect(superGrokTokenComplaint(superGrokJwt(-600), env)).toContain("EXPIRED"); + expect(superGrokTokenComplaint(superGrokJwt(60), env)).toContain("120 seconds"); + expect(superGrokTokenComplaint(superGrokJwt(90 * 60), env)).toContain("expires in"); + expect(superGrokTokenComplaint("x".repeat(80), env)).toContain("opaque"); +}); + +test("the remaining label uses minutes under an hour", () => { + const now = Date.now(); + expect(remainingLabel(now + 30_000, now)).toBe("1 more minute(s)"); + expect(remainingLabel(now + 20 * 60_000, now)).toBe("20 more minute(s)"); + expect(remainingLabel(now + 5 * 3_600_000, now)).toBe("5 more hour(s)"); + expect(remainingLabel(now + 3 * 86_400_000, now)).toBe("3 more day(s)"); +}); + test("export line is single-quoted so shells never expand the value", () => { expect(exportLine("CODEX_OAUTH_ACCESS_TOKEN", "abc$HOME!x")).toBe( "export CODEX_OAUTH_ACCESS_TOKEN='abc$HOME!x'", ); }); +test("export line escapes a single quote in the value", () => { + expect(exportLine("XAI_OAUTH_ACCESS_TOKEN", "a'; touch /tmp/pwned; '")).toBe( + String.raw`export XAI_OAUTH_ACCESS_TOKEN='a'\''; touch /tmp/pwned; '\'''`, + ); +}); + +test("OpenCode logins keep project config off", () => { + // The login cwd is the temp dir, and OpenCode reads config from the cwd and its parents. + expect(opencodeLoginEnv({ PATH: "/usr/bin" })).toEqual({ + PATH: "/usr/bin", + OPENCODE_DISABLE_PROJECT_CONFIG: "1", + }); +}); + test("opencode auth.json path honors XDG_DATA_HOME and falls back to ~/.local/share", () => { expect(opencodeAuthJsonPath({ XDG_DATA_HOME: "/custom/data" })).toBe( "/custom/data/opencode/auth.json", diff --git a/src/commands/setup-auth.ts b/src/commands/setup-auth.ts index 94371c5..2d93ac9 100644 --- a/src/commands/setup-auth.ts +++ b/src/commands/setup-auth.ts @@ -7,7 +7,7 @@ import readline from "node:readline/promises"; import { hasConfig, loadReviewConfig } from "../config/load.js"; import type { AuthConfigEntry } from "../config/schema.js"; -import { jwtExpiryMs } from "../core/auth.js"; +import { checkOauthTokenShape, jwtExpiryMs } from "../core/auth.js"; import { claudeSubscriptionActive, resolveClaudeCli } from "../core/claude-code.js"; import { resolveOpencodeCli } from "../core/opencode.js"; import { errorMessage } from "../core/util.js"; @@ -20,6 +20,12 @@ getting each credential: \`opencode auth login\` (interactive; opens your browser), then prints the \`export =…\` line to add to your shell config. An existing OpenCode ChatGPT sign-in is reused instead of re-authenticating. + • a SuperGrok subscription (oauth/xai): runs the bundled + \`opencode auth login -p xai -m "SuperGrok Subscription"\` (device code at + https://accounts.x.ai/oauth2/device), then prints the access-token export. + The token lasts hours, not days, and a review cannot renew it. A stored or + exported token is reused only while a review takes it without a warning. + The refresh token stays in OpenCode's store. • a Claude Max/Team subscription (any anthropic/… model): reuses an active \`claude\` login when present, or runs \`claude setup-token\` (interactive; opens your browser) and prints the \`export =…\` line for @@ -27,6 +33,7 @@ getting each credential: • an API key (api-key entries): prints where to create the key, the exact permissions it needs, and the export line to fill in. Meta Model API (\`meta/muse-spark-…\`) uses META_API_KEY from the Meta AI developer portal. + xAI API keys come from https://console.x.ai (XAI_API_KEY). Without a repo config, it offers the recommended ChatGPT/Codex subscription flow with the default env name. @@ -39,6 +46,8 @@ Options: export interface SetupPlan { /** oauth/openai entry — satisfiable by an `opencode auth login` ChatGPT sign-in. */ chatgptLogin?: { tokenEnv: string }; + /** oauth/xai entry — satisfiable by OpenCode's SuperGrok device login. */ + grokLogin?: { tokenEnv: string }; /** anthropic model/entry — satisfiable by a `claude setup-token` subscription login. */ claudeLogin?: { tokenEnv: string }; /** api-key entries — a human must mint these; we print instructions. */ @@ -64,6 +73,8 @@ export function planFromAuth(auth: AuthConfigEntry[], models: string[] = []): Se continue; // handled above (claude engine); mode is irrelevant here. } else if (entry.mode === "oauth" && entry.provider === "openai" && entry.tokenEnv) { plan.chatgptLogin = { tokenEnv: entry.tokenEnv }; + } else if (entry.mode === "oauth" && entry.provider === "xai" && entry.tokenEnv) { + plan.grokLogin = { tokenEnv: entry.tokenEnv }; } else if (entry.mode === "api-key" && entry.tokenEnv) { plan.manualKeys.push({ provider: entry.provider, @@ -84,34 +95,84 @@ export function opencodeAuthJsonPath(env: NodeJS.ProcessEnv = process.env): stri return path.join(dataHome, "opencode", "auth.json"); } +/** Bundled OpenCode login for a SuperGrok subscription. Device code, not a menu. */ +export const SUPERGROK_LOGIN_ARGS = [ + "auth", + "login", + "-p", + "xai", + "-m", + "SuperGrok Subscription", +] as const; + +/** + * Env for the interactive OpenCode logins. + * OpenCode loads `opencode.json` and `.opencode/` from the cwd and from every parent directory. + * The login cwd is the temp dir, which is the shared `/tmp` on Linux, so project config stays off. + */ +export function opencodeLoginEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv { + return { ...env, OPENCODE_DISABLE_PROJECT_CONFIG: "1" }; +} + +export interface StoredOauthAccess { + token: string; + expiresMs: number; +} + // @ref LLP 0007#doctor-and-setup-auth [constrained-by] — refresh tokens are single-use; they never leave OpenCode's store /** - * The stored ChatGPT sign-in's ACCESS token, if OpenCode has a live one. The - * refresh token deliberately never leaves OpenCode's store: refresh tokens are - * SINGLE-USE (rotation) and OpenCode is their sole legitimate consumer — a copy - * in a shell config or CI secret dies on the next rotation and can take the - * whole sign-in with it. The access token is a plain bearer that stays valid for - * days and never touches rotation. + * The live ACCESS token for one provider in OpenCode's auth.json. + * `refresh` is ignored: refresh tokens are SINGLE-USE, and OpenCode is their + * sole consumer. + * A copy in a shell config or CI secret dies on the next rotation. + * An expired or non-JWT access token is treated as absent. */ -async function readStoredAccessToken(): Promise<{ token: string; expiresMs: number } | null> { +export function accessTokenFromStore( + parsed: Record, + provider: string, + now = Date.now(), +): StoredOauthAccess | null { + const entry = parsed[provider]; + if (entry?.type !== "oauth" || !entry.access) { + return null; + } + const expiresMs = jwtExpiryMs(entry.access) ?? 0; + return expiresMs > now ? { token: entry.access, expiresMs } : null; +} + +async function readStoredAccessToken(provider: string): Promise { try { const raw = await readFile(opencodeAuthJsonPath(), "utf8"); const parsed = JSON.parse(raw) as Record< string, - { type?: string; access?: string } | undefined + { type?: string; access?: string; refresh?: string } | undefined >; - const openai = parsed.openai; - if (openai?.type !== "oauth" || !openai.access) { - return null; - } - const expiresMs = jwtExpiryMs(openai.access) ?? 0; - // An expired stored token means the sign-in needs redoing anyway. - return expiresMs > Date.now() ? { token: openai.access, expiresMs } : null; + return accessTokenFromStore(parsed, provider); } catch { return null; } } +/** + * What a review would say about this SuperGrok access token: an error, an expiry warning, or null. + * The review names `ecr setup-auth` as the fix for both, so either one means a new sign-in. + */ +export function superGrokTokenComplaint(token: string, tokenEnv: string): string | null { + const shape = checkOauthTokenShape("xai", token, tokenEnv); + return shape.ok ? (shape.warning ?? null) : shape.detail; +} + +export function remainingLabel(expiresMs: number, now = Date.now()): string { + const remaining = expiresMs - now; + if (remaining >= 86_400_000) { + return `${Math.max(1, Math.round(remaining / 86_400_000))} more day(s)`; + } + if (remaining >= 3_600_000) { + return `${Math.max(1, Math.round(remaining / 3_600_000))} more hour(s)`; + } + return `${Math.max(1, Math.round(remaining / 60_000))} more minute(s)`; +} + async function confirm(question: string, skip: boolean): Promise { if (skip) { return true; @@ -126,9 +187,9 @@ async function confirm(question: string, skip: boolean): Promise { } // @ref LLP 0007#doctor-and-setup-auth [constrained-by] — shell metacharacters in tokens never expand -/** The line to paste into a shell config. Single-quoted: tokens never contain '. */ +/** The line to paste into a shell config. Single-quoted, so the shell expands nothing in the value. */ export function exportLine(tokenEnv: string, value: string): string { - return `export ${tokenEnv}='${value}'`; + return `export ${tokenEnv}='${value.replace(/'/g, "'\\''")}'`; } export async function setupAuthCommand(argv: string[] = []): Promise { @@ -160,6 +221,7 @@ export async function setupAuthCommand(argv: string[] = []): Promise { if ( !plan.chatgptLogin && !plan.claudeLogin && + !plan.grokLogin && plan.manualKeys.length === 0 && plan.unsupported.length === 0 ) { @@ -223,7 +285,7 @@ export async function setupAuthCommand(argv: string[] = []): Promise { if (process.env[tokenEnv]) { err(`✓ ${tokenEnv} is already set in this shell — skipping the ChatGPT sign-in.`); } else { - let stored = await readStoredAccessToken(); + let stored = await readStoredAccessToken("openai"); if (stored) { err( `Found a live ChatGPT sign-in in OpenCode (access token valid ` + @@ -257,13 +319,14 @@ export async function setupAuthCommand(argv: string[] = []): Promise { const result = spawnSync(opencodeCli, ["auth", "login"], { stdio: "inherit", cwd: os.tmpdir(), + env: opencodeLoginEnv(), }); if (result.status !== 0) { throw new Error( `\`opencode auth login\` exited with ${result.status ?? "a signal"}; nothing was changed.`, ); } - stored = await readStoredAccessToken(); + stored = await readStoredAccessToken("openai"); if (!stored) { throw new Error( "The login finished but no live ChatGPT sign-in was stored — did you select " + @@ -285,6 +348,76 @@ export async function setupAuthCommand(argv: string[] = []): Promise { } } + if (plan.grokLogin) { + const { tokenEnv } = plan.grokLogin; + const current = process.env[tokenEnv]; + const complaint = current ? superGrokTokenComplaint(current, tokenEnv) : null; + if (current && !complaint) { + err(`✓ ${tokenEnv} is already set in this shell — skipping the SuperGrok sign-in.`); + } else { + if (complaint) { + err(`${tokenEnv} is set in this shell, but it needs a new token:`); + err(` ${complaint}`); + } + // @ref LLP 0007#doctor-and-setup-auth [implements] — SuperGrok login is the pinned OpenCode device flow; only the access token is exported, and only one a review takes without complaint + let stored = await readStoredAccessToken("xai"); + if (stored && superGrokTokenComplaint(stored.token, tokenEnv)) { + stored = null; + } + if (stored) { + err( + `Found a live SuperGrok sign-in in OpenCode (access token valid ` + + `${remainingLabel(stored.expiresMs)}).`, + ); + if (!(await confirm(`Use it for ${tokenEnv}?`, yes))) { + stored = null; + } + } + if (!stored) { + err("This will run the bundled `opencode auth login` for SuperGrok (interactive)."); + err("It prints a device code."); + err("Open https://accounts.x.ai/oauth2/device and enter that code."); + if (!(await confirm("Run it now?", yes))) { + err("Skipped the SuperGrok sign-in."); + } else { + const opencodeCli = await resolveOpencodeCli(); + if (!opencodeCli) { + throw new Error( + "The `opencode` CLI is not available (install `opencode-ai`, or add " + + "node_modules/.bin to PATH); nothing was changed.", + ); + } + const result = spawnSync(opencodeCli, [...SUPERGROK_LOGIN_ARGS], { + stdio: "inherit", + cwd: os.tmpdir(), + env: opencodeLoginEnv(), + }); + if (result.status !== 0) { + throw new Error( + `\`opencode auth login\` exited with ${result.status ?? "a signal"}; nothing was changed.`, + ); + } + stored = await readStoredAccessToken("xai"); + if (!stored) { + throw new Error( + "The login finished but no live SuperGrok access token was stored. " + + "Re-run `ecr setup-auth` to try again.", + ); + } + } + } + if (stored) { + // Access token only. refresh stays in OpenCode's store. + exports.push(exportLine(tokenEnv, stored.token)); + err( + `Note: this access token is valid for ${remainingLabel(stored.expiresMs)}, ` + + `and a review cannot renew it. Re-run \`ecr setup-auth\` for a new one; ` + + `it signs in again and replaces this export line.`, + ); + } + } + } + for (const key of plan.manualKeys) { if (process.env[key.tokenEnv]) { err(`✓ ${key.tokenEnv} is already set in this shell — skipping.`); @@ -305,6 +438,10 @@ export async function setupAuthCommand(argv: string[] = []): Promise { // @ref LLP 0007#doctor-and-setup-auth [implements] — Meta uses a manual API key err(" https://developer.meta.com/ai/ — create a Model API key with access to"); err(" Muse Spark, then store it as a dedicated review secret."); + } else if (upstream === "xai") { + // @ref LLP 0007#doctor-and-setup-auth [implements] — xAI API keys stay manual; the SuperGrok login is oauth only + err(" https://console.x.ai — create an API key and store it as XAI_API_KEY."); + err(' A SuperGrok subscription uses auth.mode "oauth" instead of this key.'); } else { err(` mint a key for the "${upstream}" provider.`); } diff --git a/src/config/schema.ts b/src/config/schema.ts index 4af1726..ea87c46 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -47,6 +47,12 @@ function sameOrigin(first: string, second: string): boolean { } } +/** + * `ecr setup-auth` prints an `auth` token env name into an `export NAME='…'` line for the user's shell config. + * The config comes from the repo, so a name with shell syntax must fail at load. + */ +const ENV_VAR_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/; + /** A remote MCP server that named review passes may call, such as a code sandbox. */ export const McpServerConfigSchema = z .object({ @@ -301,6 +307,15 @@ export const ReviewConfigSchema = z.object({ tokenEnv: z.string().optional(), }), ]) + // Checked on the union, not per field. + // A field error in the map shape falls through to the legacy shape, which drops `providers`. + .refine( + (auth) => + ("providers" in auth ? Object.values(auth.providers) : [auth]).every( + (entry) => entry.tokenEnv === undefined || ENV_VAR_NAME.test(entry.tokenEnv), + ), + { error: "auth tokenEnv must be an env var name (letters, digits and underscores)" }, + ) .default({ mode: "api-key", provider: "openai" }), review: z .object({ diff --git a/src/core/auth.ts b/src/core/auth.ts index e94f6ea..72981c0 100644 --- a/src/core/auth.ts +++ b/src/core/auth.ts @@ -7,6 +7,8 @@ import type { AuthConfigEntry, LoadedConfig } from "../config/schema.js"; export interface PreparedAuth { cleanup: () => Promise; + /** Warnings about a staged oauth token, such as one that lapses soon. The run prints them. */ + warnings: string[]; } /** Env var each provider's SDK reads for an API key (x-api-key style). */ @@ -16,6 +18,7 @@ const PROVIDER_KEY_ENV: Record = { google: "GOOGLE_GENERATIVE_AI_API_KEY", openrouter: "OPENROUTER_API_KEY", meta: "META_API_KEY", + xai: "XAI_API_KEY", }; /** @@ -37,8 +40,26 @@ const ANTHROPIC_TOKEN_ENVS: Record = { CLAUDE_CODE_REVIEW_SHARED_API_TOKEN: "anthropic", }; -/** The env vars `ecr setup-auth` exports for a Codex (ChatGPT) subscription login. */ -const CODEX_OAUTH_TOKEN_ENVS = ["CODEX_OAUTH_ACCESS_TOKEN", "CODEX_OAUTH_REFRESH_TOKEN"]; +/** + * SuperGrok access-token env. It belongs to xai the way CLAUDE_CODE_OAUTH_TOKEN + * belongs to anthropic: a non-xai entry that names it is refused. + * XAI_API_KEY is owned through PROVIDER_KEY_ENV, so it is not repeated here. + * The review stages this value into the isolated auth.json. + * It is never copied into XAI_API_KEY: an api-key entry that names it is refused. + */ +const XAI_TOKEN_ENVS: Record = { + XAI_OAUTH_ACCESS_TOKEN: "xai", +}; + +/** + * The env vars `ecr setup-auth` exports for a Codex (ChatGPT) subscription login. + * They belong to openai. + * Without an owner, an xai oauth entry could name one: a ChatGPT access token is a JWT too. + */ +const CODEX_OAUTH_TOKEN_ENVS: Record = { + CODEX_OAUTH_ACCESS_TOKEN: "openai", + CODEX_OAUTH_REFRESH_TOKEN: "openai", +}; /** * Every env var that can hold a model provider credential. @@ -47,7 +68,8 @@ const CODEX_OAUTH_TOKEN_ENVS = ["CODEX_OAUTH_ACCESS_TOKEN", "CODEX_OAUTH_REFRESH export const MODEL_CREDENTIAL_ENVS: ReadonlySet = new Set([ ...Object.values(PROVIDER_KEY_ENV), ...Object.keys(ANTHROPIC_TOKEN_ENVS), - ...CODEX_OAUTH_TOKEN_ENVS, + ...Object.keys(XAI_TOKEN_ENVS), + ...Object.keys(CODEX_OAUTH_TOKEN_ENVS), ]); /** @@ -124,7 +146,10 @@ export function checkOauthTokenShape( tokenEnv: string, ): AuthReadiness { const ok = { ok: true, detail: `oauth for ${provider}; token env ${tokenEnv} is set` }; - const fix = `Re-generate it with \`claude setup-token\` and set ${tokenEnv} to the full value.`; + const fix = + provider === "xai" + ? `Run \`ecr setup-auth\` and set ${tokenEnv} to the SuperGrok access token.` + : `Re-generate it with \`claude setup-token\` and set ${tokenEnv} to the full value.`; if (token !== token.trim()) { return { ok: false, @@ -167,6 +192,51 @@ export function checkOauthTokenShape( return { ...ok, detail: `oauth for ${provider}; token env ${tokenEnv} is set` }; } + // SuperGrok reviews stage a JWT access token with an empty refresh. + // An opaque value is the refresh token, and this run must not consume it. + // Inside 120s the CLI would try to refresh, and the isolated entry cannot. + // @ref LLP 0003#credential-resolution-and-forwarding [implements] — xAI oauth accepts a JWT access token only; opaque values and tokens inside the 120s refresh skew fail before any pass + if (provider === "xai") { + if (!isJwtAccessToken(token)) { + return { + ok: false, + detail: + `${tokenEnv} holds an opaque xAI token. ` + + `auth.mode "oauth" for xai needs the SuperGrok access token (a JWT). ` + + `Run \`ecr setup-auth\` and export the access token. ` + + `The refresh token stays in OpenCode's store.`, + }; + } + const expires = jwtExpiryMs(token); + if (expires !== null) { + const remainingMs = expires - Date.now(); + if (remainingMs <= 120_000) { + const why = + remainingMs <= 0 + ? `EXPIRED ${Math.max(1, Math.ceil(-remainingMs / 60_000))} minute(s) ago` + : "expires within 120 seconds"; + return { + ok: false, + detail: + `${tokenEnv} holds a SuperGrok access token that ${why}. ` + + `The review stages it with an empty refresh token, so OpenCode cannot renew it. ` + + `Mint a fresh one with \`ecr setup-auth\` and update ${tokenEnv}.`, + }; + } + if (remainingMs < 2 * 3_600_000) { + return { + ...ok, + warning: + `${tokenEnv}'s SuperGrok access token expires in ` + + `${Math.max(1, Math.round(remainingMs / 60_000))} minute(s). ` + + `A pass that is still running then fails, because the review cannot renew the token. ` + + `Re-mint it soon (\`ecr setup-auth\`).`, + }; + } + } + return ok; + } + // Only anthropic's formats are known well enough to say anything about. if (provider !== "anthropic") { return ok; @@ -240,8 +310,13 @@ export function checkAuthEntry( if (tokenEnv) { const keyOwner = Object.entries(PROVIDER_KEY_ENV).find(([, env]) => env === tokenEnv)?.[0] ?? - ANTHROPIC_TOKEN_ENVS[tokenEnv]; - if (keyOwner && keyOwner !== provider && keyOwner !== upstream) { + ANTHROPIC_TOKEN_ENVS[tokenEnv] ?? + XAI_TOKEN_ENVS[tokenEnv] ?? + CODEX_OAUTH_TOKEN_ENVS[tokenEnv]; + // Only an api-key alias may borrow its upstream's key: an oauth entry is staged under `provider`. + // An xai alias gets the openai-compatible SDK and no host, so it cannot reach xAI at all. + const viaAlias = mode === "api-key" && keyOwner !== "xai" && keyOwner === upstream; + if (keyOwner && keyOwner !== provider && !viaAlias) { return { ok: false, detail: @@ -251,6 +326,17 @@ export function checkAuthEntry( `or fix the provider/upstream mapping.`, }; } + // "api-key" is the schema default, so an xai entry that forgot `"mode": "oauth"` lands here. + // Refuse it before the access token is sent as an API key with no expiry check. + if (mode === "api-key" && XAI_TOKEN_ENVS[tokenEnv]) { + return { + ok: false, + detail: + `auth for ${provider} names tokenEnv "${tokenEnv}", the SuperGrok access token env, ` + + `but auth.mode is "api-key" (the default). Set "mode": "oauth" for ${provider}, ` + + `or point tokenEnv at an xAI API key (XAI_API_KEY).`, + }; + } } // anthropic is ALWAYS served by the Claude Code CLI (engine inferred from the @@ -354,6 +440,14 @@ export function checkAuthEntry( detail: `api-key for ${provider}; no tokenEnv configured and no known key env — relying on OpenCode's own login`, }; } + // An xai entry with no tokenEnv meant "OpenCode's own xAI login" before XAI_API_KEY had an owner. + // Keep that reading, so those configs still run. + if (!tokenEnv && provider === "xai") { + return { + ok: true, + detail: `api-key for xai; no tokenEnv configured and ${providerKeyEnv} is not set — relying on OpenCode's own login`, + }; + } const names = [tokenEnv, providerKeyEnv].filter(Boolean).join(" or "); return { ok: false, @@ -512,7 +606,7 @@ export function oauthAuthJsonEntry( */ // @ref LLP 0003#credential-resolution-and-forwarding [implements] — stages all OAuth credentials into one isolated auth.json under a temp XDG_DATA_HOME; anthropic never passes through this path (its credential goes straight into startClaudeCode's child env) export async function prepareAuth(config: LoadedConfig): Promise { - const noop: PreparedAuth = { cleanup: async () => {} }; + const noop: PreparedAuth = { cleanup: async () => {}, warnings: [] }; // REVIEWER_MODEL is an explicit "use this model with my own creds" override — a // common local case (e.g. the repo config targets a CI credential, but a dev @@ -537,6 +631,7 @@ export async function prepareAuth(config: LoadedConfig): Promise { // forwarding it here would reintroduce the exact secret-forwarding it prevents. const inUse = providersInUse(config); const authJson: Record = {}; + const warnings: string[] = []; for (const entry of config.auth) { const { mode, provider, tokenEnv, upstream } = entry; if (inUse && !inUse.has(provider)) { @@ -561,12 +656,17 @@ export async function prepareAuth(config: LoadedConfig): Promise { } // oauth — checkProviderAuth guarantees tokenEnv is set and present; read // defensively so TypeScript narrows and this stays correct if called directly. - if (!value) { + if (!tokenEnv || !value) { throw new Error( `auth mode "oauth" for ${provider} requires tokenEnv to name a set OAuth token env.`, ); } authJson[provider] = oauthAuthJsonEntry(provider, value); + // A staged token cannot be renewed mid-run, so the run itself must say when one lapses soon. + const { warning } = checkOauthTokenShape(provider, value, tokenEnv); + if (warning) { + warnings.push(warning); + } } if (Object.keys(authJson).length === 0) { @@ -582,5 +682,6 @@ export async function prepareAuth(config: LoadedConfig): Promise { cleanup: async () => { await rm(dir, { recursive: true, force: true }); }, + warnings, }; } diff --git a/src/core/review.ts b/src/core/review.ts index 8a103fc..2026f60 100644 --- a/src/core/review.ts +++ b/src/core/review.ts @@ -230,8 +230,9 @@ function makeRunId(): string { * seen on eas-cli#4084), and several PRs may be reviewing on the same credential at * once — so subscription runs trade a little wall-clock for a lot of reliability. * - * A subscription run is any of: an oauth (ChatGPT/Codex) entry; OR the Claude Code - * engine being in use (an `anthropic/…` model) on an OAUTH credential — a subscription + * A subscription run is any oauth entry (ChatGPT/Codex, SuperGrok, or another + * oauth provider), or the Claude Code engine being in use (an `anthropic/…` model) + * on an OAUTH credential — a subscription * token OR the local `claude` login fallback (no forwardable token). An anthropic * credential that classifies as an API KEY is metered per-request and does NOT force * the cap. Exported for tests. @@ -426,6 +427,9 @@ export async function runReview( await readRoot?.cleanup(); throw error; } + for (const warning of auth.warnings) { + progress(` auth: ${warning}`); + } const restoreCwd = async (): Promise => { if (readRoot) { diff --git a/templates/config.jsonc b/templates/config.jsonc index e0a895a..c2cf92b 100644 --- a/templates/config.jsonc +++ b/templates/config.jsonc @@ -156,6 +156,21 @@ // "openai": { "mode": "oauth", "tokenEnv": "CODEX_OAUTH_ACCESS_TOKEN" } // } } // + // SuperGrok subscription ("oauth"): tokenEnv holds the ACCESS token. + // `ecr setup-auth` runs `opencode auth login -p xai -m "SuperGrok Subscription"` + // and exports `xai.access`. The refresh token stays in OpenCode's store. + // Reviews stage that access token into an isolated auth.json. + // The token lasts hours and a review cannot renew it, so this suits local runs. + // Keep "mode": "oauth": an entry that names this env without it is refused. + // "auth": { "providers": { + // "xai": { "mode": "oauth", "tokenEnv": "XAI_OAUTH_ACCESS_TOKEN" } + // } } + // + // xAI API key (metered, not a subscription): + // "auth": { "providers": { + // "xai": { "mode": "api-key", "tokenEnv": "XAI_API_KEY" } + // } } + // // MIXING engines is supported: the engine is inferred per agent from its model, // so this anthropic entry may coexist with an openai (or any other) OpenCode // provider — an `anthropic/…` agent runs through the Claude Code CLI while an