From f16fb379640226f95ae9e47737ad241df92def53 Mon Sep 17 00:00:00 2001 From: Kudo Chien Date: Sat, 28 Nov 2026 00:32:42 +0800 Subject: [PATCH] feat: seed SuperGrok CI secrets from ecr setup-auth A SuperGrok access token lasts 6 hours, so CI needs a scheduled workflow that refreshes it. That workflow needs a refresh token that no other client uses, and setup-auth only handed out access tokens. `ecr setup-auth --ci-store --ci-target ` signs in to SuperGrok in a temporary OpenCode store and writes both tokens to GitHub Actions secrets with `gh`. Each value goes through stdin, so no token is printed. The refresh token goes to the store repo only. --- README.md | 10 ++ llp/0007-cli-commands-and-ci.explainer.md | 3 +- src/__tests__/ci-secrets.test.ts | 133 ++++++++++++++++++ src/__tests__/setup-auth.test.ts | 120 ++++++++++++++++ src/cli.ts | 2 +- src/commands/setup-auth.ts | 158 +++++++++++++++++++++- src/core/ci-secrets.ts | 106 +++++++++++++++ templates/config.jsonc | 1 + 8 files changed, 530 insertions(+), 3 deletions(-) create mode 100644 src/__tests__/ci-secrets.test.ts create mode 100644 src/core/ci-secrets.ts diff --git a/README.md b/README.md index f988bfb..200cdd6 100644 --- a/README.md +++ b/README.md @@ -1031,6 +1031,16 @@ fallback key; `ecr doctor` diagnoses setup. `ecr setup-auth` again for a new token. It signs in again unless a review would take the current token without a warning. + For CI, a scheduled workflow must refresh the token. Start that chain with + `ecr setup-auth --ci-store --ci-target `. It signs in + to SuperGrok in a temporary store, only for CI, and writes the tokens to GitHub + Actions secrets with `gh`. The store repo gets `XAI_OAUTH_REFRESH_TOKEN` and + `XAI_OAUTH_ACCESS_TOKEN`. Each target repo gets `XAI_OAUTH_ACCESS_TOKEN`. The + workflow in the store repo then sends the refresh token to xAI before the + access token expires, and it writes the new tokens back. Keep the refresh + token out of every repo that runs reviews, and do not reuse your own OpenCode + sign-in for CI. + `XAI_OAUTH_ACCESS_TOKEN` needs `"mode": "oauth"`. An entry that names it without that mode is refused. diff --git a/llp/0007-cli-commands-and-ci.explainer.md b/llp/0007-cli-commands-and-ci.explainer.md index ef818f6..46319d7 100644 --- a/llp/0007-cli-commands-and-ci.explainer.md +++ b/llp/0007-cli-commands-and-ci.explainer.md @@ -136,11 +136,12 @@ 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`]. +- 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 CI seed below is the one exception, and it uses a login that no OpenCode store keeps. - 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`]. - 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 CI seed (`--ci-store`, `--ci-target`) starts a token rotation for a SuperGrok subscription. A 6-hour access token needs a scheduled workflow that refreshes it, and that workflow needs a refresh token that no other client uses. So the seed runs the same device login with `XDG_DATA_HOME` set to a directory made for the call, reads both tokens, and deletes the directory. It sends each value to `gh secret set` through stdin, so no token is on a command line, in an error message, or on the terminal. The refresh token goes to the store repo only and is written first: with it saved, the next rotation repairs an access token write that failed. The developer's own OpenCode sign-in is not read and not changed. A token that a review would refuse is not written, and `gh` access to each repo is checked before the login [observed: `src/commands/setup-auth.ts` `parseCiSeedArgs`, `superGrokLoginInTemporaryStore`, `runCiSeed`; `src/core/ci-secrets.ts`; tests in `src/__tests__/ci-secrets.test.ts`, `src/__tests__/setup-auth.test.ts`]. The rotation workflow itself is not part of `ecr`. - 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__/ci-secrets.test.ts b/src/__tests__/ci-secrets.test.ts new file mode 100644 index 0000000..84b6353 --- /dev/null +++ b/src/__tests__/ci-secrets.test.ts @@ -0,0 +1,133 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path, { delimiter } from "node:path"; + +import { + assertSecretsReachable, + CI_ACCESS_SECRET, + CI_REFRESH_SECRET, + ciSecretWrites, + oauthPairFromStore, + parseRepoSlug, + writeSecrets, +} from "../core/ci-secrets.js"; +import { resetTrustedToolCache } from "../core/exec.js"; + +// Records each call as "argv | stdin", so a test can prove where a token went. +const FAKE_GH = `#!/bin/sh +case "$*" in + "api repos/"*"/actions/secrets/public-key") + case "$*" in *"$FAKE_GH_UNREACHABLE"*) [ -n "$FAKE_GH_UNREACHABLE" ] && { echo "HTTP 404: Not Found" >&2; exit 1; } ;; esac + printf '%s | \\n' "$*" >> "$FAKE_GH_DIR/calls.log" + printf '{"key_id":"k"}' ;; + "secret set "*) + value=$(cat) + case "$*" in *"$FAKE_GH_FAIL_WRITE"*) [ -n "$FAKE_GH_FAIL_WRITE" ] && { echo "HTTP 403: Resource not accessible" >&2; exit 1; } ;; esac + printf '%s | %s\\n' "$*" "$value" >> "$FAKE_GH_DIR/calls.log" ;; + *) echo "unexpected gh call: $*" >&2; exit 1 ;; +esac +`; + +const PAIR = { access: "eyJ.ACCESS-TOKEN.sig", refresh: "REFRESH-TOKEN" }; +const REPOS = { store: "expo/code-review-sessions", targets: ["expo/expo"] }; + +let dir = ""; +const saved: Record = {}; + +async function calls(): Promise { + return (await readFile(path.join(dir, "calls.log"), "utf8")).split("\n").filter(Boolean); +} + +beforeEach(async () => { + dir = await mkdtemp(path.join(tmpdir(), "ecr-ci-secrets-")); + await writeFile(path.join(dir, "gh"), FAKE_GH, "utf8"); + await chmod(path.join(dir, "gh"), 0o755); + await writeFile(path.join(dir, "calls.log"), "", "utf8"); + for (const name of ["PATH", "FAKE_GH_DIR", "FAKE_GH_UNREACHABLE", "FAKE_GH_FAIL_WRITE"]) { + saved[name] = process.env[name]; + } + process.env.PATH = `${dir}${delimiter}${saved.PATH ?? ""}`; + process.env.FAKE_GH_DIR = dir; + delete process.env.FAKE_GH_UNREACHABLE; + delete process.env.FAKE_GH_FAIL_WRITE; + resetTrustedToolCache(); +}); + +afterEach(async () => { + for (const [name, value] of Object.entries(saved)) { + if (value === undefined) { + delete process.env[name]; + } else { + process.env[name] = value; + } + } + resetTrustedToolCache(); + await rm(dir, { recursive: true, force: true }); +}); + +test("a repo slug is owner/repo and nothing that gh could read as a flag", () => { + expect(parseRepoSlug("expo/expo")).toBe("expo/expo"); + expect(parseRepoSlug("my-org/repo.name_2")).toBe("my-org/repo.name_2"); + for (const bad of ["expo", "expo/", "/expo", "a/b/c", "--repo/x", "a b/c", ""]) { + expect(() => parseRepoSlug(bad)).toThrow(/\//); + } +}); + +test("the token pair needs both halves of an oauth entry", () => { + expect(oauthPairFromStore({ xai: { type: "oauth", ...PAIR } }, "xai")).toEqual(PAIR); + expect(oauthPairFromStore({ xai: { type: "oauth", access: PAIR.access } }, "xai")).toBeNull(); + expect(oauthPairFromStore({ xai: { type: "oauth", refresh: PAIR.refresh } }, "xai")).toBeNull(); + expect(oauthPairFromStore({ xai: { type: "api", ...PAIR } }, "xai")).toBeNull(); + expect(oauthPairFromStore({ openai: { type: "oauth", ...PAIR } }, "xai")).toBeNull(); +}); + +test("the refresh token is written first, and only to the store repo", () => { + expect(ciSecretWrites(PAIR, REPOS)).toEqual([ + { name: CI_REFRESH_SECRET, repo: "expo/code-review-sessions", value: PAIR.refresh }, + { name: CI_ACCESS_SECRET, repo: "expo/code-review-sessions", value: PAIR.access }, + { name: CI_ACCESS_SECRET, repo: "expo/expo", value: PAIR.access }, + ]); + // A target that repeats, or that is the store, gets one write. + const repeated = ciSecretWrites(PAIR, { store: "a/s", targets: ["a/t", "a/s", "a/t"] }); + expect(repeated.map((write) => `${write.name}@${write.repo}`)).toEqual([ + `${CI_REFRESH_SECRET}@a/s`, + `${CI_ACCESS_SECRET}@a/s`, + `${CI_ACCESS_SECRET}@a/t`, + ]); +}); + +test("each secret value goes to gh through stdin, never on the command line", async () => { + await writeSecrets(ciSecretWrites(PAIR, REPOS)); + expect(await calls()).toEqual([ + `secret set ${CI_REFRESH_SECRET} --repo expo/code-review-sessions | ${PAIR.refresh}`, + `secret set ${CI_ACCESS_SECRET} --repo expo/code-review-sessions | ${PAIR.access}`, + `secret set ${CI_ACCESS_SECRET} --repo expo/expo | ${PAIR.access}`, + ]); +}); + +test("a failed write stops the rest and names what is already saved, with no token", async () => { + process.env.FAKE_GH_FAIL_WRITE = "--repo expo/expo"; + const error = await writeSecrets(ciSecretWrites(PAIR, REPOS)).catch((caught: Error) => caught); + expect(error).toBeInstanceOf(Error); + const message = (error as Error).message; + expect(message).toContain(`could not write ${CI_ACCESS_SECRET} to expo/expo`); + expect(message).toContain("HTTP 403"); + expect(message).toContain(`${CI_REFRESH_SECRET} in expo/code-review-sessions`); + expect(message).not.toContain(PAIR.access); + expect(message).not.toContain(PAIR.refresh); + expect(await calls()).toHaveLength(2); +}); + +test("an unreachable repo fails before any login or write", async () => { + await assertSecretsReachable(["expo/code-review-sessions", "expo/expo", "expo/expo"]); + expect(await calls()).toEqual([ + "api repos/expo/code-review-sessions/actions/secrets/public-key | ", + "api repos/expo/expo/actions/secrets/public-key | ", + ]); + + process.env.FAKE_GH_UNREACHABLE = "repos/expo/expo/"; + await expect(assertSecretsReachable(["expo/code-review-sessions", "expo/expo"])).rejects.toThrow( + /cannot reach the Actions secrets of expo\/expo \(HTTP 404: Not Found\).*Nothing was changed/s, + ); +}); diff --git a/src/__tests__/setup-auth.test.ts b/src/__tests__/setup-auth.test.ts index 1029c10..b060058 100644 --- a/src/__tests__/setup-auth.test.ts +++ b/src/__tests__/setup-auth.test.ts @@ -1,6 +1,11 @@ import { test, expect } from "bun:test"; +import { chmod, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; import { + parseCiSeedArgs, + superGrokLoginInTemporaryStore, planFromAuth, exportLine, opencodeAuthJsonPath, @@ -162,3 +167,118 @@ test("opencode auth.json path honors XDG_DATA_HOME and falls back to ~/.local/sh ); expect(opencodeAuthJsonPath({})).toContain("/.local/share/opencode/auth.json"); }); + +test("--ci-store selects the CI seed, and --ci-target may repeat", () => { + expect(parseCiSeedArgs([])).toBeNull(); + expect(parseCiSeedArgs(["--yes"])).toBeNull(); + expect(parseCiSeedArgs(["--ci-store", "expo/code-review-sessions"])).toEqual({ + store: "expo/code-review-sessions", + targets: [], + }); + expect( + parseCiSeedArgs([ + "--yes", + "--ci-target", + "expo/expo", + "--ci-store", + "expo/code-review-sessions", + "--ci-target", + "expo/eas-cli", + "--ci-target", + "expo/expo", + ]), + ).toEqual({ store: "expo/code-review-sessions", targets: ["expo/expo", "expo/eas-cli"] }); +}); + +test("a CI seed flag with a missing or bad repository is a usage error", () => { + expect(() => parseCiSeedArgs(["--ci-target", "expo/expo"])).toThrow(/needs --ci-store/); + expect(() => parseCiSeedArgs(["--ci-store"])).toThrow(/--ci-store needs a repository/); + expect(() => parseCiSeedArgs(["--ci-store", "--yes"])).toThrow(/--ci-store needs a repository/); + expect(() => parseCiSeedArgs(["--ci-store", "a/b", "--ci-store", "c/d"])).toThrow(/one time/); + expect(() => parseCiSeedArgs(["--ci-store", "not-a-repo"])).toThrow(/\//); + expect(() => parseCiSeedArgs(["--ci-store", "a/b", "--ci-target", "x"])).toThrow( + /\//, + ); +}); + +// Stands in for `opencode auth login`: records how it was called, then acts on FAKE_OPENCODE_MODE. +const FAKE_OPENCODE = `#!/bin/sh +{ + echo "argv=$*" + echo "data=$XDG_DATA_HOME" + echo "project_config_off=$OPENCODE_DISABLE_PROJECT_CONFIG" +} > "$FAKE_OPENCODE_DIR/call.log" +[ "$FAKE_OPENCODE_MODE" = "fail" ] && exit 3 +[ "$FAKE_OPENCODE_MODE" = "nothing" ] && exit 0 +mkdir -p "$XDG_DATA_HOME/opencode" +if [ "$FAKE_OPENCODE_MODE" = "norefresh" ]; then + printf '{"xai":{"type":"oauth","access":"eyJ.SEED.sig","refresh":"","expires":1}}' > "$XDG_DATA_HOME/opencode/auth.json" +else + printf '{"xai":{"type":"oauth","access":"eyJ.SEED.sig","refresh":"SEED-REFRESH","expires":1}}' > "$XDG_DATA_HOME/opencode/auth.json" +fi +`; + +async function withFakeOpencode( + mode: string, + body: (cli: string, callLog: () => Promise>) => Promise, +): Promise { + const dir = await mkdtemp(path.join(tmpdir(), "ecr-fake-opencode-")); + const cli = path.join(dir, "opencode"); + await writeFile(cli, FAKE_OPENCODE, "utf8"); + await chmod(cli, 0o755); + const saved = { + dir: process.env.FAKE_OPENCODE_DIR, + mode: process.env.FAKE_OPENCODE_MODE, + xdg: process.env.XDG_DATA_HOME, + }; + process.env.FAKE_OPENCODE_DIR = dir; + process.env.FAKE_OPENCODE_MODE = mode; + try { + await body(cli, async () => + Object.fromEntries( + (await readFile(path.join(dir, "call.log"), "utf8")) + .split("\n") + .filter(Boolean) + .map((line) => line.split(/=(.*)/s).slice(0, 2) as [string, string]), + ), + ); + // The login must not move this process to the temporary store. + expect(process.env.XDG_DATA_HOME).toBe(saved.xdg); + } finally { + for (const [name, value] of [ + ["FAKE_OPENCODE_DIR", saved.dir], + ["FAKE_OPENCODE_MODE", saved.mode], + ] as const) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + await rm(dir, { recursive: true, force: true }); + } +} + +test("the CI login runs in a store of its own and deletes that store", async () => { + await withFakeOpencode("ok", async (cli, callLog) => { + expect(await superGrokLoginInTemporaryStore(cli)).toEqual({ + access: "eyJ.SEED.sig", + refresh: "SEED-REFRESH", + }); + const call = await callLog(); + expect(call.argv).toBe("auth login -p xai -m SuperGrok Subscription"); + expect(call.project_config_off).toBe("1"); + expect(path.basename(call.data!)).toMatch(/^ecr-ci-seed-/); + await expect(stat(call.data!)).rejects.toThrow(); + }); +}); + +test("a CI login that fails or stores no token pair changes nothing and leaves no store", async () => { + for (const [mode, message] of [ + ["fail", /exited with 3; nothing was changed/], + ["nothing", /stored no SuperGrok access and refresh token/], + ["norefresh", /stored no SuperGrok access and refresh token/], + ] as const) { + await withFakeOpencode(mode, async (cli, callLog) => { + await expect(superGrokLoginInTemporaryStore(cli)).rejects.toThrow(message); + await expect(stat((await callLog()).data!)).rejects.toThrow(); + }); + } +}); diff --git a/src/cli.ts b/src/cli.ts index be526c4..81c1dd1 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -23,7 +23,7 @@ Usage: ecr undismiss --pr Restore a dismissed finding. ecr feedback [--repo ] [--limit ] Report what humans pushed back on (see \`ecr feedback --help\`). ecr init [--monorepo] [--scope ] Scaffold .expo-code-review/ in this repo. - ecr setup-auth [--yes] Walk through getting model credentials for local runs. + ecr setup-auth [--yes] Walk through getting model credentials for local runs, or seed CI secrets (see \`ecr setup-auth --help\`). ecr doctor [--list-scopes] Check environment, config, credentials, and scopes. ecr verify-config [--expected ] [--json] Refuse to run if a config could redirect the credential (CI guard). ecr ref-check [--root ] [--json] Fail if the review setup cites code that moved or vanished. diff --git a/src/commands/setup-auth.ts b/src/commands/setup-auth.ts index 2d93ac9..f048315 100644 --- a/src/commands/setup-auth.ts +++ b/src/commands/setup-auth.ts @@ -1,6 +1,6 @@ // @ref LLP 0007#doctor-and-setup-auth — derives a plan from auth config, then guides local credential acquisition import { spawnSync } from "node:child_process"; -import { readFile } from "node:fs/promises"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import readline from "node:readline/promises"; @@ -8,6 +8,16 @@ import readline from "node:readline/promises"; import { hasConfig, loadReviewConfig } from "../config/load.js"; import type { AuthConfigEntry } from "../config/schema.js"; import { checkOauthTokenShape, jwtExpiryMs } from "../core/auth.js"; +import { + assertSecretsReachable, + CI_ACCESS_SECRET, + CI_REFRESH_SECRET, + ciSecretWrites, + oauthPairFromStore, + parseRepoSlug, + writeSecrets, +} from "../core/ci-secrets.js"; +import type { CiSeedRepos, OauthPair } from "../core/ci-secrets.js"; import { claudeSubscriptionActive, resolveClaudeCli } from "../core/claude-code.js"; import { resolveOpencodeCli } from "../core/opencode.js"; import { errorMessage } from "../core/util.js"; @@ -40,6 +50,21 @@ with the default env name. Options: --yes Skip confirmation prompts (still interactive during the login itself). + +CI seed for a SuperGrok subscription: + ecr setup-auth --ci-store [--ci-target ]… [--yes] + + A SuperGrok access token lasts hours, so CI needs a scheduled workflow that + refreshes it. This mode starts that chain. It signs in to SuperGrok in a + temporary store, only for CI, and writes the tokens to GitHub Actions secrets + with \`gh\`. It prints no token and does nothing else. + --ci-store The repo that runs the refresh workflow. It gets + XAI_OAUTH_REFRESH_TOKEN and XAI_OAUTH_ACCESS_TOKEN. + --ci-target A repo that runs reviews. It gets XAI_OAUTH_ACCESS_TOKEN. + Repeat it for more repos. + Do not reuse your own OpenCode sign-in for CI: a refresh token is replaced + when it is used. Run this mode again when the workflow reports a lost or + refused refresh token. `; /** What setup-auth must do for a given auth config. Pure, so it's testable. */ @@ -114,6 +139,78 @@ export function opencodeLoginEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.P return { ...env, OPENCODE_DISABLE_PROJECT_CONFIG: "1" }; } +/** + * The CI seed arguments, or null for the normal flow. + * `--ci-store` selects the mode, so `--ci-target` without it is a mistake. + */ +export function parseCiSeedArgs(argv: string[]): CiSeedRepos | null { + let store: string | undefined; + const targets: string[] = []; + for (let index = 0; index < argv.length; index++) { + const flag = argv[index]; + if (flag !== "--ci-store" && flag !== "--ci-target") { + continue; + } + const value = argv[++index]; + if (value === undefined || value.startsWith("--")) { + throw new Error(`${flag} needs a repository in / form.`); + } + if (flag === "--ci-target") { + targets.push(parseRepoSlug(value)); + } else if (store !== undefined) { + throw new Error("--ci-store can be given one time only."); + } else { + store = parseRepoSlug(value); + } + } + if (store === undefined) { + if (targets.length > 0) { + throw new Error("--ci-target needs --ci-store, the repo that holds the refresh token."); + } + return null; + } + return { store, targets: [...new Set(targets)] }; +} + +// @ref LLP 0007#doctor-and-setup-auth [implements] — the CI seed is the one flow where a refresh token leaves an OpenCode store: from a store made for this call, to a GitHub secret +/** + * Run the SuperGrok device login in a store that exists only for this call, and return both tokens. + * CI needs a login of its own. + * xAI can replace a refresh token when it is used, so one shared with a laptop would break either side. + */ +export async function superGrokLoginInTemporaryStore(opencodeCli: string): Promise { + const dataHome = await mkdtemp(path.join(os.tmpdir(), "ecr-ci-seed-")); + try { + const result = spawnSync(opencodeCli, [...SUPERGROK_LOGIN_ARGS], { + stdio: "inherit", + cwd: os.tmpdir(), + env: { ...opencodeLoginEnv(), XDG_DATA_HOME: dataHome }, + }); + if (result.status !== 0) { + throw new Error( + `\`opencode auth login\` exited with ${result.status ?? "a signal"}; nothing was changed.`, + ); + } + let parsed: Parameters[0] = {}; + try { + parsed = JSON.parse( + await readFile(opencodeAuthJsonPath({ XDG_DATA_HOME: dataHome }), "utf8"), + ) as typeof parsed; + } catch { + // No store file means the login saved nothing. The check below reports it. + } + const pair = oauthPairFromStore(parsed, "xai"); + if (!pair) { + throw new Error( + "The login finished but stored no SuperGrok access and refresh token; nothing was changed.", + ); + } + return pair; + } finally { + await rm(dataHome, { recursive: true, force: true }); + } +} + export interface StoredOauthAccess { token: string; expiresMs: number; @@ -192,6 +289,52 @@ export function exportLine(tokenEnv: string, value: string): string { return `export ${tokenEnv}='${value.replace(/'/g, "'\\''")}'`; } +async function runCiSeed( + repos: CiSeedRepos, + yes: boolean, + err: (line?: string) => boolean, +): Promise { + const accessRepos = [...new Set([repos.store, ...repos.targets])]; + err("This signs in to SuperGrok for CI only and overwrites these GitHub Actions secrets:"); + err(` ${CI_REFRESH_SECRET} in ${repos.store}`); + err(` ${CI_ACCESS_SECRET} in ${accessRepos.join(", ")}`); + err("The login goes into a temporary store, not into your own OpenCode sign-in."); + if (!(await confirm("Continue?", yes))) { + err("Skipped the CI seed. Nothing was changed."); + return; + } + await assertSecretsReachable(accessRepos); + 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.", + ); + } + err("The login prints a URL and a device code. Open the URL and enter the code."); + const pair = await superGrokLoginInTemporaryStore(opencodeCli); + // A token that a review would refuse must not reach a secret. + // A warning does not block the seed: a shorter lifetime from xAI is still the token CI gets. + const shape = checkOauthTokenShape("xai", pair.access, CI_ACCESS_SECRET); + if (!shape.ok) { + throw new Error( + `The login returned an access token that a review would refuse. ${shape.detail}`, + ); + } + await writeSecrets(ciSecretWrites(pair, repos)); + err(""); + err(`✓ Wrote ${CI_REFRESH_SECRET} to ${repos.store}.`); + err(`✓ Wrote ${CI_ACCESS_SECRET} to ${accessRepos.join(", ")}.`); + const expiresMs = jwtExpiryMs(pair.access); + if (expiresMs !== null) { + err(`The access token is valid for ${remainingLabel(expiresMs)}.`); + } + if (shape.warning) { + err(`Warning: ${shape.warning}`); + } + err(`Next: start the refresh workflow in ${repos.store} one time by hand to prove the chain.`); +} + export async function setupAuthCommand(argv: string[] = []): Promise { if (argv.includes("-h") || argv.includes("--help")) { process.stdout.write(USAGE); @@ -201,7 +344,20 @@ export async function setupAuthCommand(argv: string[] = []): Promise { const out = (line = ""): boolean => process.stdout.write(`${line}\n`); const err = (line = ""): boolean => process.stderr.write(`${line}\n`); + let ciSeed: CiSeedRepos | null; + try { + ciSeed = parseCiSeedArgs(argv); + } catch (error) { + process.stderr.write(`${errorMessage(error)}\n\n${USAGE}`); + process.exitCode = 2; + return; + } + try { + if (ciSeed) { + await runCiSeed(ciSeed, yes, err); + return; + } // Plan from the repo config when there is one; otherwise offer the // recommended subscription flow with the default env name. let plan: SetupPlan; diff --git a/src/core/ci-secrets.ts b/src/core/ci-secrets.ts new file mode 100644 index 0000000..2192b52 --- /dev/null +++ b/src/core/ci-secrets.ts @@ -0,0 +1,106 @@ +// @ref LLP 0007#doctor-and-setup-auth [implements] — the CI seed sends a login made only for CI straight to GitHub Actions secrets; no token is printed or kept +import { resolveTrustedTool, run } from "./exec.js"; + +/** The secret that holds the refresh token. Only the rotation workflow in the store repo reads it. */ +export const CI_REFRESH_SECRET = "XAI_OAUTH_REFRESH_TOKEN"; +/** The secret that holds the access token. Review workflows pass it to `ecr`. */ +export const CI_ACCESS_SECRET = "XAI_OAUTH_ACCESS_TOKEN"; + +export interface CiSeedRepos { + /** Holds the refresh token and runs the rotation workflow. */ + store: string; + /** Repos that run reviews. Each one gets the access token only. */ + targets: string[]; +} + +export interface OauthPair { + access: string; + refresh: string; +} + +export interface SecretWrite { + name: string; + repo: string; + value: string; +} + +// The value goes to `gh --repo`, so it must not look like a flag or a path. +const REPO_SLUG = /^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/; + +export function parseRepoSlug(value: string): string { + if (!REPO_SLUG.test(value)) { + throw new Error(`"${value}" is not a repository in / form.`); + } + return value; +} + +/** Both tokens of one provider's oauth entry in an OpenCode auth.json, or null when either is missing. */ +export function oauthPairFromStore( + parsed: Record, + provider: string, +): OauthPair | null { + const entry = parsed[provider]; + if (entry?.type !== "oauth" || !entry.access || !entry.refresh) { + return null; + } + return { access: entry.access, refresh: entry.refresh }; +} + +/** + * The secret writes for one seed, in the order they must run. + * The refresh token goes first. + * With it saved, the rotation workflow can repair an access token write that fails after it. + */ +export function ciSecretWrites(pair: OauthPair, repos: CiSeedRepos): SecretWrite[] { + const accessRepos = [...new Set([repos.store, ...repos.targets])]; + return [ + { name: CI_REFRESH_SECRET, repo: repos.store, value: pair.refresh }, + ...accessRepos.map((repo) => ({ name: CI_ACCESS_SECRET, repo, value: pair.access })), + ]; +} + +function firstLine(text: string): string { + return text.trim().split("\n")[0] ?? ""; +} + +/** + * Fail before the login when `gh` cannot reach the Actions secrets of a repo. + * A login that cannot be saved is wasted. + */ +export async function assertSecretsReachable(repos: string[]): Promise { + const gh = await resolveTrustedTool("gh"); + for (const repo of new Set(repos)) { + const result = await run(gh, ["api", `repos/${repo}/actions/secrets/public-key`], { + check: false, + }); + if (result.code !== 0) { + throw new Error( + `\`gh\` cannot reach the Actions secrets of ${repo} (${firstLine(result.stderr) || "no detail"}). ` + + `Sign in with \`gh auth login\` as someone who can set secrets there. Nothing was changed.`, + ); + } + } +} + +/** + * Write the secrets in order and stop at the first failure. + * Each value goes to `gh` through stdin, so it is never on a command line or in an error message. + */ +export async function writeSecrets(writes: SecretWrite[]): Promise { + const gh = await resolveTrustedTool("gh"); + const done: string[] = []; + for (const write of writes) { + const result = await run(gh, ["secret", "set", write.name, "--repo", write.repo], { + input: write.value, + check: false, + }); + if (result.code !== 0) { + throw new Error( + `could not write ${write.name} to ${write.repo} (${firstLine(result.stderr) || "no detail"}). ` + + (done.length > 0 ? `Already written: ${done.join(", ")}. ` : "Nothing was written. ") + + `Run the same command again; it signs in again and writes every secret.`, + ); + } + done.push(`${write.name} in ${write.repo}`); + } +} diff --git a/templates/config.jsonc b/templates/config.jsonc index c2cf92b..e47ea64 100644 --- a/templates/config.jsonc +++ b/templates/config.jsonc @@ -161,6 +161,7 @@ // 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. + // CI needs a scheduled refresh: see the CI seed in `ecr setup-auth --help`. // Keep "mode": "oauth": an entry that names this env without it is refused. // "auth": { "providers": { // "xai": { "mode": "oauth", "tokenEnv": "XAI_OAUTH_ACCESS_TOKEN" }