feat: update token auth flow

This commit is contained in:
Peter Steinberger
2026-01-09 08:12:48 +01:00
parent a4d6638f89
commit 77d4bb8dfe
7 changed files with 145 additions and 160 deletions

View File

@@ -71,7 +71,7 @@ Tip: `--json` does **not** imply non-interactive mode. Use `--non-interactive` (
2) **Model/Auth** 2) **Model/Auth**
- **Anthropic OAuth (Claude CLI)**: on macOS the wizard checks Keychain item "Claude Code-credentials" (choose "Always Allow" so launchd starts don't block); on Linux/Windows it reuses `~/.claude/.credentials.json` if present. - **Anthropic OAuth (Claude CLI)**: on macOS the wizard checks Keychain item "Claude Code-credentials" (choose "Always Allow" so launchd starts don't block); on Linux/Windows it reuses `~/.claude/.credentials.json` if present.
- **Anthropic OAuth (recommended)**: browser flow; paste the `code#state`. - **Anthropic token (paste setup-token)**: run `claude setup-token` in your terminal, then paste the token (you can name it; blank = default).
- **OpenAI Codex OAuth (Codex CLI)**: if `~/.codex/auth.json` exists, the wizard can reuse it. - **OpenAI Codex OAuth (Codex CLI)**: if `~/.codex/auth.json` exists, the wizard can reuse it.
- **OpenAI Codex OAuth**: browser flow; paste the `code#state`. - **OpenAI Codex OAuth**: browser flow; paste the `code#state`.
- Sets `agent.model` to `openai-codex/gpt-5.2` when model is unset or `openai/*`. - Sets `agent.model` to `openai-codex/gpt-5.2` when model is unset or `openai/*`.

View File

