Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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/<id>` (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 <https://accounts.x.ai/oauth2/device>. 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
<https://console.x.ai> 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.

Expand Down
5 changes: 4 additions & 1 deletion llp/0001-trust-model.principles.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
37 changes: 29 additions & 8 deletions llp/0003-model-runtimes-and-credentials.explainer.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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

Expand Down
1 change: 1 addition & 0 deletions llp/0007-cli-commands-and-ci.explainer.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
159 changes: 159 additions & 0 deletions src/__tests__/auth.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { tmpdir } from "node:os";

import { test, expect } from "bun:test";

import {
Expand Down Expand Up @@ -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;
}
});
2 changes: 2 additions & 0 deletions src/__tests__/mcp-servers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" },
Expand Down
16 changes: 16 additions & 0 deletions src/__tests__/opencode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> };
expect(opencode.provider?.xai).toBeUndefined();
}
});

test("buildOpencodeConfig registers the no-tools stack verifier (empty tool list)", () => {
const opencode = buildOpencodeConfig(configWith({})) as {
agent: Record<string, { tools: Record<string, boolean> }>;
Expand Down
7 changes: 7 additions & 0 deletions src/__tests__/review-internals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
Loading