- Settings → Claude: Peppa runs 'claude setup-token' in tmux, shows the claude.com sign-in link, the user pastes the code into the form; the 1-year token is stored encrypted on the user (users.claude_token_enc) - Claude sessions of the owner's projects get CLAUDE_CODE_OAUTH_TOKEN; projects without an owner token keep using the machine login - disconnect / reconnect; setup times out after 10 min and its tmux session (and scrollback with the token) is killed right after saving - mock-claude setup-token; 2 new tests (56 e2e total, green) - verified on prod: the button yields the real claude.com authorize URL - OpenSpec: pep-13 archived into spec agent-credentials Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
91 lines
4.1 KiB
TypeScript
91 lines
4.1 KiB
TypeScript
// "Connect Claude" from the web: runs `claude setup-token` on this machine in a tmux
|
|
// session, hands the sign-in URL to the user, types back the code they paste into the
|
|
// web form, and stores the resulting long-lived token (encrypted) on the user.
|
|
import { homedir } from "node:os";
|
|
import { deleteSetting, getSetting, PeppaError, setClaudeToken, setSetting } from "@peppa/core";
|
|
import type { Db } from "@peppa/db";
|
|
import * as tmux from "./tmux.ts";
|
|
|
|
const SETUP_TTL_MS = 10 * 60_000;
|
|
const URL_RE = /https:\/\/\S+\/oauth\/authorize\?\S+/;
|
|
const TOKEN_RE = /sk-ant-oat\d{2}-[A-Za-z0-9_-]{20,}/;
|
|
const ERROR_RE = /(error|invalid|failed|expired)/i;
|
|
|
|
const sessionName = (userId: number) => `peppa-auth-u${userId}`;
|
|
const settingKey = (userId: number) => `claude.setup.u${userId}`;
|
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
|
|
export interface ClaudeSetup {
|
|
url: string;
|
|
startedAt: number;
|
|
}
|
|
|
|
/** Pending setup of this user (null if none or expired). */
|
|
export async function pendingClaudeSetup(db: Db, userId: number): Promise<ClaudeSetup | null> {
|
|
const s = await getSetting<ClaudeSetup>(db, settingKey(userId));
|
|
if (!s) return null;
|
|
if (Date.now() - s.startedAt > SETUP_TTL_MS || !(await tmux.hasSession(sessionName(userId)))) {
|
|
await cancelClaudeSetup(db, userId);
|
|
return null;
|
|
}
|
|
return s;
|
|
}
|
|
|
|
export async function cancelClaudeSetup(db: Db, userId: number): Promise<void> {
|
|
await deleteSetting(db, settingKey(userId));
|
|
if (await tmux.hasSession(sessionName(userId))) await tmux.killSession(sessionName(userId)).catch(() => {});
|
|
}
|
|
|
|
/** Starts `claude setup-token` and returns the sign-in URL to show the user. */
|
|
export async function startClaudeSetup(db: Db, userId: number): Promise<ClaudeSetup> {
|
|
await cancelClaudeSetup(db, userId);
|
|
await tmux.newSession({
|
|
name: sessionName(userId),
|
|
cwd: homedir(),
|
|
command: `${process.env.PEPPA_CLAUDE_BIN ?? "claude"} setup-token`,
|
|
env: { BROWSER: "/usr/bin/true" }, // don't open a browser on this machine
|
|
width: 1000,
|
|
});
|
|
for (let i = 0; i < 60; i++) {
|
|
await sleep(500);
|
|
const url = URL_RE.exec(await tmux.capturePane(sessionName(userId)))?.[0];
|
|
if (url) {
|
|
const setup = { url, startedAt: Date.now() };
|
|
await setSetting(db, settingKey(userId), setup);
|
|
return setup;
|
|
}
|
|
}
|
|
const tail = await tmux.capturePane(sessionName(userId)).catch(() => "");
|
|
await cancelClaudeSetup(db, userId);
|
|
throw new PeppaError(`claude setup-token не показал ссылку входа${tail.trim() ? `: ${tail.trim().split("\n").slice(-3).join(" ")}` : ""}`);
|
|
}
|
|
|
|
/** Types the user's code into setup-token and stores the token it prints. */
|
|
export async function finishClaudeSetup(db: Db, userId: number, code: string): Promise<void> {
|
|
const c = code.trim();
|
|
if (!c || /\s/.test(c)) throw new PeppaError("Вставьте код целиком, без пробелов");
|
|
if (!(await pendingClaudeSetup(db, userId))) throw new PeppaError("Подключение не начато или истекло — нажмите «Подключить Claude» ещё раз");
|
|
const name = sessionName(userId);
|
|
const before = await tmux.capturePane(name);
|
|
await tmux.sendText(name, c);
|
|
for (let i = 0; i < 60; i++) {
|
|
await sleep(500);
|
|
const screen = await tmux.capturePane(name, 200);
|
|
const token = TOKEN_RE.exec(screen)?.[0];
|
|
if (token) {
|
|
await setClaudeToken(db, userId, token);
|
|
await cancelClaudeSetup(db, userId); // also wipes the token from the tmux scrollback
|
|
return;
|
|
}
|
|
const after = screen.slice(screen.indexOf(c) >= 0 ? screen.indexOf(c) + c.length : before.length);
|
|
const dead = (await tmux.paneState(name)).dead;
|
|
if (dead || ERROR_RE.test(after)) {
|
|
const msg = after.replace(TOKEN_RE, "…").trim().split("\n").filter(Boolean).slice(-2).join(" ");
|
|
await cancelClaudeSetup(db, userId);
|
|
throw new PeppaError(`Claude не принял код${msg ? `: ${msg.slice(0, 200)}` : ""}. Начните заново.`);
|
|
}
|
|
}
|
|
await cancelClaudeSetup(db, userId);
|
|
throw new PeppaError("Claude не ответил на код за 30 секунд. Начните заново.");
|
|
}
|