@@ -38,10 +38,9 @@ describe("buildAuthChoiceOptions", () => {
version: 1, version: 1,
profiles: { profiles: {
[CLAUDE_CLI_PROFILE_ID]: { [CLAUDE_CLI_PROFILE_ID]: {
type: "oauth", type: "token",
provider: "anthropic", provider: "anthropic",
access: "token", token: "token",
refresh: "refresh",
expires: Date.now() + 60 * 60 * 1000, expires: Date.now() + 60 * 60 * 1000,
}, },
}, },

View File

@@ -76,9 +76,9 @@ export function buildAuthChoiceOptions(params: {
} }
options.push({ options.push({
value: "oauth", value: "token",
label: "Anthropic token (setup-token)", label: "Anthropic token (paste setup-token)",
hint: "Runs `claude setup-token`", hint: "Run `claude setup-token`, then paste the token",
}); });
options.push({ options.push({
@@ -91,11 +91,7 @@ export function buildAuthChoiceOptions(params: {
}); });
options.push({ value: "gemini-api-key", label: "Google Gemini API key" }); options.push({ value: "gemini-api-key", label: "Google Gemini API key" });
options.push({ value: "apiKey", label: "Anthropic API key" }); options.push({ value: "apiKey", label: "Anthropic API key" });
options.push({ // Token flow is currently Anthropic-only; use CLI for advanced providers.
value: "token",
label: "Paste token (advanced)",
hint: "Stores as a non-refreshable token profile",
});
options.push({ value: "minimax", label: "Minimax M2.1 (LM Studio)" }); options.push({ value: "minimax", label: "Minimax M2.1 (LM Studio)" });
if (params.includeSkip) { if (params.includeSkip) {
options.push({ value: "skip", label: "Skip for now" }); options.push({ value: "skip", label: "Skip for now" });

View File

@@ -17,10 +17,7 @@ import {
resolveEnvApiKey, resolveEnvApiKey,
} from "../agents/model-auth.js"; } from "../agents/model-auth.js";
import { loadModelCatalog } from "../agents/model-catalog.js"; import { loadModelCatalog } from "../agents/model-catalog.js";
import { import { resolveConfiguredModelRef } from "../agents/model-selection.js";
normalizeProviderId,
resolveConfiguredModelRef,
} from "../agents/model-selection.js";
import { parseDurationMs } from "../cli/parse-duration.js"; import { parseDurationMs } from "../cli/parse-duration.js";
import type { ClawdbotConfig } from "../config/config.js"; import type { ClawdbotConfig } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js"; import type { RuntimeEnv } from "../runtime.js";
@@ -29,6 +26,10 @@ import {
isRemoteEnvironment, isRemoteEnvironment,
loginAntigravityVpsAware, loginAntigravityVpsAware,
} from "./antigravity-oauth.js"; } from "./antigravity-oauth.js";
import {
buildTokenProfileId,
validateAnthropicSetupToken,
} from "./auth-token.js";
import { import {
applyGoogleGeminiModelDefault, applyGoogleGeminiModelDefault,
GOOGLE_GEMINI_DEFAULT_MODEL, GOOGLE_GEMINI_DEFAULT_MODEL,
@@ -136,65 +137,7 @@ export async function applyAuthChoice(params: {
); );
}; };
if (params.authChoice === "oauth") { if (params.authChoice === "claude-cli") {
await params.prompter.note(
[
"This will run `claude setup-token` to create a long-lived Anthropic token.",
"Requires an interactive TTY and a Claude Pro/Max subscription.",
].join("\n"),
"Anthropic token",
);
if (!process.stdin.isTTY) {
await params.prompter.note(
"`claude setup-token` requires an interactive TTY.",
"Anthropic token",
);
return { config: nextConfig, agentModelOverride };
}
const proceed = await params.prompter.confirm({
message: "Run `claude setup-token` now?",
initialValue: true,
});
if (!proceed) return { config: nextConfig, agentModelOverride };
const res = await (async () => {
const { spawnSync } = await import("node:child_process");
return spawnSync("claude", ["setup-token"], { stdio: "inherit" });
})();
if (res.error) {
await params.prompter.note(
`Failed to run claude: ${String(res.error)}`,
"Anthropic token",
);
return { config: nextConfig, agentModelOverride };
}
if (typeof res.status === "number" && res.status !== 0) {
await params.prompter.note(
`claude setup-token failed (exit ${res.status})`,
"Anthropic token",
);
return { config: nextConfig, agentModelOverride };
}
const store = ensureAuthProfileStore(params.agentDir, {
allowKeychainPrompt: true,
});
if (!store.profiles[CLAUDE_CLI_PROFILE_ID]) {
await params.prompter.note(
`No Claude CLI credentials found after setup-token. Expected ${CLAUDE_CLI_PROFILE_ID}.`,
"Anthropic token",
);
return { config: nextConfig, agentModelOverride };
}
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: CLAUDE_CLI_PROFILE_ID,
provider: "anthropic",
mode: "token",
});
} else if (params.authChoice === "claude-cli") {
const store = ensureAuthProfileStore(params.agentDir, { const store = ensureAuthProfileStore(params.agentDir, {
allowKeychainPrompt: false, allowKeychainPrompt: false,
}); });
@@ -266,24 +209,50 @@ export async function applyAuthChoice(params: {
provider: "anthropic", provider: "anthropic",
mode: "token", mode: "token",
}); });
} else if (params.authChoice === "token") { } else if (params.authChoice === "token" || params.authChoice === "oauth") {
const providerRaw = await params.prompter.text({ const profileNameRaw = await params.prompter.text({
message: "Token provider id (e.g. anthropic)", message: "Token name (blank = default)",
validate: (value) => (value?.trim() ? undefined : "Required"), placeholder: "default",
});
const provider = (await params.prompter.select({
message: "Token provider",
options: [{ value: "anthropic", label: "Anthropic (only supported)" }],
})) as "anthropic";
const profileId = buildTokenProfileId({
provider,
name: String(profileNameRaw ?? ""),
}); });
const provider = normalizeProviderId(String(providerRaw).trim());
const defaultProfileId = `${provider}:manual`;
const profileIdRaw = await params.prompter.text({ const store = ensureAuthProfileStore(params.agentDir, {
message: "Auth profile id", allowKeychainPrompt: false,
initialValue: defaultProfileId,
validate: (value) => (value?.trim() ? undefined : "Required"),
}); });
const profileId = String(profileIdRaw).trim(); const existing = store.profiles[profileId];
if (existing?.type === "token") {
const useExisting = await params.prompter.confirm({
message: `Use existing token "${profileId}"?`,
initialValue: true,
});
if (useExisting) {
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId,
provider,
mode: "token",
});
return { config: nextConfig, agentModelOverride };
}
}
await params.prompter.note(
[
"Run `claude setup-token` in your terminal.",
"Then paste the generated token below.",
].join("\n"),
"Anthropic token",
);
const tokenRaw = await params.prompter.text({ const tokenRaw = await params.prompter.text({
message: `Paste token for ${provider}`, message: "Paste Anthropic setup-token",
validate: (value) => (value?.trim() ? undefined : "Required"), validate: (value) => validateAnthropicSetupToken(String(value ?? "")),
}); });
const token = String(tokenRaw).trim(); const token = String(tokenRaw).trim();

