261 lines
13 KiB
TypeScript
261 lines
13 KiB
TypeScript
// Sign-in of agent subscriptions from the web (PEP-13 → PEP-67): the agent CLI's own login
|
||
// runs on this machine in a tmux session (`peppa-auth-sub<id>`); the superadmin opens the
|
||
// link on their device and, for Claude, pastes the code back into the web form.
|
||
// Claude — `claude setup-token`: URL → code → long-lived token, stored encrypted.
|
||
// Codex — `codex login --device-auth` with the subscription's own CODEX_HOME: URL + one-time
|
||
// code; Codex itself writes auth.json there when the user confirms on their device.
|
||
import { m } from "@peppa/shared/i18n";
|
||
import { execFile } from "node:child_process";
|
||
import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
|
||
import { homedir } from "node:os";
|
||
import { join } from "node:path";
|
||
import { deleteSetting, deleteSubscription, getSetting, getSubscription, NO_AUTOUPDATE_ENV, PeppaError, setSetting, updateSubscription, type Subscription, listSubscriptions, setSubscriptionAccount } from "@peppa/core";
|
||
import type { Db } from "@peppa/db";
|
||
import { peppaHome } from "@peppa/shared";
|
||
import * as tmux from "./tmux.ts";
|
||
|
||
const LOGIN_TTL_MS = 10 * 60_000;
|
||
const CLAUDE_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 CODEX_URL_RE = /https:\/\/\S+/;
|
||
const CODEX_CODE_RE = /\b[A-Z0-9]{4,5}-[A-Z0-9]{4,5}\b/;
|
||
|
||
const sessionName = (id: number) => `peppa-auth-sub${id}`;
|
||
const settingKey = (id: number) => `subscription.login:${id}`;
|
||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||
|
||
/** Login dir of a subscription (Codex: CODEX_HOME). Private: the CLI keeps credentials there. */
|
||
export function subscriptionDir(id: number): string {
|
||
return join(peppaHome(), "subscriptions", `s${id}`);
|
||
}
|
||
export function codexHome(id: number): string {
|
||
const dir = join(subscriptionDir(id), "codex");
|
||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||
return dir;
|
||
}
|
||
|
||
export interface PendingLogin {
|
||
kind: "claude" | "codex";
|
||
url: string;
|
||
/** Codex device auth: the one-time code to enter on the device. */
|
||
code?: string;
|
||
startedAt: number;
|
||
}
|
||
|
||
/** Pending sign-in of a subscription (null if none or expired). */
|
||
export async function pendingLogin(db: Db, id: number): Promise<PendingLogin | null> {
|
||
const s = await getSetting<PendingLogin>(db, settingKey(id));
|
||
if (!s) return null;
|
||
if (Date.now() - s.startedAt > LOGIN_TTL_MS || !(await tmux.hasSession(sessionName(id)))) {
|
||
await endLogin(db, id);
|
||
return null;
|
||
}
|
||
return s;
|
||
}
|
||
|
||
async function endLogin(db: Db, id: number): Promise<void> {
|
||
await deleteSetting(db, settingKey(id));
|
||
if (await tmux.hasSession(sessionName(id))) await tmux.killSession(sessionName(id)).catch(() => {});
|
||
}
|
||
|
||
/** Cancels a sign-in; a subscription that was never active disappears with it. */
|
||
export async function cancelLogin(db: Db, id: number): Promise<void> {
|
||
await endLogin(db, id);
|
||
const s = await getSubscription(db, id).catch(() => null);
|
||
if (s && !s.activatedAt) await removeSubscription(db, id);
|
||
}
|
||
|
||
/** Deletes a subscription with its login dir (and any sign-in in progress). */
|
||
export async function removeSubscription(db: Db, id: number): Promise<void> {
|
||
await endLogin(db, id);
|
||
await deleteSubscription(db, id);
|
||
rmSync(subscriptionDir(id), { recursive: true, force: true });
|
||
}
|
||
|
||
async function waitForScreen(id: number, re: RegExp, what: string): Promise<string> {
|
||
for (let i = 0; i < 60; i++) {
|
||
await sleep(500);
|
||
const screen = await tmux.capturePane(sessionName(id), 200).catch(() => "");
|
||
if (re.test(screen)) return screen;
|
||
if ((await tmux.paneState(sessionName(id)).catch(() => ({ dead: true }))).dead) break;
|
||
}
|
||
const tail = (await tmux.capturePane(sessionName(id)).catch(() => "")).trim();
|
||
throw new PeppaError(tail ? m("{what} не показал ссылку входа: {tail}", { what, tail: tail.split("\n").slice(-3).join(" ").slice(0, 200) }) : m("{what} не показал ссылку входа", { what }));
|
||
}
|
||
|
||
// ── Claude ───────────────────────────────────────────────────────────────────────
|
||
|
||
/** Starts `claude setup-token` for a Claude subscription and returns the sign-in URL. */
|
||
export async function startClaudeLogin(db: Db, id: number): Promise<PendingLogin> {
|
||
const sub = await getSubscription(db, id);
|
||
if (sub.provider !== "claude") throw new PeppaError(m("Это не подписка Claude"));
|
||
await endLogin(db, id);
|
||
await tmux.newSession({
|
||
name: sessionName(id),
|
||
cwd: homedir(),
|
||
command: `${process.env.PEPPA_CLAUDE_BIN ?? "claude"} setup-token`,
|
||
env: { ...NO_AUTOUPDATE_ENV, BROWSER: "/usr/bin/true" }, // don't open a browser on this machine
|
||
width: 1000,
|
||
});
|
||
try {
|
||
const url = CLAUDE_URL_RE.exec(await waitForScreen(id, CLAUDE_URL_RE, "claude setup-token"))![0];
|
||
const login: PendingLogin = { kind: "claude", url, startedAt: Date.now() };
|
||
await setSetting(db, settingKey(id), login);
|
||
return login;
|
||
} catch (e) {
|
||
await endLogin(db, id);
|
||
throw e;
|
||
}
|
||
}
|
||
|
||
/** PEP-178: the ChatGPT account of a Codex sign-in — the e-mail in auth.json's id_token. */
|
||
export function codexAccountEmail(id: number): string | null {
|
||
try {
|
||
const auth = JSON.parse(readFileSync(join(codexHome(id), "auth.json"), "utf8")) as { tokens?: { id_token?: string } };
|
||
const part = auth.tokens?.id_token?.split(".")[1];
|
||
if (!part) return null;
|
||
const claims = JSON.parse(Buffer.from(part, "base64url").toString("utf8")) as { email?: string };
|
||
return typeof claims.email === "string" && claims.email ? claims.email : null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/** PEP-178: fills in the account of Codex subscriptions signed in before the e-mail was kept. */
|
||
export async function backfillCodexAccounts(db: Db): Promise<void> {
|
||
for (const s of await listSubscriptions(db)) {
|
||
if (s.provider !== "codex" || s.accountEmail) continue;
|
||
const email = codexAccountEmail(s.id);
|
||
if (email) await setSubscriptionAccount(db, s.id, email);
|
||
}
|
||
}
|
||
|
||
/** Types the code into setup-token and stores the token it prints on the subscription. */
|
||
export async function finishClaudeLogin(db: Db, id: number, code: string, account?: string | null): Promise<void> {
|
||
const c = code.trim();
|
||
if (!c || /\s/.test(c)) throw new PeppaError(m("Вставьте код целиком, без пробелов"));
|
||
const login = await pendingLogin(db, id);
|
||
if (login?.kind !== "claude") throw new PeppaError(m("Вход не начат или истёк — начните заново"));
|
||
const name = sessionName(id);
|
||
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 updateSubscription(db, id, { secret: token, authKind: "oauth", status: "active", checkedAt: new Date() });
|
||
// PEP-178: Claude's token can't tell its account — the person says which one it is.
|
||
if (account?.trim()) await setSubscriptionAccount(db, id, account).catch(() => {});
|
||
await endLogin(db, id); // 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 endLogin(db, id);
|
||
throw new PeppaError(msg ? m("Claude не принял код: {error}. Начните заново.", { error: msg.slice(0, 200) }) : m("Claude не принял код. Начните заново."));
|
||
}
|
||
}
|
||
await endLogin(db, id);
|
||
throw new PeppaError(m("Claude не ответил на код за 30 секунд. Начните заново."));
|
||
}
|
||
|
||
/** A ready token pasted by hand (from `claude setup-token` run elsewhere). */
|
||
export async function setClaudeSubscriptionToken(db: Db, id: number, token: string): Promise<void> {
|
||
const t = token.trim();
|
||
if (!TOKEN_RE.test(t) || TOKEN_RE.exec(t)![0] !== t) throw new PeppaError(m("Это не похоже на ключ подписки Claude (sk-ant-oat…)"));
|
||
await endLogin(db, id);
|
||
await updateSubscription(db, id, { secret: t, authKind: "oauth", status: "active", checkedAt: new Date() });
|
||
}
|
||
|
||
// ── Codex ────────────────────────────────────────────────────────────────────────
|
||
|
||
/** Starts `codex login --device-auth` with the subscription's CODEX_HOME: URL + one-time code. */
|
||
export async function startCodexLogin(db: Db, id: number): Promise<PendingLogin> {
|
||
const sub = await getSubscription(db, id);
|
||
if (sub.provider !== "codex") throw new PeppaError(m("Это не подписка Codex"));
|
||
await endLogin(db, id);
|
||
await tmux.newSession({
|
||
name: sessionName(id),
|
||
cwd: homedir(),
|
||
command: `${process.env.PEPPA_CODEX_BIN ?? "codex"} login --device-auth`,
|
||
env: { ...NO_AUTOUPDATE_ENV, CODEX_HOME: codexHome(id), BROWSER: "/usr/bin/true" },
|
||
width: 300,
|
||
});
|
||
try {
|
||
const screen = await waitForScreen(id, CODEX_CODE_RE, "codex login");
|
||
const url = CODEX_URL_RE.exec(screen)?.[0];
|
||
if (!url) throw new PeppaError(m("codex login не показал ссылку входа"));
|
||
const login: PendingLogin = { kind: "codex", url, code: CODEX_CODE_RE.exec(screen)![0], startedAt: Date.now() };
|
||
await setSetting(db, settingKey(id), login);
|
||
await updateSubscription(db, id, { authKind: "device" });
|
||
return login;
|
||
} catch (e) {
|
||
await endLogin(db, id);
|
||
throw e;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Where a Codex device sign-in stands: still waiting for the user, done (auth.json written,
|
||
* subscription active) or failed. Called by the page while it shows the code.
|
||
*/
|
||
export async function pollCodexLogin(db: Db, id: number): Promise<"pending" | "active" | "failed" | "none"> {
|
||
const login = await getSetting<PendingLogin>(db, settingKey(id));
|
||
if (login?.kind !== "codex") return "none";
|
||
const name = sessionName(id);
|
||
const state = (await tmux.hasSession(name)) ? await tmux.paneState(name) : { dead: true, exitStatus: null };
|
||
if (!state.dead) {
|
||
if (Date.now() - login.startedAt > LOGIN_TTL_MS) {
|
||
await endLogin(db, id);
|
||
await updateSubscription(db, id, { status: "auth_error", lastError: m("вход не подтверждён за 10 минут") });
|
||
return "failed";
|
||
}
|
||
return "pending";
|
||
}
|
||
const screen = await tmux.capturePane(name, 200).catch(() => "");
|
||
await endLogin(db, id);
|
||
if (state.exitStatus === 0 && existsSync(join(codexHome(id), "auth.json"))) {
|
||
await updateSubscription(db, id, { status: "active", checkedAt: new Date() });
|
||
const email = codexAccountEmail(id);
|
||
if (email) await setSubscriptionAccount(db, id, email).catch(() => {});
|
||
return "active";
|
||
}
|
||
const msg = screen.trim().split("\n").filter(Boolean).slice(-2).join(" ").slice(0, 200);
|
||
await updateSubscription(db, id, { status: "auth_error", lastError: msg || m("codex login завершился с кодом {code}", { code: state.exitStatus }) });
|
||
return "failed";
|
||
}
|
||
|
||
/** API key for Codex: `codex login --with-api-key` (key on stdin, never in argv or logs). */
|
||
export async function setCodexApiKey(db: Db, id: number, key: string): Promise<void> {
|
||
const k = key.trim();
|
||
if (!k || /\s/.test(k)) throw new PeppaError(m("Вставьте ключ целиком, без пробелов"));
|
||
await endLogin(db, id);
|
||
const out = await new Promise<{ code: number | null; text: string }>((resolve) => {
|
||
const child = execFile(
|
||
process.env.PEPPA_CODEX_BIN ?? "codex",
|
||
["login", "--with-api-key"],
|
||
{ env: { ...process.env, ...NO_AUTOUPDATE_ENV, CODEX_HOME: codexHome(id) }, timeout: 60_000 },
|
||
(err, stdout, stderr) => resolve({ code: err ? ((err as { code?: number }).code ?? 1) : 0, text: `${stdout}${stderr}` }),
|
||
);
|
||
child.stdin?.end(`${k}\n`);
|
||
});
|
||
if (out.code !== 0) {
|
||
await updateSubscription(db, id, { status: "auth_error", authKind: "api_key", lastError: mask(out.text, [k]).trim().slice(-200) });
|
||
throw new PeppaError(m("Codex не принял ключ: {error}", { error: mask(out.text, [k]).trim().split("\n").slice(-1)[0]?.slice(0, 200) ?? "" }));
|
||
}
|
||
await updateSubscription(db, id, { status: "active", authKind: "api_key", checkedAt: new Date() });
|
||
}
|
||
|
||
/** Removes secrets from CLI output before it is stored or shown. */
|
||
export function mask(text: string, secrets: Array<string | null | undefined>): string {
|
||
let t = text.replace(TOKEN_RE, "sk-ant-…").replace(/\bsk-[A-Za-z0-9_-]{16,}/g, "sk-…");
|
||
for (const s of secrets) if (s && s.length > 6) t = t.split(s).join("…");
|
||
return t;
|
||
}
|
||
|
||
export type { Subscription };
|