a78b1542da
* feat: pullfrog auth codex + fresh-branch Add `pullfrog auth codex` standalone command for minting Codex (ChatGPT) subscription credentials and saving them as the `CODEX_AUTH_JSON` Pullfrog secret. Codex device-auth runs in a subprocess with an isolated `CODEX_HOME` (temp dir) so the user's `~/.codex/auth.json` is never touched. The spawned `codex login --device-auth` output is captured line-by-line, ANSI-stripped, and re-rendered with a `$ codex login --device-auth` header above dimmed sub-output on the @clack/prompts rail so the user visually understands they're seeing a sub-process. Companion `pnpm fresh-branch` script: from inside `.worktrees/<name>`, creates a schema-only Neon branch named `dev/<git-branch>`, patches the worktree's `.env` (DATABASE_URL, DATABASE_URL_UNPOOLED, NEON_DEV_BRANCH), then runs `prisma migrate reset --force` so migrations apply cleanly against a data-free copy. Refuses to run from the primary checkout or on protected branch names. Other: - bump CLI/account/repo secret value limit 4096 -> 49152 chars (matches GitHub Actions' 48KB cap; auth.json is ~4-5KB) - extract shared CLI helpers (gh/pullfrog API, secret save) into `action/commands/_shared.ts` * fix(auth): address PR review + add CodexAuthCallout, default account scope Review fixes: - handle 'error' event from `codex` spawn (ENOENT) so missing PATH bails with an actionable "install codex CLI" message instead of an unhandled Node error - escalate SIGTERM -> SIGKILL after 5s grace when killing a stuck codex child so the CLI can't get pinned indefinitely - stop the spinner with a red "failed" glyph in the catch path before clearing activeSpin, mirroring `bail` (no orphan spinner above errors) - enforce 48 KB secret value cap by *bytes* (Buffer.byteLength) not UTF-16 code units, across all 3 secret routes; matches GH Actions' byte-based limit - preserve existing blank lines + comments when fresh-branch rewrites worktree .env (no more cosmetic reformat on every run) Scope: - default to `account` scope on org-owned repos too — never silently prompt for repo scope. Pullfrog has no per-GitHub-user secret store, so account is right for both user and org owners; `--scope repo` is the explicit opt-in for repo-only. UI: - new CodexAuthCallout (sibling to ClaudeCodeOAuthCallout); surfaces `pullfrog auth codex` for ChatGPT subscribers when an OpenAI provider model is selected. wired into AgentSettings.tsx (model-costs surface) and OnboardingCard.tsx (first-time setup). no paste button — the CLI handles minting + saving end-to-end. * auth/codex: rename to neon-fresh-branch, address PR review - rename `pnpm fresh-branch` → `pnpm neon-fresh-branch` (and the script file) to disambiguate from git branches. - `--scope` help text now explains the default (account) and when to pass `repo`. - move `_shared.ts` import up with the rest in `action/commands/auth.ts` and push the `stripAnsi` helper below the import block. - `sanitizeBranchName` no longer slices: slicing after trim could reintroduce a trailing `-`/`/`. callers slice the raw input first, then sanitize. - DRY the `start` branch of the codex progress callback (single header path, optional retry log). - thread a `timedOut` flag from `runDeviceAuth` → `ProgressEvent.exit` so the retry prompt can say "device authorization timed out — retry?" instead of the generic "no auth.json was written" line when the per-attempt timeout fires. - drop the redundant `mkdirSync` after `mkdtempSync` in `codexAuth.ts`. * untrack .scratch/ (committed screenshot fixture by mistake) * auth codex: prompt for scope on orgs (mirrors init) * revert worktree.ts: out of scope for this PR * anneal: trim _shared.ts dead exports, collapse CodexSpawnError, inline packageBin * codex auth: wire end-to-end runtime consumer CODEX_AUTH_JSON is now actually usable: the action runtime materializes it as OpenCode's auth.json at the runner's real $HOME/.local/share/opencode, OpenCode routes openai requests through the ChatGPT subscription via the embedded CodexAuthPlugin, and a GitHub Actions post: hook detects any refresh-chain rotation during the run and PUTs it back to Pullfrog via a new JWT-authenticated PUT /api/runtime/secret endpoint. Key decisions: - Write to the real $HOME (not the per-run tmpdir-redirected HOME) so the file lives outside OpenCode's `/tmp/*` permission allow zone — its existing deny-default protects it without any new permission rule. - Materialization gated on agent === opencode (Codex auth is OpenAI-only, Claude never sees the file). - Defense-in-depth on Claude: deny Read/Grep/Edit/Glob + sandbox.denyRead for ~/.local/share/opencode/auth.json in managedSettings (covers Bash file-reading commands too per Claude Code permissions docs). - New `provider.managedCredentials` field on the provider config — CLI-only credentials authored via `pullfrog auth <provider>`. Counted for hasAnyKey/log-redaction but never surfaced as a paste option in init. CODEX_AUTH_JSON is the first member; OPENAI_API_KEY stays in envVars. - Eager refresh on `pullfrog auth codex`: one OAuth round-trip before setPullfrogSecret so Pullfrog's copy is the freshest in the chain (avoids the user's laptop refreshing first and stranding our copy). - Post-hook approach for write-back so it survives cancellation, timeouts, and unhandled errors in the main step. State is ferried via core.saveState since apiToken is run-scoped and not in env. - Server-side write-back endpoint is allowlist-gated to CODEX_AUTH_JSON only — never a generic secret-write surface. Looks up the secret at repo scope first, falls back to account scope. 404s on create (refresh-only, never auto-provision). * codex auth: documentation + wiki cross-links * debug: log dbSecrets keys + CODEX_AUTH_JSON presence (temporary) * debug: surface install path + parse failure preview * remove debug log lines (E2E verified) * hide CodexAuthCallout until opencode-ai bump (1.1.56's allowed-models set excludes gpt-5.5)
166 lines
6.0 KiB
TypeScript
166 lines
6.0 KiB
TypeScript
// Codex-to-OpenCode auth bridging for the action runtime.
|
|
//
|
|
// `pullfrog auth codex` stores a Codex CLI `auth.json` blob in the Pullfrog
|
|
// secret store. At runtime the harness injects it as `CODEX_AUTH_JSON` in
|
|
// process.env (via `dbSecrets` in main.ts). This utility:
|
|
//
|
|
// 1. parses + validates that env value
|
|
// 2. converts Codex's shape `{ auth_mode, tokens: { access_token, refresh_token, ... } }`
|
|
// into OpenCode's shape `{ openai: { type: "oauth", refresh, access, expires, accountId } }`
|
|
// 3. materializes it to disk at the runner's REAL `$HOME/.local/share/opencode/auth.json`
|
|
// (NOT the per-run tmpdir's HOME)
|
|
// 4. returns the path + the original refresh token so the post-run hook
|
|
// can detect a refresh and write back to Pullfrog
|
|
//
|
|
// Why real $HOME and not ctx.tmpdir-redirected HOME: the broad
|
|
// `external_directory: { "/tmp/*": "allow" }` rule on OpenCode would expose
|
|
// auth.json to the agent's filesystem tools if the file lived under
|
|
// `ctx.tmpdir` = `/tmp/pullfrog-*`. Real `$HOME/.local/share/opencode/...`
|
|
// falls outside that allow zone, so OpenCode's deny-default protects it
|
|
// without any new permission rules.
|
|
//
|
|
// `expires: 0` forces OpenCode to refresh on first request (we don't trust
|
|
// the in-blob freshness — the saved token was eager-refreshed once at
|
|
// `auth codex` time but may have aged since).
|
|
//
|
|
// See [wiki/codex-auth.md] for the full data-flow picture.
|
|
|
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
import { homedir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { log } from "./cli.ts";
|
|
|
|
const CODEX_AUTH_ENV = "CODEX_AUTH_JSON";
|
|
|
|
interface CodexAuthBlob {
|
|
auth_mode: "chatgpt";
|
|
tokens: {
|
|
access_token: string;
|
|
refresh_token: string;
|
|
id_token?: string;
|
|
account_id?: string;
|
|
};
|
|
last_refresh?: string;
|
|
}
|
|
|
|
interface OpenCodeAuthFile {
|
|
openai: {
|
|
type: "oauth";
|
|
refresh: string;
|
|
access: string;
|
|
expires: number;
|
|
accountId?: string;
|
|
};
|
|
}
|
|
|
|
export interface InstalledCodexAuth {
|
|
/** absolute path of the auth.json we wrote — caller passes this to the
|
|
* post-hook via core.saveState for refresh-detection later. */
|
|
authPath: string;
|
|
/** value to set as XDG_DATA_HOME for the OpenCode subprocess. */
|
|
xdgDataHome: string;
|
|
/** refresh_token from the env at materialization time. post-hook compares
|
|
* against the on-disk file after the run to detect whether OpenCode
|
|
* refreshed during the session. */
|
|
originalRefresh: string;
|
|
}
|
|
|
|
/** materialize CODEX_AUTH_JSON from env into a disk path OpenCode reads from.
|
|
* returns null when the env var is absent, malformed, or wrong auth mode —
|
|
* caller treats null as "no codex auth, fall through to API key flow". */
|
|
export function installCodexAuth(): InstalledCodexAuth | null {
|
|
const raw = process.env[CODEX_AUTH_ENV];
|
|
if (!raw) return null;
|
|
|
|
const blob = parseCodexBlob(raw);
|
|
if (!blob) {
|
|
log.warning(`» ${CODEX_AUTH_ENV} present but malformed; ignoring`);
|
|
return null;
|
|
}
|
|
|
|
const xdgDataHome = join(homedir(), ".local", "share");
|
|
const opencodeDir = join(xdgDataHome, "opencode");
|
|
const authPath = join(opencodeDir, "auth.json");
|
|
|
|
const opencodeAuth: OpenCodeAuthFile = {
|
|
openai: {
|
|
type: "oauth",
|
|
refresh: blob.tokens.refresh_token,
|
|
access: blob.tokens.access_token,
|
|
// expires: 0 forces OpenCode's CodexAuthPlugin to refresh on first
|
|
// request (it checks `expires < Date.now()`). safest default — we
|
|
// don't carry an `expires_in` from the Codex blob.
|
|
expires: 0,
|
|
...(blob.tokens.account_id ? { accountId: blob.tokens.account_id } : {}),
|
|
},
|
|
};
|
|
|
|
mkdirSync(opencodeDir, { recursive: true });
|
|
writeFileSync(authPath, `${JSON.stringify(opencodeAuth, null, 2)}\n`, { mode: 0o600 });
|
|
|
|
log.info(`» installed Codex auth at ${authPath}`);
|
|
|
|
return { authPath, xdgDataHome, originalRefresh: blob.tokens.refresh_token };
|
|
}
|
|
|
|
function parseCodexBlob(raw: string): CodexAuthBlob | null {
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(raw);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (!parsed || typeof parsed !== "object") return null;
|
|
const v = parsed as Record<string, unknown>;
|
|
if (v.auth_mode !== "chatgpt") return null;
|
|
const tokens = v.tokens;
|
|
if (!tokens || typeof tokens !== "object") return null;
|
|
const t = tokens as Record<string, unknown>;
|
|
if (typeof t.access_token !== "string" || t.access_token.length === 0) return null;
|
|
if (typeof t.refresh_token !== "string" || t.refresh_token.length === 0) return null;
|
|
return {
|
|
auth_mode: "chatgpt",
|
|
tokens: {
|
|
access_token: t.access_token,
|
|
refresh_token: t.refresh_token,
|
|
...(typeof t.id_token === "string" ? { id_token: t.id_token } : {}),
|
|
...(typeof t.account_id === "string" ? { account_id: t.account_id } : {}),
|
|
},
|
|
...(typeof v.last_refresh === "string" ? { last_refresh: v.last_refresh } : {}),
|
|
};
|
|
}
|
|
|
|
/** convert an on-disk OpenCode auth.json back to the Codex CLI shape so the
|
|
* post-hook can write it to the Pullfrog secret store. returns null when the
|
|
* file's `openai` entry is missing, has the wrong type, or hasn't actually
|
|
* refreshed (refresh token unchanged from `originalRefresh`). */
|
|
export function detectCodexRefresh(params: {
|
|
authFileContent: string;
|
|
originalRefresh: string;
|
|
}): string | null {
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(params.authFileContent);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (!parsed || typeof parsed !== "object") return null;
|
|
const oauth = (parsed as Record<string, unknown>).openai;
|
|
if (!oauth || typeof oauth !== "object") return null;
|
|
const o = oauth as Record<string, unknown>;
|
|
if (o.type !== "oauth") return null;
|
|
if (typeof o.refresh !== "string" || typeof o.access !== "string") return null;
|
|
if (o.refresh === params.originalRefresh) return null;
|
|
|
|
const codexShape: CodexAuthBlob = {
|
|
auth_mode: "chatgpt",
|
|
tokens: {
|
|
access_token: o.access,
|
|
refresh_token: o.refresh,
|
|
...(typeof o.accountId === "string" ? { account_id: o.accountId } : {}),
|
|
},
|
|
last_refresh: new Date().toISOString(),
|
|
};
|
|
return `${JSON.stringify(codexShape, null, 2)}\n`;
|
|
}
|