View File

@@ -0,0 +1,37 @@
import { normalizeProviderId } from "../agents/model-selection.js";
export const ANTHROPIC_SETUP_TOKEN_PREFIX = "sk-ant-oat01-";
export const ANTHROPIC_SETUP_TOKEN_MIN_LENGTH = 80;
export const DEFAULT_TOKEN_PROFILE_NAME = "default";
export function normalizeTokenProfileName(raw: string): string {
const trimmed = raw.trim();
if (!trimmed) return DEFAULT_TOKEN_PROFILE_NAME;
const slug = trimmed
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "");
return slug || DEFAULT_TOKEN_PROFILE_NAME;
}
export function buildTokenProfileId(params: {
provider: string;
name: string;
}): string {
const provider = normalizeProviderId(params.provider);
const name = normalizeTokenProfileName(params.name);
return `${provider}:${name}`;
}
export function validateAnthropicSetupToken(raw: string): string | undefined {
const trimmed = raw.trim();
if (!trimmed) return "Required";
if (!trimmed.startsWith(ANTHROPIC_SETUP_TOKEN_PREFIX)) {
return `Expected token starting with ${ANTHROPIC_SETUP_TOKEN_PREFIX}`;
}
if (trimmed.length < ANTHROPIC_SETUP_TOKEN_MIN_LENGTH) {
return "Token looks too short; paste the full setup-token";
}
return undefined;
}

View File

