// "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 { const s = await getSetting(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 { 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 { 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 { 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 секунд. Начните заново."); }