diff --git a/README.md b/README.md index 4f97ea2..fabb4fe 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,31 @@ 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. + - **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..f999694 100644 --- a/llp/0001-trust-model.principles.md +++ b/llp/0001-trust-model.principles.md @@ -104,7 +104,10 @@ 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. 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..6a12677 100644 --- a/llp/0003-model-runtimes-and-credentials.explainer.md +++ b/llp/0003-model-runtimes-and-credentials.explainer.md @@ -354,7 +354,9 @@ 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`. **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 +368,27 @@ 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 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. Under about +two hours left, the run warns and continues. 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. `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`). **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 +405,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..eafcccf 100644 --- a/llp/0007-cli-commands-and-ci.explainer.md +++ b/llp/0007-cli-commands-and-ci.explainer.md @@ -140,6 +140,7 @@ doctor resolves auth the way real reviews do: a `routing.jsonc` `defaults.auth` - 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`]. - `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`]. +- 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 live unexpired access token is offered for reuse, and a token env that is already set skips the login. An xAI api-key entry stays manual and points at `https://console.x.ai` [observed: `src/commands/setup-auth.ts` `planFromAuth`, `accessTokenFromStore`]. - 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)). ## init and dismiss diff --git a/src/__tests__/auth.test.ts b/src/__tests__/auth.test.ts index 8591182..253d4ac 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,160 @@ 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; + } +}); 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..606d4c4 100644 --- a/src/__tests__/setup-auth.test.ts +++ b/src/__tests__/setup-auth.test.ts @@ -1,6 +1,12 @@ import { test, expect } from "bun:test"; -import { planFromAuth, exportLine, opencodeAuthJsonPath } from "../commands/setup-auth.js"; +import { + planFromAuth, + exportLine, + opencodeAuthJsonPath, + accessTokenFromStore, + 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,6 +64,52 @@ 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(); +}); + 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'", diff --git a/src/commands/setup-auth.ts b/src/commands/setup-auth.ts index 94371c5..bc84175 100644 --- a/src/commands/setup-auth.ts +++ b/src/commands/setup-auth.ts @@ -20,6 +20,11 @@ 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. + An existing OpenCode SuperGrok sign-in is reused. 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 +32,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 +45,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 +72,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 +94,63 @@ 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; + +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; } } +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)`; + } + return `${Math.max(1, Math.round(remaining / 3_600_000))} more hour(s)`; +} + async function confirm(question: string, skip: boolean): Promise { if (skip) { return true; @@ -160,6 +199,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 +263,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 ` + @@ -263,7 +303,7 @@ export async function setupAuthCommand(argv: string[] = []): Promise { `\`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 +325,65 @@ export async function setupAuthCommand(argv: string[] = []): Promise { } } + if (plan.grokLogin) { + const { tokenEnv } = plan.grokLogin; + if (process.env[tokenEnv]) { + err(`✓ ${tokenEnv} is already set in this shell — skipping the SuperGrok sign-in.`); + } else { + // @ref LLP 0007#doctor-and-setup-auth [implements] — SuperGrok login is the pinned OpenCode device flow; only the access token is exported + let stored = await readStoredAccessToken("xai"); + 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(), + }); + 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 expires in ${remainingLabel(stored.expiresMs)}; ` + + `re-run \`ecr setup-auth\` then to refresh it (your OpenCode sign-in stays valid).`, + ); + } + } + } + for (const key of plan.manualKeys) { if (process.env[key.tokenEnv]) { err(`✓ ${key.tokenEnv} is already set in this shell — skipping.`); @@ -305,6 +404,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/core/auth.ts b/src/core/auth.ts index e94f6ea..dbea689 100644 --- a/src/core/auth.ts +++ b/src/core/auth.ts @@ -16,6 +16,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,6 +38,17 @@ const ANTHROPIC_TOKEN_ENVS: Record = { CLAUDE_CODE_REVIEW_SHARED_API_TOKEN: "anthropic", }; +/** + * 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. + */ +const XAI_TOKEN_ENVS: Record = { + XAI_OAUTH_ACCESS_TOKEN: "xai", +}; + /** 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"]; @@ -47,6 +59,7 @@ 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), + ...Object.keys(XAI_TOKEN_ENVS), ...CODEX_OAUTH_TOKEN_ENVS, ]); @@ -124,7 +137,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 +183,50 @@ 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). ` + + `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,7 +300,8 @@ export function checkAuthEntry( if (tokenEnv) { const keyOwner = Object.entries(PROVIDER_KEY_ENV).find(([, env]) => env === tokenEnv)?.[0] ?? - ANTHROPIC_TOKEN_ENVS[tokenEnv]; + ANTHROPIC_TOKEN_ENVS[tokenEnv] ?? + XAI_TOKEN_ENVS[tokenEnv]; if (keyOwner && keyOwner !== provider && keyOwner !== upstream) { return { ok: false, diff --git a/src/core/review.ts b/src/core/review.ts index 8a103fc..b433c51 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. diff --git a/templates/config.jsonc b/templates/config.jsonc index e0a895a..4c343cc 100644 --- a/templates/config.jsonc +++ b/templates/config.jsonc @@ -156,6 +156,19 @@ // "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. + // "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