@@ -21,7 +21,6 @@ import {
ensureAuthProfileStore, ensureAuthProfileStore,
upsertAuthProfile, upsertAuthProfile,
} from "../agents/auth-profiles.js"; } from "../agents/auth-profiles.js";
import { normalizeProviderId } from "../agents/model-selection.js";
import { parseDurationMs } from "../cli/parse-duration.js"; import { parseDurationMs } from "../cli/parse-duration.js";
import { createCliProgress } from "../cli/progress.js"; import { createCliProgress } from "../cli/progress.js";
import type { ClawdbotConfig } from "../config/config.js"; import type { ClawdbotConfig } from "../config/config.js";
@@ -47,6 +46,10 @@ import {
loginAntigravityVpsAware, loginAntigravityVpsAware,
} from "./antigravity-oauth.js"; } from "./antigravity-oauth.js";
import { buildAuthChoiceOptions } from "./auth-choice-options.js"; import { buildAuthChoiceOptions } from "./auth-choice-options.js";
import {
buildTokenProfileId,
validateAnthropicSetupToken,
} from "./auth-token.js";
import { import {
DEFAULT_GATEWAY_DAEMON_RUNTIME, DEFAULT_GATEWAY_DAEMON_RUNTIME,
GATEWAY_DAEMON_RUNTIME_OPTIONS, GATEWAY_DAEMON_RUNTIME_OPTIONS,
@@ -315,62 +318,7 @@ async function promptAuthConfig(
let next = cfg; let next = cfg;
if (authChoice === "oauth") { if (authChoice === "claude-cli") {
note(
[
"This will run `claude setup-token` to create a long-lived Anthropic token.",
"Requires an interactive TTY and a Claude Pro/Max subscription.",
].join("\n"),
"Anthropic token",
);
if (!process.stdin.isTTY) {
note(
"`claude setup-token` requires an interactive TTY.",
"Anthropic token",
);
return next;
}
const proceed = guardCancel(
await confirm({
message: "Run `claude setup-token` now?",
initialValue: true,
}),
runtime,
);
if (!proceed) return next;
const res = await (async () => {
const { spawnSync } = await import("node:child_process");
return spawnSync("claude", ["setup-token"], { stdio: "inherit" });
})();
if (res.error) {
note(`Failed to run claude: ${String(res.error)}`, "Anthropic token");
return next;
}
if (typeof res.status === "number" && res.status !== 0) {
note(`claude setup-token failed (exit ${res.status})`, "Anthropic token");
return next;
}
const store = ensureAuthProfileStore(undefined, {
allowKeychainPrompt: true,
});
if (!store.profiles[CLAUDE_CLI_PROFILE_ID]) {
note(
`No Claude CLI credentials found after setup-token. Expected ${CLAUDE_CLI_PROFILE_ID}.`,
"Anthropic token",
);
return next;
}
next = applyAuthProfileConfig(next, {
profileId: CLAUDE_CLI_PROFILE_ID,
provider: "anthropic",
mode: "token",
});
} else if (authChoice === "claude-cli") {
const store = ensureAuthProfileStore(undefined, { const store = ensureAuthProfileStore(undefined, {
allowKeychainPrompt: false, allowKeychainPrompt: false,
}); });
@@ -407,30 +355,66 @@ async function promptAuthConfig(
provider: "anthropic", provider: "anthropic",
mode: "token", mode: "token",
}); });
} else if (authChoice === "token") { } else if (authChoice === "token" || authChoice === "oauth") {
const providerRaw = guardCancel( const profileNameRaw = guardCancel(
await text({ await text({
message: "Token provider id (e.g. anthropic)", message: "Token name (blank = default)",
validate: (value) => (value?.trim() ? undefined : "Required"), placeholder: "default",
}), }),
runtime, runtime,
); );
const provider = normalizeProviderId(String(providerRaw).trim());
const defaultProfileId = `${provider}:manual`; const provider = guardCancel(
const profileIdRaw = guardCancel( await select({
await text({ message: "Token provider",
message: "Auth profile id", options: [
initialValue: defaultProfileId, {
validate: (value) => (value?.trim() ? undefined : "Required"), value: "anthropic",
label: "Anthropic (only supported)",
},
],
}),
runtime,
) as "anthropic";
const profileId = buildTokenProfileId({
provider,
name: String(profileNameRaw ?? ""),
});
const store = ensureAuthProfileStore(undefined, {
allowKeychainPrompt: false,
});
const existing = store.profiles[profileId];
if (existing?.type === "token") {
const useExisting = guardCancel(
await confirm({
message: `Use existing token "${profileId}"?`,
initialValue: true,
}), }),
runtime, runtime,
); );
const profileId = String(profileIdRaw).trim(); if (useExisting) {
next = applyAuthProfileConfig(next, {
profileId,
provider,
mode: "token",
});
return next;
}
}
note(
[
"Run `claude setup-token` in your terminal.",
"Then paste the generated token below.",
].join("\n"),
"Anthropic token",
);
const tokenRaw = guardCancel( const tokenRaw = guardCancel(
await text({ await text({
message: `Paste token for ${provider}`, message: "Paste Anthropic setup-token",
validate: (value) => (value?.trim() ? undefined : "Required"), validate: (value) => validateAnthropicSetupToken(String(value ?? "")),
}), }),
runtime, runtime,
); );

View File

@@ -2,13 +2,13 @@ import type { CliDeps } from "../cli/deps.js";
import { withProgress } from "../cli/progress.js"; import { withProgress } from "../cli/progress.js";
import { loadConfig } from "../config/config.js"; import { loadConfig } from "../config/config.js";
import { success } from "../globals.js"; import { success } from "../globals.js";
import type { OutboundDeliveryResult } from "../infra/outbound/deliver.js";
import { buildOutboundResultEnvelope } from "../infra/outbound/envelope.js"; import { buildOutboundResultEnvelope } from "../infra/outbound/envelope.js";
import { import {
buildOutboundDeliveryJson, buildOutboundDeliveryJson,
formatGatewaySummary, formatGatewaySummary,
formatOutboundDeliverySummary, formatOutboundDeliverySummary,
} from "../infra/outbound/format.js"; } from "../infra/outbound/format.js";
import type { OutboundDeliveryResult } from "../infra/outbound/deliver.js";
import { import {
type MessagePollResult, type MessagePollResult,
type MessageSendResult, type MessageSendResult,